From c7300763a917fc7ac976fe2f3ae4e02ed0f817f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= <16311043+immakermatty@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:50:54 +0000 Subject: [PATCH 01/31] hosted: configurable client session TTL T3CODE_CLIENT_SESSION_TTL sets the default lifetime of newly issued client sessions, so a hosted Environment's paired browser stays signed in longer than upstream's fixed 30 days. The value is a positive duration such as 365d; an invalid one fails config resolution. The seam in SessionStore stays one line. On v0.1.3: upstream added privateNetworkOnly next to the row's config fields (#24588); both stay. The config test now uses upstream's minimalWebFlags helper. On v0.1.4: unchanged; the seam applies cleanly. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/auth/SessionStore.test.ts | 19 ++++++++++++++++ apps/server/src/auth/SessionStore.ts | 4 +++- apps/server/src/cli/config.test.ts | 27 +++++++++++++++++++++++ apps/server/src/cli/config.ts | 21 ++++++++++++++++++ apps/server/src/config.ts | 3 +++ 5 files changed, 73 insertions(+), 1 deletion(-) diff --git a/apps/server/src/auth/SessionStore.test.ts b/apps/server/src/auth/SessionStore.test.ts index c94adf8761d06..2f5df9287cd55 100644 --- a/apps/server/src/auth/SessionStore.test.ts +++ b/apps/server/src/auth/SessionStore.test.ts @@ -288,6 +288,25 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => { ), ); + it.effect("uses the configured default lifetime for client sessions", () => + Effect.gen(function* () { + const sessions = yield* SessionStore.SessionStore; + const issued = yield* sessions.issue({ subject: "long-lived-browser" }); + + yield* TestClock.adjust(Duration.days(364)); + const stillValid = yield* sessions.verify(issued.token); + expect(stillValid.sessionId).toBe(issued.sessionId); + + yield* TestClock.adjust(Duration.days(2)); + const expired = yield* Effect.flip(sessions.verify(issued.token)); + expect(expired._tag).toBe("SessionTokenExpiredError"); + }).pipe( + Effect.provide( + Layer.merge(layerSessionStore({ clientSessionTtl: Duration.days(365) }), TestClock.layer()), + ), + ), + ); + it.effect("atomically replaces active sessions with the same subject and method", () => Effect.gen(function* () { const sessions = yield* SessionStore.SessionStore; diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index 0ef7a692fd6db..7934341387cbf 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -644,7 +644,9 @@ const make = Effect.gen(function* () { ); const issuedAt = yield* DateTime.now; const expiresAt = DateTime.add(issuedAt, { - milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL), + milliseconds: Duration.toMillis( + input?.ttl ?? serverConfig.clientSessionTtl ?? DEFAULT_SESSION_TTL, + ), }); const claims: SessionClaims = { v: 1, diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index c7f47c655dc22..5be5fef5716c8 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -6,6 +6,7 @@ import * as NodeOS from "node:os"; import { assert, expect, it } from "@effect/vitest"; import * as ConfigProvider from "effect/ConfigProvider"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -910,4 +911,30 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { }); }), ); + + it.effect("reads the client session lifetime from env and rejects invalid values", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const resolveWith = (env: Record) => + resolveServerConfig( + minimalWebFlags(join(NodeOS.tmpdir(), "t3-cli-config-session-ttl-base")), + Option.none(), + ).pipe( + Effect.provide( + Layer.mergeAll(ConfigProvider.layer(ConfigProvider.fromEnv({ env })), NetService.layer), + ), + ); + + const unset = yield* resolveWith({}); + expect(unset.clientSessionTtl).toBeUndefined(); + + const configured = yield* resolveWith({ T3CODE_CLIENT_SESSION_TTL: "365d" }); + expect(configured.clientSessionTtl).toEqual(Duration.days(365)); + + for (const value of ["0d", "forever", "-1d"]) { + const error = yield* resolveWith({ T3CODE_CLIENT_SESSION_TTL: value }).pipe(Effect.flip); + expect(String(error)).toContain("T3CODE_CLIENT_SESSION_TTL"); + } + }), + ); }); diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index 00621e332deb9..91baa46be48a0 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -129,6 +129,26 @@ const EnvServerConfig = Config.all({ ), port: Config.Port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)), host: Config.String("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)), + clientSessionTtl: Config.String("T3CODE_CLIENT_SESSION_TTL").pipe( + Config.mapEffect((value) => { + const duration = parseDurationInput(value); + const milliseconds = duration === null ? Number.NaN : Duration.toMillis(duration); + return duration !== null && Number.isFinite(milliseconds) && milliseconds > 0 + ? Effect.succeed(duration) + : Effect.fail( + new Config.ConfigError( + new Schema.SchemaError( + new SchemaIssue.InvalidValue({ + message: + "T3CODE_CLIENT_SESSION_TTL must be a positive duration such as 30d or 365d.", + }), + ), + ), + ); + }), + Config.option, + Config.map(Option.getOrUndefined), + ), t3Home: Config.String("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)), devUrl: Config.URL("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)), devAllowedOrigins: Config.String("T3CODE_DEV_ALLOWED_ORIGINS").pipe( @@ -501,6 +521,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct desktopBrowserFd, desktopBrowserControlFd, resourceMonitorPath, + clientSessionTtl: env.clientSessionTtl, autoBootstrapProjectFromCwd, logWebSocketEvents, tailscaleServeEnabled, diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 91d443308776c..842520fb880ab 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -1,5 +1,6 @@ import * as Context from "effect/Context"; import * as Clock from "effect/Clock"; +import type * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -102,6 +103,8 @@ export class ServerConfig extends Context.Service< readonly desktopBrowserFd?: number | undefined; readonly desktopBrowserControlFd?: number | undefined; readonly resourceMonitorPath?: string | undefined; + /** Default lifetime of newly issued client sessions (`T3CODE_CLIENT_SESSION_TTL`). */ + readonly clientSessionTtl?: Duration.Duration | undefined; readonly autoBootstrapProjectFromCwd: boolean; readonly logWebSocketEvents: boolean; readonly tailscaleServeEnabled: boolean; From d4a583e55ce5dfcb9224bdcd3e08b329b60a1e95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= <16311043+immakermatty@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:50:54 +0000 Subject: [PATCH 02/31] hosted: serve behind an explicit HTTPS external origin T3CODE_EXTERNAL_ORIGIN names the canonical HTTPS origin of a server that listens on loopback behind the Environment's gateway. Auth then treats it as remote-reachable (one-time-token pairing only) and issues a Secure, host-only __Host- session cookie that sibling subdomains cannot set or overwrite. The value must be a bare https origin; anything else fails config resolution. On v0.1.3: the row's externalOrigin fields sit beside upstream's new privateNetworkOnly (#24588); both stay. The auth seams are unchanged. Since #24588 a launcher-managed server without a host listens on 0.0.0.0, so the Environment's explicit T3CODE_HOST=127.0.0.1 is now load-bearing. The config test uses upstream's minimalWebFlags helper. On v0.1.4: unchanged; the seam applies cleanly. Co-Authored-By: Claude Opus 5.5 --- .../src/auth/EnvironmentAuthPolicy.test.ts | 21 +++ apps/server/src/auth/EnvironmentAuthPolicy.ts | 5 +- apps/server/src/auth/SessionStore.ts | 1 + apps/server/src/auth/http.ts | 4 + apps/server/src/auth/utils.ts | 7 + apps/server/src/cli/config.test.ts | 34 +++++ apps/server/src/cli/config.ts | 25 ++++ apps/server/src/config.ts | 2 + .../src/lazurio/hostedSessionCookie.test.ts | 136 ++++++++++++++++++ 9 files changed, 234 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/lazurio/hostedSessionCookie.test.ts diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.test.ts b/apps/server/src/auth/EnvironmentAuthPolicy.test.ts index 06189cc53331e..739a4398c260a 100644 --- a/apps/server/src/auth/EnvironmentAuthPolicy.test.ts +++ b/apps/server/src/auth/EnvironmentAuthPolicy.test.ts @@ -79,4 +79,25 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => { ), ), ); + it.effect( + "uses remote-reachable policy for a loopback web server behind an external origin", + () => + Effect.gen(function* () { + const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("remote-reachable"); + expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]); + expect(descriptor.sessionCookieName).toBe("__Host-t3_session"); + }).pipe( + Effect.provide( + layerEnvironmentAuthPolicy({ + mode: "web", + host: "127.0.0.1", + port: 3773, + externalOrigin: new URL("https://t3code.management.example.test/"), + }), + ), + ), + ); }); diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.ts b/apps/server/src/auth/EnvironmentAuthPolicy.ts index 141fd86aa52ab..7bbb96ab0d213 100644 --- a/apps/server/src/auth/EnvironmentAuthPolicy.ts +++ b/apps/server/src/auth/EnvironmentAuthPolicy.ts @@ -18,7 +18,9 @@ export class EnvironmentAuthPolicy extends Context.Service< export const make = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity; - const isRemoteReachable = isRemoteReachableHost(config.host); + // A loopback bind behind an external origin is still reached remotely. + const isRemoteReachable = + config.externalOrigin !== undefined || isRemoteReachableHost(config.host); const policy = config.mode === "desktop" @@ -45,6 +47,7 @@ export const make = Effect.gen(function* () { mode: config.mode, port: config.port, host: config.host, + externalOrigin: config.externalOrigin, instanceKey: config.stateDir, environmentId: yield* serverEnvironment.getEnvironmentId, development: config.devUrl !== undefined, diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index 7934341387cbf..d3304c063a233 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -501,6 +501,7 @@ const make = Effect.gen(function* () { mode: serverConfig.mode, port: serverConfig.port, host: serverConfig.host, + externalOrigin: serverConfig.externalOrigin, instanceKey: serverConfig.stateDir, environmentId: yield* serverEnvironment.getEnvironmentId, development: serverConfig.devUrl !== undefined, diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index e570be1b4793a..72f7d4fd4f079 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -204,6 +204,8 @@ const appendSessionCookie = (cookieName: string, token: string, expiresAt: DateT httpOnly: true, path: "/", sameSite: "lax", + // Browsers accept `__Host-` cookies only when they are Secure. + ...(cookieName.startsWith("__Host-") ? { secure: true } : {}), }), ).pipe( Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed")), @@ -319,6 +321,8 @@ export const layer = HttpApiBuilder.group( httpOnly: true, path: "/", sameSite: "lax", + // Browsers accept `__Host-` cookies only when they are Secure. + ...(cookieName.startsWith("__Host-") ? { secure: true } : {}), }), ).pipe(Effect.catch(() => failEnvironmentInternal("browser_session_cookie_failed"))); const sessionCookies = result.expireNormalCookie diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts index dc89a5da81140..0b8f7b7d96550 100644 --- a/apps/server/src/auth/utils.ts +++ b/apps/server/src/auth/utils.ts @@ -16,6 +16,7 @@ export function resolveSessionCookieName(input: { readonly mode: "web" | "desktop"; readonly port: number; readonly host: string | undefined; + readonly externalOrigin?: URL | undefined; readonly instanceKey: string; readonly environmentId: string; readonly development: boolean; @@ -24,6 +25,12 @@ export function resolveSessionCookieName(input: { return `${SESSION_COOKIE_NAME}_${input.port}`; } + // A server behind its own HTTPS origin owns the whole host, so it can use a + // Secure, host-only cookie that sibling subdomains cannot set or overwrite. + if (!input.development && input.externalOrigin !== undefined) { + return `__Host-${SESSION_COOKIE_NAME}`; + } + const instanceHash = NodeCrypto.createHash("sha256") .update( !input.development && isRemoteReachableHost(input.host) diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 5be5fef5716c8..7235ad8c38612 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -937,4 +937,38 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { } }), ); + + it.effect("reads an HTTPS external origin from env and rejects anything else", () => + Effect.gen(function* () { + const { join } = yield* Path.Path; + const flags = { + ...minimalWebFlags(join(NodeOS.tmpdir(), "t3-cli-config-external-origin-base")), + host: Option.some("127.0.0.1"), + }; + const resolveWith = (env: Record) => + resolveServerConfig(flags, Option.none()).pipe( + Effect.provide( + Layer.mergeAll(ConfigProvider.layer(ConfigProvider.fromEnv({ env })), NetService.layer), + ), + ); + + expect((yield* resolveWith({})).externalOrigin).toBeUndefined(); + const configured = yield* resolveWith({ + T3CODE_EXTERNAL_ORIGIN: " https://t3code.management.example.test ", + }); + expect(configured.externalOrigin?.origin).toBe("https://t3code.management.example.test"); + + for (const value of [ + "t3code.management.example.test", + "http://t3code.management.example.test", + "https://user@t3code.management.example.test", + "https://t3code.management.example.test/t3code/", + "https://t3code.management.example.test/?workspace=management", + "https://t3code.management.example.test/#pairing-token", + ]) { + const error = yield* resolveWith({ T3CODE_EXTERNAL_ORIGIN: value }).pipe(Effect.flip); + expect(String(error), value).toContain("T3CODE_EXTERNAL_ORIGIN"); + } + }), + ); }); diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index 91baa46be48a0..1cc521395c2bf 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -129,6 +129,30 @@ const EnvServerConfig = Config.all({ ), port: Config.Port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)), host: Config.String("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)), + externalOrigin: Config.String("T3CODE_EXTERNAL_ORIGIN").pipe( + Config.mapEffect((value) => { + const url = URL.parse(value.trim()); + return url !== null && + url.protocol === "https:" && + url.username === "" && + url.password === "" && + url.pathname === "/" && + url.search === "" && + url.hash === "" + ? Effect.succeed(new URL(url.origin)) + : Effect.fail( + new Config.ConfigError( + new Schema.SchemaError( + new SchemaIssue.InvalidValue({ + message: "T3CODE_EXTERNAL_ORIGIN must be an absolute HTTPS origin.", + }), + ), + ), + ); + }), + Config.option, + Config.map(Option.getOrUndefined), + ), clientSessionTtl: Config.String("T3CODE_CLIENT_SESSION_TTL").pipe( Config.mapEffect((value) => { const duration = parseDurationInput(value); @@ -507,6 +531,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct serverTracePath, host, ...(privateNetworkOnly ? { privateNetworkOnly } : {}), + externalOrigin: env.externalOrigin, staticDir, devUrl, ...(devAuthToken === undefined ? {} : { devAuthToken }), diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 842520fb880ab..6220f0ce57567 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -87,6 +87,8 @@ export class ServerConfig extends Context.Service< readonly host: string | undefined; /** Set when the host was defaulted to a private-network listener for the service. */ readonly privateNetworkOnly?: boolean | undefined; + /** Canonical HTTPS browser origin of a reverse-proxied server (`T3CODE_EXTERNAL_ORIGIN`). */ + readonly externalOrigin?: URL | undefined; readonly cwd: string; readonly baseDir: string; readonly staticDir: string | undefined; diff --git a/apps/server/src/lazurio/hostedSessionCookie.test.ts b/apps/server/src/lazurio/hostedSessionCookie.test.ts new file mode 100644 index 0000000000000..332225c5773ca --- /dev/null +++ b/apps/server/src/lazurio/hostedSessionCookie.test.ts @@ -0,0 +1,136 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { EnvironmentHttpApi } from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Etag from "effect/http/Etag"; +import * as HttpPlatform from "effect/http/HttpPlatform"; +import * as HttpRouter from "effect/http/HttpRouter"; +import * as HttpApi from "effect/http-api/HttpApi"; +import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; + +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; +import * as AuthHttp from "../auth/http.ts"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; + +// A hosted Environment serves T3 on loopback behind its own HTTPS origin (T3CODE_EXTERNAL_ORIGIN). +const EXTERNAL_ORIGIN = new URL("https://t3code.management.example.test/"); + +class AuthTestApi extends HttpApi.make("environment").add(EnvironmentHttpApi.groups.auth) {} + +// Production builds never set `devUrl`, and neither does this config: a dev server keeps upstream's cookie. +const layerEnvironmentAuth = (overrides: Partial) => + EnvironmentAuth.layer.pipe( + Layer.provide(SqlitePersistence.layerMemory), + Layer.provideMerge(ServerSecretStore.layer), + Layer.provide(ServerEnvironment.layerIdentity), + Layer.provideMerge( + Layer.effect( + ServerConfig.ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + return { ...config, ...overrides } satisfies ServerConfig.ServerConfig["Service"]; + }), + ).pipe( + Layer.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-hosted-session-cookie-test-" }), + ), + ), + ), + ); + +/** Serves the auth routes on the EnvironmentAuth that mints the pairing credential. */ +const serveAuthRoutes = Effect.fn("serveAuthRoutes")(function* ( + overrides: Partial, +) { + const services = yield* Layer.build(layerEnvironmentAuth(overrides)); + const pairing = yield* Context.get( + services, + EnvironmentAuth.EnvironmentAuth, + ).issuePairingCredential(); + const routes = HttpApiBuilder.layer(AuthTestApi).pipe( + Layer.provide(AuthHttp.layer), + Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(Layer.succeedContext(services)), + Layer.provideMerge( + HttpPlatform.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(Etag.layerWeak), + ), + ), + Layer.provide(NodeServices.layer), + ); + const web = yield* Effect.acquireRelease( + Effect.sync(() => HttpRouter.toWebHandler(routes, { disableLogger: true })), + (web) => Effect.promise(() => web.dispose()), + ); + const context = Context.make(Crypto.Crypto, yield* Crypto.Crypto).pipe( + Context.add( + ServerSecretStore.ServerSecretStore, + Context.get(services, ServerSecretStore.ServerSecretStore), + ), + ); + return { + credential: pairing.credential, + handle: (request: Request) => Effect.promise(() => web.handler(request, context)), + }; +}); + +const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const postJson = (path: string, body: unknown) => + new Request(`http://127.0.0.1${path}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: encodeJson(body), + }); + +// Live clock: the pairing credential is minted here and redeemed inside the router. +it.live("sets a Secure host-only session cookie behind an external origin", () => + Effect.gen(function* () { + const { credential, handle } = yield* serveAuthRoutes({ + mode: "web", + host: "127.0.0.1", + externalOrigin: EXTERNAL_ORIGIN, + }); + + const response = yield* handle(postJson("/api/auth/browser-session", { credential })); + + expect(response.status).toBe(200); + const cookies = response.headers.getSetCookie(); + expect(cookies).toHaveLength(1); + expect(cookies[0]).toMatch(/^__Host-t3_session=/); + expect(cookies[0]).toContain("; Secure"); + expect(cookies[0]).toContain("; Path=/"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.live("migrates a legacy cookie to a Secure host-only cookie behind an external origin", () => + Effect.gen(function* () { + const { credential, handle } = yield* serveAuthRoutes({ + mode: "web", + host: "192.168.1.50", + externalOrigin: EXTERNAL_ORIGIN, + }); + const bootstrap = yield* handle(postJson("/api/auth/browser-session", { credential })); + const currentCookie = bootstrap.headers.getSetCookie()[0]?.split(";", 1)[0] ?? ""; + const legacyCookie = currentCookie.replace(/^__Host-t3_session=/, "t3_session="); + expect(legacyCookie).toMatch(/^t3_session=./); + + const response = yield* handle( + new Request("http://127.0.0.1/api/auth/session", { headers: { cookie: legacyCookie } }), + ); + + expect(response.status).toBe(200); + expect(yield* Effect.promise(() => response.json())).toMatchObject({ authenticated: true }); + const migrated = response.headers + .getSetCookie() + .find((cookie) => cookie.startsWith("__Host-t3_session=")); + expect(migrated).toContain("; Secure"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); From 914ab6fb82524348fe8e98bfa51fac7e82bde78d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= <16311043+immakermatty@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:50:55 +0000 Subject: [PATCH 03/31] hosted: explicit environment label T3CODE_ENVIRONMENT_LABEL, when set, is the Environment's label ahead of the pretty hostname and the hostname, so a hosted Environment shows the name its Organization gave it rather than the VM's hostname. On v0.1.3: ServerEnvironmentLabel.ts is unchanged upstream; the hunk and its overlay test replay as they were. On v0.1.4: unchanged; the seam applies cleanly. Co-Authored-By: Claude Opus 5.5 --- .../src/environment/ServerEnvironmentLabel.ts | 5 ++ .../src/lazurio/environmentLabel.test.ts | 50 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 apps/server/src/lazurio/environmentLabel.test.ts diff --git a/apps/server/src/environment/ServerEnvironmentLabel.ts b/apps/server/src/environment/ServerEnvironmentLabel.ts index 73ff4a7639103..08dadde78cca7 100644 --- a/apps/server/src/environment/ServerEnvironmentLabel.ts +++ b/apps/server/src/environment/ServerEnvironmentLabel.ts @@ -182,6 +182,11 @@ const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* ( input: ResolveServerEnvironmentLabelInput, ) { + const configuredLabel = normalizeLabel((yield* HostProcess.Environment).T3CODE_ENVIRONMENT_LABEL); + if (configuredLabel) { + return configuredLabel; + } + const friendlyHostLabel = yield* resolveFriendlyHostLabel(); if (friendlyHostLabel) { return friendlyHostLabel; diff --git a/apps/server/src/lazurio/environmentLabel.test.ts b/apps/server/src/lazurio/environmentLabel.test.ts new file mode 100644 index 0000000000000..b67433f687d42 --- /dev/null +++ b/apps/server/src/lazurio/environmentLabel.test.ts @@ -0,0 +1,50 @@ +import { afterEach, describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { vi } from "vite-plus/test"; + +import * as ProcessRunner from "../processRunner.ts"; +import * as ServerEnvironmentLabel from "../environment/ServerEnvironmentLabel.ts"; + +// A containerised Environment has a generated hostname, so Lazurio's Machines name it explicitly. +const runMock = vi.fn(); + +const layerTest = Layer.merge( + FileSystem.layerNoop({}), + Layer.succeed( + ProcessRunner.ProcessRunner, + ProcessRunner.ProcessRunner.of({ + run: (input) => runMock(input), + }), + ), +); + +afterEach(() => { + runMock.mockReset(); +}); + +describe("resolveServerEnvironmentLabel", () => { + it.effect("prefers the explicit T3CODE_ENVIRONMENT_LABEL", () => + Effect.gen(function* () { + const result = yield* ServerEnvironmentLabel.resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + }).pipe( + Effect.provide( + Layer.mergeAll( + layerTest, + Layer.succeed(HostProcess.Platform, "linux"), + Layer.succeed(HostProcess.Hostname, "buildbox"), + Layer.succeed(HostProcess.Environment, { + T3CODE_ENVIRONMENT_LABEL: " Acme / Management ", + }), + ), + ), + ); + + expect(result).toBe("Acme / Management"); + expect(runMock).not.toHaveBeenCalled(); + }), + ); +}); From f41f483809c476883524f3370efe8c40e800c762 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= <16311043+immakermatty@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:51:23 +0000 Subject: [PATCH 04/31] feat: in-app update from the configured release channel T3CODE_RELEASE_REPOSITORY (owner/name) selects whose GitHub Releases the release index, `t3 update`, the boot service, remote self-update and the install scripts use; unset, the Lazurio distribution installs and updates from Lazurio/t3code. A server run by the service launcher checks its own channel there at startup and every six hours (never when unmanaged, on preview builds, or with T3CODE_UPDATE_CHECK_ENABLED=false) and advertises a strictly newer release as `availableServerUpdate`. The index picks the highest version per channel, not the first one published. Once the launcher has committed this server's version, the server points the user's `t3` link at its own runtime, so the CLI and the server stay on one version after an in-app Update. On v0.1.3 the server, CLI and boot-service seams are unchanged (launcher protocol 3). Upstream removed the composer's "Server update available" notice (#25401) and now offers updates from the update button at the bottom of the sidebar and Settings -> Environments. The advertised release therefore moves onto that button: collectServerUpdateTargets takes a server's advertised release as its target (it is strictly newer by construction, so the version-core comparison, which ignores a fork's prerelease suffix, is skipped), and useUpdateEverything no longer holds such a target until it is on npm, because the release lives in the server's own channel. The composer keeps only the running/failed notice; its Retry targets the advertised version. The install scripts are rebuilt on upstream's new lookup (#22907): stable reads github.com//releases/latest, the other trains page the API up to ten pages, and each answer is filtered by the runtime's train rule instead of upstream's narrow vX.Y.Z pattern, which rejects X.Y.Z-lazurio.N. install-scripts.test.ts now serves releases/latest (with its Accept header) and two API pages, and checks which URLs each train reads. Overlay comments are cut to the new four-line limit. On v0.1.4 the client no longer asks a server to continue its threads (continueRunningThreads is gone from the web, #26238): a server prepares the continuation itself on every graceful stop. The five web seams that passed the request along keep only the overlay's targetVersion. The update dialog shows one row per machine (#26210); a server whose target differs from the version in its header shows its own targetVersion (servers offer their channels' releases, stable or preview), and the dialog promises that threads may continue only to a server with the threadRestartContinuation capability from 0.0.46-0 (SHUTDOWN_CONTINUATION_SINCE in updateEverything.logic.ts), since older releases continued only on the client's request. watchAvailableServerUpdate gets FetchHttpClient.layer inside ServerEnvironment's make, so CLI commands that build the layer need no HTTP client of their own. That provision shadowed the test layer's HTTP client, so the guard of ServerEnvironment.test.ts now stubs FetchHttpClient.Fetch, lets the forked check run and expects no request from a web or desktop server; forcing managed: true makes it fail. releaseIndex.test's cases count the requests the same way, with a managed stable server as the case that does ask, so dropping the unmanaged early return fails them too. Upstream's own installer test (install.test.ts, #22490) now names pingdotgg/t3code in T3CODE_RELEASE_REPOSITORY, because its fixture serves upstream's repository; without it the installer asks for Lazurio/t3code and exits. The v0.1.3 line missed this because the fork CI ran only its fixed gate and changed tests, and install.test.ts was neither. The launcher protocol stays 3. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/cli/update.test.ts | 14 +- apps/server/src/cli/update.ts | 68 ++---- apps/server/src/cloud/bootService.ts | 6 +- apps/server/src/cloud/pinnedRuntime.test.ts | 43 ++++ apps/server/src/cloud/pinnedRuntime.ts | 41 +++- apps/server/src/cloud/releaseIndex.test.ts | 213 ++++++++++++++++++ apps/server/src/cloud/releaseIndex.ts | 163 ++++++++++++++ apps/server/src/cloud/selfUpdate.test.ts | 14 ++ apps/server/src/cloud/selfUpdate.ts | 10 +- .../src/environment/ServerEnvironment.test.ts | 11 + .../src/environment/ServerEnvironment.ts | 20 +- apps/server/src/lazurio/launcherLink.test.ts | 153 +++++++++++++ apps/server/src/lazurio/launcherLink.ts | 78 +++++++ apps/server/src/server.ts | 6 + .../chat/useAutoBalanceUpdateBanner.tsx | 2 +- .../chat/useSystemComposerBanners.tsx | 2 +- .../settings/ConnectionsSettings.tsx | 6 +- .../settings/SavedEnvironmentRows.tsx | 4 +- .../sidebar/UpdateEverythingDialog.tsx | 5 + .../sidebar/updateEverything.logic.test.ts | 72 +++++- .../sidebar/updateEverything.logic.ts | 49 +++- .../components/sidebar/useUpdateEverything.ts | 18 +- .../web/src/lazurio/serverUpdateOffer.test.ts | 76 +++++++ apps/web/src/versionSkew.test.ts | 79 ++++++- apps/web/src/versionSkew.ts | 35 ++- docs/user/background-service.md | 5 + docs/user/updating.md | 8 + packages/contracts/src/environment.ts | 4 + packages/shared/src/cliRelease.test.ts | 44 +++- packages/shared/src/cliRelease.ts | 43 +++- scripts/install-scripts.test.ts | 154 +++++++++++++ scripts/install.ps1 | 41 +++- scripts/install.sh | 44 +++- scripts/install.test.ts | 2 + 34 files changed, 1403 insertions(+), 130 deletions(-) create mode 100644 apps/server/src/cloud/releaseIndex.test.ts create mode 100644 apps/server/src/cloud/releaseIndex.ts create mode 100644 apps/server/src/lazurio/launcherLink.test.ts create mode 100644 apps/server/src/lazurio/launcherLink.ts create mode 100644 apps/web/src/lazurio/serverUpdateOffer.test.ts create mode 100644 scripts/install-scripts.test.ts diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.ts index e6a6eb5ee1dbf..e8eb9fcc7df21 100644 --- a/apps/server/src/cli/update.test.ts +++ b/apps/server/src/cli/update.test.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { CLI_RELEASE_INDEX_PAGE_SIZE } from "@t3tools/shared/cliRelease"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; @@ -12,19 +13,24 @@ import { repointLauncher, resolveLauncherPath, resolveNewestVersion } from "./up afterEach(() => vi.restoreAllMocks()); -it.effect("authenticates each release page until the requested channel is found", () => +it.effect("authenticates each release page up to the last one", () => Effect.gen(function* () { const pages: string[] = []; const httpClient = HttpClient.make((request) => { const url = new URL(request.url); assert.equal(url.origin, "https://api.github.com"); - assert.equal(url.pathname, "/repos/pingdotgg/t3code/releases"); + assert.equal(url.pathname, "/repos/Lazurio/t3code/releases"); assert.equal(request.headers.accept, "application/vnd.github+json"); assert.equal(request.headers.authorization, "Bearer gh-token"); const page = url.searchParams.get("page") ?? ""; pages.push(page); - const tag_name = page === "1" ? "v1.2.4-preview.20260101.1" : "v1.2.3"; - return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json([{ tag_name }]))); + const releases = + page === "1" + ? Array.from({ length: CLI_RELEASE_INDEX_PAGE_SIZE }, (_, index) => ({ + tag_name: `v1.2.4-preview.20260101.${index + 1}`, + })) + : [{ tag_name: "v1.2.3" }]; + return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(releases))); }); const version = yield* resolveNewestVersion("stable").pipe( Effect.provideService(HostProcess.Environment, { GH_TOKEN: "gh-token" }), diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index e35be6e4ed739..bdd4ccb5260d5 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -2,9 +2,8 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { CLI_RELEASE_BASE_URL_ENV, CLI_RELEASE_CHANNELS, - cliReleaseIndexPageUrl, + CLI_RELEASE_REPOSITORY_ENV, cliReleaseChannelOf, - newestCliReleaseVersion, type CliReleaseChannel, } from "@t3tools/shared/cliRelease"; import * as Console from "effect/Console"; @@ -16,7 +15,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/cli"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { FetchHttpClient, HttpClient } from "effect/http"; import packageJson from "../../package.json" with { type: "json" }; import * as BootService from "../cloud/bootService.ts"; @@ -29,6 +28,7 @@ import { prunePinnedRuntimes, windowsShimTarget, } from "../cloud/pinnedRuntime.ts"; +import { resolveNewestReleaseVersion } from "../cloud/releaseIndex.ts"; import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts"; import * as ProcessRunner from "../processRunner.ts"; import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; @@ -44,50 +44,14 @@ export class CliUpdateError extends Schema.TaggedError()("CliUpd } } -const ReleaseIndex = Schema.Array( - Schema.Struct({ - tag_name: Schema.String, - draft: Schema.optional(Schema.Boolean), - }), -); -const decodeReleaseIndex = Schema.decodeUnknownEffect(Schema.fromJsonString(ReleaseIndex)); - -const RELEASE_INDEX_TIMEOUT = Duration.seconds(30); -const RELEASE_INDEX_MAX_PAGES = 10; - export const resolveNewestVersion = Effect.fn("cli.update.resolve_newest")(function* ( channel: CliReleaseChannel, ) { - const httpClient = yield* HttpClient.HttpClient; const environment = yield* HostProcess.Environment; - const githubToken = environment.GH_TOKEN?.trim() || environment.GITHUB_TOKEN?.trim() || undefined; - for (let page = 1; page <= RELEASE_INDEX_MAX_PAGES; page += 1) { - const request = HttpClientRequest.get(cliReleaseIndexPageUrl(page)).pipe( - HttpClientRequest.setHeader("Accept", "application/vnd.github+json"), - ); - const authenticatedRequest = - githubToken === undefined - ? request - : HttpClientRequest.setHeader(request, "Authorization", `Bearer ${githubToken}`); - const body = yield* httpClient.execute(authenticatedRequest).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap((response) => response.text), - Effect.mapError(() => new CliUpdateError({ reason: "Could not list t3 releases." })), - Effect.timeoutOrElse({ - duration: RELEASE_INDEX_TIMEOUT, - orElse: () => Effect.fail(new CliUpdateError({ reason: "Timed out listing t3 releases." })), - }), - ); - const releases = yield* decodeReleaseIndex(body).pipe( - Effect.mapError( - () => new CliUpdateError({ reason: "The t3 release index had an unexpected shape." }), - ), - ); - const version = newestCliReleaseVersion(releases, channel); - if (version !== undefined) return version; - if (releases.length === 0) break; - } - return yield* new CliUpdateError({ reason: `No published ${channel} release was found.` }); + const repository = environment[CLI_RELEASE_REPOSITORY_ENV]?.trim() || undefined; + return yield* resolveNewestReleaseVersion(channel, repository).pipe( + Effect.mapError((error) => new CliUpdateError({ reason: error.reason })), + ); }); /** @@ -309,6 +273,7 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: { reason: `'${input.requestedVersion}' is not an exact t3 version.`, }); } + const releaseRepository = environment[CLI_RELEASE_REPOSITORY_ENV]?.trim() || undefined; const progress = createUpdateProgress(); progress.status("Checking for updates..."); const targetVersion = yield* ( @@ -430,6 +395,7 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: { platform, arch, releaseBaseUrl: environment[CLI_RELEASE_BASE_URL_ENV]?.trim() || undefined, + releaseRepository, validate: (paths) => runner .run({ @@ -455,18 +421,10 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: { ), }).pipe( Effect.ensuring(Effect.sync(progress.finish)), - Effect.catchIf( - (error): error is PinnedRuntimeInstallError => - error._tag === "PinnedRuntimeInstallError" && - error.step.startsWith("downloading the t3 release checksums") && - String(error.cause).includes("404"), - () => - Effect.fail( - new CliUpdateError({ - reason: `No release archive was published for t3@${targetVersion}.`, - }), - ), - ), + Effect.catchTags({ + PinnedRuntimeReleaseNotPublishedError: (error) => + Effect.fail(new CliUpdateError({ reason: error.message })), + }), ); const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined; diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 15b3b16a7bc0f..7f599b0d3091a 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -12,7 +12,7 @@ import * as Path from "effect/Path"; import { HttpClient } from "effect/http"; import * as Schema from "effect/Schema"; -import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; +import { CLI_RELEASE_BASE_URL_ENV, CLI_RELEASE_REPOSITORY_ENV } from "@t3tools/shared/cliRelease"; import * as ProcessRunner from "../processRunner.ts"; import { @@ -527,6 +527,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const releaseBaseUrl = Option.getOrUndefined( yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option), ); + const releaseRepository = Option.getOrUndefined( + yield* Config.String(CLI_RELEASE_REPOSITORY_ENV).pipe(Config.option), + ); const homeDir = yield* Config.String("HOME").pipe(Config.withDefault("")); const installerPath = yield* Config.String("PATH").pipe(Config.withDefault("")); const runningInsideService = @@ -729,6 +732,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { platform, arch, releaseBaseUrl, + releaseRepository, validate: (runtime) => runner .run({ diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 82230858891c4..2c99f51bf4965 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -21,6 +21,7 @@ import { PinnedRuntimeInstallError, type PinnedRuntimeProgress, prunePinnedRuntimes, + PinnedRuntimeReleaseNotPublishedError, } from "./pinnedRuntime.ts"; import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts"; @@ -179,6 +180,48 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { }), ); + it.effect("names the release repository when the version was never published there", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-missing-" }); + const requests: string[] = []; + const notFound = HttpClient.make((request) => { + requests.push(request.url); + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("Not Found", { status: 404 })), + ); + }); + const install = (releaseBaseUrl?: string) => + ensurePinnedRuntimeInstalled({ + baseDir, + version, + fs, + path, + platform: "linux", + arch: "x64", + httpClient: notFound, + releaseBaseUrl, + releaseRepository: "acme/t3code", + runner: extractingRunner(fs, path), + validate: () => Effect.die("must not validate a missing release"), + }).pipe(Effect.flip); + + const error = yield* install(); + assert.instanceOf(error, PinnedRuntimeReleaseNotPublishedError); + assert.equal(error.message, `t3@${version} is not published in acme/t3code releases.`); + assert.deepEqual(requests, [ + `https://github.com/acme/t3code/releases/download/v${version}/SHA256SUMS`, + ]); + + const mirrored = yield* install("https://mirror.example/t3"); + assert.equal( + mirrored.message, + `t3@${version} is not published in https://mirror.example/t3.`, + ); + }), + ); + it.effect("validates a staging tree before atomically publishing it", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index e8db9892634d3..22a54c0d46ddf 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -9,7 +9,7 @@ import * as Schema from "effect/Schema"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import * as Semaphore from "effect/Semaphore"; -import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; import { CLI_RELEASE_CHECKSUMS_FILE, @@ -17,6 +17,7 @@ import { cliArchivePlatformKey, cliArchiveTarCommand, cliReleaseDownloadBaseUrl, + cliReleaseRepository, parseChecksums, } from "@t3tools/shared/cliRelease"; @@ -95,6 +96,19 @@ export class PinnedRuntimePreflightBlockedError extends Schema.TaggedError()( + "PinnedRuntimeReleaseNotPublishedError", + { + version: Schema.String, + /** The release repository, or the mirror when one is configured. */ + source: Schema.String, + }, +) { + override get message(): string { + return `t3@${this.version} is not published in ${this.source}.`; + } +} /** Tar writes the executable before native packages; only a validated install gets a sentinel. */ @@ -112,6 +126,7 @@ interface PinnedRuntimeInstallInput { readonly httpClient: HttpClient.HttpClient; readonly releaseBaseUrl?: string | undefined; readonly onProgress?: (progress: PinnedRuntimeProgress) => void; + readonly releaseRepository?: string | undefined; } const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* ( @@ -178,16 +193,38 @@ const installFromArchive = Effect.fn("cloud.pinned_runtime.install_archive")(fun }); } const httpClient = input.httpClient; - const baseUrl = cliReleaseDownloadBaseUrl(input.version, input.releaseBaseUrl); + const baseUrl = cliReleaseDownloadBaseUrl( + input.version, + input.releaseBaseUrl, + input.releaseRepository, + ); const fileName = cliArchiveFileName(input.version, platformKey); input.onProgress?.({ stage: "download", received: 0, total: undefined }); + // Every published release has a checksums file, so a 404 here means the + // version was never released where this machine downloads from. Say that + // plainly: it is the answer when a client asks for a version that exists + // only on another release channel or repository. const checksums = parseChecksums( new TextDecoder().decode( yield* fetchReleaseAsset( httpClient, `${baseUrl}/${CLI_RELEASE_CHECKSUMS_FILE}`, "downloading the t3 release checksums", + ).pipe( + Effect.catchIf( + (error) => + HttpClientError.isHttpClientError(error.cause) && error.cause.response?.status === 404, + () => + Effect.fail( + new PinnedRuntimeReleaseNotPublishedError({ + version: input.version, + source: input.releaseBaseUrl?.trim() + ? input.releaseBaseUrl.trim() + : `${cliReleaseRepository(input.releaseRepository)} releases`, + }), + ), + ), ), ), ); diff --git a/apps/server/src/cloud/releaseIndex.test.ts b/apps/server/src/cloud/releaseIndex.test.ts new file mode 100644 index 0000000000000..ad3b50b9e8816 --- /dev/null +++ b/apps/server/src/cloud/releaseIndex.test.ts @@ -0,0 +1,213 @@ +import { expect, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import * as TestClock from "effect/testing/TestClock"; +import { HttpClient, HttpClientResponse } from "effect/http"; + +import { + checkServerUpdate, + resolveNewestReleaseVersion, + watchAvailableServerUpdate, +} from "./releaseIndex.ts"; + +type Release = { tag_name: string; draft?: boolean }; + +// Serves GitHub's list-releases response per repository, one array per page +// (a bare array is page 1), and records every URL asked for. +const releaseIndexClient = ( + index: Record | ReadonlyArray>>, + requested: string[] = [], +) => + HttpClient.make((request) => + Effect.sync(() => { + requested.push(request.url); + const url = new URL(request.url); + const repository = /^\/repos\/([^/]+\/[^/]+)\/releases$/.exec(url.pathname)?.[1] ?? ""; + const entries = index[repository] ?? []; + const pages = (Array.isArray(entries[0]) ? entries : [entries]) as ReadonlyArray< + ReadonlyArray + >; + const releases = pages[Number(url.searchParams.get("page")) - 1] ?? []; + return HttpClientResponse.fromWeb(request, Response.json(releases)); + }), + ); + +const acmeReleases = { + "acme/t3code": [ + { tag_name: "v0.0.42-acme.1" }, + { tag_name: "v0.0.42-acme.3", draft: true }, + { tag_name: "v0.0.42-acme.2" }, + { tag_name: "v0.0.41-acme.7" }, + ], +}; + +const withEnv = (env: Record) => + Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))); + +it.effect("lists releases from the configured repository", () => + Effect.gen(function* () { + const requested: string[] = []; + const version = yield* resolveNewestReleaseVersion("stable", "acme/t3code").pipe( + Effect.provideService(HttpClient.HttpClient, releaseIndexClient(acmeReleases, requested)), + ); + expect(version).toBe("0.0.42-acme.2"); + expect(requested).toEqual([ + "https://api.github.com/repos/acme/t3code/releases?per_page=100&page=1", + ]); + + const error = yield* resolveNewestReleaseVersion("nightly", "acme/t3code").pipe( + Effect.provideService(HttpClient.HttpClient, releaseIndexClient(acmeReleases)), + Effect.flip, + ); + expect(error.message).toBe("No published nightly release was found in acme/t3code."); + }), +); + +it.effect.each([ + { environment: { GH_TOKEN: " gh-token ", GITHUB_TOKEN: "github-token" }, token: "gh-token" }, + { environment: { GH_TOKEN: " ", GITHUB_TOKEN: " github-token " }, token: "github-token" }, + { environment: { GITHUB_TOKEN: "github-token" }, token: "github-token" }, + { environment: { GH_TOKEN: " ", GITHUB_TOKEN: " " }, token: undefined }, + { environment: {}, token: undefined }, +])("selects release authentication from $environment", ({ environment, token }) => + Effect.gen(function* () { + const authorizations: Array = []; + const httpClient = HttpClient.make((request) => { + authorizations.push(request.headers.authorization); + return Effect.succeed( + HttpClientResponse.fromWeb(request, Response.json([{ tag_name: "v1.2.3" }])), + ); + }); + const version = yield* resolveNewestReleaseVersion("stable").pipe( + Effect.provideService(HostProcess.Environment, environment), + Effect.provideService(HttpClient.HttpClient, httpClient), + ); + expect(version).toBe("1.2.3"); + expect(authorizations).toEqual([token === undefined ? undefined : `Bearer ${token}`]); + }), +); + +it.effect("compares versions across every page, not just the first hit", () => + Effect.gen(function* () { + // A full first page (.1 plus 99 nightlies) and the higher .2 on page 2, + // published earlier: publish order is not version order. + const pageOne = [ + { tag_name: "v0.0.42-acme.1" }, + ...Array.from({ length: 99 }, (_, run) => ({ + tag_name: `v0.0.43-nightly.20260901.${run + 1}`, + })), + ]; + const requested: string[] = []; + const client = releaseIndexClient( + { "acme/t3code": [pageOne, [{ tag_name: "v0.0.42-acme.2" }]] }, + requested, + ); + expect( + yield* resolveNewestReleaseVersion("stable", "acme/t3code").pipe( + Effect.provideService(HttpClient.HttpClient, client), + ), + ).toBe("0.0.42-acme.2"); + // Page 2 is short, so it is the last page asked for. + expect(requested).toHaveLength(2); + expect( + yield* checkServerUpdate("0.0.42-acme.1", "acme/t3code").pipe( + Effect.provideService(HttpClient.HttpClient, client), + ), + ).toBe("0.0.42-acme.2"); + }), +); + +it.effect("skips a tag the launcher would refuse as not exact SemVer", () => + Effect.gen(function* () { + const client = releaseIndexClient({ + "acme/t3code": [{ tag_name: "v0.0.43-acme.01" }, { tag_name: "v0.0.42-acme.2" }], + }); + expect( + yield* checkServerUpdate("0.0.42-acme.1", "acme/t3code").pipe( + Effect.provideService(HttpClient.HttpClient, client), + ), + ).toBe("0.0.42-acme.2"); + }), +); + +it.effect("offers only a release newer than the running version", () => + Effect.gen(function* () { + const check = (currentVersion: string) => + checkServerUpdate(currentVersion, "acme/t3code").pipe( + Effect.provideService(HttpClient.HttpClient, releaseIndexClient(acmeReleases)), + ); + expect(yield* check("0.0.42-acme.1")).toBe("0.0.42-acme.2"); + expect(yield* check("0.0.41")).toBe("0.0.42-acme.2"); + expect(yield* check("0.0.42-acme.2")).toBeUndefined(); + // A stable release outranks its prereleases, so nothing here is newer. + expect(yield* check("0.0.42")).toBeUndefined(); + }), +); + +it.effect("a managed server advertises the newer release on its channel", () => + Effect.gen(function* () { + const available = yield* watchAvailableServerUpdate({ + managed: true, + currentVersion: "0.0.42-acme.1", + }).pipe( + Effect.provideService(HttpClient.HttpClient, releaseIndexClient(acmeReleases)), + withEnv({ T3CODE_RELEASE_REPOSITORY: "acme/t3code" }), + ); + const version = yield* SubscriptionRef.changes(available).pipe( + Stream.filter((value) => value !== undefined), + Stream.runHead, + ); + expect(version._tag === "Some" ? version.value : undefined).toBe("0.0.42-acme.2"); + }), +); + +// The check runs forked, so each case lets it run before counting what it asked for. The managed +// stable server shows that the count sees a check. +it.effect.each([ + { + name: "a managed stable server checks", + managed: true, + currentVersion: "0.0.1", + env: {}, + checks: 1, + }, + { name: "an unmanaged server never checks", managed: false, currentVersion: "0.0.1", env: {} }, + { + name: "a server with the check turned off never checks", + managed: true, + currentVersion: "0.0.1", + env: { T3CODE_UPDATE_CHECK_ENABLED: "false" }, + }, + { + name: "a preview build never checks", + managed: true, + currentVersion: "0.0.1-preview.20260911.4", + env: {}, + }, + { + name: "an unmanaged server with a malformed check flag never checks", + managed: false, + currentVersion: "0.0.1", + env: { T3CODE_UPDATE_CHECK_ENABLED: "maybe" }, + }, + { + name: "a preview build with a malformed check flag never checks", + managed: true, + currentVersion: "0.0.1-preview.20260911.4", + env: { T3CODE_UPDATE_CHECK_ENABLED: "maybe" }, + }, +])("$name", ({ managed, currentVersion, env, checks = 0 }) => + Effect.gen(function* () { + const requested: string[] = []; + const available = yield* watchAvailableServerUpdate({ managed, currentVersion }).pipe( + Effect.provideService(HttpClient.HttpClient, releaseIndexClient({}, requested)), + withEnv(env), + ); + yield* TestClock.adjust("1 second"); + expect(requested).toHaveLength(checks); + expect(yield* SubscriptionRef.get(available)).toBeUndefined(); + }), +); diff --git a/apps/server/src/cloud/releaseIndex.ts b/apps/server/src/cloud/releaseIndex.ts new file mode 100644 index 0000000000000..02a068773dc63 --- /dev/null +++ b/apps/server/src/cloud/releaseIndex.ts @@ -0,0 +1,163 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { + CLI_RELEASE_INDEX_PAGE_SIZE, + CLI_RELEASE_REPOSITORY_ENV, + cliReleaseChannelOf, + cliReleaseIndexPageUrl, + cliReleaseRepository, + newestCliReleaseVersion, + type CliReleaseChannel, +} from "@t3tools/shared/cliRelease"; +import * as Config from "effect/Config"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; + +import { compareExactServiceVersions, isExactServiceVersion } from "./serviceProtocol.ts"; + +export class ReleaseIndexError extends Schema.TaggedError()( + "ReleaseIndexError", + { reason: Schema.String }, +) { + override get message(): string { + return this.reason; + } +} + +const ReleaseIndex = Schema.Array( + Schema.Struct({ + tag_name: Schema.String, + draft: Schema.optional(Schema.Boolean), + }), +); +const decodeReleaseIndex = Schema.decodeUnknownEffect(Schema.fromJsonString(ReleaseIndex)); + +const RELEASE_INDEX_TIMEOUT = Duration.seconds(30); +// Enough to walk past a long run of nightlies without hammering the API; a +// bounded walk of at most this many requests per lookup. +const RELEASE_INDEX_MAX_PAGES = 10; + +/** + * The index is ordered by publish time, not version, so every page up to the bound is read and + * the highest exact-SemVer version wins; the launcher refuses anything else. GH_TOKEN, else + * GITHUB_TOKEN, authenticates each request so the anonymous rate limit doesn't fail the lookup. + */ +export const resolveNewestReleaseVersion = Effect.fn("cloud.release_index.resolve_newest")( + function* (channel: CliReleaseChannel, repository?: string | undefined) { + const httpClient = yield* HttpClient.HttpClient; + const environment = yield* HostProcess.Environment; + const githubToken = + environment.GH_TOKEN?.trim() || environment.GITHUB_TOKEN?.trim() || undefined; + const source = cliReleaseRepository(repository); + const installable: Array<(typeof ReleaseIndex.Type)[number]> = []; + for (let page = 1; page <= RELEASE_INDEX_MAX_PAGES; page += 1) { + const request = HttpClientRequest.get(cliReleaseIndexPageUrl(page, repository)).pipe( + HttpClientRequest.setHeader("Accept", "application/vnd.github+json"), + ); + const body = yield* httpClient + .execute( + githubToken === undefined + ? request + : HttpClientRequest.setHeader(request, "Authorization", `Bearer ${githubToken}`), + ) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.text), + Effect.mapError( + () => new ReleaseIndexError({ reason: `Could not list t3 releases in ${source}.` }), + ), + Effect.timeoutOrElse({ + duration: RELEASE_INDEX_TIMEOUT, + orElse: () => + Effect.fail( + new ReleaseIndexError({ reason: `Timed out listing t3 releases in ${source}.` }), + ), + }), + ); + const releases = yield* decodeReleaseIndex(body).pipe( + Effect.mapError( + () => + new ReleaseIndexError({ + reason: `The t3 release index of ${source} had an unexpected shape.`, + }), + ), + ); + installable.push( + ...releases.filter( + (release) => + release.tag_name.startsWith("v") && isExactServiceVersion(release.tag_name.slice(1)), + ), + ); + if (releases.length < CLI_RELEASE_INDEX_PAGE_SIZE) break; + } + const version = newestCliReleaseVersion(installable, channel); + if (version !== undefined) return version; + return yield* new ReleaseIndexError({ + reason: `No published ${channel} release was found in ${source}.`, + }); + }, +); + +/** Opts a managed server out of checking for updates, for hosts without GitHub access. */ +const SERVER_UPDATE_CHECK_ENABLED_ENV = "T3CODE_UPDATE_CHECK_ENABLED"; +const SERVER_UPDATE_CHECK_INTERVAL = Duration.hours(6); + +/** + * The newest release on `currentVersion`'s channel in the release repository + * when it is strictly newer than `currentVersion`, else undefined. Uses the + * same precedence the service launcher enforces, so an advertised version is + * one the launcher will accept. + */ +export const checkServerUpdate = Effect.fn("cloud.release_index.check_server_update")(function* ( + currentVersion: string, + repository?: string | undefined, +) { + const newest = yield* resolveNewestReleaseVersion( + cliReleaseChannelOf(currentVersion), + repository, + ); + return compareExactServiceVersions(newest, currentVersion) > 0 ? newest : undefined; +}); + +/** + * Checked at startup and every few hours; a failed check retries with backoff and keeps the + * previous answer. Only a boot-service server checks, since only it can install the answer, and + * never with the check turned off or on a preview build, which is never offered as an update. + */ +export const watchAvailableServerUpdate = Effect.fn("cloud.release_index.watch_server_update")( + function* (input: { readonly managed: boolean; readonly currentVersion: string }) { + const available = yield* SubscriptionRef.make(undefined); + // Eligibility first: a server that never checks must not fail on the flag. + if (!input.managed || cliReleaseChannelOf(input.currentVersion) === "preview") { + return available; + } + const enabled = yield* Config.Boolean(SERVER_UPDATE_CHECK_ENABLED_ENV).pipe( + Config.withDefault(true), + ); + if (!enabled) return available; + + const repository = Option.getOrUndefined( + yield* Config.String(CLI_RELEASE_REPOSITORY_ENV).pipe(Config.option), + ); + yield* checkServerUpdate(input.currentVersion, repository).pipe( + Effect.flatMap((version) => SubscriptionRef.set(available, version)), + Effect.tapError((error) => + Effect.logWarning("Could not check for a server update", { reason: error.reason }), + ), + Effect.retry({ + schedule: Schedule.exponential("1 minute").pipe( + Schedule.modifyDelay(({ duration }) => + Effect.succeed(Duration.min(duration, SERVER_UPDATE_CHECK_INTERVAL)), + ), + ), + }), + Effect.repeat(Schedule.spaced(SERVER_UPDATE_CHECK_INTERVAL)), + Effect.forkScoped, + ); + return available; + }, +); diff --git a/apps/server/src/cloud/selfUpdate.test.ts b/apps/server/src/cloud/selfUpdate.test.ts index 84877d41a70c9..069cff213c59d 100644 --- a/apps/server/src/cloud/selfUpdate.test.ts +++ b/apps/server/src/cloud/selfUpdate.test.ts @@ -32,6 +32,9 @@ const archiveBytes = new TextEncoder().encode("not really a tarball"); const releaseHttpClient = (order: string[], beforeDownload?: Effect.Effect) => HttpClient.make((request) => Effect.gen(function* () { + if (!request.url.includes("/v1.1.0/")) { + return HttpClientResponse.fromWeb(request, new Response("Not Found", { status: 404 })); + } if (request.url.endsWith("/SHA256SUMS")) { const digest = yield* Effect.promise(() => crypto.subtle.digest("SHA-256", archiveBytes)); const hex = Array.from(new Uint8Array(digest), (byte) => @@ -167,6 +170,17 @@ it.layer(NodeServices.layer)("server self update", (it) => { }), ); + it.effect("refuses a version the release repository never published", () => + Effect.gen(function* () { + const { selfUpdate, order } = yield* makeHarness(); + const error = yield* selfUpdate.update({ targetVersion: "1.2.0" }).pipe(Effect.flip); + expect(error.reason).toMatch(/^t3@1\.2\.0 is not published in \S+/); + expect(order).toEqual([]); + // The refusal does not leave the update slot taken. + expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).targetVersion).toBe("1.1.0"); + }), + ); + it.effect("allows only one update at a time", () => Effect.gen(function* () { const requested = yield* Deferred.make(); diff --git a/apps/server/src/cloud/selfUpdate.ts b/apps/server/src/cloud/selfUpdate.ts index ab6a69fc50a83..b648c17ffd1a9 100644 --- a/apps/server/src/cloud/selfUpdate.ts +++ b/apps/server/src/cloud/selfUpdate.ts @@ -20,7 +20,7 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { HttpClient } from "effect/http"; -import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; +import { CLI_RELEASE_BASE_URL_ENV, CLI_RELEASE_REPOSITORY_ENV } from "@t3tools/shared/cliRelease"; import packageJson from "../../package.json" with { type: "json" }; import * as ServerConfig from "../config.ts"; @@ -106,6 +106,9 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () { const releaseBaseUrl = Option.getOrUndefined( yield* Config.String(CLI_RELEASE_BASE_URL_ENV).pipe(Config.option), ); + const releaseRepository = Option.getOrUndefined( + yield* Config.String(CLI_RELEASE_REPOSITORY_ENV).pipe(Config.option), + ); const inFlight = yield* Ref.make(false); yield* pruneRuntimesOnStart({ baseDir: serverConfig.baseDir, managed: launcher.managed }).pipe( @@ -156,6 +159,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () { platform, arch, releaseBaseUrl, + releaseRepository, validate: (runtime) => runner .run({ @@ -229,7 +233,9 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () { Effect.mapError((error) => error._tag === "PinnedRuntimePreflightBlockedError" ? failWith(error.reason, error) - : failWith(`Could not prepare t3@${targetVersion}.`, error), + : error._tag === "PinnedRuntimeReleaseNotPublishedError" + ? failWith(error.message, error) + : failWith(`Could not prepare t3@${targetVersion}.`, error), ), ); diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index 7cebccb2a1f7c..95ab08c8d1f59 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -6,6 +6,8 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; +import { FetchHttpClient } from "effect/http"; import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -90,9 +92,12 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { yield* fs.symlink(entry, `${prefix}/bin/t3`); const config = yield* makeServerConfig(baseDir); yield* fs.makeDirectory(config.stateDir, { recursive: true }); + const fetched: string[] = []; for (const mode of ["web", "desktop"] as const) { const descriptor = yield* Effect.gen(function* () { const environment = yield* ServerEnvironment.ServerEnvironment; + // Lets a forked update check run before the layer closes. + yield* TestClock.adjust("1 second"); return yield* environment.getDescriptor; }).pipe( Effect.provide( @@ -105,6 +110,10 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { Effect.provideService(HostProcess.IsExecutable, false), Effect.provideService(HostProcess.Platform, "linux"), Effect.provideService(HostProcess.Environment, {}), + Effect.provideService(FetchHttpClient.Fetch, async (input) => { + fetched.push(String(input)); + return Response.json([]); + }), ); expect(descriptor.capabilities.serverInstallation).toEqual( mode === "web" ? { kind: "npm-global", prefix } : undefined, @@ -120,6 +129,8 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { threadAutoSettlementScope: true, }); } + // Only a boot-service server checks for updates. + expect(fetched).toEqual([]); }), ); it.effect.each([ diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 2b9b1f95b0719..31472b4a45471 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -12,11 +12,14 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import { FetchHttpClient } from "effect/http"; import packageJson from "../../package.json" with { type: "json" }; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import { resolveServerInstallation } from "../cli/invocation.ts"; import { readAgentActivityPublishingActive } from "../cloud/config.ts"; +import { watchAvailableServerUpdate } from "../cloud/releaseIndex.ts"; import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts"; import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; @@ -202,6 +205,11 @@ export const make = Effect.gen(function* () { const desktopAppUpdate = serverSelfUpdate === "desktop-managed" && serverConfig.desktopTelemetryControlFd !== undefined; + // Its own HTTP client, so commands that build this layer outside the server need none. + const availableServerUpdate = yield* watchAvailableServerUpdate({ + managed: serverSelfUpdate === "boot-service", + currentVersion: packageJson.version, + }).pipe(Effect.provide(FetchHttpClient.layer)); const descriptor: ExecutionEnvironmentDescriptor = { environmentId, @@ -275,11 +283,17 @@ export const make = Effect.gen(function* () { return ServerEnvironment.of({ getEnvironmentId: Effect.succeed(environmentId), - // Publishing opt-in and relay links change at runtime; read the capability per request. - getDescriptor: readAgentActivityPublishingActive(secrets).pipe( - Effect.map((agentActivityPublishing) => ({ + // Publishing opt-in, relay links and the update check change at runtime; read them per request. + getDescriptor: Effect.all([ + readAgentActivityPublishingActive(secrets), + SubscriptionRef.get(availableServerUpdate), + ]).pipe( + Effect.map(([agentActivityPublishing, availableVersion]) => ({ ...descriptor, capabilities: { ...descriptor.capabilities, agentActivityPublishing }, + ...(availableVersion === undefined + ? {} + : { availableServerUpdate: { version: availableVersion } }), })), ), }); diff --git a/apps/server/src/lazurio/launcherLink.test.ts b/apps/server/src/lazurio/launcherLink.test.ts new file mode 100644 index 0000000000000..b5e5458ab77d0 --- /dev/null +++ b/apps/server/src/lazurio/launcherLink.test.ts @@ -0,0 +1,153 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import { repointLauncherLink } from "./launcherLink.ts"; + +const PREVIOUS = "0.0.45-lazurio.9"; +const CURRENT = "0.1.0-lazurio.1"; +const committed = { + protocol: 3, + activeVersion: CURRENT, + update: { id: "update-1", fromVersion: PREVIOUS, targetVersion: CURRENT, status: "committed" }, +}; + +/** + * A T3 home with both runtimes installed and the install scripts' `t3` link + * still on the previous one, as an in-app Update leaves it. + */ +const makeHome = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-launcher-link-" }); + const baseDir = path.join(home, ".t3"); + const runtime = (version: string) => path.join(baseDir, "runtime", "versions", version, "t3"); + for (const version of [PREVIOUS, CURRENT]) { + yield* fs.makeDirectory(path.dirname(runtime(version)), { recursive: true }); + yield* fs.writeFileString(runtime(version), ""); + } + const link = path.join(home, ".local", "bin", "t3"); + yield* fs.makeDirectory(path.dirname(link), { recursive: true }); + yield* fs.symlink(runtime(PREVIOUS), link); + const writeState = (state: unknown) => + fs.writeFileString(path.join(baseDir, "runtime", "service-state.json"), JSON.stringify(state)); + return { home, baseDir, runtime, link, writeState }; +}); + +const onHost = + (home: string, environment: NodeJS.ProcessEnv = {}) => + (effect: Effect.Effect) => + effect.pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provideService(HostProcess.Environment, environment), + Effect.provideService(HostProcess.Platform, "linux"), + ); + +it.layer(NodeServices.layer)("repointLauncherLink", (it) => { + it.effect("points the t3 command at the runtime the launcher committed", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { home, baseDir, runtime, link, writeState } = yield* makeHome; + // A second launcher, found where a bare `t3` resolves on PATH. + const onPath = path.join(home, "bin", "t3"); + yield* fs.makeDirectory(path.dirname(onPath), { recursive: true }); + yield* fs.symlink(runtime(PREVIOUS), onPath); + yield* writeState(committed); + const repoint = repointLauncherLink({ managed: true, baseDir, version: CURRENT }).pipe( + onHost(home, { PATH: path.dirname(onPath) }), + ); + + assert.deepStrictEqual(yield* repoint, [onPath, link]); + assert.equal(yield* fs.readLink(onPath), runtime(CURRENT)); + assert.equal(yield* fs.readLink(link), runtime(CURRENT)); + // A restart on the same version leaves the links as they are. + assert.deepStrictEqual(yield* repoint, []); + }).pipe(Effect.scoped), + ); + + it.effect.each([ + { + name: "while the update trial can still roll back", + state: { + protocol: 3, + activeVersion: PREVIOUS, + update: { + id: "update-1", + fromVersion: PREVIOUS, + targetVersion: CURRENT, + dbPath: "/home/user/.t3/userdata/state.sqlite", + status: "pending", + }, + }, + }, + { + name: "when the launcher selected another version", + state: { protocol: 3, activeVersion: PREVIOUS }, + }, + { name: "without a launcher state", state: undefined }, + ])("leaves the t3 command alone $name", ({ state }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { home, baseDir, runtime, link, writeState } = yield* makeHome; + if (state !== undefined) yield* writeState(state); + + const repointed = yield* repointLauncherLink({ + managed: true, + baseDir, + version: CURRENT, + }).pipe(onHost(home)); + + assert.deepStrictEqual(repointed, []); + assert.equal(yield* fs.readLink(link), runtime(PREVIOUS)); + }).pipe(Effect.scoped), + ); + + it.effect("never touches a t3 that is not a link into this T3 home", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { home, baseDir, link, writeState } = yield* makeHome; + yield* writeState(committed); + // A `t3` from another install on PATH, and a plain copy where the install scripts link. + const elsewhere = path.join(home, "other", "lib", "t3", "bin.mjs"); + const foreign = path.join(home, "bin", "t3"); + yield* fs.makeDirectory(path.dirname(elsewhere), { recursive: true }); + yield* fs.writeFileString(elsewhere, ""); + yield* fs.makeDirectory(path.dirname(foreign), { recursive: true }); + yield* fs.symlink(elsewhere, foreign); + yield* fs.remove(link); + yield* fs.writeFileString(link, "copy"); + + const repointed = yield* repointLauncherLink({ + managed: true, + baseDir, + version: CURRENT, + }).pipe(onHost(home, { PATH: path.dirname(foreign) })); + + assert.deepStrictEqual(repointed, []); + assert.equal(yield* fs.readLink(foreign), elsewhere); + assert.equal(yield* fs.readFileString(link), "copy"); + }).pipe(Effect.scoped), + ); + + it.effect("does nothing for a server the service launcher does not run", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { home, baseDir, runtime, link, writeState } = yield* makeHome; + yield* writeState(committed); + + const repointed = yield* repointLauncherLink({ + managed: false, + baseDir, + version: CURRENT, + }).pipe(onHost(home)); + + assert.deepStrictEqual(repointed, []); + assert.equal(yield* fs.readLink(link), runtime(PREVIOUS)); + }).pipe(Effect.scoped), + ); +}); diff --git a/apps/server/src/lazurio/launcherLink.ts b/apps/server/src/lazurio/launcherLink.ts new file mode 100644 index 0000000000000..f9d818d0b2218 --- /dev/null +++ b/apps/server/src/lazurio/launcherLink.ts @@ -0,0 +1,78 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; + +import packageJson from "../../package.json" with { type: "json" }; +import { repointLauncher, resolveLauncherPath } from "../cli/update.ts"; +import { pinnedRuntimePaths } from "../cloud/pinnedRuntime.ts"; +import { parseServiceState, SERVICE_STATE_FILE } from "../cloud/serviceProtocol.ts"; + +/** + * An in-app Update moves only the launcher's `activeVersion`; an older `t3` would write pairings + * into a database the newer server does not read (Lazurio/t3code#30). A trial that can still roll + * back never moves the link, and only a link into this home's `runtime/versions` moves, never a + * foreign `t3`, by the same rules `t3 update` repoints by. + */ +export const repointLauncherLink = Effect.fn("lazurio.launcher_link.repoint")(function* (input: { + /** Whether the boot-service launcher runs this server. */ + readonly managed: boolean; + readonly baseDir: string; + readonly version?: string; +}) { + const version = input.version ?? packageJson.version; + const platform = yield* HostProcess.Platform; + // Windows has no boot service, and its `t3.cmd` shim is rewritten only by `t3 update`. + if (!input.managed || platform === "win32") return []; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const state = yield* fs + .readFileString(path.join(input.baseDir, "runtime", SERVICE_STATE_FILE)) + .pipe( + Effect.map(parseServiceState), + Effect.orElseSucceed(() => undefined), + ); + if (state?.activeVersion !== version || state.update?.status === "pending") return []; + + const runtime = pinnedRuntimePaths(path, input.baseDir, version, platform); + const environment = yield* HostProcess.Environment; + // Where a bare `t3` resolves, and where the install scripts put the link. + const links = new Set(); + const onPath = yield* resolveLauncherPath.pipe( + Effect.provideService(HostProcess.InvokedAs, "t3"), + ); + if (onPath !== undefined) links.add(onPath); + const binDir = + environment["T3CODE_INSTALL_BIN_DIR"]?.trim() || + path.join(yield* HostProcess.HomeDirectory, ".local", "bin"); + links.add(path.join(binDir, "t3")); + + const repointed: Array = []; + for (const link of links) { + const target = yield* fs.readLink(link).pipe(Effect.option); + if ( + Option.isSome(target) && + path.resolve(path.dirname(link), target.value) === runtime.entryPath + ) { + continue; + } + const moved = yield* repointLauncher({ + launchedAs: link, + versionsDir: path.dirname(runtime.versionDir), + targetEntryPath: runtime.entryPath, + }).pipe( + Effect.catchTags({ + CliUpdateError: (error) => + Effect.logWarning("Could not point the t3 command at this server's runtime", { + reason: error.reason, + }).pipe(Effect.as(Option.none())), + }), + ); + if (Option.isSome(moved)) { + yield* Effect.logInfo("Pointed the t3 command at this server's runtime", { link, version }); + repointed.push(moved.value); + } + } + return repointed; +}); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 741fc73103b7d..0a04b5e4b21b3 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -167,6 +167,7 @@ import * as CloudCliState from "./cloud/CliState.ts"; import * as ServerSelfUpdate from "./cloud/selfUpdate.ts"; import * as DesktopAppUpdate from "./desktopUpdate/DesktopAppUpdate.ts"; import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; +import { repointLauncherLink } from "./lazurio/launcherLink.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as HostResources from "./resourceTelemetry/HostResources.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; @@ -803,6 +804,11 @@ const layerMakeServer = Layer.unwrap( Effect.gen(function* () { yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie); yield* awaitActivation; + // Lazurio/t3code#30: activation follows the launcher's commit; the user's `t3` follows it too. + yield* repointLauncherLink({ + managed: (yield* ServiceLauncherClient.ServiceLauncherClient).managed, + baseDir: config.baseDir, + }); const server = yield* HttpServer.HttpServer; const address = server.address; if (typeof address === "string" || !("port" in address)) { diff --git a/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx b/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx index 60f93aa54b965..60e4a0956d8d3 100644 --- a/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx +++ b/apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx @@ -62,7 +62,7 @@ export function useAutoBalanceUpdateBanner( selfUpdate, installation: environment.serverConfig?.environment.capabilities.serverInstallation, desktopAppUpdate, - targetVersion: state.status === "idle" ? mismatch!.clientVersion : state.targetVersion, + targetVersion: state.status === "idle" ? mismatch!.targetVersion : state.targetVersion, connected: environment.connection.phase === "connected", remoteUpdate: selfUpdate !== null && (selfUpdate !== "desktop-managed" || desktopAppUpdate), state, diff --git a/apps/web/src/components/chat/useSystemComposerBanners.tsx b/apps/web/src/components/chat/useSystemComposerBanners.tsx index 28b0899fc80b6..840fced834611 100644 --- a/apps/web/src/components/chat/useSystemComposerBanners.tsx +++ b/apps/web/src/components/chat/useSystemComposerBanners.tsx @@ -239,7 +239,7 @@ export function useSystemComposerBanners(input: SystemComposerBannersInput) { selfUpdate={versionMismatchSelfUpdate} installation={versionMismatchInstallation} desktopAppUpdate={versionMismatchDesktopAppUpdate} - targetVersion={versionMismatch.clientVersion} + targetVersion={versionMismatch.targetVersion} label="Retry" variant="ghost" /> diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 502dc8c6a6e1d..93a6a91cedbd0 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -205,7 +205,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" | selfUpdate, installation: environment.serverConfig?.environment.capabilities.serverInstallation, desktopAppUpdate, - targetVersion: mismatch.clientVersion, + targetVersion: mismatch.targetVersion, }, ]; }, @@ -1097,11 +1097,11 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" | primaryServerConfig?.environment.capabilities.serverInstallation } desktopAppUpdate={supportsDesktopAppUpdate(primaryServerConfig)} - targetVersion={primaryVersionMismatch.clientVersion} + targetVersion={primaryVersionMismatch.targetVersion} label={ primaryServerUpdateState.status === "failed" ? "Retry update" - : `Update to ${primaryVersionMismatch.clientVersion}` + : `Update to ${primaryVersionMismatch.targetVersion}` } /> ) : primaryServerUpdateState.status === "idle" && primaryServerConfig ? ( diff --git a/apps/web/src/components/settings/SavedEnvironmentRows.tsx b/apps/web/src/components/settings/SavedEnvironmentRows.tsx index fee5b9857a6ae..6dd04ef04ff84 100644 --- a/apps/web/src/components/settings/SavedEnvironmentRows.tsx +++ b/apps/web/src/components/settings/SavedEnvironmentRows.tsx @@ -234,7 +234,7 @@ export function SavedBackendListRow({ : "Switched off" }${ versionMismatch - ? `\nUpdate available: ${versionMismatch.serverVersion} → ${versionMismatch.clientVersion}` + ? `\nUpdate available: ${versionMismatch.serverVersion} → ${versionMismatch.targetVersion}` : "" }`; @@ -375,7 +375,7 @@ export function SavedBackendListRow({ selfUpdate={resolveServerSelfUpdateCapability(environment.serverConfig)} installation={environment.serverConfig?.environment.capabilities.serverInstallation} desktopAppUpdate={supportsDesktopAppUpdate(environment.serverConfig)} - targetVersion={versionMismatch.clientVersion} + targetVersion={versionMismatch.targetVersion} label={serverUpdateState.status === "failed" ? "Retry update" : "Update"} appearance="icon" /> diff --git a/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx b/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx index 8cd5c5ca777d5..b0946bba89473 100644 --- a/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx +++ b/apps/web/src/components/sidebar/UpdateEverythingDialog.tsx @@ -150,6 +150,11 @@ function UpdateEverythingDialogContent({ {row.app !== null ? APP_LABELS[row.app] : null} + {row.targetVersion !== null ? ( + + {row.targetVersion} + + ) : null} {row.app === null && row.skipped !== null ? ( Skipped ) : null} diff --git a/apps/web/src/components/sidebar/updateEverything.logic.test.ts b/apps/web/src/components/sidebar/updateEverything.logic.test.ts index 3739308f7b1c7..d0d4884cce0b1 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.test.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.test.ts @@ -87,12 +87,21 @@ describe("collectRestartingMachines", () => { id: string, overrides: Partial = {}, enabled = false, + capability = true, + serverVersion = "0.1.4", ) => { - const base = machine(id, "0.0.40", "boot-service", overrides); + const base = machine(id, serverVersion, "boot-service", overrides); + const environment = base.serverConfig!.environment; return { ...base, serverConfig: { - environment: base.serverConfig!.environment, + environment: { + ...environment, + capabilities: { + ...environment.capabilities, + ...(capability ? { threadRestartContinuation: true } : {}), + }, + }, settings: { continueThreadsAfterServerUpdate: enabled }, }, }; @@ -102,21 +111,27 @@ describe("collectRestartingMachines", () => { withContinuation("alvin", {}, true), withContinuation("opted-out", {}, false), machine("old", "0.0.40", "boot-service"), + withContinuation("no-capability", {}, true, false), + withContinuation("no-shutdown-continuation", {}, true, true, "0.0.45-lazurio.9"), withContinuation("providers-only"), ]; - const servers = ["alvin", "opted-out", "old"].map((id) => ({ - environmentId: EnvironmentId.make(id), - })); + const servers = ["alvin", "opted-out", "old", "no-capability", "no-shutdown-continuation"].map( + (id) => ({ + environmentId: EnvironmentId.make(id), + }), + ); expect(collectRestartingMachines(machines, servers, true)).toEqual([ { environmentId: "this-app", continuesThreads: true }, { environmentId: "alvin", continuesThreads: true }, { environmentId: "opted-out", continuesThreads: false }, { environmentId: "old", continuesThreads: false }, + { environmentId: "no-capability", continuesThreads: false }, + { environmentId: "no-shutdown-continuation", continuesThreads: false }, ]); expect( collectRestartingMachines(machines, servers, false).map((entry) => entry.environmentId), - ).toEqual(["alvin", "opted-out", "old"]); + ).toEqual(["alvin", "opted-out", "old", "no-capability", "no-shutdown-continuation"]); }); }); @@ -176,4 +191,49 @@ describe("describeUpdateEverything", () => { ["TheoRoom", null, "not connected", []], ]); }); + + it("names each server's own target when the servers go to different releases", () => { + const id = EnvironmentId.make; + const server = (environmentId: string, targetVersion: string) => ({ + environmentId: id(environmentId), + serverLabel: environmentId, + selfUpdate: "boot-service" as const, + targetVersion, + }); + const plan = { + localVersion: null, + localMachines: [], + providerMachines: [], + skipped: [], + }; + + const mixed = describeUpdateEverything({ + ...plan, + servers: [server("stable", "0.1.4-lazurio.1"), server("canary", "0.1.4-preview.20261029.1")], + }); + expect(mixed.version).toBeNull(); + expect(mixed.rows.map(({ label, targetVersion }) => [label, targetVersion])).toEqual([ + ["stable", "0.1.4-lazurio.1"], + ["canary", "0.1.4-preview.20261029.1"], + ]); + + const shared = describeUpdateEverything({ + ...plan, + servers: [server("one", "0.1.4-lazurio.1"), server("two", "0.1.4-lazurio.1")], + }); + expect(shared.version).toBe("0.1.4-lazurio.1"); + expect(shared.rows.map((row) => row.targetVersion)).toEqual([null, null]); + + const local = describeUpdateEverything({ + ...plan, + localVersion: "0.1.4", + servers: [server("advertised", "0.1.4-lazurio.1"), server("same", "0.1.4")], + }); + expect(local.version).toBe("0.1.4"); + expect(local.rows.map(({ label, targetVersion }) => [label, targetVersion])).toEqual([ + ["This app", null], + ["advertised", "0.1.4-lazurio.1"], + ["same", null], + ]); + }); }); diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts index 469e5a0faf674..486d7743409cd 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.ts @@ -1,8 +1,10 @@ import type { ServerUpdateState } from "@t3tools/client-runtime/state/server"; import type { EnvironmentId, ServerConfig } from "@t3tools/contracts"; import { cliReleaseChannelOf } from "@t3tools/shared/cliRelease"; +import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver"; import { + advertisedServerUpdateVersion, resolveServerSelfUpdateCapability, resolveVersionMismatch, supportsDesktopAppUpdate, @@ -22,6 +24,17 @@ export interface UpdateEverythingMachine { readonly updateState: ServerUpdateState; } +// Lazurio overlay: the update request no longer asks a server to continue its threads; a server +// prepares the continuation on a graceful stop itself, which releases before 0.0.46 do not. +const SHUTDOWN_CONTINUATION_SINCE = "0.0.46-0"; + +function preparesContinuationOnShutdown(serverVersion: string): boolean { + return ( + parseSemver(serverVersion) !== null && + compareSemverVersions(serverVersion, SHUTDOWN_CONTINUATION_SINCE) >= 0 + ); +} + export interface RestartingMachine { readonly environmentId: EnvironmentId; readonly continuesThreads: boolean; @@ -45,7 +58,11 @@ export function collectRestartingMachines( return [ { environmentId: machine.environmentId, - continuesThreads: config.settings.continueThreadsAfterServerUpdate === true, + // Lazurio overlay: only a server with the capability continues threads after a restart. + continuesThreads: + config.environment.capabilities.threadRestartContinuation === true && + preparesContinuationOnShutdown(config.environment.serverVersion) && + config.settings.continueThreadsAfterServerUpdate === true, }, ]; }); @@ -68,8 +85,12 @@ export function collectServerUpdateTargets( for (const machine of machines) { const config = machine.serverConfig; if (machine.hostedByThisApp) continue; + // Lazurio overlay: a server advertises only a strictly newer release from its own channel. + const advertised = advertisedServerUpdateVersion(config); + const machineTarget = advertised ?? targetVersion; if ( config !== null && + advertised === undefined && resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null ) { continue; @@ -101,7 +122,7 @@ export function collectServerUpdateTargets( const serverVersion = config.environment.serverVersion; if ( selfUpdate !== "desktop-managed" && - cliReleaseChannelOf(serverVersion) !== cliReleaseChannelOf(targetVersion) + cliReleaseChannelOf(serverVersion) !== cliReleaseChannelOf(machineTarget) ) { skip(`on the ${cliReleaseChannelOf(serverVersion)} channel`); continue; @@ -112,7 +133,7 @@ export function collectServerUpdateTargets( selfUpdate, installation: config.environment.capabilities.serverInstallation, desktopAppUpdate, - targetVersion, + targetVersion: machineTarget, }); } return { targets, skipped }; @@ -373,6 +394,8 @@ export interface UpdateEverythingRow { readonly app: "this-app" | "server" | "desktop-app" | null; readonly skipped: string | null; readonly providers: ReadonlyArray; + /** Lazurio overlay: the server's own target where it is not the dialog's one version. */ + readonly targetVersion: string | null; } function countLabel(count: number, noun: string): string | null { @@ -415,6 +438,7 @@ export function describeUpdateEverything(plan: UpdateEverythingPlan): { app: null, skipped: null, providers: [], + targetVersion: null, }; rows.set(environmentId, { ...row, ...change }); }; @@ -424,9 +448,21 @@ export function describeUpdateEverything(plan: UpdateEverythingPlan): { update(machine.environmentId, machine.label, { app: "this-app" }); } } + // Lazurio overlay: servers can advertise different releases, so one shared version is only the + // header's when every server goes to it; otherwise each server's row names its own. + const serverTargets = new Set( + plan.servers + .filter((server) => server.selfUpdate !== "desktop-managed") + .map((server) => server.targetVersion), + ); + const version = + plan.localVersion ?? (serverTargets.size === 1 ? ([...serverTargets][0] ?? null) : null); for (const server of plan.servers) { + const app = server.selfUpdate === "desktop-managed" ? "desktop-app" : "server"; update(server.environmentId, server.serverLabel, { - app: server.selfUpdate === "desktop-managed" ? "desktop-app" : "server", + app, + targetVersion: + app === "server" && server.targetVersion !== version ? server.targetVersion : null, }); } for (const machine of plan.providerMachines) { @@ -438,10 +474,7 @@ export function describeUpdateEverything(plan: UpdateEverythingPlan): { return { summary, - version: - plan.localVersion ?? - plan.servers.find((server) => server.selfUpdate !== "desktop-managed")?.targetVersion ?? - null, + version, providerCount, rows: Array.from(rows.values()), }; diff --git a/apps/web/src/components/sidebar/useUpdateEverything.ts b/apps/web/src/components/sidebar/useUpdateEverything.ts index af38bbf5d4bc4..9c819e3f10ed5 100644 --- a/apps/web/src/components/sidebar/useUpdateEverything.ts +++ b/apps/web/src/components/sidebar/useUpdateEverything.ts @@ -9,9 +9,15 @@ import { useNpmReleasePublished } from "~/state/npmRelease"; import { environmentIdsKey } from "~/state/environmentAtomList"; import { environmentUpdateStatesAtom } from "~/state/server"; import { environmentSessionStatesAtom } from "~/state/session"; +import { advertisedServerUpdateVersion } from "~/versionSkew"; import { getProviderUpdateRunOutcome } from "../ProviderUpdateLaunchNotification.logic"; import { useProviderUpdates } from "../ProviderUpdatesAction"; -import { canUpdateServer, type ServerUpdateOutcome, useServerUpdate } from "../ServerUpdateAction"; +import { + canUpdateServer, + type ServerUpdateOutcome, + type ServerUpdateTarget, + useServerUpdate, +} from "../ServerUpdateAction"; import { closeFinishedUpdateRun, collectRestartingMachines, @@ -59,11 +65,17 @@ export function useUpdateEverything(localUpdateVersion: string | null) { targetVersion, ); // Desktop-managed servers use their app feed; only npm installs need to wait for publication. - const needsNpm = behindServers.some((server) => server.selfUpdate !== "desktop-managed"); + // Lazurio overlay: a release a server advertised is on its own release channel, not on npm. + const waitsForNpm = (server: ServerUpdateTarget) => + server.selfUpdate !== "desktop-managed" && + advertisedServerUpdateVersion( + machines.find((machine) => machine.environmentId === server.environmentId)?.serverConfig, + ) === undefined; + const needsNpm = behindServers.some(waitsForNpm); const published = useNpmReleasePublished(needsNpm ? targetVersion : null); const servers = published ? behindServers - : behindServers.filter((server) => server.selfUpdate === "desktop-managed"); + : behindServers.filter((server) => !waitsForNpm(server)); const skipped: ReadonlyArray = [ ...unreachable, ...behindServers diff --git a/apps/web/src/lazurio/serverUpdateOffer.test.ts b/apps/web/src/lazurio/serverUpdateOffer.test.ts new file mode 100644 index 0000000000000..235b12b89a45d --- /dev/null +++ b/apps/web/src/lazurio/serverUpdateOffer.test.ts @@ -0,0 +1,76 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + collectServerUpdateTargets, + type UpdateEverythingMachine, +} from "../components/sidebar/updateEverything.logic"; + +// The sidebar's update button offers the release a boot-service server advertised from its own +// channel, even to the web app that same server hosts, where there is no version skew. +function machine( + id: string, + serverVersion: string, + options: { + readonly selfUpdate: "boot-service" | "desktop-managed"; + readonly available?: string; + }, +): UpdateEverythingMachine { + return { + environmentId: EnvironmentId.make(id), + label: id, + serverConfig: { + environment: { + environmentId: EnvironmentId.make(id), + label: id, + platform: { os: "linux", arch: "x64" }, + serverVersion, + capabilities: { + repositoryIdentity: true, + serverSelfUpdate: options.selfUpdate, + ...(options.selfUpdate === "desktop-managed" ? { desktopAppUpdate: true } : {}), + }, + ...(options.available ? { availableServerUpdate: { version: options.available } } : {}), + }, + settings: { continueThreadsAfterServerUpdate: false }, + }, + connected: true, + hostedByThisApp: false, + canMaintain: true, + updateState: { status: "idle" }, + }; +} + +describe("the sidebar update button and a server-advertised release", () => { + it("updates a server to the release it advertised, not to this app's version", () => { + const { targets, skipped } = collectServerUpdateTargets( + [ + machine("hosting", "0.1.3-lazurio.0", { + selfUpdate: "boot-service", + available: "0.1.3-lazurio.1", + }), + machine("current", "0.1.3-lazurio.0", { selfUpdate: "boot-service" }), + ], + "0.1.3-lazurio.0", + ); + + expect(targets.map((target) => [target.serverLabel, target.targetVersion])).toEqual([ + ["hosting", "0.1.3-lazurio.1"], + ]); + expect(skipped).toEqual([]); + }); + + it("ignores an advertisement from a server the boot service does not manage", () => { + const { targets } = collectServerUpdateTargets( + [ + machine("desktop", "0.1.3-lazurio.0", { + selfUpdate: "desktop-managed", + available: "0.1.3-lazurio.1", + }), + ], + "0.1.3-lazurio.0", + ); + + expect(targets).toEqual([]); + }); +}); diff --git a/apps/web/src/versionSkew.test.ts b/apps/web/src/versionSkew.test.ts index 627b974177392..41e5f71ca08a5 100644 --- a/apps/web/src/versionSkew.test.ts +++ b/apps/web/src/versionSkew.test.ts @@ -13,6 +13,7 @@ import { isServerUpdateFailureDismissed, isVersionMismatchDismissed, manualServerUpdateCommand, + resolveServerConfigVersionMismatch, resolveVersionMismatch, } from "./versionSkew"; @@ -56,6 +57,7 @@ describe("versionSkew", () => { expect(resolveVersionMismatch("0.0.33")).toEqual({ clientVersion: "0.0.34", serverVersion: "0.0.33", + targetVersion: "0.0.34", hint: MISMATCH_HINT, }); }); @@ -80,6 +82,7 @@ describe("versionSkew", () => { expect(resolveVersionMismatch(serverVersion)).toEqual({ clientVersion: "0.0.34-nightly.20260824.1125", serverVersion, + targetVersion: "0.0.34-nightly.20260824.1125", hint: MISMATCH_HINT, }); }, @@ -96,6 +99,7 @@ describe("versionSkew", () => { expect(resolveVersionMismatch("0.0.34")).toEqual({ clientVersion: "0.0.35-nightly.20260818.1124", serverVersion: "0.0.34", + targetVersion: "0.0.35-nightly.20260818.1124", hint: MISMATCH_HINT, }); }); @@ -104,6 +108,7 @@ describe("versionSkew", () => { expect(resolveVersionMismatch("dev")).toEqual({ clientVersion: "0.0.34", serverVersion: "dev", + targetVersion: "0.0.34", hint: MISMATCH_HINT, }); @@ -112,10 +117,10 @@ describe("versionSkew", () => { expect(resolveVersionMismatch("0.0.34")).toMatchObject({ serverVersion: "0.0.34" }); }); - it("keys dismissals by environment, client version, and server version", () => { + it("keys dismissals by environment, target version, and server version", () => { const environmentId = EnvironmentId.make("environment-dismissal"); const key = buildVersionMismatchDismissalKey(environmentId, { - clientVersion: APP_VERSION, + targetVersion: APP_VERSION, serverVersion: "9.9.9", }); @@ -127,10 +132,78 @@ describe("versionSkew", () => { expect( isVersionMismatchDismissed( buildVersionMismatchDismissalKey(environmentId, { - clientVersion: APP_VERSION, + targetVersion: APP_VERSION, serverVersion: "9.9.10", }), ), ).toBe(false); }); + + describe("server-advertised updates", () => { + const serverConfig = ( + serverVersion: string, + options: { + readonly serverSelfUpdate?: "boot-service" | "desktop-managed"; + readonly available?: string; + }, + ) => ({ + environment: { + environmentId: EnvironmentId.make("environment-vm"), + label: "VM", + platform: { os: "linux", arch: "x64" } as const, + serverVersion, + capabilities: { + repositoryIdentity: true, + ...(options.serverSelfUpdate ? { serverSelfUpdate: options.serverSelfUpdate } : {}), + }, + ...(options.available ? { availableServerUpdate: { version: options.available } } : {}), + }, + }); + + it("offers the advertised release to a browser served by the same server", () => { + branding.APP_VERSION = "0.0.42-acme.1"; + expect( + resolveServerConfigVersionMismatch( + serverConfig("0.0.42-acme.1", { + serverSelfUpdate: "boot-service", + available: "0.0.42-acme.2", + }), + ), + ).toMatchObject({ serverVersion: "0.0.42-acme.1", targetVersion: "0.0.42-acme.2" }); + }); + + it("prefers the advertised release over a newer client from another train", () => { + branding.APP_VERSION = "0.0.45"; + expect( + resolveServerConfigVersionMismatch( + serverConfig("0.0.42-acme.1", { + serverSelfUpdate: "boot-service", + available: "0.0.43-acme.1", + }), + )?.targetVersion, + ).toBe("0.0.43-acme.1"); + }); + + it("falls back to client skew without an advertised release", () => { + branding.APP_VERSION = "0.0.45"; + expect( + resolveServerConfigVersionMismatch( + serverConfig("0.0.42", { serverSelfUpdate: "boot-service" }), + )?.targetVersion, + ).toBe("0.0.45"); + expect( + resolveServerConfigVersionMismatch( + serverConfig("0.0.45", { serverSelfUpdate: "boot-service" }), + ), + ).toBeNull(); + }); + + it("ignores an advertisement from a server the boot service does not manage", () => { + expect( + resolveServerConfigVersionMismatch( + serverConfig("0.0.34", { serverSelfUpdate: "desktop-managed", available: "0.0.40" }), + ), + ).toBeNull(); + }); + }); }); diff --git a/apps/web/src/versionSkew.ts b/apps/web/src/versionSkew.ts index 321e712f8a124..332ef26ec5ff4 100644 --- a/apps/web/src/versionSkew.ts +++ b/apps/web/src/versionSkew.ts @@ -14,6 +14,8 @@ import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorag export interface VersionMismatch { readonly clientVersion: string; readonly serverVersion: string; + /** The version an update installs: this client's, or the release the server advertised. */ + readonly targetVersion: string; readonly hint: string; } @@ -73,14 +75,40 @@ export function resolveVersionMismatch( return { clientVersion: normalizedClientVersion, serverVersion: normalizedServerVersion, + targetVersion: normalizedClientVersion, hint: "Version mismatch. Try syncing the client and server to the same T3 Code version.", }; } +/** Only a server the boot service manages checks its own release channel for a newer release. */ +export function advertisedServerUpdateVersion( + serverConfig: Pick | null | undefined, +): string | undefined { + const environment = serverConfig?.environment; + return environment?.capabilities.serverSelfUpdate === "boot-service" + ? environment.availableServerUpdate?.version + : undefined; +} + +/** + * A boot-service server advertises a newer release from its own channel. That target wins over + * this client's version, which may not exist there, and it reaches a browser that server serves, + * which never sees skew. Otherwise the client-ahead skew applies. + */ export function resolveServerConfigVersionMismatch( serverConfig: Pick | null | undefined, ): VersionMismatch | null { - return resolveVersionMismatch(serverConfig?.environment.serverVersion); + const environment = serverConfig?.environment; + const advertised = advertisedServerUpdateVersion(serverConfig); + if (environment && advertised) { + return { + clientVersion: normalizeVersion(APP_VERSION) ?? APP_VERSION, + serverVersion: environment.serverVersion, + targetVersion: advertised, + hint: "A newer T3 Code release is available for this server.", + }; + } + return resolveVersionMismatch(environment?.serverVersion); } export function resolveServerSelfUpdateCapability( @@ -108,11 +136,12 @@ export function manualServerUpdateCommand( return `${runner} t3@${targetVersion}`; } +/** Keyed by the offered target, so dismissing one release does not hide the next. */ export function buildVersionMismatchDismissalKey( environmentId: EnvironmentId, - mismatch: Pick, + mismatch: Pick, ): string { - return `${environmentId}:${mismatch.clientVersion}:${mismatch.serverVersion}`; + return `${environmentId}:${mismatch.targetVersion}:${mismatch.serverVersion}`; } function readVersionMismatchDismissals(): VersionMismatchDismissals { diff --git a/docs/user/background-service.md b/docs/user/background-service.md index be4ad66ff3ab4..9ec7b13fc99be 100644 --- a/docs/user/background-service.md +++ b/docs/user/background-service.md @@ -35,6 +35,11 @@ maintainers' test train: its builds can be broken and are never offered as updates, so the installer and `t3 update` ask for confirmation before installing one. +Set `T3CODE_RELEASE_REPOSITORY=owner/name` to install and update from a fork's +releases, or `T3CODE_RELEASE_BASE_URL` to download from a mirror. The install +script, `t3 update`, and the service honor both when they are set in their +environment. + `t3 uninstall` removes the background service, the `t3` launcher, and the downloaded versions after showing you the list and asking once. Your projects, threads, and settings under `~/.t3/userdata` are kept, along with `service.env` diff --git a/docs/user/updating.md b/docs/user/updating.md index ad5d93b5759a2..fb98a8aa92e7a 100644 --- a/docs/user/updating.md +++ b/docs/user/updating.md @@ -4,6 +4,14 @@ The app you use and the server running your agents can be on different machines. When a server is behind your web or desktop app, the update button at the bottom of the sidebar and **Settings → Environments** offer to update it. +A server running as a [background service](./background-service.md) also checks +its own release train every few hours; a preview build never checks. When a +newer release is out, the update button at the bottom of the sidebar and +**Settings → Environments** offer it, also in the web app that server hosts, and +update the server to that release. The official desktop and mobile apps do not +offer it. Set `T3CODE_UPDATE_CHECK_ENABLED=false` in the service's environment to +turn the check off. + ## Update everything at once The update button at the bottom of the sidebar updates every connected machine diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index a65a91e0d3921..36343f9dfeeaf 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -160,6 +160,10 @@ export const ExecutionEnvironmentDescriptor = Schema.Struct({ serverVersion: TrimmedNonEmptyString, orchestrationProtocolVersion: Schema.optionalKey(Schema.Int), capabilities: ExecutionEnvironmentCapabilities, + /** A newer release the server found on its own release channel, which + server.updateServer can install. Only boot-service managed servers + check; absent when there is nothing newer and on older servers. */ + availableServerUpdate: Schema.optionalKey(Schema.Struct({ version: TrimmedNonEmptyString })), }); export type ExecutionEnvironmentDescriptor = typeof ExecutionEnvironmentDescriptor.Type; diff --git a/packages/shared/src/cliRelease.test.ts b/packages/shared/src/cliRelease.test.ts index b0aa61765e45a..e5c710d887389 100644 --- a/packages/shared/src/cliRelease.test.ts +++ b/packages/shared/src/cliRelease.test.ts @@ -1,8 +1,32 @@ import { describe, expect, it } from "vite-plus/test"; -import { cliArchiveTarCommand, newestCliReleaseVersion, parseChecksums } from "./cliRelease.ts"; +import { + cliArchiveTarCommand, + cliReleaseDownloadBaseUrl, + cliReleaseIndexPageUrl, + cliReleaseRepository, + newestCliReleaseVersion, + parseChecksums, +} from "./cliRelease.ts"; describe("cliRelease", () => { + it("follows a configured release repository unless a mirror is set", () => { + // The Lazurio distribution's own releases unless the variable names another repository. + expect(cliReleaseRepository(undefined)).toBe("Lazurio/t3code"); + expect(cliReleaseRepository(" ")).toBe("Lazurio/t3code"); + expect(cliReleaseRepository(" acme/t3code ")).toBe("acme/t3code"); + expect(cliReleaseRepository("pingdotgg/t3code")).toBe("pingdotgg/t3code"); + expect(cliReleaseDownloadBaseUrl("1.2.3-acme.1", undefined, "acme/t3code")).toBe( + "https://github.com/acme/t3code/releases/download/v1.2.3-acme.1", + ); + expect(cliReleaseDownloadBaseUrl("1.2.3", "https://mirror.example/t3", "acme/t3code")).toBe( + "https://mirror.example/t3/v1.2.3", + ); + expect(cliReleaseIndexPageUrl(2, "acme/t3code")).toBe( + "https://api.github.com/repos/acme/t3code/releases?per_page=100&page=2", + ); + }); + it("parses sha256sum output including binary-mode markers", () => { const checksums = parseChecksums( [ @@ -39,4 +63,22 @@ describe("cliRelease", () => { expect(newestCliReleaseVersion(releases, "stable")).toBe("1.2.3"); expect(newestCliReleaseVersion([{ tag_name: "v1.2.3" }], "preview")).toBeUndefined(); }); + + it("picks by semver precedence, not listing order", () => { + // A fork's own prerelease train rides the stable channel. + const releases = [ + { tag_name: "v1.2.2-acme.3" }, + { tag_name: "v1.2.3-acme.10", draft: true }, + { tag_name: "v1.2.3-acme.2" }, + { tag_name: "v1.2.3-acme.9" }, + { tag_name: "v1.2.3-acme.1" }, + ]; + expect(newestCliReleaseVersion(releases, "stable")).toBe("1.2.3-acme.9"); + expect( + newestCliReleaseVersion([{ tag_name: "v1.2.3-acme.9" }, { tag_name: "v1.2.3" }], "stable"), + ).toBe("1.2.3"); + expect( + newestCliReleaseVersion([{ tag_name: "v1.1.9" }, { tag_name: "v1.2.0" }], "stable"), + ).toBe("1.2.0"); + }); }); diff --git a/packages/shared/src/cliRelease.ts b/packages/shared/src/cliRelease.ts index 94bd3cffa168c..b831cdb3f98f7 100644 --- a/packages/shared/src/cliRelease.ts +++ b/packages/shared/src/cliRelease.ts @@ -1,7 +1,19 @@ -const CLI_RELEASE_REPOSITORY = "pingdotgg/t3code"; -export const CLI_RELEASES_PAGE_URL = `https://github.com/${CLI_RELEASE_REPOSITORY}/releases`; +import { compareSemverVersions } from "./semver.ts"; + +// Lazurio overlay (Lazurio/t3code#22): the Lazurio distribution installs and updates from its own +// releases, also from a shell that lacks the service's T3CODE_RELEASE_REPOSITORY. Upstream's is +// pingdotgg/t3code. +const CLI_RELEASE_DEFAULT_REPOSITORY = "Lazurio/t3code"; +export const CLI_RELEASES_PAGE_URL = `https://github.com/${CLI_RELEASE_DEFAULT_REPOSITORY}/releases`; export const CLI_RELEASE_CHECKSUMS_FILE = "SHA256SUMS"; export const CLI_RELEASE_BASE_URL_ENV = "T3CODE_RELEASE_BASE_URL"; +/** The `owner/name` GitHub repository whose releases are installed and offered as updates. */ +export const CLI_RELEASE_REPOSITORY_ENV = "T3CODE_RELEASE_REPOSITORY"; + +/** The configured release repository, or the Lazurio distribution's own when unset. */ +export function cliReleaseRepository(repository: string | undefined): string { + return repository?.trim() || CLI_RELEASE_DEFAULT_REPOSITORY; +} // Keep archive keys aligned with the Linux matrix, Windows ARM64 build, and cli_archive rows in release.yml. // Node single-executables do not support darwin-x64 and segfault at startup. @@ -36,13 +48,14 @@ export function cliArchiveFileName(version: string, platformKey: CliArchivePlatf return `t3-${version}-${platformKey}.${platformKey.startsWith("win32") ? "zip" : "tar.gz"}`; } -const CLI_RELEASE_DEFAULT_BASE_URL = `https://github.com/${CLI_RELEASE_REPOSITORY}/releases/download`; - export function cliReleaseDownloadBaseUrl( version: string, - baseUrl: string | undefined = CLI_RELEASE_DEFAULT_BASE_URL, + baseUrl?: string | undefined, + repository?: string | undefined, ): string { - return `${(baseUrl?.trim() || CLI_RELEASE_DEFAULT_BASE_URL).replace(/\/+$/, "")}/v${version}`; + const root = + baseUrl?.trim() || `https://github.com/${cliReleaseRepository(repository)}/releases/download`; + return `${root.replace(/\/+$/, "")}/v${version}`; } export function parseChecksums(text: string): ReadonlyMap { @@ -68,12 +81,17 @@ export function cliReleaseChannelOf(version: string): CliReleaseChannel { return channel === "nightly" || channel === "preview" ? channel : "stable"; } +export const CLI_RELEASE_INDEX_PAGE_SIZE = 100; + /** Page until the channel matches; nightlies can push preview/stable releases past the first page. */ -export function cliReleaseIndexPageUrl(page: number): string { - return `https://api.github.com/repos/${CLI_RELEASE_REPOSITORY}/releases?per_page=100&page=${page}`; +export function cliReleaseIndexPageUrl(page: number, repository?: string | undefined): string { + return `https://api.github.com/repos/${cliReleaseRepository(repository)}/releases?per_page=${CLI_RELEASE_INDEX_PAGE_SIZE}&page=${page}`; } -/** Draft assets are not downloadable. */ +/** + * Highest semver wins, not publish order: a later patch to an older line must not win. + * Drafts are skipped because their assets are not downloadable. + */ export function newestCliReleaseVersion( releases: ReadonlyArray<{ readonly tag_name: string; @@ -81,11 +99,12 @@ export function newestCliReleaseVersion( }>, channel: CliReleaseChannel, ): string | undefined { + let newest: string | undefined; for (const release of releases) { if (release.draft) continue; const version = /^v(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/.exec(release.tag_name)?.[1]; - if (version === undefined) continue; - if (cliReleaseChannelOf(version) === channel) return version; + if (version === undefined || cliReleaseChannelOf(version) !== channel) continue; + if (newest === undefined || compareSemverVersions(version, newest) > 0) newest = version; } - return undefined; + return newest; } diff --git a/scripts/install-scripts.test.ts b/scripts/install-scripts.test.ts new file mode 100644 index 0000000000000..d588d7720c4a0 --- /dev/null +++ b/scripts/install-scripts.test.ts @@ -0,0 +1,154 @@ +// @effect-diagnostics nodeBuiltinImport:off - runs the real install script in a shell against a fake curl. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +import { describe, expect, it } from "@effect/vitest"; +import { cliReleaseChannelOf, type CliReleaseChannel } from "@t3tools/shared/cliRelease"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; + +// Listing order as GitHub returns it. The first tag carries "nightly" after a +// fork's own suffix, which the runtime counts as stable; every surface that +// installs or updates must agree on that. +const tags = [ + "v1.2.3-acme-nightly.20260901.1", + "v1.2.3-nightly.20260901.2", + "v1.2.3-preview.20260901.3", + "v1.2.2-acme.1", +]; + +// What an installer should pick for a channel: the first listed tag the +// runtime assigns to that channel. +const expectedPick = (channel: CliReleaseChannel) => + tags.map((tag) => tag.slice(1)).find((version) => cliReleaseChannelOf(version) === channel); + +const scriptsDir = import.meta.dirname; + +// GitHub lists releases newest first, 100 per page; the second page holds the preview. +const pages = [tags.slice(0, 2), tags.slice(2)]; + +// The release GitHub marks latest. The release workflow marks only stable releases latest. +const latest = tags.find((tag) => cliReleaseChannelOf(tag.slice(1)) === "stable"); + +describe("install.sh", () => { + // Runs the real script against a fake curl that serves the release pages and + // `releases/latest` and 404s everything else, so the script stops right after + // choosing a version and names it in its error. It logs every URL it serves. + const installWith = (channel: CliReleaseChannel) => { + const work = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-install-sh-")); + try { + // The API pretty-prints the list, one key per line. + pages.forEach((page, index) => + NodeFS.writeFileSync( + NodePath.join(work, `page-${index + 1}.json`), + `[\n${page.map((tag) => ` {\n "tag_name": "${tag}",\n "draft": false\n }`).join(",\n")}\n]\n`, + ), + ); + // github.com answers `Accept: application/json` with one compact line. + NodeFS.writeFileSync( + NodePath.join(work, "latest.json"), + `{"id":1,"tag_name":"${latest}","update_url":"/acme/t3code/releases/tag/${latest}"}`, + ); + const log = NodePath.join(work, "requests.log"); + const bin = NodePath.join(work, "bin"); + NodeFS.mkdirSync(bin); + const curl = NodePath.join(bin, "curl"); + NodeFS.writeFileSync( + curl, + [ + "#!/bin/sh", + 'url=""; out=""; accept=""', + 'while [ "$#" -gt 0 ]; do', + ' case "$1" in', + ' -o) out="$2"; shift ;;', + ' -H) accept="$2"; shift ;;', + ' http*) url="$1" ;;', + " esac", + " shift", + "done", + `printf '%s\\n' "$url" >> "${log}"`, + 'case "$url" in', + ` https://api.github.com/repos/acme/t3code/releases\\?per_page=100\\&page=[12]) cp "${work}/page-\${url##*=}.json" "$out"; printf 200 ;;`, + ` https://api.github.com/*) printf '[]\\n' > "$out"; printf 200 ;;`, + " https://github.com/acme/t3code/releases/latest)", + ' if [ "$accept" = "Accept: application/json" ]; then', + ` cp "${work}/latest.json" "$out"; printf 200`, + ' else : > "$out"; printf 406; fi ;;', + ' *) : > "$out"; printf 404 ;;', + "esac", + "", + ].join("\n"), + ); + NodeFS.chmodSync(curl, 0o755); + const result = NodeChildProcess.spawnSync("sh", [NodePath.join(scriptsDir, "install.sh")], { + encoding: "utf8", + env: { + PATH: `${bin}:${process.env.PATH ?? ""}`, + HOME: work, + T3CODE_HOME: NodePath.join(work, "t3"), + T3CODE_INSTALL_BIN_DIR: NodePath.join(work, "t3-bin"), + T3CODE_RELEASE_REPOSITORY: "acme/t3code", + T3CODE_CHANNEL: channel, + }, + }); + const requests = NodeFS.readFileSync(log, "utf8").trim().split("\n"); + return { stderr: result.stderr, requests }; + } finally { + NodeFS.rmSync(work, { recursive: true, force: true }); + } + }; + + const indexRequests = (requests: ReadonlyArray) => + requests.filter((url) => !url.includes("/releases/download/")); + + it.effect.each(["stable", "nightly", "preview"] as const)( + "picks the %s release the runtime would", + (channel) => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const version = expectedPick(channel); + expect(version).toBeDefined(); + expect(installWith(channel).stderr).toContain(`t3 ${version} has no release archive`); + }), + ); + + it.effect("reads stable from releases/latest and pages the API for the other trains", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const api = "https://api.github.com/repos/acme/t3code/releases?per_page=100&page="; + expect(indexRequests(installWith("stable").requests)).toEqual([ + "https://github.com/acme/t3code/releases/latest", + ]); + expect(indexRequests(installWith("nightly").requests)).toEqual([`${api}1`]); + expect(indexRequests(installWith("preview").requests)).toEqual([`${api}1`, `${api}2`]); + }), + ); +}); + +describe("install.ps1", () => { + // No PowerShell in this test environment: evaluate the script's train rule + // itself. The pattern is plain .NET regex syntax that JavaScript shares. + const script = NodeFS.readFileSync(NodePath.join(scriptsDir, "install.ps1"), "utf8"); + const trainPattern = /\$candidate -match '([^']+)'/.exec(script)?.[1]; + + it("classifies every tag the way the runtime does", () => { + expect(trainPattern).toBeDefined(); + const train = new RegExp(trainPattern ?? "$^"); + for (const tag of tags) { + const trainOf = train.exec(tag)?.[1] ?? "stable"; + expect(trainOf, tag).toBe(cliReleaseChannelOf(tag.slice(1))); + expect(train.exec(tag.slice(1))?.[1] ?? "stable", tag).toBe(trainOf); + } + }); + + it("reads stable from releases/latest and filters every lookup by the train rule", () => { + expect(script).toMatch( + /releases\/latest" -Headers @\{ "User-Agent" = "t3-install"; "Accept" = "application\/json" \}/, + ); + expect(script).toMatch(/\$tag = & \$ofTrain \$release\n/); + expect(script).toMatch(/\$tag = & \$ofTrain \$releases\n/); + expect(script).toMatch(/\(& \$trainOf \$_\.tag_name\) -eq \$channel/); + }); +}); diff --git a/scripts/install.ps1 b/scripts/install.ps1 index 60a70fefc7211..d1c8aac6dbff7 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -9,14 +9,18 @@ # T3CODE_VERSION exact version to install (overrides T3CODE_CHANNEL) # T3CODE_HOME T3 home directory (default: ~\.t3) # T3CODE_INSTALL_BIN_DIR where t3.exe is linked (default: ~\.local\bin) -# T3CODE_RELEASE_BASE_URL mirror for releases/download (default: GitHub) +# T3CODE_RELEASE_REPOSITORY GitHub repository (owner/name) whose releases to +# install (default: Lazurio/t3code, the Lazurio +# distribution's own; upstream's is pingdotgg/t3code) +# T3CODE_RELEASE_BASE_URL mirror for releases/download (default: the +# repository's GitHub Releases) # # The archive is unpacked into $T3CODE_HOME\runtime\versions\, the # same layout `t3 service install` uses, so the service reuses this download. $ErrorActionPreference = "Stop" [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$repo = "pingdotgg/t3code" +$repo = if ($env:T3CODE_RELEASE_REPOSITORY) { $env:T3CODE_RELEASE_REPOSITORY.Trim() } else { "Lazurio/t3code" } $baseUrl = if ($env:T3CODE_RELEASE_BASE_URL) { $env:T3CODE_RELEASE_BASE_URL.TrimEnd("/") } else { "https://github.com/$repo/releases/download" } $t3Home = if ($env:T3CODE_HOME) { $env:T3CODE_HOME } else { Join-Path $HOME ".t3" } $binDir = if ($env:T3CODE_INSTALL_BIN_DIR) { $env:T3CODE_INSTALL_BIN_DIR } else { Join-Path $HOME ".local\bin" } @@ -124,32 +128,47 @@ $arch = switch ($rawArch) { default { Fail "unsupported architecture $rawArch" } } +# The release train of a version or v-tag, by the rule the runtime uses: a +# nightly or preview identifier right after major.minor.patch names its train; +# every other version, including a fork's own prerelease suffix, is stable. +$trainOf = { + param([string] $candidate) + if ($candidate -match '^v?\d+\.\d+\.\d+-(nightly|preview)\.\d{8}\.\d+$') { $Matches[1] } else { "stable" } +} + $channel = if ($env:T3CODE_CHANNEL) { $env:T3CODE_CHANNEL } else { "stable" } $version = $env:T3CODE_VERSION if (-not $version) { - $tagPattern = switch ($channel) { - "stable" { '^v\d+\.\d+\.\d+$' } - "nightly" { '^v\d+\.\d+\.\d+-nightly\.\d+\.\d+$' } - "preview" { '^v\d+\.\d+\.\d+-preview\.\d+\.\d+$' } - default { Fail "T3CODE_CHANNEL must be stable, nightly, or preview" } + # Tags are v. Only tags of the requested train are considered, so a + # stable install can never pick up a nightly or preview build by accident. + if ($channel -notin @("stable", "nightly", "preview")) { + Fail "T3CODE_CHANNEL must be stable, nightly, or preview" + } + $ofTrain = { + param($releases) + ($releases | Where-Object { + -not $_.draft -and + $_.tag_name -match '^v\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$' -and + (& $trainOf $_.tag_name) -eq $channel + } | Select-Object -First 1).tag_name } if ($channel -eq "stable") { - # release.yml marks only plain stable releases latest. This is a github.com + # The release workflow marks only stable releases latest. This is a github.com # page, so it is not cut off by a page of newer nightlies or the API quota. $release = Invoke-RestMethod -Uri "https://github.com/$repo/releases/latest" -Headers @{ "User-Agent" = "t3-install"; "Accept" = "application/json" } - $tag = ($release | Where-Object { $_.tag_name -match $tagPattern }).tag_name + $tag = & $ofTrain $release } else { $tag = $null for ($page = 1; -not $tag -and $page -le 10; $page++) { $releases = Invoke-RestMethod -Uri "https://api.github.com/repos/$repo/releases?per_page=100&page=$page" -Headers @{ "User-Agent" = "t3-install" } - $tag = ($releases | Where-Object { -not $_.draft -and $_.tag_name -match $tagPattern } | Select-Object -First 1).tag_name + $tag = & $ofTrain $releases if (-not $releases) { break } } } if (-not $tag) { Fail "could not find a $channel release; set T3CODE_VERSION" } $version = $tag.Substring(1) } -if ($version -match '-preview\.') { +if ((& $trainOf $version) -eq "preview") { Write-Warning "t3 $version is a preview build. Preview builds are cut by maintainers from unreleased branches to exercise the release pipeline. They can be broken, receive no fixes, and are never offered as updates. Set T3CODE_CHANNEL=stable (the default) for a supported build." if ($channel -ne "preview" -and -not $env:T3CODE_VERSION) { Fail "refusing a preview build that was not explicitly requested" diff --git a/scripts/install.sh b/scripts/install.sh index 4c164c45040f8..b068947636717 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -10,14 +10,18 @@ # T3CODE_VERSION exact version to install (overrides T3CODE_CHANNEL) # T3CODE_HOME T3 home directory (default: ~/.t3) # T3CODE_INSTALL_BIN_DIR where the `t3` symlink goes (default: ~/.local/bin) -# T3CODE_RELEASE_BASE_URL mirror for releases/download (default: GitHub) +# T3CODE_RELEASE_REPOSITORY GitHub repository (owner/name) whose releases to +# install (default: Lazurio/t3code, the Lazurio +# distribution's own; upstream's is pingdotgg/t3code) +# T3CODE_RELEASE_BASE_URL mirror for releases/download (default: the +# repository's GitHub Releases) # # The archive is unpacked into $T3CODE_HOME/runtime/versions/, the # same layout `t3 service install` uses, so the service reuses this download # instead of fetching the release again. set -eu -repo="pingdotgg/t3code" +repo="${T3CODE_RELEASE_REPOSITORY:-Lazurio/t3code}" base_url="${T3CODE_RELEASE_BASE_URL:-https://github.com/${repo}/releases/download}" t3_home="${T3CODE_HOME:-$HOME/.t3}" bin_dir="${T3CODE_INSTALL_BIN_DIR:-$HOME/.local/bin}" @@ -142,25 +146,47 @@ else fail "sha256sum or shasum is required" fi +# The release train of a version, by the rule the runtime uses: a nightly or +# preview identifier right after major.minor.patch names its train; every other +# version, including a fork's own prerelease suffix, is stable. +train_of() { + case "$(printf '%s\n' "$1" | grep -Eo '^[0-9]+\.[0-9]+\.[0-9]+-(nightly|preview)\.[0-9]{8}\.[0-9]+$')" in + *-nightly.*) printf 'nightly\n' ;; + *-preview.*) printf 'preview\n' ;; + *) printf 'stable\n' ;; + esac +} + +# The first v tag of train $2 in the release JSON file $1, in listing order. +first_of_train() { + for candidate in $(sed -n 's/.*"tag_name": *"v\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\(-[0-9A-Za-z.-]*\)\{0,1\}\)".*/\1/p' "$1"); do + if [ "$(train_of "$candidate")" = "$2" ]; then + printf '%s\n' "$candidate" + return 0 + fi + done +} + channel="${T3CODE_CHANNEL:-stable}" version="${T3CODE_VERSION:-}" if [ -z "$version" ]; then + # Tags are v. Only tags of the requested train are considered, so a + # stable install can never pick up a nightly or preview build by accident. case "$channel" in - stable) tag_pattern='v\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)' ;; - nightly | preview) tag_pattern="v\([0-9][^\"]*-${channel}\.[0-9]*\.[0-9]*\)" ;; + stable | nightly | preview) ;; *) fail "T3CODE_CHANNEL must be stable, nightly, or preview" ;; esac tmp_index="$(mktemp)" if [ "$channel" = stable ]; then - # release.yml marks only plain stable releases latest. This is a github.com + # The release workflow marks only stable releases latest. This is a github.com # page, so it is not cut off by a page of newer nightlies or the API quota. fetch "https://github.com/${repo}/releases/latest" "$tmp_index" application/json - version="$(sed -n "s/.*\"tag_name\": *\"${tag_pattern}\".*/\1/p" "$tmp_index" | head -n 1)" + version="$(first_of_train "$tmp_index" "$channel")" else page=1 while [ -z "$version" ] && [ "$page" -le 10 ]; do fetch "https://api.github.com/repos/${repo}/releases?per_page=100&page=${page}" "$tmp_index" - version="$(sed -n "s/.*\"tag_name\": *\"${tag_pattern}\".*/\1/p" "$tmp_index" | head -n 1)" + version="$(first_of_train "$tmp_index" "$channel")" grep -q '"tag_name"' "$tmp_index" || break page=$((page + 1)) done @@ -168,8 +194,8 @@ if [ -z "$version" ]; then rm -f "$tmp_index" [ -n "$version" ] || fail "could not find a ${channel} release; set T3CODE_VERSION" fi -case "$version" in - *-preview.*) +case "$(train_of "$version")" in + preview) printf '%s\n' \ "t3 ${version} is a preview build." \ " Preview builds are cut by maintainers from unreleased branches to exercise the release" \ diff --git a/scripts/install.test.ts b/scripts/install.test.ts index 5be7acc8e004d..e84a74a0d5b2b 100644 --- a/scripts/install.test.ts +++ b/scripts/install.test.ts @@ -59,6 +59,8 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("installer chan T3CODE_INSTALL_BIN_DIR: NodePath.join(root, "bin"), // A wrong version must fail here instead of downloading a real release. T3CODE_RELEASE_BASE_URL: origin, + // The fixture serves upstream's repository; the distribution defaults to its own. + T3CODE_RELEASE_REPOSITORY: "pingdotgg/t3code", }, stdio: ["ignore", "pipe", "pipe"], }); From c332cf1480f6d3451038bb5424214a4c021783df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= <16311043+immakermatty@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:51:35 +0000 Subject: [PATCH 05/31] lazurio: unsent prompt draft by link from the shell MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Launchpad's "+ Nový modul" opens Chat with #lazurio-prompt=&lazurio-org= in the fragment. main.tsx takes it off the address before the router reads it; once the primary environment is live, the text and project folder come from this origin's /.lazurio/prompts/, and a new thread opens in that project (in a managed Environment, its Lazurio Folder project) with the text in the composer, never sent. Upstream's /new?prompt= links carry the text in the address, so the overlay keeps its own. The tab keeps only the id and the login across the pairing reload, never the text; it is taken once and expires after two minutes. On v0.1.3 the router, history and provider-auth delivery moved from main.tsx into startAppServices() in appInit.tsx (#25004), so the capture now runs on the line before `const router = startAppServices()`, still before any router exists; it now also runs before provider-auth delivery, which acts only on its own fragment. ChatRouteLayout was rewritten for Settings and Usage as modals over the thread (#24847); is its first child and stays mounted while a modal is open. The component's one effect carries a justified react-effect-budget suppression and its comments are cut to four lines. It imports prefersCzech from row 9's threadTabs.ts and reads lazurioFolder from row 15's server config, so this row alone does not typecheck. On v0.1.4: upstream deleted lib/projectPaths.ts (#26238); the draft reads findProjectByPath and inferProjectTitleFromPath from @t3tools/client-runtime/state/projects. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/lazurio/LazurioPromptDraft.tsx | 92 ++++++ apps/web/src/lazurio/promptDraft.test.ts | 300 ++++++++++++++++++++ apps/web/src/lazurio/promptDraft.ts | 232 +++++++++++++++ apps/web/src/main.tsx | 4 + apps/web/src/routes/_chat.tsx | 2 + 5 files changed, 630 insertions(+) create mode 100644 apps/web/src/lazurio/LazurioPromptDraft.tsx create mode 100644 apps/web/src/lazurio/promptDraft.test.ts create mode 100644 apps/web/src/lazurio/promptDraft.ts diff --git a/apps/web/src/lazurio/LazurioPromptDraft.tsx b/apps/web/src/lazurio/LazurioPromptDraft.tsx new file mode 100644 index 0000000000000..a656a33330255 --- /dev/null +++ b/apps/web/src/lazurio/LazurioPromptDraft.tsx @@ -0,0 +1,92 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { + findProjectByPath, + inferProjectTitleFromPath, +} from "@t3tools/client-runtime/state/projects"; +import { Atom } from "effect/reactivity"; +import { useEffect, useRef } from "react"; + +import { stackedThreadToast, toastManager } from "~/components/ui/toast"; +import { useComposerDraftStore } from "../composerDraftStore"; +import { useNewThreadHandler } from "../hooks/useHandleNewThread"; +import { newProjectId } from "../lib/utils"; +import { readProjects, waitForProject } from "../state/entities"; +import { projectEnvironment } from "../state/projects"; +import { primaryServerConfigAtom } from "../state/server"; +import { environmentShell } from "../state/shell"; +import { useAtomCommand } from "../state/use-atom-command"; +import { failedPromptDraftText, openPromptDraft, takeLazurioPromptLink } from "./promptDraft"; +import { prefersCzech } from "./threadTabs"; + +// The primary environment once its shell is live: its project list is +// complete, so a missing project is really missing, and commands reach it. +// Null until then (still loading, or disconnected), and the link waits. +const livePrimaryEnvironmentIdAtom = Atom.make((get) => { + const serverConfig = get(primaryServerConfigAtom); + if (serverConfig === null) return null; + const environmentId = serverConfig.environment.environmentId; + return get(environmentShell.stateValueAtom(environmentId)).status === "live" + ? environmentId + : null; +}).pipe(Atom.withLabel("lazurio-prompt-draft-live-primary-environment")); + +/** + * Lazurio overlay (Lazurio/t3code#35): once the primary environment is live, opens the linked + * prompt in a new thread of the project at its folder (a managed Environment's Lazurio Folder + * project), text in the composer and nothing sent. Renders nothing. + */ +export function LazurioPromptDraft() { + const primaryEnvironmentId = useAtomValue(livePrimaryEnvironmentIdAtom); + const lazurioFolder = useAtomValue(primaryServerConfigAtom)?.lazurioFolder; + const handleNewThread = useNewThreadHandler(); + const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); + const started = useRef(false); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- waits for the environment to go live, then runs a one-shot fetch outside React + useEffect(() => { + if (started.current || primaryEnvironmentId === null) return; + const link = takeLazurioPromptLink(); + if (link === null) return; + started.current = true; + void openPromptDraft(link, { + origin: window.location.origin, + fetch: (url, init) => window.fetch(url, init), + findProject: (cwd) => { + const project = findProjectByPath( + readProjects().filter((candidate) => candidate.environmentId === primaryEnvironmentId), + cwd, + ); + return project ? scopeProjectRef(project.environmentId, project.id) : null; + }, + addProject: async (cwd) => { + const projectId = newProjectId(); + const created = await createProject({ + environmentId: primaryEnvironmentId, + input: { + projectId, + title: inferProjectTitleFromPath(cwd), + workspaceRoot: cwd, + createWorkspaceRootIfMissing: false, + defaultModelSelection: null, + }, + }); + if (created._tag === "Failure") return null; + const projectRef = scopeProjectRef(primaryEnvironmentId, projectId); + await waitForProject(projectRef, 3_000).catch(() => null); + return projectRef; + }, + lazurioFolder, + openThread: (projectRef) => handleNewThread(projectRef), + setPrompt: (draftId, text) => useComposerDraftStore.getState().setPrompt(draftId, text), + }).then((outcome) => { + if (outcome === "failed") { + toastManager.add( + stackedThreadToast({ type: "error", ...failedPromptDraftText(prefersCzech()) }), + ); + } + }); + }, [createProject, handleNewThread, lazurioFolder, primaryEnvironmentId]); + + return null; +} diff --git a/apps/web/src/lazurio/promptDraft.test.ts b/apps/web/src/lazurio/promptDraft.test.ts new file mode 100644 index 0000000000000..86275b9a8f4f2 --- /dev/null +++ b/apps/web/src/lazurio/promptDraft.test.ts @@ -0,0 +1,300 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { + capturePromptLink, + failedPromptDraftText, + fetchPrompt, + type LinkStorage, + openPromptDraft, + type PromptDraftDependencies, + readPromptLink, + stripPromptLink, +} from "./promptDraft"; + +const origin = "https://t3code.vm-01.example.lazurio.io"; +const link = { id: "new-module", organization: "Example-Org" } as const; +const document = { + schema: "lazurio.prompt.v1", + id: "new-module", + text: "I want to found a new module.\n\nAsk me first.", + cwd: "/home/operator/Lazurio/organizations/example_GEN3", +}; + +/** A tab's session storage, kept across the reloads a test simulates. */ +function sessionStorage() { + const items = new Map(); + const storage: LinkStorage = { + getItem: (key) => items.get(key) ?? null, + setItem: (key, value) => void items.set(key, value), + removeItem: (key) => void items.delete(key), + }; + return { items, getStorage: () => storage }; +} + +function answer(body: unknown, init: ResponseInit & { url?: string } = {}): Response { + const response = new Response(typeof body === "string" ? body : JSON.stringify(body), { + status: 200, + headers: { "content-type": "application/json; charset=utf-8" }, + ...init, + }); + Object.defineProperty(response, "url", { + value: init.url ?? `${origin}/.lazurio/prompts/new-module?org=Example-Org`, + }); + return response; +} + +describe("the link", () => { + it("carries only a prompt id and an Organization login, in the fragment", () => { + expect( + readPromptLink( + new URL(`${origin}/pair#token=abc&lazurio-prompt=new-module&lazurio-org=Example-Org`), + ), + ).toEqual(link); + expect( + readPromptLink(new URL(`${origin}/#lazurio-prompt=new-module&lazurio-org=Example-Org`)), + ).toEqual(link); + }); + + it("refuses text, a query, a missing or repeated part and anything outside the grammar", () => { + for (const href of [ + `${origin}/#lazurio-prompt=new-module`, + `${origin}/#lazurio-org=Example-Org`, + `${origin}/?lazurio-prompt=new-module&lazurio-org=Example-Org`, + `${origin}/#lazurio-prompt=new-module&lazurio-org=Example-Org&lazurio-prompt=other`, + `${origin}/#lazurio-prompt=Do%20this%20now&lazurio-org=Example-Org`, + `${origin}/#lazurio-prompt=new-module&lazurio-org=a%2Fb`, + `${origin}/#lazurio-prompt=new-module&lazurio-org=-x`, + `${origin}/#lazurio-prompt=${"a".repeat(65)}&lazurio-org=Example-Org`, + `${origin}/#lazurio-text=hello&lazurio-org=Example-Org`, + `${origin}/pair#token=abc`, + ]) { + expect([href, readPromptLink(new URL(href))]).toEqual([href, null]); + } + }); + + it("is stripped from the address, leaving everything else as it was", () => { + expect( + stripPromptLink( + new URL(`${origin}/pair#token=abc&lazurio-prompt=new-module&lazurio-org=Example-Org`), + ).href, + ).toBe(`${origin}/pair#token=abc`); + expect( + stripPromptLink(new URL(`${origin}/#lazurio-prompt=new-module&lazurio-org=Example-Org`)).href, + ).toBe(`${origin}/`); + expect(stripPromptLink(new URL(`${origin}/pair#token=abc`)).href).toBe( + `${origin}/pair#token=abc`, + ); + }); + + it("is taken once at boot, before the router reads the address", () => { + const replace = vi.fn(); + const location = { + href: `${origin}/pair#token=abc&lazurio-prompt=new-module&lazurio-org=Example-Org`, + }; + const take = capturePromptLink(location, replace, sessionStorage().getStorage, 0); + expect(replace).toHaveBeenCalledWith(`${origin}/pair#token=abc`); + expect(take()).toEqual(link); + expect(take()).toBeNull(); + const untouched = vi.fn(); + expect( + capturePromptLink( + { href: `${origin}/pair#token=abc` }, + untouched, + sessionStorage().getStorage, + 0, + )(), + ).toBeNull(); + expect(untouched).not.toHaveBeenCalled(); + }); + + it("outlives the pairing page's reload in this tab, without its text, once and briefly", () => { + const boot = (href: string, tab: ReturnType, now: number) => + capturePromptLink({ href }, () => {}, tab.getStorage, now); + const pairing = `${origin}/pair#token=abc&lazurio-prompt=new-module&lazurio-org=Example-Org`; + + const tab = sessionStorage(); + boot(pairing, tab, 1_000); + expect([...tab.items.values()]).toEqual([ + "lazurio-prompt=new-module&lazurio-org=Example-Org&expires=121000", + ]); + const take = boot(`${origin}/`, tab, 6_000); + expect(take()).toEqual(link); + expect(take()).toBeNull(); + expect(tab.items.size).toBe(0); + expect(boot(`${origin}/`, tab, 7_000)()).toBeNull(); + + const late = sessionStorage(); + boot(pairing, late, 1_000); + expect(boot(`${origin}/`, late, 121_000)()).toBeNull(); + + const blocked: LinkStorage = { + getItem: () => { + throw new DOMException("blocked", "SecurityError"); + }, + setItem: () => { + throw new DOMException("blocked", "SecurityError"); + }, + removeItem: () => { + throw new DOMException("blocked", "SecurityError"); + }, + }; + expect( + capturePromptLink( + { href: pairing }, + () => {}, + () => blocked, + 1_000, + )(), + ).toEqual(link); + }); +}); + +describe("the text", () => { + it("comes only from this origin's /.lazurio/prompts/, without credentials elsewhere", async () => { + const fetcher = vi.fn(async () => answer(document)); + await expect(fetchPrompt(link, origin, fetcher)).resolves.toEqual({ + text: document.text, + cwd: document.cwd, + }); + expect(fetcher).toHaveBeenCalledTimes(1); + const [url, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe(`${origin}/.lazurio/prompts/new-module?org=Example-Org`); + expect(init).toMatchObject({ + credentials: "same-origin", + redirect: "error", + cache: "no-store", + }); + }); + + it("is nothing for an unknown id, a failed fetch, a non-JSON or wrong answer, or another origin", async () => { + const cases: Array<[string, () => Promise]> = [ + ["404", async () => answer({ error: "not-found" }, { status: 404 })], + [ + "network", + async () => { + throw new TypeError("Failed to fetch"); + }, + ], + ["html", async () => answer("", { headers: { "content-type": "text/html" } })], + ["not json", async () => answer("{", { headers: { "content-type": "application/json" } })], + ["schema", async () => answer({ ...document, schema: "lazurio.prompt.v2" })], + ["id", async () => answer({ ...document, id: "other" })], + ["empty text", async () => answer({ ...document, text: " " })], + ["long text", async () => answer({ ...document, text: "x".repeat(16 * 1024 + 1) })], + ["text type", async () => answer({ ...document, text: 42 })], + ["relative cwd", async () => answer({ ...document, cwd: "organizations/example" })], + ["no cwd", async () => answer({ ...document, cwd: undefined })], + [ + "other origin", + async () => answer(document, { url: "https://evil.example/.lazurio/prompts/new-module" }), + ], + ["array", async () => answer([document])], + ]; + for (const [name, fetcher] of cases) { + await expect([name, await fetchPrompt(link, origin, fetcher)]).toEqual([name, null]); + } + }); +}); + +function dependencies(overrides: Partial = {}) { + const calls: string[] = []; + const projectRef = { environmentId: "primary", projectId: "project-1" } as never; + const base: PromptDraftDependencies = { + origin, + fetch: async () => answer(document), + findProject: (cwd) => { + calls.push(`find ${cwd}`); + return projectRef; + }, + addProject: async (cwd) => { + calls.push(`add ${cwd}`); + return projectRef; + }, + openThread: async () => { + calls.push("open"); + return { draftId: "draft-1" as never }; + }, + setPrompt: (draftId, text) => { + calls.push(`prompt ${String(draftId)} ${text}`); + }, + }; + return { calls, dependencies: { ...base, ...overrides } }; +} + +describe("the draft", () => { + it("opens a new thread in the project rooted at cwd and leaves the text in its composer", async () => { + const { calls, dependencies: deps } = dependencies(); + await expect(openPromptDraft(link, deps)).resolves.toBe("opened"); + expect(calls).toEqual([`find ${document.cwd}`, "open", `prompt draft-1 ${document.text}`]); + }); + + it("adds the Organization's folder as a project when there is none", async () => { + const { calls, dependencies: deps } = dependencies({ + findProject: (cwd) => { + calls.push(`find ${cwd}`); + return null; + }, + }); + await expect(openPromptDraft(link, deps)).resolves.toBe("opened"); + expect(calls).toEqual([ + `find ${document.cwd}`, + `add ${document.cwd}`, + "open", + `prompt draft-1 ${document.text}`, + ]); + }); + + it("opens in a managed environment's Folder project whatever the cwd, and adds nothing", async () => { + const folder = "/home/operator/Lazurio"; + const { calls, dependencies: deps } = dependencies({ lazurioFolder: folder }); + await expect(openPromptDraft(link, deps)).resolves.toBe("opened"); + expect(calls).toEqual([`find ${folder}`, "open", `prompt draft-1 ${document.text}`]); + + const missing = dependencies({ lazurioFolder: folder, findProject: () => null }); + await expect(openPromptDraft(link, missing.dependencies)).resolves.toBe("failed"); + expect(missing.calls).toEqual([]); + }); + + it("asks again when another navigation overtook the new thread", async () => { + let attempts = 0; + const { calls, dependencies: deps } = dependencies({ + openThread: async () => { + attempts += 1; + calls.push("open"); + return attempts === 1 ? null : { draftId: "draft-2" as never }; + }, + }); + await expect(openPromptDraft(link, deps)).resolves.toBe("opened"); + expect(calls.slice(1)).toEqual(["open", "open", `prompt draft-2 ${document.text}`]); + }); + + it("inserts nothing when the text, the project or the thread is not there", async () => { + for (const overrides of [ + { fetch: async () => answer({ error: "not-found" }, { status: 404 }) }, + { findProject: () => null, addProject: async () => null }, + { openThread: async () => null }, + { + openThread: async () => { + throw new Error("navigation failed"); + }, + }, + ] satisfies Array>) { + const { calls, dependencies: deps } = dependencies(overrides); + await expect(openPromptDraft(link, deps)).resolves.toBe("failed"); + expect(calls.some((call) => call.startsWith("prompt"))).toBe(false); + } + }); +}); + +describe("the toast when the prompt does not open", () => { + it("says so in Czech where the browser is Czech, and in English elsewhere", () => { + expect(failedPromptDraftText(true)).toEqual({ + title: "Připravené zadání se nepodařilo otevřít", + description: "Do pole zprávy se nic nepřidalo.", + }); + expect(failedPromptDraftText(false)).toEqual({ + title: "Could not open the prepared prompt", + description: "Nothing was added to the composer.", + }); + }); +}); diff --git a/apps/web/src/lazurio/promptDraft.ts b/apps/web/src/lazurio/promptDraft.ts new file mode 100644 index 0000000000000..571d63efeae7c --- /dev/null +++ b/apps/web/src/lazurio/promptDraft.ts @@ -0,0 +1,232 @@ +import type { ScopedProjectRef } from "@t3tools/contracts"; + +import type { DraftId } from "../composerDraftStore"; + +/** + * Lazurio overlay (Lazurio/t3code#35): a `#lazurio-prompt=&lazurio-org=` link never + * carries text. Text and folder come from this origin's `/.lazurio/prompts/?org=`, + * behind the same sign-in; any other answer puts nothing in the composer, and nothing here sends. + */ + +export interface PromptLink { + readonly id: string; + readonly organization: string; +} + +export interface PreparedPrompt { + readonly text: string; + /** The absolute root of the project the new thread opens in. */ + readonly cwd: string; +} + +const PROMPT_PARAM = "lazurio-prompt"; +const ORGANIZATION_PARAM = "lazurio-org"; +const PROMPT_ID = /^[a-z][a-z0-9-]{0,63}$/; +const GITHUB_LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/; +const PROMPT_SCHEMA = "lazurio.prompt.v1"; +const MAX_PROMPT_LENGTH = 16 * 1024; +const ABSOLUTE_PATH = /^(?:\/|[A-Za-z]:[\\/])/; + +const fragmentOf = (url: URL) => new URLSearchParams(url.hash.slice(1)); + +function linkOf(params: URLSearchParams): PromptLink | null { + const ids = params.getAll(PROMPT_PARAM); + const organizations = params.getAll(ORGANIZATION_PARAM); + const [id] = ids; + const [organization] = organizations; + if (ids.length !== 1 || organizations.length !== 1 || !id || !organization) return null; + if (!PROMPT_ID.test(id) || !GITHUB_LOGIN.test(organization)) return null; + return { id, organization }; +} + +/** The prompt a link names, or null: exactly one id and one login, of their grammar. */ +export function readPromptLink(url: URL): PromptLink | null { + return linkOf(fragmentOf(url)); +} + +/** The same address without the prompt's parameters; everything else stays as it was. */ +export function stripPromptLink(url: URL): URL { + const next = new URL(url.href); + const fragment = fragmentOf(next); + if (!fragment.has(PROMPT_PARAM) && !fragment.has(ORGANIZATION_PARAM)) return next; + fragment.delete(PROMPT_PARAM); + fragment.delete(ORGANIZATION_PARAM); + next.hash = fragment.toString(); + return next; +} + +// The pairing page reloads once it has signed in, so a link it carried has to +// outlive that reload: this tab keeps the id and the login, never the text, +// under one key, until the link is taken or expires. +const STORED_LINK_KEY = "lazurio:prompt-link"; +const STORED_LINK_EXPIRES = "expires"; +const STORED_LINK_LIFETIME_MS = 2 * 60_000; + +/** A tab's session storage; any access may throw where storage is blocked. */ +export type LinkStorage = Pick; + +function withStorage( + getStorage: () => LinkStorage, + use: (storage: LinkStorage) => A, + orElse: A, +) { + try { + return use(getStorage()); + } catch { + return orElse; + } +} + +/** + * Takes the prompt link off the address once, at boot, before the router or + * the pairing read it, or else the link this tab kept across a reload. Returns + * the reader of the link: it hands it over once and is empty afterwards. + */ +export function capturePromptLink( + location: { readonly href: string }, + replace: (href: string) => void, + getStorage: () => LinkStorage, + now: number, +): () => PromptLink | null { + const url = new URL(location.href); + const linked = readPromptLink(url); + const stripped = stripPromptLink(url); + if (stripped.href !== url.href) replace(stripped.href); + let pending = linked; + if (linked !== null) { + const stored = new URLSearchParams({ + [PROMPT_PARAM]: linked.id, + [ORGANIZATION_PARAM]: linked.organization, + [STORED_LINK_EXPIRES]: String(now + STORED_LINK_LIFETIME_MS), + }); + withStorage(getStorage, (storage) => storage.setItem(STORED_LINK_KEY, `${stored}`), undefined); + } else { + const stored = new URLSearchParams( + withStorage(getStorage, (storage) => storage.getItem(STORED_LINK_KEY), null) ?? "", + ); + if (now < Number(stored.get(STORED_LINK_EXPIRES))) pending = linkOf(stored); + } + return () => { + const taken = pending; + pending = null; + withStorage(getStorage, (storage) => storage.removeItem(STORED_LINK_KEY), undefined); + return taken; + }; +} + +/** The prompt's text and project folder from this origin, or null on anything unexpected. */ +export async function fetchPrompt( + link: PromptLink, + origin: string, + fetcher: (url: string, init: RequestInit) => Promise, +): Promise { + const url = new URL(`/.lazurio/prompts/${encodeURIComponent(link.id)}`, origin); + url.searchParams.set("org", link.organization); + try { + const response = await fetcher(url.href, { + credentials: "same-origin", + redirect: "error", + cache: "no-store", + headers: { accept: "application/json" }, + }); + if (!response.ok || new URL(response.url).origin !== url.origin) return null; + if (!(response.headers.get("content-type") ?? "").startsWith("application/json")) return null; + const value: unknown = await response.json(); + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + const { schema, id, text, cwd } = value as Record; + if (schema !== PROMPT_SCHEMA || id !== link.id) return null; + if (typeof text !== "string" || text.trim().length === 0 || text.length > MAX_PROMPT_LENGTH) { + return null; + } + if (typeof cwd !== "string" || !ABSOLUTE_PATH.test(cwd)) return null; + return { text, cwd }; + } catch { + return null; + } +} + +/** What opening a prompt needs from the app; none of it can send a message. */ +export interface PromptDraftDependencies { + readonly origin: string; + readonly fetch: (url: string, init: RequestInit) => Promise; + /** The primary environment's project rooted exactly at `cwd`, if any. */ + readonly findProject: (cwd: string) => ScopedProjectRef | null; + /** Adds `cwd` as a project of the primary environment, as "Add project" does. */ + readonly addProject: (cwd: string) => Promise; + /** + * The primary environment's Lazurio Folder when it is managed (LazurioPlatform F51). Every new + * thread there starts in the Folder, which takes no other project, so the prompt opens in the + * Folder's project whatever its `cwd`, and nothing is added. + */ + readonly lazurioFolder?: string | undefined; + /** Opens a new thread draft in the project; null when another navigation overtook it. */ + readonly openThread: (projectRef: ScopedProjectRef) => Promise<{ draftId: DraftId } | null>; + readonly setPrompt: (draftId: DraftId, text: string) => void; +} + +const OPEN_ATTEMPTS = 3; + +/** + * Opens the prompt a link named: a new thread in the project rooted at its + * folder (added as a project when there is none), or in a managed + * environment in its Lazurio Folder's project, with the text in the + * composer, unsent. + */ +export async function openPromptDraft( + link: PromptLink, + dependencies: PromptDraftDependencies, +): Promise<"opened" | "failed"> { + const prompt = await fetchPrompt(link, dependencies.origin, dependencies.fetch); + if (prompt === null) return "failed"; + try { + const projectRef = + dependencies.lazurioFolder === undefined + ? (dependencies.findProject(prompt.cwd) ?? (await dependencies.addProject(prompt.cwd))) + : dependencies.findProject(dependencies.lazurioFolder); + if (projectRef === null) return "failed"; + // The index route opens a draft of the latest project at the same time; + // whichever navigation lands second makes the other one return null. + for (let attempt = 0; attempt < OPEN_ATTEMPTS; attempt += 1) { + const opened = await dependencies.openThread(projectRef); + if (opened !== null) { + dependencies.setPrompt(opened.draftId, prompt.text); + return "opened"; + } + } + return "failed"; + } catch { + return "failed"; + } +} + +/** + * The toast when a prepared prompt does not open (Lazurio/t3code#75): Czech where the person's + * browser is, as everywhere the overlay speaks, English elsewhere. + */ +export const failedPromptDraftText = (czech: boolean) => + czech + ? { + title: "Připravené zadání se nepodařilo otevřít", + description: "Do pole zprávy se nic nepřidalo.", + } + : { + title: "Could not open the prepared prompt", + description: "Nothing was added to the composer.", + }; + +let takePending: () => PromptLink | null = () => null; + +/** Call once in `main.tsx`, before the router is created. */ +export function captureLazurioPromptLink(): void { + takePending = capturePromptLink( + window.location, + (href) => window.history.replaceState(window.history.state, "", href), + () => window.sessionStorage, + Date.now(), + ); +} + +/** The link taken at boot, once. */ +export function takeLazurioPromptLink(): PromptLink | null { + return takePending(); +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index d6cf4ce77b91b..2bb63ad3537ff 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -9,6 +9,10 @@ import { isElectron } from "./env"; import { startAppServices } from "./appInit"; import { AppRoot } from "./AppRoot"; import { clearChunkReloadGuard, reloadOnceForChunkLoadError } from "./lib/chunkReloadGuard"; +import { captureLazurioPromptLink } from "./lazurio/promptDraft"; + +// Lazurio overlay: take a prompt link off the address before the router reads it. +captureLazurioPromptLink(); const router = startAppServices(); diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx index 8b5d7af3468ab..0153098b3376e 100644 --- a/apps/web/src/routes/_chat.tsx +++ b/apps/web/src/routes/_chat.tsx @@ -9,6 +9,7 @@ import { resolveThreadRouteTarget, type ThreadRouteTarget } from "../threadRoute import { retainThreadFindForRoute } from "../components/chat/threadFindStore"; import { ThreadLinkPrompt } from "../components/promptLinks/ThreadLinkPrompt"; import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; +import { LazurioPromptDraft } from "~/lazurio/LazurioPromptDraft"; function threadRouteTargetKey(target: ThreadRouteTarget | null) { if (!target) return null; @@ -30,6 +31,7 @@ function ChatRouteLayout() { const shownTarget = modalOpen ? backgroundTarget : threadTarget; return ( <> + {shownTarget?.kind === "server" && !modalOpen ? ( ) : null} From 51e7ced9e25b08ded79902ec28f33c5048a69926 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= <16311043+immakermatty@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:51:35 +0000 Subject: [PATCH 06/31] feat(web): Lazurio shell slot index.html loads the Environment's Lazurio shell (/.lazurio/shell.js, served by the Launchpad and absent outside Lazurio) and places its beside #root and after it. #root is padded by the rail's width, T3's fixed-position sidebar is contained beside the rail, and the shell's colour roles derive from T3's own sidebar tokens so the shell follows every T3 theme. SidebarChromeHeader now renders the original top row and, under it, the shell's ; undefined, the element renders nothing. Outside Buddy's bubble the Chat composer keeps the corner of Buddy's launcher free: while the shell draws the launcher, --lazurio-buddy-clearance on the document is the width it takes from the right edge, and the composer stack moves left, then narrows, just enough (LazurioPlatform F60, addendum of 2026-10-25). Unset, the composer stays where T3 puts it. On v0.1.3 both files merge cleanly: the new boot-error screens (#25317, #25345), the Inter font (#24865) and the sidebar footer changes (#25270) do not touch the seams. Settings is now a modal over the thread (#24847) and no longer renders its own column head; the thread and legacy sidebars still do. On v0.1.4: unchanged; the seams apply cleanly. The launcher clearance comes back to this row from row 28's commit, which carried it on v0.1.3. Co-Authored-By: Claude Opus 5.5 --- apps/web/index.html | 68 +++++++++++++++++++ .../src/components/sidebar/SidebarChrome.tsx | 18 ++++- 2 files changed, 84 insertions(+), 2 deletions(-) diff --git a/apps/web/index.html b/apps/web/index.html index a7a5e7450b3de..1f0f410bbc41c 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -669,8 +669,75 @@ } T3 Code (Beta) + + + +
@@ -678,6 +745,7 @@
+ diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index ec161e9998548..e27dacd951674 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -1,6 +1,6 @@ import { ArrowLeftIcon, ChartNoAxesColumnIcon, SettingsIcon } from "lucide-react"; import type { ReactNode } from "react"; -import { memo } from "react"; +import { createElement, memo } from "react"; import { Link, useLocation, useNavigate } from "@tanstack/react-router"; import { useEnvironmentIdentificationMode } from "../../hooks/useSettings"; @@ -31,7 +31,7 @@ import { SidebarUpdateArchitectureWarning, SidebarUpdatePill } from "./SidebarUp import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { observeResize } from "~/lib/observeResize"; -export const SidebarChromeHeader = memo(function SidebarChromeHeader({ +const SidebarChromeTitlebar = memo(function SidebarChromeTitlebar({ isElectron, }: { isElectron: boolean; @@ -76,6 +76,20 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({ ); }); +// Lazurio shell (docs/operations/lazurio-fork-release.md): every sidebar's top row, with its toggle +// and the wordmark, has the column head under it: the Environment picker and the app switch. +// Undefined, the element renders nothing. +export const SidebarChromeHeader = memo(function SidebarChromeHeader(props: { + isElectron: boolean; +}) { + return ( + <> + + {createElement("lazurio-column-head", { active: "chat" })} + + ); +}); + export function SidebarBrandWidthProbe({ onWidthChange, }: { From 9b92af6b83316c1eeae51b6c4b2e907ebe372303 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= <16311043+immakermatty@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:51:46 +0000 Subject: [PATCH 07/31] feat(server): each thread's provider processes get its agent-browser session On a Lazurio Environment every thread's agents work in the shared Environment browser through the agent-browser CLI, each thread in its own window. The CLI takes its session from AGENT_BROWSER_SESSION, so every process T3 starts for a thread carries the thread's session name: agent processes through a decorator around the server's AgentScope, Codex threads through their thread config (one app-server serves every thread), and a thread's terminals through the environment their shells start with. The variable only names the session. On v0.1.3 the three seams apply unchanged. AgentScope gained `stop` and a launch `unit` (#21299); the decorator spreads the inner scope and the launch, so upstream's reaping of an exited agent's systemd scope still receives its unit. The test mocks get `stop`, and the pass-through test now also checks that the decorated scope forwards `stop`. The terminal seam sits above upstream's shortened managed-install comment. Overlay comments are cut to the four-line limit. On v0.1.4: the Claude runner needs PortScanner.PortDiscovery since #22542, so the overlay's Claude test provides PortScanner.layerTest. #23913 only adds Delegate=yes to the agent scope; the AgentScope seam is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/lazurio/agentBrowserSession.test.ts | 674 ++++++++++++++++++ .../server/src/lazurio/agentBrowserSession.ts | 121 ++++ .../Adapters/CodexAdapterV2.test.ts | 22 +- .../Adapters/CodexAdapterV2.ts | 3 + apps/server/src/server.ts | 4 +- apps/server/src/terminal/Manager.ts | 3 + 6 files changed, 825 insertions(+), 2 deletions(-) create mode 100644 apps/server/src/lazurio/agentBrowserSession.test.ts create mode 100644 apps/server/src/lazurio/agentBrowserSession.ts diff --git a/apps/server/src/lazurio/agentBrowserSession.test.ts b/apps/server/src/lazurio/agentBrowserSession.test.ts new file mode 100644 index 0000000000000..514e0da75469d --- /dev/null +++ b/apps/server/src/lazurio/agentBrowserSession.test.ts @@ -0,0 +1,674 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the fake Claude CLI uses Node streams and events +import * as NodeCrypto from "node:crypto"; +import * as NodeEvents from "node:events"; +import * as NodeStream from "node:stream"; + +import type { SpawnedProcess, SpawnOptions } from "@anthropic-ai/claude-agent-sdk"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { + CodexSettings, + EnvironmentId, + ProviderInstanceId, + ProviderSessionId, + ThreadId, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import { AgentScope, type AgentScopeShape } from "@t3tools/shared/AgentScope"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as CodexClient from "effect-codex-app-server/client"; +import * as CodexReplay from "effect-codex-app-server/replay"; +import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import * as Schema from "effect/Schema"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import * as ServerConfig from "../config.ts"; +import * as ClaudeAdapterV2 from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +import * as CodexAdapterV2 from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as PortScanner from "../preview/PortScanner.ts"; +import * as AgentScopeLive from "../process/agentScope.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import { + AGENT_BROWSER_SESSION_ENV, + agentBrowserSessionName, + codexThreadConfig, + decorateAgentScope, + setTerminalSession, +} from "./agentBrowserSession.ts"; + +const threadId = ThreadId.make("4a1f9c2e-7b3d-4e5f-8a6b-9c0d1e2f3a4b"); +const sessionName = "t3-4a1f9c2e-7b3d-4e5f-8a6b-9c0d1e2f3a4b"; +const otherThreadId = ThreadId.make("5b2e0d3f-8c4e-4f6a-9b7c-0d1e2f3a4b5c"); +const otherSessionName = "t3-5b2e0d3f-8c4e-4f6a-9b7c-0d1e2f3a4b5c"; + +const codexSettings = Schema.decodeSync(CodexSettings)({}); +const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", +}); + +describe("agent-browser session name", () => { + it("is t3- and the thread id when the id already fits agent-browser's grammar", () => { + assert.strictEqual(agentBrowserSessionName(threadId), sessionName); + assert.strictEqual(agentBrowserSessionName("under_score-and-dash"), "t3-under_score-and-dash"); + assert.strictEqual(agentBrowserSessionName("x".repeat(61)), `t3-${"x".repeat(61)}`); + }); + + it("keeps a readable start of a sanitized or cut id and never gives two threads one session", () => { + // Imported threads are `import::`, and an instance id + // may take 64 characters: cutting alone would give every such thread the same name. + const longInstance = `codex-${"w".repeat(58)}`; + const ids = [ + "thread.with:colons/and/slashes", + "thread:with:colons:and:slashes", + "thread-with-colons-and-slashes", + "vlákno-č", + "vlákno-ř", + "emoji-\u{1F642}", + "x".repeat(62), + "x".repeat(100), + `import:codex:${threadId}`, + `import:${longInstance}:019a1b2c-3d4e-7f80-9a1b-2c3d4e5f6a70`, + `import:${longInstance}:019a1b2c-3d4e-7f80-9a1b-2c3d4e5f6a71`, + // Two imported ids whose 32-bit FNV-1a suffixes collided (review of Lazurio/t3code#41). + `import:codex-${"w".repeat(58)}:f64cccd6-59c8-42a7-aa0e-319969aeccc9`, + `import:codex-${"w".repeat(58)}:3c4a8834-35dc-418d-a6dd-d8d1934ab83f`, + ]; + const names = ids.map(agentBrowserSessionName); + for (const name of names) assert.match(name, /^t3-[A-Za-z0-9_-]{1,61}$/); + assert.strictEqual(new Set(names).size, ids.length); + // A readable start, then 32 hex digits of the exact id's SHA-256. + assert.match(names[0] ?? "", /^t3-thread-with-colons-and-slash-[0-9a-f]{32}$/); + assert.strictEqual(names[2], "t3-thread-with-colons-and-slashes"); + assert.match(names[7] ?? "", new RegExp(`^t3-${"x".repeat(28)}-[0-9a-f]{32}$`)); + assert.strictEqual( + names[0], + `t3-thread-with-colons-and-slash-${NodeCrypto.createHash("sha256") + .update("thread.with:colons/and/slashes", "utf8") + .digest("hex") + .slice(0, 32)}`, + ); + // The same thread always gets the same session. + assert.deepStrictEqual(ids.map(agentBrowserSessionName), names); + }); +}); + +describe("a thread's terminal", () => { + // The environment the terminal manager built for the thread's shell. + const terminalEnvironment = () => ({ PATH: "/usr/bin", TERM: "xterm-256color" }); + + it("carries the thread's session, the one the thread's agents carry", () => { + const env: NodeJS.ProcessEnv = terminalEnvironment(); + setTerminalSession(env, threadId, "linux"); + assert.deepStrictEqual(env, { + ...terminalEnvironment(), + [AGENT_BROWSER_SESSION_ENV]: sessionName, + }); + // Another thread's terminal has that thread's own, and an imported thread's id is named as + // for its agents. + const imported = `import:codex:${otherThreadId}`; + const other: NodeJS.ProcessEnv = terminalEnvironment(); + setTerminalSession(other, imported, "darwin"); + assert.strictEqual(other[AGENT_BROWSER_SESSION_ENV], agentBrowserSessionName(imported)); + // A session the server inherited never names the thread's terminal. + const inherited: NodeJS.ProcessEnv = { ...terminalEnvironment(), AGENT_BROWSER_SESSION: "x" }; + setTerminalSession(inherited, threadId, "linux"); + assert.strictEqual(inherited[AGENT_BROWSER_SESSION_ENV], sessionName); + }); + + it("leaves the environment of a terminal without a thread, and on Windows, as it is", () => { + for (const thread of [undefined, ""]) { + const env: NodeJS.ProcessEnv = terminalEnvironment(); + setTerminalSession(env, thread, "linux"); + assert.deepStrictEqual(env, terminalEnvironment()); + } + const windows: NodeJS.ProcessEnv = terminalEnvironment(); + setTerminalSession(windows, threadId, "win32"); + assert.deepStrictEqual(windows, terminalEnvironment()); + }); +}); + +/** A directory with an executable `name` in it, removed with the test's scope. */ +const executableIn = (name: string) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "lazurio-agent-bin-" }); + const file = path.join(directory, name); + yield* fileSystem.writeFileString(file, "#!/bin/sh\n"); + yield* fileSystem.chmod(file, 0o755); + return { directory, file }; + }); + +/** An agent scope that returns every launch as it is and records what it was asked. */ +const recordingAgentScope = () => { + const inputs: Array[0]> = []; + const cleared: Array = []; + const shape: AgentScopeShape = { + wrap: (input) => + Effect.sync(() => { + inputs.push(input); + return { command: input.command, args: input.args }; + }), + oomKilled: (thread) => Effect.succeed(thread === "oom-killed-thread"), + stop: () => Effect.void, + clear: (thread) => + Effect.sync(() => { + cleared.push(thread); + }), + }; + return { inputs, cleared, layer: Layer.succeed(AgentScope, shape) }; +}; + +/** The server's AgentScope as server.ts builds it, around `inner`, on `platform`. */ +const decorated = (inner: Layer.Layer, platform: NodeJS.Platform = "linux") => + Effect.service(AgentScope).pipe( + Effect.provide(decorateAgentScope(inner)), + Effect.provideService(HostProcess.Platform, platform), + ); + +describe("the server's agent scope", () => { + it.effect("starts a thread's agent under env with the thread's session", () => + Effect.gen(function* () { + const { directory } = yield* executableIn("pi"); + const inner = recordingAgentScope(); + const scope = yield* decorated(inner.layer); + + const launch = yield* scope.wrap({ + command: "pi", + args: ["--mode", "rpc"], + name: "pi", + threadId, + env: { PATH: directory }, + }); + + assert.deepStrictEqual(launch, { + command: "/usr/bin/env", + args: [`${AGENT_BROWSER_SESSION_ENV}=${sessionName}`, "pi", "--mode", "rpc"], + }); + // The rest of the scope is upstream's. + assert.strictEqual(inner.inputs.length, 1); + assert.isTrue(yield* scope.oomKilled("oom-killed-thread")); + yield* scope.clear(threadId); + assert.deepStrictEqual(inner.cleared, [threadId]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("leaves processes without a thread, Codex's shared app-server and Windows alone", () => + Effect.gen(function* () { + const { directory } = yield* executableIn("agent"); + const inner = recordingAgentScope(); + const launch = { command: "agent", args: ["--serve"] }; + const linux = yield* decorated(inner.layer); + const windows = yield* decorated(inner.layer, "win32"); + + // A terminal or a server of no thread (OpenCode) passes no thread. + assert.deepStrictEqual( + yield* linux.wrap({ ...launch, name: "terminal", env: { PATH: directory } }), + launch, + ); + // A shared process, as upstream marks Codex's app-server, serves every thread of its instance. + assert.deepStrictEqual( + yield* linux.wrap({ + ...launch, + name: "codex", + threadId, + shared: true, + env: { PATH: directory }, + }), + launch, + ); + assert.deepStrictEqual( + yield* windows.wrap({ ...launch, name: "claude", threadId, env: { PATH: directory } }), + launch, + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("passes every other field of upstream's launch, and its stop, through", () => + Effect.gen(function* () { + const { directory } = yield* executableIn("pi"); + // Upstream's `stop` reaps the launch's systemd unit, so the wrapper must keep it. + const unit = "t3code-pi-0000.scope"; + const stopped: Array = []; + const inner: AgentScopeShape = { + wrap: ({ command, args }) => Effect.succeed({ command, args, unit }), + oomKilled: () => Effect.succeed(false), + stop: (stoppedUnit) => + Effect.sync(() => { + stopped.push(stoppedUnit); + }), + clear: () => Effect.void, + }; + const scope = yield* decorated(Layer.succeed(AgentScope, inner)); + + const launch = yield* scope.wrap({ + command: "pi", + args: [], + name: "pi", + threadId, + env: { PATH: directory }, + }); + + assert.strictEqual(launch.command, "/usr/bin/env"); + assert.propertyVal(launch, "unit", unit); + yield* scope.stop(unit); + assert.deepStrictEqual(stopped, [unit]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("leaves a command that does not resolve to fail at spawn as upstream's", () => + Effect.gen(function* () { + const { directory } = yield* executableIn("agent"); + const scope = yield* decorated(recordingAgentScope().layer); + const missing = { command: "missing-agent", args: [], name: "muse", threadId }; + + assert.deepStrictEqual(yield* scope.wrap({ ...missing, env: { PATH: directory } }), { + command: "missing-agent", + args: [], + }); + assert.deepStrictEqual( + yield* scope.wrap({ ...missing, command: `${directory}/missing-agent` }), + { command: `${directory}/missing-agent`, args: [] }, + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("wraps upstream's Linux agent scope, which runs the agent in a systemd scope", () => + Effect.gen(function* () { + const { directory } = yield* executableIn("agent"); + const fileSystem = yield* FileSystem.FileSystem; + for (const tool of ["systemd-run", "systemctl"]) { + yield* fileSystem.writeFileString(`${directory}/${tool}`, ""); + yield* fileSystem.chmod(`${directory}/${tool}`, 0o755); + } + // A user manager that accepts every scope and knows no unit. + const runner = ProcessRunner.ProcessRunner.of({ + run: ({ args }) => + Effect.succeed({ + stdout: args[1] === "show" ? "LoadState=not-found\nActiveState=inactive\n" : "", + stderr: "", + code: ChildProcessSpawner.ExitCode(0), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }), + }); + const upstream = Layer.effect(AgentScope, AgentScopeLive.make); + const scope = yield* decorated(upstream).pipe( + Effect.provideService(ProcessRunner.ProcessRunner, runner), + Effect.provideService(HostProcess.Environment, { + PATH: directory, + XDG_RUNTIME_DIR: "/run/user/1", + }), + ); + + const launch = yield* scope.wrap({ command: "agent", args: [], name: "acp", threadId }); + + assert.strictEqual(launch.command, "/usr/bin/env"); + assert.deepStrictEqual(launch.args.slice(0, 3), [ + `${AGENT_BROWSER_SESSION_ENV}=${sessionName}`, + "/bin/sh", + "-c", + ]); + assert.isTrue(launch.args.some((arg) => arg.startsWith("--unit=t3code-acp-"))); + assert.strictEqual(launch.args.at(-1), `${directory}/agent`); + }).pipe( + Effect.scoped, + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "lazurio-agent-scope-" }).pipe( + Layer.provideMerge(NodeServices.layer), + ), + ), + ), + ); +}); + +const mcpSessionOf = (thread: ThreadId) => ({ + environmentId: EnvironmentId.make("environment-agent-browser"), + threadId: thread, + providerSessionId: `mcp-${thread}`, + providerInstanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + endpoint: "http://127.0.0.1:1/mcp", + authorizationHeader: "Bearer fixture", + browserToolsAvailable: true, +}); + +/** Codex's answer to `thread/start`. */ +const startedThread = (id: number, nativeThreadId: string) => ({ + type: "emit_inbound" as const, + label: `thread/start ${nativeThreadId}`, + frame: { + id, + result: { + thread: { + id: nativeThreadId, + sessionId: nativeThreadId, + forkedFromId: null, + preview: "", + ephemeral: false, + modelProvider: "openai", + createdAt: 1782622440, + updatedAt: 1782622440, + status: { type: "idle" }, + path: `/tmp/${nativeThreadId}.jsonl`, + cwd: "/workspace", + cliVersion: "0.144.0", + source: "vscode", + threadSource: null, + agentNickname: null, + agentRole: null, + gitInfo: null, + name: null, + turns: [], + }, + model: "gpt-5.4", + modelProvider: "openai", + serviceTier: null, + cwd: "/workspace", + instructionSources: [], + approvalPolicy: "on-request", + approvalsReviewer: "user", + sandbox: { type: "workspaceWrite", writableRoots: [], networkAccess: false }, + reasoningEffort: "medium", + }, + }, +}); + +/** The `thread/start` Codex must receive for a thread: its config names the thread's session. */ +const threadStart = (id: number, session: string) => ({ + type: "expect_outbound" as const, + label: `thread/start ${session}`, + frame: { + id, + method: "thread/start", + params: { + config: { + ...CodexAdapterV2.CODEX_THREAD_CONFIG, + "shell_environment_policy.set.AGENT_BROWSER_SESSION": session, + }, + }, + }, +}); + +describe("Codex threads", () => { + it("name their own session in their thread config, and only with a thread's session", () => { + assert.deepStrictEqual(codexThreadConfig(undefined), {}); + assert.deepStrictEqual(codexThreadConfig(mcpSessionOf(threadId)), { + "shell_environment_policy.set.AGENT_BROWSER_SESSION": sessionName, + }); + }); + + it.effect("start their one app-server without any thread's session", () => + Effect.gen(function* () { + const { directory, file } = yield* executableIn("codex"); + const spawned: Array<{ readonly command: string; readonly args: ReadonlyArray }> = []; + // The spawn boundary: what the app-server would start with. Refusing keeps it unstarted. + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) { + spawned.push({ command: command.command, args: command.args }); + } + return Effect.fail( + PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }), + ); + }); + const factory = yield* CodexAdapterV2.CodexAppServerClientFactory.pipe( + Effect.provide( + CodexAdapterV2.layerAppServerClientFactory.pipe( + Layer.provide(decorateAgentScope(recordingAgentScope().layer)), + ), + ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ); + + yield* factory + .open({ + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + threadId, + providerSessionId: ProviderSessionId.make("provider-session-agent-browser"), + runtimePolicy, + settings: { ...codexSettings, binaryPath: file }, + environment: { PATH: directory }, + }) + .pipe(Effect.scoped, Effect.exit); + + assert.deepStrictEqual( + spawned.map((launch) => launch.command), + [file], + ); + assert.notInclude(spawned[0]?.args.join(" "), AGENT_BROWSER_SESSION_ENV); + }).pipe( + Effect.scoped, + Effect.provide(NodeServices.layer), + Effect.provideService(HostProcess.Platform, "linux"), + ), + ); + + it.effect("on one app-server each start a thread that names its own session", () => + Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* mcpSessions.set(mcpSessionOf(threadId)); + yield* mcpSessions.set(mcpSessionOf(otherThreadId)); + // The replay fails the request when a frame differs from the one it expects. + const transcript: CodexReplay.CodexAppServerReplayTranscript = { + provider: "codex", + protocol: "codex.app-server", + version: "0.144.0", + scenario: "lazurio-agent-browser-session", + entries: [ + { + type: "expect_outbound", + label: "initialize", + frame: { + id: 1, + method: "initialize", + params: { + clientInfo: { name: "T3 Code", title: "T3 Code", version: "ignored" }, + capabilities: { + experimentalApi: true, + optOutNotificationMethods: ["turn/diff/updated"], + extensions: { + "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] }, + }, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "initialize", + frame: { + id: 1, + result: { + userAgent: "T3 Code/0.156.1", + codexHome: "/tmp/codex-home", + platformFamily: "unix", + platformOs: "linux", + }, + }, + }, + { type: "expect_outbound", label: "initialized", frame: { method: "initialized" } }, + threadStart(2, sessionName), + startedThread(2, "native-thread-one"), + threadStart(3, otherSessionName), + startedThread(3, "native-thread-two"), + ], + }; + const clientFactory: CodexAdapterV2.CodexAppServerClientFactoryShape = { + open: (input) => + Layer.build(CodexReplay.layerReplay(transcript)).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterOpenSessionError({ + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + providerSessionId: input.providerSessionId, + cause, + }), + ), + Effect.flatMap((context) => + Effect.service(CodexClient.CodexAppServerClient).pipe(Effect.provide(context)), + ), + ), + }; + const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({ + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + settings: codexSettings, + environment: {}, + clientFactory, + crypto: yield* Crypto.Crypto, + fileSystem: yield* FileSystem.FileSystem, + idAllocator: yield* IdAllocator.IdAllocatorV2, + serverConfig: yield* ServerConfig.ServerConfig, + }); + const modelSelection = { + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + model: "gpt-5.4", + }; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-shared"), + modelSelection, + runtimePolicy, + }); + + const first = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); + const second = yield* runtime.ensureThread({ + threadId: otherThreadId, + modelSelection, + runtimePolicy, + }); + + assert.strictEqual(first.nativeThreadRef?.nativeId, "native-thread-one"); + assert.strictEqual(second.nativeThreadRef?.nativeId, "native-thread-two"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + ServerConfig.layerTest(process.cwd(), { prefix: "lazurio-codex-session-" }), + ).pipe(Layer.provideMerge(NodeServices.layer)), + ), + ), + ); +}); + +// Stands in for the Claude CLI behind the SDK's spawn hook: records how it was started and +// answers its control requests. +function makeFakeClaudeCli() { + const spawns: Array = []; + const spawn = (options: SpawnOptions): SpawnedProcess => { + spawns.push(options); + const stdin = new NodeStream.PassThrough(); + const stdout = new NodeStream.PassThrough(); + const child = Object.assign(new NodeEvents.EventEmitter(), { + stdin, + stdout, + killed: false, + exitCode: null as number | null, + kill: () => { + stdout.end(); + child.emit("exit", null, "SIGTERM"); + return true; + }, + }); + let pending = ""; + stdin.on("data", (chunk: Buffer) => { + pending += chunk.toString("utf8"); + for (let end = pending.indexOf("\n"); end >= 0; end = pending.indexOf("\n")) { + const frame = JSON.parse(pending.slice(0, end)); + pending = pending.slice(end + 1); + if (frame.type !== "control_request") continue; + const response = { subtype: "success", request_id: frame.request_id, response: {} }; + stdout.write(`${JSON.stringify({ type: "control_response", response })}\n`); + } + }); + stdin.on("end", () => { + stdout.end(); + child.emit("exit", 0, null); + }); + return child; + }; + return { spawn, spawns }; +} + +/** Opens and closes a Claude Code session of the thread through the server's agent scope. */ +const startClaude = (pathToClaudeCodeExecutable: string, environment: NodeJS.ProcessEnv) => + Effect.gen(function* () { + const cli = makeFakeClaudeCli(); + const runner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner; + const session = yield* runner.open({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-agent-browser"), + options: { + ...ClaudeAdapterV2.makeClaudeQueryOptions({ + modelSelection: { + instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), + model: "claude-sonnet-4-6", + }, + nativeThreadId: "native-thread-claude-agent-browser", + resume: false, + cwd: null, + environment, + }), + pathToClaudeCodeExecutable, + spawnClaudeCodeProcess: cli.spawn, + }, + }); + yield* session.close; + return cli.spawns; + }).pipe( + Effect.provide( + ClaudeAdapterV2.layerQueryRunner.pipe( + Layer.provide(decorateAgentScope(recordingAgentScope().layer)), + Layer.provide(PortScanner.layerTest), + ), + ), + Effect.provideService( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ); + +describe("Claude Code", () => { + it.effect("as a native binary starts with the thread's session", () => + Effect.gen(function* () { + const { directory, file } = yield* executableIn("claude"); + + const spawns = yield* startClaude(file, { PATH: directory }); + + assert.strictEqual(spawns.length, 1); + assert.strictEqual(spawns[0]?.command, "/usr/bin/env"); + assert.deepStrictEqual(spawns[0]?.args.slice(0, 2), [ + `${AGENT_BROWSER_SESSION_ENV}=${sessionName}`, + file, + ]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("through a script entry starts without one: the SDK runs it through node", () => + Effect.gen(function* () { + const spawns = yield* startClaude("/opt/claude/cli.js", { PATH: "/usr/bin" }); + + assert.strictEqual(spawns.length, 1); + assert.notStrictEqual(spawns[0]?.command, "/usr/bin/env"); + assert.isTrue(spawns[0]?.args.includes("/opt/claude/cli.js")); + assert.notInclude(spawns[0]?.args.join(" "), AGENT_BROWSER_SESSION_ENV); + }).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/lazurio/agentBrowserSession.ts b/apps/server/src/lazurio/agentBrowserSession.ts new file mode 100644 index 0000000000000..0f582168eb571 --- /dev/null +++ b/apps/server/src/lazurio/agentBrowserSession.ts @@ -0,0 +1,121 @@ +// @effect-diagnostics nodeBuiltinImport:off -- the session name is a synchronous SHA-256 of the thread id. +/** + * Lazurio overlay (root decision 0191): AGENT_BROWSER_SESSION names a thread's window in the + * Environment browser and its holder-file strip; it permits nothing. It reaches agents through + * AgentScope, Codex through its thread config, terminals through their spawn env; processes not + * started for one thread (OpenCode, Cursor, Grok on Linux, scripted Claude) and Windows get none. + */ + +import * as NodeCrypto from "node:crypto"; + +import type { McpProviderSessionConfig } from "@t3tools/provider-core/server/mcpSession"; +import { AgentScope, type AgentScopeShape } from "@t3tools/shared/AgentScope"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { resolveCommandPath } from "@t3tools/shared/shell"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; + +export const AGENT_BROWSER_SESSION_ENV = "AGENT_BROWSER_SESSION"; + +/** agent-browser accepts [A-Za-z0-9_-] in a session name; its dashboard takes 64 characters. */ +const SESSION_NAME_LIMIT = 64; + +/** Hex digits of the id's SHA-256 kept in a cut or rewritten name. */ +const DIGEST_LENGTH = 32; + +/** SHA-256 of the UTF-8 bytes, as hex. */ +const sha256Hex = (value: string): string => + NodeCrypto.createHash("sha256").update(value, "utf8").digest("hex"); + +/** + * `t3-` and the thread id. An id with characters outside [A-Za-z0-9_-], or too long to fit, has + * them replaced by `-`, is cut, and ends in 32 hex digits (128 bits) of the SHA-256 of the exact + * id, so that two threads never share a session, and with it a window: a shorter, non- + * cryptographic suffix let two imported thread ids of the same instance collide. + */ +export function agentBrowserSessionName(threadId: string): string { + const sanitized = threadId.replace(/[^A-Za-z0-9_-]/g, "-"); + const name = `t3-${sanitized}`; + if (sanitized === threadId && name.length <= SESSION_NAME_LIMIT) return name; + const digest = sha256Hex(threadId).slice(0, DIGEST_LENGTH); + return `${name.slice(0, SESSION_NAME_LIMIT - DIGEST_LENGTH - 1)}-${digest}`; +} + +/** + * The thread's session in the config of its Codex thread (`thread/start`, `thread/resume` and + * `thread/fork`): Codex sets it in the environment of the commands that thread's agent runs, + * which is how agents call agent-browser, xdg-open and `gh auth login --web`. The app-server's + * own process and its MCP servers serve every thread and get none. + */ +export const codexThreadConfig = ( + mcpSession: Pick | undefined, +) => + mcpSession === undefined + ? {} + : { + [`shell_environment_policy.set.${AGENT_BROWSER_SESSION_ENV}`]: agentBrowserSessionName( + mcpSession.threadId, + ), + }; + +/** + * Lazurio/t3code#73: a page a thread's shell opens (`BROWSER`, `xdg-open`) joins the thread's + * strip. Terminals reach the agent scope without their thread, so the session travels in the + * shell's environment instead; without a thread, and on Windows, the environment stays as it is. + */ +export function setTerminalSession( + env: NodeJS.ProcessEnv, + threadId: string | undefined, + platform: NodeJS.Platform, +): void { + if (platform === "win32" || !threadId) return; + env[AGENT_BROWSER_SESSION_ENV] = agentBrowserSessionName(threadId); +} + +const make = Effect.gen(function* () { + const inner = yield* AgentScope; + const platform = yield* HostProcess.Platform; + // `/usr/bin/env` is POSIX; Windows keeps upstream's launch. + if (platform === "win32") return inner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const hostEnvironment = yield* HostProcess.Environment; + const resolves = (command: string, env: NodeJS.ProcessEnv) => + resolveCommandPath(command, { env }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(HostProcess.Platform, platform), + Effect.map((resolved) => resolved !== null), + ); + return { + ...inner, + wrap: Effect.fn("LazurioAgentBrowserSession.wrap")(function* (input) { + const launch = yield* inner.wrap(input); + // A shared process (Codex's app-server) serves every thread of its instance. + if (input.threadId === undefined || input.shared === true) return launch; + // A missing binary keeps failing at spawn, not as `env`'s exit 127. + if (!(yield* resolves(input.command, input.env ?? hostEnvironment))) return launch; + // `env` execs the launch, so the PID, stdio and process group stay the agent's, and any + // other field of the launch passes through. + return { + ...launch, + command: "/usr/bin/env", + args: [ + `${AGENT_BROWSER_SESSION_ENV}=${agentBrowserSessionName(input.threadId)}`, + launch.command, + ...launch.args, + ], + }; + }), + } satisfies AgentScopeShape; +}); + +/** + * The server's AgentScope with each thread's agent processes started under + * `/usr/bin/env AGENT_BROWSER_SESSION=`, around whatever `agentScope` + * returns (on Linux, upstream's systemd scope). + */ +export const decorateAgentScope = (agentScope: Layer.Layer) => + Layer.effect(AgentScope, make).pipe(Layer.provide(agentScope)); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 69fca8c0825b8..8e7b02a9aeabb 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1330,7 +1330,26 @@ describe("CodexAdapterV2 post-settle continuation", () => { nativeThreadId: "launch-mcp-thread", nativeTurnId: "unused", prompt: "unused", - }).slice(0, 5), + }) + .slice(0, 5) + .map((entry) => + entry.type === "expect_outbound" && entry.label === "thread/start" + ? { + ...entry, + frame: { + id: 2, + method: "thread/start", + params: { + config: { + ...CodexAdapterV2.CODEX_THREAD_CONFIG, + // Lazurio overlay (root decision 0191): the thread's agent-browser session. + "shell_environment_policy.set.AGENT_BROWSER_SESSION": `t3-thread-${scenario}`, + }, + }, + }, + } + : entry, + ), }), () => Effect.void, (method, params) => @@ -1350,6 +1369,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { tool_timeout_sec: 3_900, http_headers: { Authorization: "Bearer secret-codex-token" }, }, + "shell_environment_policy.set.AGENT_BROWSER_SESSION": "t3-thread-launch-mcp-servers", }, }, ]); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 58cd4a0c0c17b..d0b409fa700a9 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -120,6 +120,7 @@ import { codexAppServerArgs, resolveCodexLaunchArgs } from "../../provider/codex import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as LazurioAgentBrowserSession from "../../lazurio/agentBrowserSession.ts"; import { MCP_APP_EXTENSION_ID, MCP_APP_MIME_TYPE, @@ -1345,6 +1346,8 @@ function codexThreadRuntimeParams(input: { }, }, }), + // Lazurio overlay (root decision 0191): the thread's agent-browser session. + ...LazurioAgentBrowserSession.codexThreadConfig(mcpSession), }, }; } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 0a04b5e4b21b3..a622d86ec6b26 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -35,6 +35,7 @@ import { import { fixPath } from "./os-jank.ts"; import * as Ws from "./ws.ts"; import * as AgentScopeLive from "./process/agentScope.ts"; +import * as LazurioAgentBrowserSession from "./lazurio/agentBrowserSession.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts"; import * as PullRequestHttp from "./pullRequest/http.ts"; @@ -1108,7 +1109,8 @@ const layerMakeServer = Layer.unwrap( Layer.provide(layerApplicationObservability), Layer.provideMerge(FetchHttpClient.layer), Layer.provide(VcsProcess.layer), - Layer.provideMerge(AgentScopeLive.layer), + // Lazurio overlay (root decision 0191): each thread's agents get its agent-browser session. + Layer.provideMerge(LazurioAgentBrowserSession.decorateAgentScope(AgentScopeLive.layer)), Layer.provideMerge(layerPlatformServices), ); }), diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 4c5229a7bae4f..1bb654e266989 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -61,6 +61,7 @@ import * as Stream from "effect/Stream"; import * as SynchronizedRef from "effect/SynchronizedRef"; import * as ServerConfig from "../config.ts"; +import * as LazurioAgentBrowserSession from "../lazurio/agentBrowserSession.ts"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts"; @@ -2429,6 +2430,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func platform, yield* HostProcess.HomeDirectory, ); + // Lazurio overlay (Lazurio/t3code#73): the thread's agent-browser session. + LazurioAgentBrowserSession.setTerminalSession(terminalEnv, session.threadId, platform); // Append managed install directories so agent commands resolve without shadowing user/system tools. if ( options.managedBinaryCacheDir !== undefined && From 842e51755185c927bb6ef11b4e64885d3b27beda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= <16311043+immakermatty@users.noreply.github.com> Date: Thu, 29 Oct 2026 19:51:49 +0000 Subject: [PATCH 08/31] feat(web): the right panel shows the thread's Environment browser tabs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a Lazurio Environment the web client has no browser of its own: one shared Chromium runs on the Environment, and its view on the gateway shows one remote tab per address. The right panel shows the thread's tabs from the server's list (an event stream from the thread's holder file), each in a frame that stays mounted for instant switching; a new reveal opens the inline panel, a person's × lets go of the tab with Vrátit, and a plain click on a remote-tab link in the chat opens it in the panel. Another Lazurio Environment's tab opens as a tab of its own with a coloured border. Upstream's own server browser stays hidden there because the server omits capabilities.serverBrowser (row 10). The seams are one hook call and one wrapper in ChatView, the strip's title, icon, tooltip and menu in RightPanelTabs, and the surface kind in rightPanelStore. On v0.1.3 RightPanelTabs and rightPanelStore merge cleanly (#25464 moved the tab-list listeners, storage version is still 14). ChatView's only conflict is the import list next to upstream's new preview canvas imports (#25006); the hook call and the wrapper merge cleanly. ChatView now stays mounted, inert, under the Settings and Usage modals (#24847), so the thread's stream and frames stay live there. Overlay comments are cut to the four-line limit and the six effects of LazurioEnvironmentBrowser.tsx (stream, listeners, timer, draft lifecycle) carry justified react-effect-budget suppressions. The row imports LazurioNewTab.tsx and a singletonSurface case of row 13, so it typechecks and its browser tests run only with row 13. On v0.1.4 upstream's workspaceLabel calls surfaceTitle(...) for the focused surface (#25877); the overlay passes that call its frame titles (lazurio.titles) as it does for the tab's title, so a focused Environment browser tab is labelled by its page. Upstream's new Servers panel (#22542) opens a discovered server through openDiscoveredPort into its own preview, which a Lazurio Environment does not have; with the thread's Environment browser the click now opens the server's address as a new tab of that browser, in front (openPageInPanel in lazurio/threadTabs.ts, one line in ThreadServersPanel.tsx). Without a strip (the Environment browser not declared or not yet answered) the click goes to upstream's preview only where the client or the Environment has one (isPreviewAvailableFor); on a Lazurio Environment it says the Environment browser is not available instead of opening a dead preview tab. threadServersPanel.browser.test.tsx checks all three: a click opens an Environment browser surface; without a strip it shows the notice; and without a strip where the client has a preview it leaves the click to upstream's openDiscoveredPort. The tab's view frame carries data-workspace-focus-default, as Nová karta does. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/components/ChatView.tsx | 22 +- apps/web/src/components/RightPanelTabs.tsx | 32 +- .../components/chat/ThreadServersPanel.tsx | 3 + ...LazurioEnvironmentBrowser.browser.test.tsx | 892 +++++++++++++++++ .../src/lazurio/LazurioEnvironmentBrowser.tsx | 584 +++++++++++ apps/web/src/lazurio/browserView.ts | 50 + .../src/lazurio/environmentBrowser.test.ts | 297 ++++++ apps/web/src/lazurio/environmentBrowser.ts | 171 ++++ .../threadServersPanel.browser.test.tsx | 126 +++ .../src/lazurio/threadTabs.browser.test.ts | 609 ++++++++++++ apps/web/src/lazurio/threadTabs.test.ts | 212 ++++ apps/web/src/lazurio/threadTabs.ts | 915 ++++++++++++++++++ apps/web/src/rightPanelStore.ts | 27 +- 13 files changed, 3931 insertions(+), 9 deletions(-) create mode 100644 apps/web/src/lazurio/LazurioEnvironmentBrowser.browser.test.tsx create mode 100644 apps/web/src/lazurio/LazurioEnvironmentBrowser.tsx create mode 100644 apps/web/src/lazurio/browserView.ts create mode 100644 apps/web/src/lazurio/environmentBrowser.test.ts create mode 100644 apps/web/src/lazurio/environmentBrowser.ts create mode 100644 apps/web/src/lazurio/threadServersPanel.browser.test.tsx create mode 100644 apps/web/src/lazurio/threadTabs.browser.test.ts create mode 100644 apps/web/src/lazurio/threadTabs.test.ts create mode 100644 apps/web/src/lazurio/threadTabs.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d6d3e09536070..5551817b47f35 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -158,6 +158,10 @@ import { } from "../rightPanelStore"; import { isPreviewSupportedInRuntime, useThreadPreviewState } from "../previewStateStore"; import { previewRuntimeTabId } from "../browser/previewRuntimeTabId"; +import { + LazurioRightPanelSurfaces, + useLazurioThreadTabs, +} from "../lazurio/LazurioEnvironmentBrowser"; import { ThreadPreviewMiniPlayer, useThreadPreviewCanvasSource, @@ -1037,6 +1041,11 @@ export default function ChatView(props: ChatViewProps) { const canReuseTerminal = activeThreadKnownSessionsRaw !== null; const previewPanelOpen = activeRightPanelKind === "preview" && browserAvailable; const rightPanelOpen = rightPanelState.isOpen; + // Lazurio overlay: the thread's Environment browser tabs in the panel (apps/web/src/lazurio). + useLazurioThreadTabs(activeThreadRef, { + inlinePanel: !shouldUsePlanSidebarSheet, + draft: !isServerThread, + }); const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } = usePanelAnimationSettings(); const rightPanelPresenceValue = { @@ -3094,7 +3103,7 @@ export default function ChatView(props: ChatViewProps) { return ; } - const rightPanelContent = activeThreadRef ? ( + const rightPanelActiveContent = activeThreadRef ? ( ) : null; + // Lazurio overlay: every Environment browser tab of the thread keeps its frame beside the + // surface in view (apps/web/src/lazurio). + const rightPanelContent = activeThreadRef ? ( + + {rightPanelActiveContent} + + ) : null; const panelToggleControlProps = { terminalAvailable: activeProject !== null, terminalOpen: terminalUiState.terminalOpen, diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index dd62a684e92e4..3560bce447efd 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -84,6 +84,7 @@ import { } from "~/state/pullRequests"; import { useEnvironmentQuery } from "~/state/query"; import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; +import * as Lazurio from "~/lazurio/LazurioEnvironmentBrowser"; import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell"; import { FaviconImage } from "./preview/PreviewFaviconIcon"; @@ -195,7 +196,8 @@ type TabContextMenuAction = | "close" | "close-others" | "close-to-right" - | "close-all"; + | "close-all" + | Lazurio.TabMenuAction; const TAB_SCROLL_EDGE_TOLERANCE = 1; const TAB_DRAG_MODIFIERS = [restrictToHorizontalAxis, restrictToFirstScrollableAncestor]; @@ -310,6 +312,8 @@ function RightPanelEmptyState(props: { pullRequestAvailable: boolean; pullRequestsAvailable: boolean; deviceAvailable: boolean; + /** Lazurio overlay: why the Environment browser is not here yet, instead of upstream's line. */ + browserNote: string | null; }) { const [highlight, setHighlight] = useState(-1); @@ -319,7 +323,7 @@ function RightPanelEmptyState(props: { icon: Globe2, shortcut: "B", available: props.browserAvailable, - disabledReason: SURFACE_UNAVAILABLE_HINTS.browser, + disabledReason: props.browserNote ?? SURFACE_UNAVAILABLE_HINTS.browser, onClick: props.onAddBrowser, }, { @@ -526,6 +530,9 @@ function RightPanelEmptyState(props: { ), )} + {props.browserNote === null ? null : ( +

{props.browserNote}

+ )} ); @@ -535,6 +542,7 @@ function surfaceTitle( surface: RightPanelSurface, sessions: Readonly>, terminalLabelsById: ReadonlyMap, + lazurioTitles: Lazurio.FrameTitles, ): string { switch (surface.kind) { case "diff": @@ -556,6 +564,8 @@ function surfaceTitle( return "Pull requests"; case "device": return surface.title ?? surface.target?.name ?? "Device"; + case "environment-browser": + return Lazurio.surfaceTitle(surface, lazurioTitles); case "preview": { const snapshot = surface.resourceId ? sessions[surface.resourceId] : null; if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser"; @@ -644,6 +654,8 @@ function SurfaceIcon({ ); case "pull-requests": return ; + case "environment-browser": + return ; case "device": return surface.target?.platform === "ios" ? ( @@ -909,7 +921,7 @@ function RightPanelTab( title={title} /> ) : ( - title + )} @@ -1066,6 +1078,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { onClick: props.onAddDevice, }, ] as const; + const lazurio = Lazurio.useRightPanel(addSurfaceActions); const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent) => { const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent); @@ -1104,6 +1117,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { }), }); } + items.push(...Lazurio.tabMenuItems(surface)); items.push( { id: "close", label: "Close" }, { @@ -1157,6 +1171,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) { break; case null: break; + default: + Lazurio.runTabMenuAction(action, surface); } }; const handleTabAuxClick = (event: ReactMouseEvent, surface: RightPanelSurface) => { @@ -1227,7 +1243,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { workspaceFocusKey={`panel:${props.environmentId}:${props.activeSurfaceId ?? "empty"}`} workspaceLabel={ focusedSurface - ? `Workspace panel: ${surfaceTitle(focusedSurface, props.previewSessions, props.terminalLabelsById)}` + ? `Workspace panel: ${surfaceTitle(focusedSurface, props.previewSessions, props.terminalLabelsById, lazurio.titles)}` : "Workspace panel" } mode={props.mode} @@ -1271,7 +1287,12 @@ export function RightPanelTabs(props: RightPanelTabsProps) { dragDisabled={!props.onMoveSurface || renamingDevice === surface.id} active={surface.id === props.activeSurfaceId} pending={props.pendingSurfaceIds.has(surface.id)} - title={surfaceTitle(surface, props.previewSessions, props.terminalLabelsById)} + title={surfaceTitle( + surface, + props.previewSessions, + props.terminalLabelsById, + lazurio.titles, + )} audio={tabAudioState( previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null, )} @@ -1446,6 +1467,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { pullRequestAvailable={props.pullRequestAvailable} pullRequestsAvailable={props.pullRequestsAvailable} deviceAvailable={props.deviceAvailable} + browserNote={lazurio.browserNote} /> ) : ( props.children diff --git a/apps/web/src/components/chat/ThreadServersPanel.tsx b/apps/web/src/components/chat/ThreadServersPanel.tsx index 353f6032b6f87..299e38aabd812 100644 --- a/apps/web/src/components/chat/ThreadServersPanel.tsx +++ b/apps/web/src/components/chat/ThreadServersPanel.tsx @@ -21,6 +21,7 @@ import { useEnvironment } from "../../state/environments"; import { previewEnvironment } from "../../state/preview"; import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; +import { openPageInPanel } from "../../lazurio/threadTabs"; import { openDiscoveredPort } from "../preview/openDiscoveredPort"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -74,6 +75,8 @@ export function ThreadServersPanel(props: { .catch((error: unknown) => reportFailure("Unable to open in browser", error)); return; } + // Lazurio overlay: with the Environment browser, the page opens there (lazurio/threadTabs.ts). + if (await openPageInPanel(threadRef, server.url)) return; const result = await openDiscoveredPort({ threadRef, port: server, openPreview }); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { reportFailure("Unable to open preview", squashAtomCommandFailure(result)); diff --git a/apps/web/src/lazurio/LazurioEnvironmentBrowser.browser.test.tsx b/apps/web/src/lazurio/LazurioEnvironmentBrowser.browser.test.tsx new file mode 100644 index 0000000000000..26373a89fe959 --- /dev/null +++ b/apps/web/src/lazurio/LazurioEnvironmentBrowser.browser.test.tsx @@ -0,0 +1,892 @@ +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { type EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; +import type { ReactNode } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { act, fakeTimers, render, stubGlobal } from "../../test/render"; +import { RightPanelTabs } from "../components/RightPanelTabs"; +import { toastManager } from "../components/ui/toast"; +import { dismissContextMenu } from "../contextMenuFallback"; +import { + type RightPanelSurface, + selectThreadRightPanelState, + type ThreadRightPanelState, + useRightPanelStore, +} from "../rightPanelStore"; +import { + ENVIRONMENT_ELEMENT, + LazurioRightPanelSurfaces, + useLazurioThreadTabs, +} from "./LazurioEnvironmentBrowser"; +import { + newTabSurface, + reloadSurface, + rememberTitle, + resetThreadTabs, + syncOf, + tabSurfaceId, + type ThreadTab, + type ThreadTabsSnapshot, + useThreadTabsStore, +} from "./threadTabs"; + +// The threads below are of the page's own environment. +vi.mock(import("../state/environments"), async (original) => ({ + ...(await original()), + usePrimaryEnvironmentId: (() => "env-1") as never, +})); +// The router's route: the chat's hook reads which thread it shows when a thread's view closes. +const route = vi.hoisted(() => ({ + state: { matches: [] as Array<{ readonly params: Record }> }, +})); +vi.mock(import("@tanstack/react-router"), async (original) => ({ + ...(await original()), + useRouter: (() => route) as never, +})); +vi.mock(import("~/hooks/useTheme"), async (original) => ({ + ...(await original()), + useTheme: () => ({ theme: "light", resolvedTheme: "light", themeHalves: null }) as never, +})); +vi.mock(import("~/browser/browserDefaults"), async (original) => ({ + ...(await original()), + useBrowserDefaults: () => ({ profiles: [] }) as never, +})); + +// The page's own view, beside T3 on a Lazurio Environment. The page's origin is the test +// runner's; the cases that depend on it are in environmentBrowser.test.ts. +const viewOrigin = "https://browser.vm-01.example.lazurio.io"; +const id = (n: number) => n.toString(16).toUpperCase().padStart(32, "0"); +const tab = (n: number) => ({ id: tabSurfaceId(id(n)), kind: "environment-browser" }) as const; +const viewOf = (n: number) => `${viewOrigin}/t/${id(n)}`; +const files = { id: "files", kind: "files" } as const; +const threadA = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-A")); +const threadB = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-B")); +// Another Environment's people's view of one of its tabs, where an agent works over SSH. +const foreignId = "fedcba9876543210".repeat(2); +const foreignOrigin = "https://browser.vm-02.acme.lazurio.io"; +const foreignView = `${foreignOrigin}/t/${foreignId}`; +const foreignTab = { + id: `environment-browser:${foreignId}`, + kind: "environment-browser", + view: foreignView, +} as const; + +const snapshot = ( + tabs: ReadonlyArray & { readonly tabId: string }>, + overrides: Partial = {}, +): ThreadTabsSnapshot => ({ + available: true, + epoch: "epoch-1", + revision: 1, + threadId: "thread-A", + strip: "t3-thread-A", + viewOrigin, + tabs: tabs.map((entry) => ({ + view: `${viewOrigin}/t/${entry.tabId}`, + agent: false, + alsoHeldBy: [], + ...entry, + })), + ...overrides, +}); +const panel = (threadRef: ScopedThreadRef = threadA) => + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadRef); +const setPanel = (state: ThreadRightPanelState) => + useRightPanelStore.setState({ byThreadKey: { [scopedThreadKey(threadA)]: state } }); +const withSnapshot = (answer: ThreadTabsSnapshot | null, threadRef: ScopedThreadRef = threadA) => + useThreadTabsStore.setState((state) => ({ + snapshots: { ...state.snapshots, [scopedThreadKey(threadRef)]: answer }, + })); +const showRoute = (params: Record) => { + route.state.matches = [{ params }]; +}; + +/** + * One test's page, from nothing: the stores start empty, the route shows no thread, the server's + * streams are fakes the test emits on, and its POSTs answer with thread A's holder file. + */ +function setup() { + route.state.matches = []; + resetThreadTabs(); + useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} }); + const posted: Array<{ readonly action: string; readonly body: unknown }> = []; + let held: ThreadTab[] = []; + const opened: FakeEventSource[] = []; + class FakeEventSource { + readonly listeners = new Map void>>(); + closed = false; + constructor(readonly url: string) { + opened.push(this); + } + addEventListener(type: string, listener: (event: MessageEvent) => void) { + this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]); + } + close() { + this.closed = true; + } + emit(type: string, data: unknown) { + return act(() => { + for (const listener of this.listeners.get(type) ?? []) { + listener(new MessageEvent(type, { data: JSON.stringify(data) })); + } + }); + } + } + const stubs = new DisposableStack(); + stubs.use(stubGlobal("EventSource", FakeEventSource)); + stubs.use( + stubGlobal("fetch", async (url: string, init: RequestInit) => { + const action = url.split("/").at(-1) ?? ""; + const body = JSON.parse(String(init.body)) as { readonly tabId: string }; + posted.push({ action, body }); + held = + action === "hold" + ? held.some((entry) => entry.tabId === body.tabId) + ? held + : [...held, { tabId: body.tabId, view: "", agent: false, alsoHeldBy: [] }] + : held.filter((entry) => entry.tabId !== body.tabId); + return new Response(JSON.stringify(snapshot(held)), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }), + ); + return { + /** The POSTs the page sent. */ + posted, + /** What thread A's holder file holds from now on. */ + hold: (tabs: ReadonlyArray) => { + held = [...tabs]; + }, + opened, + /** The stream the page opened last. */ + stream: () => { + const source = opened.at(-1); + if (source === undefined) throw new Error("No event stream"); + return source; + }, + [Symbol.dispose]: () => stubs.dispose(), + }; +} + +// The hook reads the route from its mocked useRouter, and nothing else here needs a router. +const renderUi = (ui: ReactNode) => render(ui, { router: false }); + +const settled = async (threadRef: ScopedThreadRef = threadA) => { + const sync = syncOf(threadRef); + let queue: Promise; + do { + queue = sync.queue; + await queue; + } while (queue !== sync.queue); +}; + +/** The panel's content, as ChatView draws it. */ +const surfacesOf = ( + threadRef: ScopedThreadRef, + surfaces: readonly RightPanelSurface[], + activeSurfaceId: string, +) => ( + + {activeSurfaceId === files.id ?

Files in view

: null} +
+); + +function frameOf(container: HTMLElement, view: string): HTMLIFrameElement { + const frame = container.querySelector(`iframe[src="${view}"]`); + if (frame === null) throw new Error(`No frame shows ${view}`); + return frame; +} + +const isHidden = (frame: HTMLIFrameElement) => frame.closest("[inert]") !== null; +const tell = (frame: HTMLIFrameElement, data: unknown, origin = viewOrigin) => + act(() => { + window.dispatchEvent( + new MessageEvent("message", { data, origin, source: frame.contentWindow }), + ); + }); + +describe("the panel's Environment browser frames", () => { + it("stay mounted while the panel shows the thread, only the active one in view", async () => { + using _page = setup(); + withSnapshot(snapshot([{ tabId: id(1) }, { tabId: id(2) }])); + const surfaces = [tab(1), files, tab(2)]; + await using screen = await renderUi(surfacesOf(threadA, surfaces, tab(1).id)); + const [first, second] = [ + frameOf(screen.container, viewOf(1)), + frameOf(screen.container, viewOf(2)), + ]; + expect([isHidden(first), isHidden(second)]).toEqual([false, true]); + await screen.rerender(surfacesOf(threadA, surfaces, tab(2).id)); + expect([frameOf(screen.container, viewOf(1)), frameOf(screen.container, viewOf(2))]).toEqual([ + first, + second, + ]); + expect([isHidden(first), isHidden(second)]).toEqual([true, false]); + // Another kind of surface in view: both frames stay, both hidden. + await screen.rerender(surfacesOf(threadA, surfaces, files.id)); + expect(screen.container.textContent).toContain("Files in view"); + expect([isHidden(first), isHidden(second)]).toEqual([true, true]); + // Closing a tab ends its frame and keeps the others. + await screen.rerender(surfacesOf(threadA, [tab(1), files], files.id)); + expect(screen.container.querySelectorAll("iframe")).toHaveLength(1); + // Another thread's panel has frames of its own. + withSnapshot(snapshot([{ tabId: id(1) }]), threadB); + await screen.rerender(surfacesOf(threadB, [tab(1)], tab(1).id)); + expect(frameOf(screen.container, viewOf(1))).not.toBe(first); + }); + + it("wait for the server's view origin, and say when the Environment offers no browser", async () => { + using _page = setup(); + await using screen = await renderUi(surfacesOf(threadA, [tab(1)], tab(1).id)); + expect(screen.container.querySelector("iframe")).toBeNull(); + expect(screen.container.textContent).not.toContain("Browser unavailable"); + await act(() => withSnapshot(null)); + expect(screen.container.textContent).toBe( + "Browser unavailableThis Environment does not offer its browser now. Its tabs come back when it does.", + ); + }); + + it("say it in Czech where the browser is Czech", async () => { + using _page = setup(); + using _czech = vi.spyOn(window.navigator, "language", "get").mockReturnValue("cs-CZ"); + withSnapshot(null); + await using screen = await renderUi(surfacesOf(threadA, [tab(1)], tab(1).id)); + expect(screen.container.textContent).toBe( + "Prohlížeč není k dispoziciToto Prostředí teď prohlížeč nenabízí. Jeho záložky se vrátí, až ho zase nabídne.", + ); + }); + + it("leave the desktop app's panel as it is", async () => { + using _page = setup(); + using _desktop = stubGlobal("desktopBridge", { preview: {} }); + await using screen = await renderUi(surfacesOf(threadA, [tab(1), files], files.id)); + expect(screen.container.querySelectorAll("iframe")).toHaveLength(0); + expect(screen.container.innerHTML).toBe("

Files in view

"); + }); + + it("take the title a frame tells, hold a page's new tab in front or behind, and drop a tab that ended", async () => { + using page = setup(); + const listed = snapshot([{ tabId: id(1) }, { tabId: id(2) }]); + page.hold(listed.tabs); + withSnapshot(listed); + setPanel({ isOpen: true, activeSurfaceId: tab(1).id, surfaces: [tab(1), tab(2)] }); + await using screen = await renderUi(surfacesOf(threadA, [tab(1), tab(2)], tab(1).id)); + await tell(frameOf(screen.container, viewOf(1)), { + type: "lazurio-browser:info", + url: "https://example.com/docs", + title: "Docs", + view: viewOf(1), + }); + expect(useThreadTabsStore.getState().titles[tab(1).id]).toBe("Docs"); + // From the hidden tab: it joins the panel behind the tab in view. + await tell(frameOf(screen.container, viewOf(2)), { + type: "lazurio-browser:new-tab", + view: viewOf(3), + url: "x", + }); + expect(panel()).toEqual({ + isOpen: true, + activeSurfaceId: tab(1).id, + surfaces: [tab(1), tab(2), tab(3)], + }); + // From the tab in view: in front, as in the person's browser. + await tell(frameOf(screen.container, viewOf(1)), { + type: "lazurio-browser:new-tab", + view: viewOf(4), + url: "x", + }); + expect(panel().activeSurfaceId).toBe(tab(4).id); + await settled(); + expect( + page.posted.map((entry) => [entry.action, (entry.body as { tabId: string }).tabId]), + ).toEqual([ + ["hold", id(3)], + ["hold", id(4)], + ]); + // A tab that ended leaves at once and is let go of; an older snapshot does not bring it back. + page.posted.length = 0; + await tell(frameOf(screen.container, viewOf(2)), { + type: "lazurio-browser:closed", + view: viewOf(2), + }); + expect(panel().surfaces.map((surface) => surface.id)).not.toContain(tab(2).id); + await settled(); + expect(page.posted).toEqual([ + { action: "release", body: { threadId: "thread-A", tabId: id(2) } }, + ]); + }); + + it("ignore messages from another window, another origin, or another type", async () => { + using page = setup(); + withSnapshot(snapshot([{ tabId: id(1) }])); + setPanel({ isOpen: true, activeSurfaceId: tab(1).id, surfaces: [tab(1)] }); + await using screen = await renderUi(surfacesOf(threadA, [tab(1)], tab(1).id)); + const newTab = { type: "lazurio-browser:new-tab", view: viewOf(3), url: "x" }; + await act(() => { + window.dispatchEvent( + new MessageEvent("message", { data: newTab, origin: viewOrigin, source: window }), + ); + }); + await tell(frameOf(screen.container, viewOf(1)), newTab, "https://evil.example"); + await tell(frameOf(screen.container, viewOf(1)), { ...newTab, type: "lazurio-browser:open" }); + expect(panel().surfaces).toEqual([tab(1)]); + expect(page.posted).toEqual([]); + }); + + it("show only the view: no head row above it, and no line about a shared tab", async () => { + using _page = setup(); + withSnapshot( + snapshot([ + { + tabId: id(1), + agent: true, + alsoHeldBy: [ + { strip: "launchpad", label: "Launchpad" }, + { strip: "t3-thread-B", label: "Web shop" }, + ], + }, + ]), + ); + await using screen = await renderUi(surfacesOf(threadA, [tab(1)], tab(1).id)); + // The view's own bar is the panel's only toolbar; the strip's dot and tooltip say the rest. + expect(frameOf(screen.container, viewOf(1)).title).toBe("Environment browser"); + expect(screen.container.querySelectorAll("button, a, [role='note']")).toHaveLength(0); + expect(screen.container.textContent).toBe(""); + }); + + it("name their frames in Czech for assistive technology where the browser is Czech", async () => { + using _page = setup(); + using _czech = vi.spyOn(window.navigator, "language", "get").mockReturnValue("cs-CZ"); + withSnapshot(snapshot([{ tabId: id(1) }])); + await using screen = await renderUi(surfacesOf(threadA, [tab(1), foreignTab], tab(1).id)); + expect(frameOf(screen.container, viewOf(1)).title).toBe("Prohlížeč Prostředí"); + expect(frameOf(screen.container, foreignView).title).toBe("Prohlížeč jiného Prostředí"); + }); + + it("make a fresh frame of a tab reloaded through the store, also of one behind the tab in view", async () => { + using _page = setup(); + withSnapshot(snapshot([{ tabId: id(1) }, { tabId: id(2) }])); + await using screen = await renderUi(surfacesOf(threadA, [tab(1), tab(2)], tab(1).id)); + const [first, second] = [ + frameOf(screen.container, viewOf(1)), + frameOf(screen.container, viewOf(2)), + ]; + await act(() => reloadSurface(tab(2).id)); + expect(frameOf(screen.container, viewOf(1))).toBe(first); + expect(frameOf(screen.container, viewOf(2))).not.toBe(second); + expect(isHidden(frameOf(screen.container, viewOf(2)))).toBe(true); + }); +}); + +describe("another Environment's browser in the panel", () => { + const signInNotice = "Sign in to this Environment's browser"; + + it("frames it inside a coloured border, leaves naming it to its view's bar, and tells it only this page's origin", async () => { + using _page = setup(); + withSnapshot(snapshot([{ tabId: id(1) }])); + await using screen = await renderUi(surfacesOf(threadA, [tab(1), foreignTab], foreignTab.id)); + const foreign = frameOf(screen.container, foreignView); + expect(foreign.getAttribute("referrerpolicy")).toBe("origin"); + expect(foreign.title).toBe("Another Environment's browser"); + // Marked as that Environment's by its border; this Environment's tab has none. + expect(foreign.closest(".border-warning")).not.toBeNull(); + expect(frameOf(screen.container, viewOf(1)).closest(".border-warning")).toBeNull(); + // No head: the view's own bar names that Environment, as its switcher does. + expect(screen.container.querySelector(ENVIRONMENT_ELEMENT)).toBeNull(); + expect(screen.container.querySelectorAll("button, a")).toHaveLength(0); + expect(screen.container.textContent).toBe(""); + expect(frameOf(screen.container, viewOf(1)).title).toBe("Environment browser"); + }); + + it("asks the person to sign in there where its view does not come up, naming that Environment", async () => { + using _page = setup(); + // The frame's first wait starts as it mounts. + using _timers = fakeTimers(); + await using screen = await renderUi(surfacesOf(threadA, [foreignTab], foreignTab.id)); + const notice = () => screen.container.textContent?.includes(signInNotice) ?? false; + await act(() => { + frameOf(screen.container, foreignView).dispatchEvent(new Event("load")); + }); + await act(() => vi.advanceTimersByTime(3_999)); + expect(notice()).toBe(false); + await act(() => vi.advanceTimersByTime(1)); + expect(notice()).toBe(true); + // The shell's element names that Environment above the notice's title, as that Environment's + // switcher does; until the shell knows it (or without the element), it says only that the + // browser is another Environment's. The fork has no naming rule of its own. + const name = screen.container.querySelector(ENVIRONMENT_ELEMENT); + expect(name?.getAttribute("environment")).toBe("vm-02.acme"); + expect(name?.getAttribute("lang")).toBe("en"); + expect(name?.textContent).toBe("Another Environment's browser"); + expect(screen.container.textContent).toContain(`Another Environment's browser${signInNotice}`); + expect(screen.container.textContent).not.toContain("Acme · vm-02"); + expect(screen.container.querySelector("img")).toBeNull(); + const before = frameOf(screen.container, foreignView); + const reload = [...screen.container.querySelectorAll("button")].find( + (button) => button.textContent === "Reload", + ); + await act(() => reload?.click()); + expect(frameOf(screen.container, foreignView)).not.toBe(before); + expect(notice()).toBe(false); + // Its view comes up after all and tells its tab: no notice. + await tell( + frameOf(screen.container, foreignView), + { + type: "lazurio-browser:info", + url: "https://example.com/", + title: "Example", + view: foreignView, + }, + foreignOrigin, + ); + await act(() => vi.advanceTimersByTime(60_000)); + expect(notice()).toBe(false); + expect(screen.container.querySelector(ENVIRONMENT_ELEMENT)).toBeNull(); + }); +}); + +const closes = ["Close", "Close others", "Close to the right", "Close all"]; +const noop = () => undefined; + +/** One test's strip of the thread the chat shows (as ChatView's hook sets it), with titles its + * frames told. */ +function setupStrip() { + const page = setup(); + useThreadTabsStore.setState({ inView: threadA }); + rememberTitle(tab(1).id, "Docs"); + rememberTitle(tab(2).id, "Shop"); + rememberTitle(foreignTab.id, "Report"); + return { + page, + [Symbol.dispose]: () => { + dismissContextMenu(); + page[Symbol.dispose](); + }, + }; +} + +/** Upstream's strip over the panel's frames, as ChatView draws them. */ +const strip = (surfaces: readonly RightPanelSurface[], activeSurfaceId: string) => ( + ({ + terminalFocus: false, + terminalOpen: false, + previewFocus: false, + previewOpen: false, + isWeb: true, + isDesktop: false, + })} + surfaces={surfaces} + environmentId={null} + activeSurfaceId={activeSurfaceId} + pendingSurfaceIds={new Set()} + previewSessions={{}} + desktopByTabId={{}} + terminalLabelsById={new Map()} + onActivate={noop} + onCloseSurface={noop} + onCloseOtherSurfaces={noop} + onCloseSurfacesToRight={noop} + onCloseAllSurfaces={noop} + onCopyFilePath={noop} + onAddBrowser={noop} + onAddBrowserInProfile={noop} + onAddTerminal={noop} + onAddPullRequest={noop} + onAddPullRequests={noop} + onAddDiff={noop} + onAddFiles={noop} + onAddDevice={noop} + browserAvailable={false} + terminalAvailable + diffAvailable={false} + filesAvailable + pullRequestAvailable={false} + pullRequestsAvailable={false} + deviceAvailable + > + + {null} + + +); + +const stripTab = (container: HTMLElement, title: string) => { + const element = [...container.querySelectorAll("[data-active-tab]")].find( + (entry) => entry.textContent === title, + ); + if (element === undefined) throw new Error(`The strip has no tab ${title}`); + return element; +}; + +/** Right-clicks the strip's tab titled `title`: its menu's items. */ +async function openMenu(container: HTMLElement, title: string) { + const element = stripTab(container, title); + await act(() => { + element.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true })); + }); + return vi.waitFor(() => { + const items = [...document.body.querySelectorAll('[data-level="0"] button')]; + expect(items).not.toHaveLength(0); + return items; + }); +} +const said = (items: readonly HTMLButtonElement[]) => + items.map((item) => `${item.textContent}${item.disabled ? " (unavailable)" : ""}`); +// The menu takes a choice from the frame after it opens, as after a person's right-click, so the +// click repeats until the menu closes on it. +const choose = (items: readonly HTMLButtonElement[], label: string) => + act(() => + vi.waitFor(() => { + const item = items.find((entry) => entry.textContent === label); + item?.click(); + expect(item?.isConnected).toBe(false); + }), + ); + +describe("the strip tab's title and tooltip", () => { + it("titles a tab with what its frame tells, and its tooltip adds an agent at work and the places that hold it", async () => { + using _strip = setupStrip(); + rememberTitle(tab(1).id, null); + withSnapshot( + snapshot([ + { tabId: id(1), agent: true, alsoHeldBy: [{ strip: "launchpad", label: "Launchpad" }] }, + ]), + ); + await using screen = await renderUi(strip([tab(1), files], tab(1).id)); + // The compiled strip memoizes its tabs by their inputs: the frame's title must reach it. + expect(stripTab(screen.container, "Browser")).toBeDefined(); + await tell(frameOf(screen.container, viewOf(1)), { + type: "lazurio-browser:info", + url: "https://example.com/docs", + title: "Docs", + view: viewOf(1), + }); + const docs = stripTab(screen.container, "Docs"); + expect(docs.querySelector('[aria-label="Close Docs"]')).not.toBeNull(); + await userEvent.hover(docs.querySelector("span.truncate")!); + await expect + .poll(() => document.querySelector('[data-slot="tooltip-popup"][data-open]')?.textContent, { + timeout: 3_000, + }) + .toBe("Docs · an agent works here · shared, also in Apps"); + }); +}); + +describe("the strip tab's menu", () => { + it("offers Open in new tab and Reload for an Environment browser tab, before upstream's closes", async () => { + using _strip = setupStrip(); + withSnapshot(snapshot([{ tabId: id(1) }])); + await using screen = await renderUi( + strip([tab(1), foreignTab, newTabSurface(), files], tab(1).id), + ); + expect(said(await openMenu(screen.container, "Docs"))).toEqual([ + "Open in new tab", + "Reload", + ...closes, + ]); + dismissContextMenu(); + expect(said(await openMenu(screen.container, "Report"))).toEqual([ + "Open in new tab", + "Reload", + ...closes, + ]); + }); + + it("offers only upstream's items for Nová karta and upstream's own surfaces", async () => { + using _strip = setupStrip(); + withSnapshot(snapshot([{ tabId: id(1) }])); + await using screen = await renderUi(strip([newTabSurface(), files, tab(1)], tab(1).id)); + expect(said(await openMenu(screen.container, "New tab"))).toEqual(closes); + dismissContextMenu(); + expect(said(await openMenu(screen.container, "Files"))).toEqual(closes); + }); + + it("offers neither while the tab has no view address", async () => { + using _strip = setupStrip(); + // Before the server's first answer, and where this Environment offers no browser. + await using screen = await renderUi(strip([tab(1), files], files.id)); + const unavailable = ["Open in new tab (unavailable)", "Reload (unavailable)", ...closes]; + expect(said(await openMenu(screen.container, "Docs"))).toEqual(unavailable); + dismissContextMenu(); + await act(() => withSnapshot(null)); + expect(said(await openMenu(screen.container, "Docs"))).toEqual(unavailable); + }); + + it("opens the tab's view in a new tab of the person's browser", async () => { + using _strip = setupStrip(); + withSnapshot(snapshot([{ tabId: id(1) }])); + await using screen = await renderUi(strip([tab(1), foreignTab], tab(1).id)); + using open = vi.spyOn(window, "open").mockReturnValue(null); + await choose(await openMenu(screen.container, "Docs"), "Open in new tab"); + await choose(await openMenu(screen.container, "Report"), "Open in new tab"); + expect(open.mock.calls).toEqual([ + [viewOf(1), "_blank", "noopener"], + [foreignView, "_blank", "noopener"], + ]); + }); + + it("reloads the tab's frame, also of a tab behind the one in view", async () => { + using _strip = setupStrip(); + withSnapshot(snapshot([{ tabId: id(1) }, { tabId: id(2) }])); + await using screen = await renderUi(strip([tab(1), tab(2)], tab(1).id)); + const [first, second] = [ + frameOf(screen.container, viewOf(1)), + frameOf(screen.container, viewOf(2)), + ]; + await choose(await openMenu(screen.container, "Shop"), "Reload"); + expect(frameOf(screen.container, viewOf(2))).not.toBe(second); + expect(isHidden(frameOf(screen.container, viewOf(2)))).toBe(true); + expect(frameOf(screen.container, viewOf(1))).toBe(first); + await choose(await openMenu(screen.container, "Docs"), "Reload"); + expect(frameOf(screen.container, viewOf(1))).not.toBe(first); + }); +}); + +describe("the chat's hook", () => { + function Chat(props: { + readonly threadRef: ScopedThreadRef; + readonly inlinePanel?: boolean; + readonly draft?: boolean; + }) { + useLazurioThreadTabs(props.threadRef, { + inlinePanel: props.inlinePanel ?? true, + draft: props.draft ?? false, + }); + return ( +
+ ); + } + /** The chat of a thread, on the route that shows it. */ + const chatOn = (threadRef: ScopedThreadRef, inlinePanel = true) => { + showRoute({ environmentId: threadRef.environmentId, threadId: threadRef.threadId }); + return ; + }; + + it("follows the thread's list from the server's stream, and closes it with the view", async () => { + using page = setup(); + await using screen = await renderUi(chatOn(threadA)); + expect(page.stream().url).toBe("/api/lazurio/thread-tabs/events?threadId=thread-A"); + expect(useThreadTabsStore.getState().inView).toEqual(threadA); + await page.stream().emit("snapshot", snapshot([{ tabId: id(1) }, { tabId: id(2) }])); + expect(panel()).toMatchObject({ surfaces: [tab(1), tab(2)], isOpen: false }); + await page.stream().emit("snapshot", snapshot([{ tabId: id(2) }])); + expect(panel().surfaces).toEqual([tab(2)]); + // Unavailable leaves the strip as it is. + await page.stream().emit("snapshot", { available: false }); + expect(panel().surfaces).toEqual([tab(2)]); + const source = page.stream(); + await screen.rerender(

Elsewhere

); + expect(source.closed).toBe(true); + expect(useThreadTabsStore.getState().inView).toBeNull(); + }); + + it("opens no stream for a draft, and follows the thread once its first message makes it one", async () => { + using page = setup(); + // The draft keeps its ref when it becomes a thread (ChatView's promotion is data-driven). + await using screen = await renderUi(); + expect(page.opened).toHaveLength(0); + expect(useThreadTabsStore.getState().draftInView).toEqual(threadA); + expect(useThreadTabsStore.getState().inView).toBeNull(); + await screen.rerender(); + expect(page.stream().url).toBe("/api/lazurio/thread-tabs/events?threadId=thread-A"); + expect(useThreadTabsStore.getState().draftInView).toBeNull(); + expect(useThreadTabsStore.getState().inView).toEqual(threadA); + await page.stream().emit("snapshot", snapshot([{ tabId: id(1) }])); + expect(panel().surfaces).toEqual([tab(1)]); + // Another draft in view takes the line; leaving it clears it. + await screen.rerender(); + expect(useThreadTabsStore.getState().draftInView).toEqual(threadB); + await screen.rerender(

Elsewhere

); + expect(useThreadTabsStore.getState().draftInView).toBeNull(); + }); + + it("asks nothing for a thread of another environment, or in the desktop app", async () => { + using page = setup(); + await using screen = await renderUi( + chatOn(scopeThreadRef("env-2" as EnvironmentId, ThreadId.make("thread-C"))), + ); + expect(page.opened).toHaveLength(0); + using _desktop = stubGlobal("desktopBridge", { preview: {} }); + await screen.rerender(chatOn(threadA)); + expect(page.opened).toHaveLength(0); + }); + + it("opens the inline panel on a tab an agent revealed after the baseline, never a sheet", async () => { + using page = setup(); + await using screen = await renderUi(chatOn(threadA)); + await page + .stream() + .emit("snapshot", snapshot([{ tabId: id(1), revealRequest: { id: "epoch-1:1" } }])); + expect(panel().isOpen).toBe(false); + await page.stream().emit( + "snapshot", + snapshot([ + { tabId: id(1), revealRequest: { id: "epoch-1:1" } }, + { tabId: id(2), revealRequest: { id: "epoch-1:2" } }, + ]), + ); + expect(panel()).toMatchObject({ isOpen: true, activeSurfaceId: tab(2).id }); + await act(() => useRightPanelStore.getState().close(threadA)); + await screen.rerender(chatOn(threadA, false)); + await page + .stream() + .emit("snapshot", snapshot([{ tabId: id(2), revealRequest: { id: "epoch-1:3" } }])); + expect(panel().isOpen).toBe(false); + }); + + it("opens the panel on a page revealed while the thread's view was closed, unless the person left the thread", async () => { + using page = setup(); + await using screen = await renderUi(chatOn(threadA)); + await page.stream().emit("snapshot", snapshot([])); + // The view closes and opens again while the route still shows the thread (ChatView mounting + // anew), and the agent reveals a page in between: the new stream's first snapshot opens it. + const first = page.stream(); + await screen.rerender(

Loading

); + expect(first.closed).toBe(true); + await screen.rerender(chatOn(threadA)); + await page + .stream() + .emit("snapshot", snapshot([{ tabId: id(1), revealRequest: { id: "epoch-1:1" } }])); + expect(panel()).toMatchObject({ isOpen: true, activeSurfaceId: tab(1).id }); + // The person closes the panel and goes to Settings, and the agent reveals a page meanwhile. + // Back on the thread, its first snapshot is a baseline: the panel stays closed. + await act(() => useRightPanelStore.getState().close(threadA)); + showRoute({}); + await screen.rerender(

Settings

); + await screen.rerender(chatOn(threadA)); + await page + .stream() + .emit("snapshot", snapshot([{ tabId: id(1), revealRequest: { id: "epoch-1:2" } }])); + expect(panel().isOpen).toBe(false); + }); + + it("adds another Environment's tab the server announces, in front when revealed", async () => { + using page = setup(); + await using _screen = await renderUi(chatOn(threadA)); + await page.stream().emit("snapshot", snapshot([])); + await page.stream().emit("foreign", { tabId: foreignId.toUpperCase(), view: foreignView }); + expect(panel()).toMatchObject({ isOpen: false, surfaces: [foreignTab] }); + await page + .stream() + .emit("foreign", { tabId: foreignId, view: foreignView, revealRequest: { id: "e:1" } }); + expect(panel()).toEqual({ + isOpen: true, + activeSurfaceId: foreignTab.id, + surfaces: [foreignTab], + }); + await act(() => useRightPanelStore.getState().closeSurface(threadA, foreignTab.id)); + await page + .stream() + .emit("foreign", { tabId: foreignId, view: foreignView, revealRequest: { id: "e:2" } }); + expect(panel()).toEqual({ + isOpen: true, + activeSurfaceId: foreignTab.id, + surfaces: [foreignTab], + }); + expect(page.posted).toEqual([]); + }); + + it("lets go of tabs the person closes in the strip, one toast for Close all, nothing for the list's own changes", async () => { + using page = setup(); + await using _screen = await renderUi(chatOn(threadA)); + using toasts = vi.spyOn(toastManager, "add"); + const listed = snapshot([ + { tabId: id(1), agent: true }, + { tabId: id(2), alsoHeldBy: [{ strip: "launchpad", label: "Launchpad" }] }, + { tabId: id(3) }, + ]); + page.hold(listed.tabs); + await page.stream().emit("snapshot", listed); + await act(() => useRightPanelStore.getState().activateSurface(threadA, tab(1).id)); + await act(() => useRightPanelStore.getState().closeSurface(threadA, tab(1).id)); + await settled(); + expect(page.posted).toEqual([ + { action: "release", body: { threadId: "thread-A", tabId: id(1) } }, + ]); + expect(toasts.mock.calls.at(-1)?.[0]).toMatchObject({ + title: "The tab left this thread.", + description: "An agent works in it, so it stays open.", + }); + // Close all closes one surface at a time: one toast that restores all. + page.posted.length = 0; + toasts.mockClear(); + await act(() => { + for (const surface of panel().surfaces) { + useRightPanelStore.getState().closeSurface(threadA, surface.id); + } + }); + await settled(); + expect(toasts).toHaveBeenCalledTimes(1); + expect(page.posted.map((entry) => (entry.body as { tabId: string }).tabId).sort()).toEqual([ + id(2), + id(3), + ]); + const undo = toasts.mock.calls[0]?.[0].actionProps as { onClick: () => void } | undefined; + await act(() => undo?.onClick()); + expect(panel().surfaces).toEqual([tab(2), tab(3)]); + // A tab the list lost leaves without a word. + await settled(); + page.posted.length = 0; + toasts.mockClear(); + await page.stream().emit("snapshot", snapshot([{ tabId: id(2) }])); + await act(() => undefined); + expect(toasts).not.toHaveBeenCalled(); + expect(page.posted).toEqual([]); + }); + + it("opens a link to one remote tab in the panel on a plain click, held, and leaves other clicks alone", async () => { + using page = setup(); + await using screen = await renderUi(chatOn(threadA)); + await page.stream().emit("snapshot", snapshot([])); + const [agentTab, foreignLink, outside] = [...screen.container.querySelectorAll("a")]; + // What the browser would follow: every click the panel leaves alone, never followed here. + let followed: string | null = null; + const follow = (event: MouseEvent) => { + followed = (event.target as HTMLAnchorElement).href; + event.preventDefault(); + }; + document.addEventListener("click", follow); + using _follow = { [Symbol.dispose]: () => document.removeEventListener("click", follow) }; + const click = async (link: HTMLAnchorElement | undefined, init: MouseEventInit = {}) => { + followed = null; + await act(() => { + link?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, ...init })); + }); + return followed; + }; + for (const gesture of [ + { ctrlKey: true }, + { metaKey: true }, + { shiftKey: true }, + { altKey: true }, + ]) { + expect(await click(agentTab, gesture)).toBe(viewOf(7)); + } + expect(await click(outside)).toBe("https://example.com/"); + expect(await click(agentTab)).toBeNull(); + expect(panel()).toEqual({ isOpen: true, activeSurfaceId: tab(7).id, surfaces: [tab(7)] }); + await settled(); + expect(page.posted).toEqual([{ action: "hold", body: { threadId: "thread-A", tabId: id(7) } }]); + expect(await click(foreignLink)).toBeNull(); + expect(panel().activeSurfaceId).toBe(foreignTab.id); + }); +}); diff --git a/apps/web/src/lazurio/LazurioEnvironmentBrowser.tsx b/apps/web/src/lazurio/LazurioEnvironmentBrowser.tsx new file mode 100644 index 0000000000000..67568f180aaad --- /dev/null +++ b/apps/web/src/lazurio/LazurioEnvironmentBrowser.tsx @@ -0,0 +1,584 @@ +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import type { ContextMenuItem, ScopedThreadRef } from "@t3tools/contracts"; +import { ExternalLink, Globe2, LogIn, Plus } from "lucide-react"; +import { type AnyRouter, useRouter } from "@tanstack/react-router"; +import { createElement, type ReactNode, useEffect, useRef, useState } from "react"; + +import { Button } from "~/components/ui/button"; +import { + Empty, + EmptyContent, + EmptyDescription, + EmptyHeader, + EmptyMedia, + EmptyTitle, +} from "~/components/ui/empty"; +import { RefreshIcon } from "~/components/ui/refresh-icon"; +import { cn } from "~/lib/utils"; +import { isPreviewSupportedInRuntime } from "../previewStateStore"; +import { type RightPanelSurface, useRightPanelStore } from "../rightPanelStore"; +import { usePrimaryEnvironmentId } from "../state/environments"; +import type { LazurioBrowserView } from "./browserView"; +import { + type ForeignEnvironmentBrowserTab, + foreignEnvironmentBrowserTab, + isPlainPrimaryClick, + readEnvironmentBrowserMessage, + viewEnvironmentId, +} from "./environmentBrowser"; +import { NewTabSurface, type SurfaceAction, useNewTab, useNewTabDefined } from "./LazurioNewTab"; +import { + type ClosedTabs, + draftBrowserNote, + type EnvironmentBrowserSurface, + enterDraft, + enterThreadTabs, + isNewTabSurface, + leaveDraft, + leaveThreadTabs, + letGoOfTabs, + openLinkInPanel, + parseForeignTab, + parseThreadTabsAnswer, + prefersCzech, + receiveForeign, + receiveSnapshot, + reloadSurface, + rememberTitle, + routeShowsThread, + showForeignTab, + showOwnTab, + snapshotOf, + syncOf, + tabEnded, + tabIdOfSurface, + tabSurfaceId, + tabTooltip, + type ThreadTab, + type ThreadTabsSnapshot, + THREAD_TABS_ROUTE, + useThreadTabsStore, +} from "./threadTabs"; + +// RightPanelTabs reaches the overlay through this one module: Nová karta is LazurioNewTab.tsx's. +export { NewTab, NewTabButton } from "./LazurioNewTab"; + +/** + * The thread where the Environment browser can serve it, else null: a thread of this page's own + * environment, in the web client. The desktop app keeps its own browser, and a thread of another + * environment has its tabs in that environment's browser. + */ +function useEnvironmentBrowserThread(threadRef: ScopedThreadRef | null): ScopedThreadRef | null { + const primaryEnvironmentId = usePrimaryEnvironmentId(); + return threadRef !== null && + threadRef.environmentId === primaryEnvironmentId && + !isPreviewSupportedInRuntime() + ? threadRef + : null; +} + +/** + * Whether the person is still on the thread when its view closes. It is read from the route the + * router is on by then, so a view that only mounts anew keeps what the device saw (threadTabs.ts). + */ +const stillShown = (router: AnyRouter, threadRef: ScopedThreadRef) => + routeShowsThread(router.state.matches.at(-1)?.params ?? {}, threadRef); + +/** A row of the chat's timeline: a message, or the work the agent did. */ +const CHAT_ROW = "[data-timeline-root]"; + +const parseData = (data: unknown) => { + try { + return JSON.parse(String(data)) as unknown; + } catch { + return null; + } +}; + +/** + * A tab of this Environment that the person closed in the strip, by any close action, while the + * list still has it or its hold is pending: the thread lets go of it. Store changes in one task + * (upstream's Close all closes one at a time) make one batch and one toast. + */ +function watchClosedTabs(threadRef: ScopedThreadRef): () => void { + const key = scopedThreadKey(threadRef); + let batch: { + original: readonly RightPanelSurface[]; + closed: EnvironmentBrowserSurface[]; + activeBefore: string | null; + openBefore: boolean; + } | null = null; + return useRightPanelStore.subscribe((state, previous) => { + const before = previous.byThreadKey[key]; + const after = state.byThreadKey[key]; + if (before === undefined || before === after) return; + const sync = syncOf(threadRef); + const snapshot = snapshotOf(threadRef); + const listed = new Set(snapshot?.tabs.map((tab) => tab.tabId) ?? []); + const remaining = new Set((after?.surfaces ?? []).map((surface) => surface.id)); + const closed = before.surfaces.filter((surface): surface is EnvironmentBrowserSurface => { + if (remaining.has(surface.id)) return false; + const tab = tabIdOfSurface(surface); + if (tab === null || sync.ended.has(tab) || sync.released.has(tab)) return false; + return listed.has(tab) || sync.pending.has(tab); + }); + if (closed.length === 0) return; + if (batch === null) { + const started = { + original: before.surfaces, + closed: [] as EnvironmentBrowserSurface[], + activeBefore: before.activeSurfaceId, + openBefore: before.isOpen, + }; + batch = started; + queueMicrotask(() => { + batch = null; + const tabs: ClosedTabs = { + surfaces: started.closed.map((surface) => ({ + surface, + index: started.original.findIndex((entry) => entry.id === surface.id), + })), + activeBefore: started.activeBefore, + openBefore: started.openBefore, + }; + letGoOfTabs(threadRef, tabs); + }); + } + batch.closed.push(...closed); + }); +} + +/** + * Lazurio overlay: ChatView's one hook. The strip follows the server's list of the thread's tabs, + * a new reveal opens the inline panel (never the sheet), and a plain click on a remote-tab link in + * the chat opens it in the panel. A draft opens no stream: the server would answer 404, which an + * EventSource never retries, so the stream starts once the draft is a thread (Lazurio/t3code#53). + */ +export function useLazurioThreadTabs( + input: ScopedThreadRef | null, + options: { readonly inlinePanel: boolean; readonly draft: boolean }, +): void { + const threadRef = useEnvironmentBrowserThread(input); + const { inlinePanel, draft } = options; + const router = useRouter(); + + // Before the stream's effect, so a thread that comes into view has its panel's kind already. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors the panel kind into the module state the stream reads + useEffect(() => { + if (threadRef !== null) syncOf(threadRef).inlinePanel = inlinePanel; + }, [threadRef, inlinePanel]); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a draft's presence in view is a mount lifecycle the module tracks + useEffect(() => { + if (threadRef === null || !draft) return; + enterDraft(threadRef); + return () => leaveDraft(threadRef, stillShown(router, threadRef)); + }, [threadRef, draft, router]); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the server's EventSource of the thread's tabs + useEffect(() => { + if (threadRef === null || draft) return; + enterThreadTabs(threadRef); + const events = new EventSource( + `${THREAD_TABS_ROUTE}/events?threadId=${encodeURIComponent(threadRef.threadId)}`, + ); + events.addEventListener("snapshot", (event) => { + const answer = parseThreadTabsAnswer(parseData(event.data)); + if (answer !== null) receiveSnapshot(threadRef, answer); + }); + events.addEventListener("foreign", (event) => { + const tab = parseForeignTab(parseData(event.data)); + if (tab !== null) receiveForeign(threadRef, tab); + }); + const stopWatching = watchClosedTabs(threadRef); + return () => { + events.close(); + stopWatching(); + leaveThreadTabs(threadRef, stillShown(router, threadRef)); + }; + }, [threadRef, draft, router]); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a capturing document listener for chat link clicks + useEffect(() => { + if (threadRef === null) return; + const openInPanel = (event: MouseEvent) => { + if (!isPlainPrimaryClick(event) || !(event.target instanceof Element)) return; + const link = event.target.closest("a[href]"); + if (!(link instanceof HTMLAnchorElement) || link.closest(CHAT_ROW) === null) return; + if (!openLinkInPanel(threadRef, link.href)) return; + // The panel took this click: no new browser tab, and no link handling of the chat's own. + event.preventDefault(); + event.stopPropagation(); + }; + // Capturing on the document runs before the chat's own handlers of the link. + document.addEventListener("click", openInPanel, true); + return () => document.removeEventListener("click", openInPanel, true); + }, [threadRef]); +} + +/** + * How long another Environment's view has to tell its tab: after its page loaded, and in all. A + * gateway that sends a frame to its sign-in, which refuses to render in a frame, loads an error + * page within a second; a view that comes up tells its tab right after it connects. + */ +const FOREIGN_VIEW_AFTER_LOAD_MS = 4_000; +const FOREIGN_VIEW_MS = 15_000; + +/** The shell's element that names an Environment as its switcher does (LazurioPlatform F39, + * addendum of 2026-10-12). */ +export const ENVIRONMENT_ELEMENT = "lazurio-environment"; + +/** Another Environment's view, said without naming it: its frame's title, and its name until the + * shell knows that Environment, or where the Environment's Platform predates the element. */ +const anotherEnvironment = (czech: boolean) => + czech ? "Prohlížeč jiného Prostředí" : "Another Environment's browser"; + +/** Another Environment's name over the notice to sign in there, where its view, whose own bar names + * it, did not come up: the shell's ``, which shows its children until the + * page's shell knows that Environment. */ +function ForeignEnvironmentName(props: { + readonly environment: LazurioBrowserView; + readonly czech: boolean; +}) { + return createElement( + ENVIRONMENT_ELEMENT, + { + environment: viewEnvironmentId(props.environment), + lang: props.czech ? "cs" : "en", + className: "max-w-full truncate rounded-md border px-2 py-1 font-medium text-sm", + }, + anotherEnvironment(props.czech), + ); +} + +const isEnvironmentBrowserSurface = ( + surface: RightPanelSurface, +): surface is EnvironmentBrowserSurface => surface.kind === "environment-browser"; + +/** + * Every Environment browser tab of the thread keeps a mounted frame beside the surface in view, in + * one grid cell, for instant switching. A hidden frame keeps its size (visibility, not display): + * the view sizes its remote window to its page area, so a frame without one would shrink the + * agent's window too. The desktop app has its own browser and keeps upstream's panel. + */ +export function LazurioRightPanelSurfaces(props: { + readonly threadRef: ScopedThreadRef; + readonly surfaces: readonly RightPanelSurface[]; + readonly activeSurfaceId: string | null; + readonly children: ReactNode; +}) { + if (isPreviewSupportedInRuntime()) return props.children; + const threadKey = scopedThreadKey(props.threadRef); + return ( +
+
{props.children}
+ {props.surfaces.filter(isEnvironmentBrowserSurface).map((surface) => { + const shown = surface.id === props.activeSurfaceId; + if (isNewTabSurface(surface)) { + return shown ? ( +
+ +
+ ) : null; + } + return ( +
+ +
+ ); + })} +
+ ); +} + +/** The server's last answer for the thread the chat shows, whose strip RightPanelTabs draws. */ +const snapshotInView = (state: ReturnType) => + state.inView === null ? undefined : state.snapshots[scopedThreadKey(state.inView)]; + +/** The titles the frames report, by surface id. */ +export type FrameTitles = ReturnType["titles"]; + +/** + * RightPanelTabs's one hook: whether "+" and the empty panel open Nová karta (`newTab`, + * LazurioNewTab.tsx), the empty panel's line on a draft, and the titles the frames report. The + * strip is compiled and memoizes its tabs by their inputs, so a tab's title follows its frame only + * because the titles reach `surfaceTitle` through here, never read from the store while it renders. + */ +export function useRightPanel(actions: ReadonlyArray) { + const newTab = useNewTab(actions); + const titles = useThreadTabsStore((state) => state.titles); + // A draft on an Environment whose shell offers Nová karta, unless the server already said that + // this Environment has no browser for another thread. + const draftNote = useThreadTabsStore( + (state) => + state.draftInView !== null && + !Object.values(state.snapshots).some((answer) => answer === null), + ); + const defined = useNewTabDefined(); + return { + newTab, + /** The empty panel's line about the Environment browser, or null for upstream's. */ + browserNote: draftNote && defined ? draftBrowserNote(prefersCzech()) : null, + titles, + }; +} + +/** The strip's title of an Environment browser tab: what its frame reported, or Nová karta. */ +export function surfaceTitle(surface: EnvironmentBrowserSurface, titles: FrameTitles): string { + if (isNewTabSurface(surface)) return prefersCzech() ? "Nová karta" : "New tab"; + return titles[surface.id] ?? "Browser"; +} + +const tabOfInView = + (surfaceId: string) => (state: ReturnType) => + snapshotInView(state)?.tabs.find((tab) => tabSurfaceId(tab.tabId) === surfaceId); + +/** + * The strip tab's tooltip, in place of upstream's title (RightPanelTab): an Environment browser + * tab of the thread in view adds an agent at work and the other places that hold it, any other + * surface keeps its title. It follows the server's facts itself, so the tab's props stay upstream's. + */ +export function TabTooltip(props: { readonly surface: RightPanelSurface; readonly title: string }) { + const tab = useThreadTabsStore(tabOfInView(props.surface.id)); + return tabTooltip(props.title, tab, prefersCzech()); +} + +/** The strip's icon of an Environment browser tab, marked while an agent works in it or another + * place holds it too. */ +export function SurfaceIcon({ surface }: { readonly surface: EnvironmentBrowserSurface }) { + const tab: ThreadTab | undefined = useThreadTabsStore(tabOfInView(surface.id)); + if (isNewTabSurface(surface)) return ; + const shared = tab !== undefined && tab.alsoHeldBy.length > 0; + return ( + + + {tab?.agent || shared ? ( + + ) : null} + + ); +} + +/** + * A foreign tab frames its own view; this Environment's tab frames `/t/` from the + * server's answer, so no address is stored. `view` is undefined until that answer and null where + * this Environment offers no browser. + */ +function viewOfTab( + surface: EnvironmentBrowserSurface, + snapshot: ThreadTabsSnapshot | null | undefined, +): { + readonly foreign: ForeignEnvironmentBrowserTab | null; + readonly view: string | null | undefined; +} { + const foreign = + surface.view === undefined + ? null + : foreignEnvironmentBrowserTab( + surface.view, + window.location.origin, + snapshot?.viewOrigin ?? null, + ); + const tabId = tabIdOfSurface(surface); + const view = + foreign !== null + ? foreign.view + : tabId !== null && snapshot !== undefined && snapshot !== null + ? `${snapshot.viewOrigin}/t/${tabId}` + : snapshot === null + ? null + : undefined; + return { foreign, view }; +} + +/** The overlay's items of the strip tab's menu (RightPanelTabs `TabContextMenuAction`). */ +export type TabMenuAction = "lazurio-open-in-new-tab" | "lazurio-reload"; + +/** + * "Open in new tab" and "Reload" before upstream's close items, for Environment browser tabs other + * than Nová karta; in English like the rest of that menu. Read from the thread in view when the + * menu opens, and disabled until the tab's view address is known. + */ +export function tabMenuItems(surface: RightPanelSurface): ContextMenuItem[] { + if (!isEnvironmentBrowserSurface(surface) || isNewTabSurface(surface)) return []; + const disabled = !viewOfTab(surface, snapshotInView(useThreadTabsStore.getState())).view; + return [ + { id: "lazurio-open-in-new-tab", label: "Open in new tab", disabled }, + { id: "lazurio-reload", label: "Reload", disabled }, + ]; +} + +/** + * Runs an item of `tabMenuItems`: the tab's view in a new tab of the person's browser, or a fresh + * frame of it, also while another tab is in front. + */ +export function runTabMenuAction(action: TabMenuAction, surface: RightPanelSurface): void { + if (!isEnvironmentBrowserSurface(surface)) return; + if (action === "lazurio-reload") { + reloadSurface(surface.id); + return; + } + const { view } = viewOfTab(surface, snapshotInView(useThreadTabsStore.getState())); + if (view) window.open(view, "_blank", "noopener"); +} + +/** + * The view of one remote tab in a frame, with the view's own bar as the only toolbar. Tabs its + * page opens join the panel and the thread holds them; an ended tab leaves (root decision 0191 + * point 12, F47 point 6). Another Environment's tab gets a coloured border, and where its view does + * not come up the panel asks the person to sign in at that Environment. + */ +function LazurioEnvironmentBrowser(props: { + readonly threadRef: ScopedThreadRef; + readonly surface: EnvironmentBrowserSurface; + readonly shown: boolean; +}) { + const { threadRef, surface, shown } = props; + const snapshot = useThreadTabsStore((state) => state.snapshots[scopedThreadKey(threadRef)]); + // The frame's address; undefined until the server's first answer, null without a browser. + const { foreign, view } = viewOfTab(surface, snapshot); + // Each reload is a fresh frame (its key). + const request = useThreadTabsStore((state) => state.reloads[surface.id] ?? 0); + + // The requests whose frame told its tab (its view came up), fired load, or ran out of time. + const [cameUp, setCameUp] = useState(null); + const [loaded, setLoaded] = useState(null); + const [late, setLate] = useState(null); + const frame = useRef(null); + const isForeign = foreign !== null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- listens for postMessage from the framed view + useEffect(() => { + if (!view) return; + const listen = (event: MessageEvent) => { + const message = readEnvironmentBrowserMessage( + event, + frame.current?.contentWindow ?? null, + view, + ); + if (message?.type === "info") { + setCameUp(request); + rememberTitle(surface.id, message.title); + } else if (message?.type === "new-tab") { + const target = /\/t\/([0-9A-Fa-f]{32})$/.exec(message.tab.view)?.[1]; + if (isForeign) showForeignTab(threadRef, message.tab.view, shown); + else if (target !== undefined) showOwnTab(threadRef, target, shown); + } else if (message?.type === "closed") { + tabEnded(threadRef, surface.id); + } + }; + window.addEventListener("message", listen); + return () => window.removeEventListener("message", listen); + }, [view, threadRef, surface.id, shown, request, isForeign, frame]); + + // Another Environment's view tells its tab soon after its page loads, or it never came up. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a timer that gives the foreign view a deadline + useEffect(() => { + if (!isForeign || !view || cameUp === request) return; + const wait = loaded === request ? FOREIGN_VIEW_AFTER_LOAD_MS : FOREIGN_VIEW_MS; + const timer = window.setTimeout(() => setLate(request), wait); + return () => window.clearTimeout(timer); + }, [isForeign, view, request, loaded, cameUp]); + const signIn = isForeign && Boolean(view) && late === request && cameUp !== request; + const czech = prefersCzech(); + // The frame's name for assistive technology, in the overlay's language. + const title = + foreign === null + ? czech + ? "Prohlížeč Prostředí" + : "Environment browser" + : anotherEnvironment(czech); + + return ( +
+ {view ? ( +
+