From 2327f82cd989a994a704a5cd017adcae8f0cd934 Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Tue, 17 Nov 2026 17:10:24 -0600 Subject: [PATCH 1/4] refactor: a renamed desktop build names its environment through the label file The desktop no longer sends its display name to the server. A renamed build, like t3code-diy's side-by-side app, writes `environment-label` in its T3 home, which the server already reads for sandboxes. T3CODE_DESKTOP_DISPLAY_NAME still names the app's windows and About panel. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app/DesktopEnvironment.ts | 3 - .../DesktopBackendConfiguration.test.ts | 32 ----------- .../backend/DesktopBackendConfiguration.ts | 4 -- apps/server/src/cli/config.test.ts | 31 ----------- apps/server/src/cli/config.ts | 2 - apps/server/src/config.ts | 2 - .../src/environment/ServerEnvironment.ts | 1 - .../ServerEnvironmentLabel.test.ts | 55 ------------------- .../src/environment/ServerEnvironmentLabel.ts | 9 +-- packages/contracts/src/desktopBootstrap.ts | 2 - 10 files changed, 1 insertion(+), 140 deletions(-) diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts index 1574840c94761..019bb1931cbda 100644 --- a/apps/desktop/src/app/DesktopEnvironment.ts +++ b/apps/desktop/src/app/DesktopEnvironment.ts @@ -73,8 +73,6 @@ export class DesktopEnvironment extends Context.Service< readonly otlpProtocol: OtlpProtocol; readonly branding: DesktopAppBranding; readonly displayName: string; - /** Set only by a renamed build; the backend names its environment after it. */ - readonly displayNameOverride: Option.Option; readonly appUserModelId: string; readonly linuxDesktopEntryName: string; readonly linuxApplicationsDir: string; @@ -233,7 +231,6 @@ const make = Effect.fn("desktop.environment.make")(function* ( otlpProtocol: config.otlpProtocol, branding, displayName, - displayNameOverride: config.displayNameOverride, appUserModelId: Option.getOrElse(config.appUserModelIdOverride, () => isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code", ), diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index d30d3e810beeb..565a50f193e0f 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -68,7 +68,6 @@ function layerEnvironment( readonly otlpTracesUrl?: string; readonly otlpMetricsUrl?: string; readonly otlpLogsUrl?: string; - readonly displayNameOverride?: string; }, ) { return DesktopEnvironment.layer({ @@ -95,7 +94,6 @@ function layerEnvironment( T3CODE_OTLP_TRACES_URL: options?.otlpTracesUrl, T3CODE_OTLP_METRICS_URL: options?.otlpMetricsUrl, T3CODE_OTLP_LOGS_URL: options?.otlpLogsUrl, - T3CODE_DESKTOP_DISPLAY_NAME: options?.displayNameOverride, }), ), ), @@ -256,8 +254,6 @@ describe("DesktopBackendConfiguration", () => { assert.equal(first.bootstrap.t3Home, environment.baseDir); assert.equal(first.bootstrap.tailscaleServeEnabled, true); assert.equal(first.bootstrap.tailscaleServePort, 8443); - // A build without a display-name override lets the server name itself as before. - assert.isFalse("environmentLabel" in first.bootstrap); assert.match(first.bootstrap.desktopBootstrapSecret ?? "", /^[0-9a-f]{64}$/i); assert.equal( second.bootstrap.desktopBootstrapSecret, @@ -324,34 +320,6 @@ describe("DesktopBackendConfiguration", () => { }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); - it.effect("resolvePrimary names the environment after a renamed build's display name", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - const config = yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - return yield* configuration.resolvePrimary; - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslEnvironment.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge( - layerEnvironment(baseDir, { displayNameOverride: "T3 Code Custom" }), - ), - ), - ), - ); - - assert.equal(config.bootstrap.environmentLabel, "T3 Code Custom"); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index c91fe5facf42c..82f0a30a40cd9 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -552,10 +552,6 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv onSome: (resourceMonitorPath) => ({ resourceMonitorPath }), }), ...buildObservabilityFragment(input.observabilitySettings), - ...Option.match(environment.displayNameOverride, { - onNone: () => ({}), - onSome: (environmentLabel) => ({ environmentLabel }), - }), }; return { diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 7e298d6855d2b..ddbc49e1ced74 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -543,37 +543,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { }), ); - it.effect("names the environment after the desktop's display name only when it sends one", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-label-" }); - const resolveWith = (bootstrap: DesktopBackendBootstrapValue) => - openBootstrapFd(bootstrap).pipe( - Effect.flatMap((fd) => - resolveServerConfig( - { ...minimalDesktopFlags(baseDir), bootstrapFd: Option.some(fd) }, - Option.none(), - ), - ), - Effect.provide( - Layer.mergeAll( - ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), - NetService.layer, - ), - ), - ); - - const renamed = yield* resolveWith( - makeDesktopBootstrap({ environmentLabel: "T3 Code Custom" }), - ); - const plain = yield* resolveWith(makeDesktopBootstrap()); - - assert.strictEqual(renamed.environmentLabel, "T3 Code Custom"); - assert.isUndefined(plain.environmentLabel); - assert.isFalse("environmentLabel" in plain); - }), - ); - it.effect("reports saved settings as the source of endpoints read from settings.json", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index 45c80ee3fa526..a59e976215864 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -394,7 +394,6 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct const desktopBrowserFd = bootstrap?.desktopBrowserFd; const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd; const resourceMonitorPath = bootstrap?.resourceMonitorPath; - const environmentLabel = bootstrap?.environmentLabel; const autoBootstrapProjectFromCwd = Option.getOrElse( resolveOptionPrecedence( Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd), @@ -524,7 +523,6 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct desktopBootstrapToken, ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }), ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }), - ...(environmentLabel === undefined ? {} : { environmentLabel }), desktopTelemetryFd, desktopTelemetryControlFd, ...(desktopAppUpdate === undefined ? {} : { desktopAppUpdate }), diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 27c576c4be9bd..45dfb4cda43d7 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -111,8 +111,6 @@ export class ServerConfig extends Context.Service< readonly desktopBrowserFd?: number | undefined; readonly desktopBrowserControlFd?: number | undefined; readonly resourceMonitorPath?: string | undefined; - /** The desktop's display name, sent only by renamed builds; names this environment. */ - readonly environmentLabel?: string | undefined; readonly autoBootstrapProjectFromCwd: boolean; readonly logWebSocketEvents: boolean; readonly tailscaleServeEnabled: boolean; diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 428c31e410fef..31e28ce3ca340 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -196,7 +196,6 @@ export const make = Effect.gen(function* () { const label = yield* resolveServerEnvironmentLabel({ cwdBaseName, baseDir: serverConfig.baseDir, - displayName: serverConfig.environmentLabel, }); const machine = yield* detectServerEnvironmentMachineKind(); const launcher = yield* resolveServiceLauncherMode(); diff --git a/apps/server/src/environment/ServerEnvironmentLabel.test.ts b/apps/server/src/environment/ServerEnvironmentLabel.test.ts index cb6c24b34e4b3..8e65afc7a0c0b 100644 --- a/apps/server/src/environment/ServerEnvironmentLabel.test.ts +++ b/apps/server/src/environment/ServerEnvironmentLabel.test.ts @@ -126,58 +126,3 @@ it.effect("prefers the label provisioning writes into the base directory", () => expect(label).toBe("Boat sandbox"); }).pipe(Effect.provide(TestLayer)), ); - -it.effect("uses the desktop's display name ahead of the computer name", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-label-" }); - - // A renamed side-by-side build would otherwise share the computer name with the official app. - const label = yield* resolveServerEnvironmentLabel({ - cwdBaseName: "workspace", - baseDir, - displayName: " T3 Code Custom ", - }); - - expect(label).toBe("T3 Code Custom"); - }).pipe(Effect.provide(TestLayer)), -); - -it.effect("keeps the provisioned label file ahead of the desktop's display name", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-label-" }); - yield* fileSystem.writeFileString(path.join(baseDir, "environment-label"), "Boat sandbox\n"); - - const label = yield* resolveServerEnvironmentLabel({ - cwdBaseName: "workspace", - baseDir, - displayName: "T3 Code Custom", - }); - - expect(label).toBe("Boat sandbox"); - }).pipe(Effect.provide(TestLayer)), -); - -it.effect("falls back to the host name when no display name is set or it is blank", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-label-" }); - - const withoutName = yield* resolveServerEnvironmentLabel({ cwdBaseName: "workspace", baseDir }); - const blankName = yield* resolveServerEnvironmentLabel({ - cwdBaseName: "workspace", - baseDir, - displayName: " ", - }); - - expect(withoutName).toBe("omars-macbook-pro"); - expect(blankName).toBe("omars-macbook-pro"); - }).pipe( - // No friendly-name probe runs off macOS and Linux, so the host name decides. - Effect.provideService(HostProcess.Platform, "freebsd"), - Effect.provideService(HostProcess.Hostname, "omars-macbook-pro"), - Effect.provide(TestLayer), - ), -); diff --git a/apps/server/src/environment/ServerEnvironmentLabel.ts b/apps/server/src/environment/ServerEnvironmentLabel.ts index e817b526d71b5..fdc13798f29e4 100644 --- a/apps/server/src/environment/ServerEnvironmentLabel.ts +++ b/apps/server/src/environment/ServerEnvironmentLabel.ts @@ -9,10 +9,8 @@ import * as ProcessRunner from "../processRunner.ts"; interface ResolveServerEnvironmentLabelInput { readonly cwdBaseName: string; - /** Explicit label file directory. Provisioned sandboxes write `environment-label` here. */ + /** T3 home. Provisioned sandboxes and renamed desktop builds write `environment-label` here. */ readonly baseDir?: string; - /** The name a renamed desktop build (such as t3code-diy's side-by-side app) gives itself. */ - readonly displayName?: string | undefined; } const ServerEnvironmentLabelCommandProbe = Schema.Literals([ @@ -228,11 +226,6 @@ export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironment } } - const displayName = normalizeLabel(input.displayName); - if (displayName) { - return displayName; - } - const friendlyHostLabel = yield* resolveFriendlyHostLabel(); if (friendlyHostLabel) { return friendlyHostLabel; diff --git a/packages/contracts/src/desktopBootstrap.ts b/packages/contracts/src/desktopBootstrap.ts index a87095835e7d2..5148aa2c1c82e 100644 --- a/packages/contracts/src/desktopBootstrap.ts +++ b/packages/contracts/src/desktopBootstrap.ts @@ -31,8 +31,6 @@ export const DesktopBackendBootstrap = Schema.Struct({ desktopBrowserFd: Schema.optionalKey(PositiveInt), desktopBrowserControlFd: Schema.optionalKey(PositiveInt), resourceMonitorPath: Schema.optionalKey(TrimmedNonEmptyString), - // Only a renamed build sends its display name; the server then names its environment after it. - environmentLabel: Schema.optionalKey(TrimmedNonEmptyString), }); export type DesktopBackendBootstrap = typeof DesktopBackendBootstrap.Type; From 61b1daf566841527e1c44ea446ac952daa7b5eb7 Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Tue, 17 Nov 2026 17:20:06 -0600 Subject: [PATCH 2/4] test: fork test cases live in their own .sandbox test files Sandbox cases appended to upstream test files move to sibling *.sandbox.test.ts files, so those upstream files match upstream again and stop conflicting on the nightly rebase. The environment label no longer needs Path, so ServerEnvironmentLabel.test.ts stays identical to upstream. Co-Authored-By: Claude Opus 5.5 --- .../ServerEnvironmentLabel.sandbox.test.ts | 28 ++ .../ServerEnvironmentLabel.test.ts | 35 +-- .../src/environment/ServerEnvironmentLabel.ts | 4 +- apps/server/src/http.sandbox.test.ts | 45 +++ apps/server/src/http.test.ts | 34 --- .../Orchestrator.control-reads.test.ts | 48 --- .../Orchestrator.sandbox.test.ts | 89 ++++++ .../ThreadStop.sandbox.test.ts | 163 ++++++++++ .../src/orchestration-v2/ThreadStop.test.ts | 91 +----- .../src/usage/cliproxyApi.sandbox.test.ts | 81 +++++ apps/server/src/usage/cliproxyApi.test.ts | 70 +---- .../components/ChatView.logic.sandbox.test.ts | 38 +++ .../web/src/components/ChatView.logic.test.ts | 37 --- ...SettingsPanel.environment.browser.test.tsx | 29 -- ...Panel.environment.sandbox.browser.test.tsx | 279 ++++++++++++++++++ .../settings/scopedSettings.sandbox.test.ts | 192 ++++++++++++ .../settings/scopedSettings.test.ts | 111 ------- .../settings/settingsScope.sandbox.test.ts | 104 +++++++ .../components/settings/settingsScope.test.ts | 48 +-- .../threadActionMenu.logic.sandbox.test.ts | 54 ++++ .../components/threadActionMenu.logic.test.ts | 26 -- .../src/environmentGrouping.sandbox.test.ts | 96 ++++++ apps/web/src/environmentGrouping.test.ts | 56 ---- apps/web/src/modelSelection.sandbox.test.ts | 82 +++++ apps/web/src/modelSelection.test.ts | 26 -- .../src/handoff.sandbox.test.ts | 49 +++ packages/client-runtime/src/handoff.test.ts | 13 - .../src/state/runtime.sandbox.test.ts | 195 ++++++++++++ .../client-runtime/src/state/runtime.test.ts | 49 --- .../src/server/driver.sandbox.test.ts | 210 +++++++++++++ .../src/server/driver.test.ts | 119 -------- 31 files changed, 1714 insertions(+), 787 deletions(-) create mode 100644 apps/server/src/environment/ServerEnvironmentLabel.sandbox.test.ts create mode 100644 apps/server/src/http.sandbox.test.ts create mode 100644 apps/server/src/orchestration-v2/Orchestrator.sandbox.test.ts create mode 100644 apps/server/src/orchestration-v2/ThreadStop.sandbox.test.ts create mode 100644 apps/server/src/usage/cliproxyApi.sandbox.test.ts create mode 100644 apps/web/src/components/ChatView.logic.sandbox.test.ts create mode 100644 apps/web/src/components/settings/ProviderSettingsPanel.environment.sandbox.browser.test.tsx create mode 100644 apps/web/src/components/settings/scopedSettings.sandbox.test.ts create mode 100644 apps/web/src/components/settings/settingsScope.sandbox.test.ts create mode 100644 apps/web/src/components/threadActionMenu.logic.sandbox.test.ts create mode 100644 apps/web/src/environmentGrouping.sandbox.test.ts create mode 100644 apps/web/src/modelSelection.sandbox.test.ts create mode 100644 packages/client-runtime/src/handoff.sandbox.test.ts create mode 100644 packages/client-runtime/src/state/runtime.sandbox.test.ts create mode 100644 packages/provider-acp-registry/src/server/driver.sandbox.test.ts diff --git a/apps/server/src/environment/ServerEnvironmentLabel.sandbox.test.ts b/apps/server/src/environment/ServerEnvironmentLabel.sandbox.test.ts new file mode 100644 index 0000000000000..979f716ffc741 --- /dev/null +++ b/apps/server/src/environment/ServerEnvironmentLabel.sandbox.test.ts @@ -0,0 +1,28 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { 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 Path from "effect/Path"; + +import * as ProcessRunner from "../processRunner.ts"; +import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts"; + +const TestLayer = Layer.mergeAll( + NodeServices.layer, + ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)), +); + +it.effect("prefers the label provisioning writes into the base directory", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-label-" }); + yield* fileSystem.writeFileString(path.join(baseDir, "environment-label"), " Boat sandbox\n"); + + // No sudo, systemd, or writable /etc is needed for this path, which is why provisioning uses it. + const label = yield* resolveServerEnvironmentLabel({ cwdBaseName: "workspace", baseDir }); + + expect(label).toBe("Boat sandbox"); + }).pipe(Effect.provide(TestLayer)), +); diff --git a/apps/server/src/environment/ServerEnvironmentLabel.test.ts b/apps/server/src/environment/ServerEnvironmentLabel.test.ts index 8e65afc7a0c0b..6cf235d67814b 100644 --- a/apps/server/src/environment/ServerEnvironmentLabel.test.ts +++ b/apps/server/src/environment/ServerEnvironmentLabel.test.ts @@ -1,11 +1,9 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, expect, it } from "@effect/vitest"; +import { assert, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Path from "effect/Path"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; @@ -41,7 +39,6 @@ it.effect("falls back to the hostname when hostnamectl never answers", () => Effect.provide( Layer.mergeAll( FileSystem.layerNoop({ exists: () => Effect.succeed(false) }), - Path.layer, ProcessRunner.layer.pipe( Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, neverExits)), ), @@ -94,35 +91,13 @@ it.effect("qualifies the inherited Windows hostname only inside WSL", () => Effect.provideService(HostProcess.Environment, { WSL_DISTRO_NAME: "Ubuntu" }), Effect.provideService(ProcessRunner.ProcessRunner, exitsWithFailure), Effect.provide( - Layer.mergeAll( - FileSystem.layerNoop({ - exists: (path) => Effect.succeed(files[path] != null), - readFileString: (path) => Effect.succeed(files[path] ?? ""), - }), - Path.layer, - ), + FileSystem.layerNoop({ + exists: (path) => Effect.succeed(files[path] != null), + readFileString: (path) => Effect.succeed(files[path] ?? ""), + }), ), ); assert.equal(label, expected, kernel); } }), ); - -const TestLayer = Layer.mergeAll( - NodeServices.layer, - ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer)), -); - -it.effect("prefers the label provisioning writes into the base directory", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-label-" }); - yield* fileSystem.writeFileString(path.join(baseDir, "environment-label"), " Boat sandbox\n"); - - // No sudo, systemd, or writable /etc is needed for this path, which is why provisioning uses it. - const label = yield* resolveServerEnvironmentLabel({ cwdBaseName: "workspace", baseDir }); - - expect(label).toBe("Boat sandbox"); - }).pipe(Effect.provide(TestLayer)), -); diff --git a/apps/server/src/environment/ServerEnvironmentLabel.ts b/apps/server/src/environment/ServerEnvironmentLabel.ts index fdc13798f29e4..a2d6cf94f7db0 100644 --- a/apps/server/src/environment/ServerEnvironmentLabel.ts +++ b/apps/server/src/environment/ServerEnvironmentLabel.ts @@ -2,7 +2,6 @@ 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 * as Schema from "effect/Schema"; import * as ProcessRunner from "../processRunner.ts"; @@ -202,8 +201,7 @@ const isWsl = Effect.fn("isWsl")(function* () { */ const readConfiguredLabel = Effect.fn("readConfiguredLabel")(function* (baseDir: string) { const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const labelPath = path.join(baseDir, "environment-label"); + const labelPath = `${baseDir}/environment-label`; const exists = yield* fileSystem.exists(labelPath).pipe(Effect.orElseSucceed(() => false)); if (!exists) return null; return yield* fileSystem.readFileString(labelPath).pipe( diff --git a/apps/server/src/http.sandbox.test.ts b/apps/server/src/http.sandbox.test.ts new file mode 100644 index 0000000000000..48c6ac4d196a5 --- /dev/null +++ b/apps/server/src/http.sandbox.test.ts @@ -0,0 +1,45 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { HttpRouter, HttpServerResponse } from "effect/http"; +import { describe } from "vite-plus/test"; + +import * as ServerConfig from "./config.ts"; +import * as ServerHttp from "./http.ts"; + +describe("browser API CORS behind a sandbox proxy", () => { + it("adds no CORS headers when the proxy in front answers CORS", async () => { + const layerRoute = Layer.effectDiscard( + Effect.gen(function* () { + const router = yield* HttpRouter.HttpRouter; + yield* router.add("GET", "/api/environment", HttpServerResponse.empty()); + }), + ); + const layerProxyConfig = Layer.effect( + ServerConfig.ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + return { ...config, proxyHandlesCors: true }; + }), + ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "http-cors-proxy-" }))); + const layerApp = Layer.merge(layerRoute, ServerHttp.layerBrowserApiCors).pipe( + Layer.provide(layerProxyConfig), + Layer.provide(NodeServices.layer), + ); + const { handler, dispose } = HttpRouter.toWebHandler(layerApp, { disableLogger: true }); + + try { + const response = await handler( + new Request("https://backend.example/api/environment", { + headers: { origin: "https://app.t3.codes" }, + }), + ); + + // Daytona's proxy adds the origin it echoes; a second value here would fail the request. + expect(response.headers.get("access-control-allow-origin")).toBeNull(); + } finally { + await dispose(); + } + }); +}); diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index d3e5f10209baf..7b747647984d4 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -174,40 +174,6 @@ describe("browser API CORS", () => { await dispose(); } }); - - it("adds no CORS headers when the proxy in front answers CORS", async () => { - const layerRoute = Layer.effectDiscard( - Effect.gen(function* () { - const router = yield* HttpRouter.HttpRouter; - yield* router.add("GET", "/api/environment", HttpServerResponse.empty()); - }), - ); - const layerProxyConfig = Layer.effect( - ServerConfig.ServerConfig, - Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - return { ...config, proxyHandlesCors: true }; - }), - ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "http-cors-proxy-" }))); - const layerApp = Layer.merge(layerRoute, ServerHttp.layerBrowserApiCors).pipe( - Layer.provide(layerProxyConfig), - Layer.provide(NodeServices.layer), - ); - const { handler, dispose } = HttpRouter.toWebHandler(layerApp, { disableLogger: true }); - - try { - const response = await handler( - new Request("https://backend.example/api/environment", { - headers: { origin: "https://app.t3.codes" }, - }), - ); - - // Daytona's proxy adds the origin it echoes; a second value here would fail the request. - expect(response.headers.get("access-control-allow-origin")).toBeNull(); - } finally { - await dispose(); - } - }); }); describe("untraced requests", () => { diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 60bbffbbdc7ce..274c15a5f7089 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -2991,51 +2991,3 @@ it.effect( assert.equal(yield* captureReads, quietParent); }).pipe(Effect.provide(layerTest)), ); - -it.effect("keeps a sandbox chat on the sandbox bridge whatever client asks to switch", () => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const projections = yield* ProjectionStore.ProjectionStoreV2; - const threadId = ThreadId.make("thread:sandbox-bridge-switch"); - const bridgeSelection = { instanceId: ProviderInstanceId.make("sandboxes"), model: "sandbox" }; - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("create-sandbox-bridge-switch"), - threadId, - projectId: ProjectId.make("project:sandbox-bridge-switch"), - title: "Sandbox chat", - modelSelection: bridgeSelection, - runtimeMode: "approval-required", - interactionMode: "default", - branch: null, - worktreePath: null, - createdBy: "user", - creationSource: "web", - }); - for (const command of [ - { - type: "thread.model-selection.set", - commandId: CommandId.make("switch-sandbox-bridge-model"), - threadId, - modelSelection, - }, - { - type: "message.dispatch", - commandId: CommandId.make("send-sandbox-bridge-other-model"), - threadId, - messageId: MessageId.make("message:sandbox-bridge-other-model"), - text: "Run this here", - attachments: [], - modelSelection, - dispatchMode: { type: "start_immediately" }, - createdBy: "user", - creationSource: "mobile", - }, - ] as const) { - const failure = yield* orchestrator.dispatch(command).pipe(Effect.flip); - assert.instanceOf(failure, Orchestrator.OrchestratorDispatchError); - assert.include(String(failure.cause), "keeps the sandbox's agent"); - } - assert.deepEqual((yield* projections.getThread(threadId)).modelSelection, bridgeSelection); - }).pipe(Effect.provide(layerTest)), -); diff --git a/apps/server/src/orchestration-v2/Orchestrator.sandbox.test.ts b/apps/server/src/orchestration-v2/Orchestrator.sandbox.test.ts new file mode 100644 index 0000000000000..957e68b729db9 --- /dev/null +++ b/apps/server/src/orchestration-v2/Orchestrator.sandbox.test.ts @@ -0,0 +1,89 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed for metadata controls"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "sandbox-control" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), +); + +it.effect("keeps a sandbox chat on the sandbox bridge whatever client asks to switch", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:sandbox-bridge-switch"); + const bridgeSelection = { instanceId: ProviderInstanceId.make("sandboxes"), model: "sandbox" }; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-sandbox-bridge-switch"), + threadId, + projectId: ProjectId.make("project:sandbox-bridge-switch"), + title: "Sandbox chat", + modelSelection: bridgeSelection, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + for (const command of [ + { + type: "thread.model-selection.set", + commandId: CommandId.make("switch-sandbox-bridge-model"), + threadId, + modelSelection, + }, + { + type: "message.dispatch", + commandId: CommandId.make("send-sandbox-bridge-other-model"), + threadId, + messageId: MessageId.make("message:sandbox-bridge-other-model"), + text: "Run this here", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "mobile", + }, + ] as const) { + const failure = yield* orchestrator.dispatch(command).pipe(Effect.flip); + assert.instanceOf(failure, Orchestrator.OrchestratorDispatchError); + assert.include(String(failure.cause), "keeps the sandbox's agent"); + } + assert.deepEqual((yield* projections.getThread(threadId)).modelSelection, bridgeSelection); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/ThreadStop.sandbox.test.ts b/apps/server/src/orchestration-v2/ThreadStop.sandbox.test.ts new file mode 100644 index 0000000000000..f20e60569b7b5 --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadStop.sandbox.test.ts @@ -0,0 +1,163 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EventId, + MessageId, + type OrchestrationV2DomainEvent, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + SANDBOX_BRIDGE_INSTANCE_ID, + SANDBOX_BRIDGE_MODEL, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as CommandReceiptStore from "./CommandReceiptStore.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; +import * as EventStore from "./EventStore.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ThreadManagementService from "./ThreadManagementService.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const bridgeSelection = { + instanceId: ProviderInstanceId.make(SANDBOX_BRIDGE_INSTANCE_ID), + model: SANDBOX_BRIDGE_MODEL, +}; +const bridgeAdapter = { + instanceId: bridgeSelection.instanceId, + driver: ProviderDriverKind.make("acpRegistry"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("Runs here never reach a provider"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = ThreadManagementService.layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + EventStore.layer.pipe(Layer.provide(layerDatabase)), + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "thread-stop-sandbox" }, + ProviderAdapterRegistry.layerFromAdapters([bridgeAdapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), + ), + ), + Layer.provideMerge(ServerSettings.layerTest()), + Layer.provideMerge(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), +); + +const send = (threadId: ThreadId, text: string, type: "start_immediately" | "queue_after_active") => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`send:${threadId}:${text}`), + threadId, + messageId: MessageId.make(`message:${threadId}:${text}`), + text, + attachments: [], + dispatchMode: { type }, + createdBy: "user", + creationSource: "web", + }); + }); + +const threadState = (threadId: ThreadId) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projection = yield* orchestrator.getThreadProjection(threadId); + return { + runs: projection.runs.map((run) => `${run.status}${run.queueHeld === true ? ":held" : ""}`), + }; + }); + +it.effect.each([ + ["30 minutes", "queued"], + ["2 hours", "cancelled"], +] as const)("a sandbox chat's message after %s leaves its held message %s", ([age, status]) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make(`thread:stop-sandbox-held:${status}`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${threadId}`), + threadId, + projectId: ProjectId.make("project:thread-stop"), + title: threadId, + modelSelection: bridgeSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* send(threadId, "active", "start_immediately"); + yield* send(threadId, "queued before the stop", "queue_after_active"); + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make(`stop:${threadId}`), + threadId, + }); + assert.deepEqual((yield* threadState(threadId)).runs, ["interrupted", "queued:held"]); + + yield* TestClock.adjust(age); + yield* send(threadId, "back", "start_immediately"); + assert.deepEqual((yield* threadState(threadId)).runs, ["interrupted", status, "starting"]); + }).pipe(Effect.provide(layerTest)), +); + +it.effect.each([ + ["30 minutes", "starting"], + ["2 hours", "cancelled"], +] as const)("a sandbox chat's message queued %s before its run ends is %s", ([age, status]) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make(`thread:sandbox-queued:${status}`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${threadId}`), + threadId, + projectId: ProjectId.make("project:thread-stop"), + title: threadId, + modelSelection: bridgeSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* send(threadId, "active", "start_immediately"); + yield* send(threadId, "queued behind it", "queue_after_active"); + assert.deepEqual((yield* threadState(threadId)).runs, ["starting", "queued"]); + + yield* TestClock.adjust(age); + const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + const now = yield* DateTime.now; + yield* projections.apply({ + id: EventId.make(`event:sandbox-queued:${status}`), + type: "run.updated", + threadId, + runId: active.id, + occurredAt: now, + payload: { ...active, status: "completed", completedAt: now }, + } as OrchestrationV2DomainEvent); + yield* orchestrator.resumeQueuedRuns; + assert.deepEqual((yield* threadState(threadId)).runs, ["completed", status]); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index d50cc591cea42..fc52191d32b29 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -13,8 +13,6 @@ import { ProviderThreadId, ProviderTurnId, RuntimeRequestId, - SANDBOX_BRIDGE_INSTANCE_ID, - SANDBOX_BRIDGE_MODEL, ScheduledTaskId, ThreadId, TurnItemId, @@ -57,15 +55,6 @@ const adapter = { planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), openSession: () => Effect.die("Runs here never reach a provider"), } as ProviderAdapter.ProviderAdapterV2["Service"]; -const bridgeSelection = { - instanceId: ProviderInstanceId.make(SANDBOX_BRIDGE_INSTANCE_ID), - model: SANDBOX_BRIDGE_MODEL, -}; -const bridgeAdapter = { - ...adapter, - instanceId: bridgeSelection.instanceId, - driver: ProviderDriverKind.make("acpRegistry"), -} as ProviderAdapter.ProviderAdapterV2["Service"]; const layerDatabase = SqlitePersistence.layerMemory; const layerTest = ThreadManagementService.layer.pipe( Layer.provideMerge( @@ -76,7 +65,7 @@ const layerTest = ThreadManagementService.layer.pipe( EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), ProviderReplayHarness.layerWithRegistry( { name: "thread-stop" }, - ProviderAdapterRegistry.layerFromAdapters([adapter, bridgeAdapter]), + ProviderAdapterRegistry.layerFromAdapters([adapter]), { databaseLayer: layerDatabase, runEffectWorker: false }, ), ), @@ -811,84 +800,6 @@ it.effect("a message the user sends after Stop releases the held queue; an agent }).pipe(Effect.provide(layerTest)), ); -it.effect.each([ - ["30 minutes", "queued"], - ["2 hours", "cancelled"], -] as const)("a sandbox chat's message after %s leaves its held message %s", ([age, status]) => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const threadId = ThreadId.make(`thread:stop-sandbox-held:${status}`); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make(`create:${threadId}`), - threadId, - projectId: ProjectId.make("project:thread-stop"), - title: threadId, - modelSelection: bridgeSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdBy: "user", - creationSource: "web", - }); - yield* send(threadId, "active", "start_immediately"); - yield* send(threadId, "queued before the stop", "queue_after_active"); - yield* orchestrator.dispatch({ - type: "thread.stop", - commandId: CommandId.make(`stop:${threadId}`), - threadId, - }); - assert.deepEqual((yield* threadState(threadId)).runs, ["interrupted", "queued:held"]); - - yield* TestClock.adjust(age); - yield* send(threadId, "back", "start_immediately"); - assert.deepEqual((yield* threadState(threadId)).runs, ["interrupted", status, "starting"]); - }).pipe(Effect.provide(layerTest)), -); - -it.effect.each([ - ["30 minutes", "starting"], - ["2 hours", "cancelled"], -] as const)("a sandbox chat's message queued %s before its run ends is %s", ([age, status]) => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const projections = yield* ProjectionStore.ProjectionStoreV2; - const threadId = ThreadId.make(`thread:sandbox-queued:${status}`); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make(`create:${threadId}`), - threadId, - projectId: ProjectId.make("project:thread-stop"), - title: threadId, - modelSelection: bridgeSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - createdBy: "user", - creationSource: "web", - }); - yield* send(threadId, "active", "start_immediately"); - yield* send(threadId, "queued behind it", "queue_after_active"); - assert.deepEqual((yield* threadState(threadId)).runs, ["starting", "queued"]); - - yield* TestClock.adjust(age); - const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; - const now = yield* DateTime.now; - yield* projections.apply({ - id: EventId.make(`event:sandbox-queued:${status}`), - type: "run.updated", - threadId, - runId: active.id, - occurredAt: now, - payload: { ...active, status: "completed", completedAt: now }, - } as OrchestrationV2DomainEvent); - yield* orchestrator.resumeQueuedRuns; - assert.deepEqual((yield* threadState(threadId)).runs, ["completed", status]); - }).pipe(Effect.provide(layerTest)), -); - it.effect( "an agent's auto send queues behind a run that is still stopping instead of steering it", () => diff --git a/apps/server/src/usage/cliproxyApi.sandbox.test.ts b/apps/server/src/usage/cliproxyApi.sandbox.test.ts new file mode 100644 index 0000000000000..a7d807b2f7268 --- /dev/null +++ b/apps/server/src/usage/cliproxyApi.sandbox.test.ts @@ -0,0 +1,81 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { HttpClient, HttpClientResponse, UrlParams } from "effect/http"; + +import { makeCliproxyApi } from "./cliproxyApi.ts"; + +const config = { + kind: "cliproxy", + url: "http://hub.test:8317", + managementKey: "management-secret", + enabled: true, +} as const; + +describe("CLIProxyAPI client keys", () => { + it.effect("appends one key with PATCH and removes only that key with DELETE", () => + Effect.gen(function* () { + const requests: Array<{ + method: string; + url: string; + auth: string | undefined; + body: unknown; + }> = []; + const http = HttpClient.make((request) => { + requests.push({ + method: request.method, + url: [request.url, UrlParams.toString(request.urlParams)].filter(Boolean).join("?"), + auth: request.headers.authorization, + body: + request.body._tag === "Uint8Array" + ? JSON.parse(new TextDecoder().decode(request.body.body)) + : undefined, + }); + return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ status: "ok" }))); + }); + const api = yield* makeCliproxyApi.pipe( + Effect.provideService(HttpClient.HttpClient, http), + Effect.provide(NodeCrypto.layer), + ); + yield* api.addApiKey(config, "t3-sandbox-web-0123456789abcdef"); + yield* api.removeApiKey(config, "t3-sandbox-web-0123456789abcdef"); + expect(requests).toEqual([ + { + method: "PATCH", + url: "http://hub.test:8317/v0/management/api-keys", + auth: "Bearer management-secret", + // An `old` the hub does not have makes it append `new` instead of replacing a key. + body: { + old: "t3-sandbox-web-0123456789abcdef", + new: "t3-sandbox-web-0123456789abcdef", + }, + }, + { + method: "DELETE", + url: "http://hub.test:8317/v0/management/api-keys?value=t3-sandbox-web-0123456789abcdef", + auth: "Bearer management-secret", + body: undefined, + }, + ]); + }), + ); + + it.effect("names the status, never the key, when the hub refuses it", () => + Effect.gen(function* () { + const http = HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ error: "t3-sandbox-web-0123456789abcdef" }, { status: 403 }), + ), + ), + ); + const api = yield* makeCliproxyApi.pipe( + Effect.provideService(HttpClient.HttpClient, http), + Effect.provide(NodeCrypto.layer), + ); + const error = yield* Effect.flip(api.addApiKey(config, "t3-sandbox-web-0123456789abcdef")); + expect(error.detail).toBe("The hub answered with HTTP 403."); + }), + ); +}); diff --git a/apps/server/src/usage/cliproxyApi.test.ts b/apps/server/src/usage/cliproxyApi.test.ts index bf356a80771f8..5002d2223d1ba 100644 --- a/apps/server/src/usage/cliproxyApi.test.ts +++ b/apps/server/src/usage/cliproxyApi.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; -import { HttpClient, HttpClientError, HttpClientResponse, UrlParams } from "effect/http"; +import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import { makeCliproxyApi } from "./cliproxyApi.ts"; @@ -721,71 +721,3 @@ describe("CLIProxyAPI built-in management API", () => { }), ); }); - -describe("CLIProxyAPI client keys", () => { - it.effect("appends one key with PATCH and removes only that key with DELETE", () => - Effect.gen(function* () { - const requests: Array<{ - method: string; - url: string; - auth: string | undefined; - body: unknown; - }> = []; - const http = HttpClient.make((request) => { - requests.push({ - method: request.method, - url: [request.url, UrlParams.toString(request.urlParams)].filter(Boolean).join("?"), - auth: request.headers.authorization, - body: - request.body._tag === "Uint8Array" - ? JSON.parse(new TextDecoder().decode(request.body.body)) - : undefined, - }); - return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ status: "ok" }))); - }); - const api = yield* makeCliproxyApi.pipe( - Effect.provideService(HttpClient.HttpClient, http), - Effect.provide(NodeCrypto.layer), - ); - yield* api.addApiKey(config, "t3-sandbox-web-0123456789abcdef"); - yield* api.removeApiKey(config, "t3-sandbox-web-0123456789abcdef"); - expect(requests).toEqual([ - { - method: "PATCH", - url: "http://hub.test:8317/v0/management/api-keys", - auth: "Bearer management-secret", - // An `old` the hub does not have makes it append `new` instead of replacing a key. - body: { - old: "t3-sandbox-web-0123456789abcdef", - new: "t3-sandbox-web-0123456789abcdef", - }, - }, - { - method: "DELETE", - url: "http://hub.test:8317/v0/management/api-keys?value=t3-sandbox-web-0123456789abcdef", - auth: "Bearer management-secret", - body: undefined, - }, - ]); - }), - ); - - it.effect("names the status, never the key, when the hub refuses it", () => - Effect.gen(function* () { - const http = HttpClient.make((request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - Response.json({ error: "t3-sandbox-web-0123456789abcdef" }, { status: 403 }), - ), - ), - ); - const api = yield* makeCliproxyApi.pipe( - Effect.provideService(HttpClient.HttpClient, http), - Effect.provide(NodeCrypto.layer), - ); - const error = yield* Effect.flip(api.addApiKey(config, "t3-sandbox-web-0123456789abcdef")); - expect(error.detail).toBe("The hub answered with HTTP 403."); - }), - ); -}); diff --git a/apps/web/src/components/ChatView.logic.sandbox.test.ts b/apps/web/src/components/ChatView.logic.sandbox.test.ts new file mode 100644 index 0000000000000..a056731b7b27d --- /dev/null +++ b/apps/web/src/components/ChatView.logic.sandbox.test.ts @@ -0,0 +1,38 @@ +import { waitingMessageCanResend } from "./ChatView.logic"; +import { describe, expect, it } from "vite-plus/test"; + +describe("waitingMessageCanResend", () => { + const ready = { + waitingDraftId: "draft-1", + draftId: "draft-1", + isLocalDraftThread: true, + onSandbox: true, + canOperateThread: true, + isSendBusy: false, + isRevertingCheckpoint: false, + threadDetailLoading: false, + clientSettingsHydrated: true, + needsLoadBalancing: false, + activeEnvironmentUnavailable: false, + hasPendingUserInput: false, + feedbackUploading: false, + }; + + it("resends once the draft is idle", () => { + expect(waitingMessageCanResend(ready)).toBe(true); + }); + + // A sandbox paired a moment ago can show its project before its session grants this app any + // scope; a send then would be dropped while the message no longer waits. + it("waits until the draft's sandbox lets this app start threads", () => { + expect(waitingMessageCanResend({ ...ready, canOperateThread: false })).toBe(false); + expect(waitingMessageCanResend({ ...ready, onSandbox: false, canOperateThread: false })).toBe( + true, + ); + }); + + it("waits only for its own draft", () => { + expect(waitingMessageCanResend({ ...ready, draftId: "draft-2" })).toBe(false); + expect(waitingMessageCanResend({ ...ready, waitingDraftId: null })).toBe(false); + }); +}); diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 823cea78999b0..dbbb445a5ec95 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -17,7 +17,6 @@ import { withMessageContext, deriveAvailableRevertTurnCounts, deriveThreadPendingBackgroundTasks, - waitingMessageCanResend, } from "./ChatView.logic"; import { isThreadEnvironmentLocked, @@ -1641,39 +1640,3 @@ describe("prepareRevertedMessageAttachments", () => { expect(store.getComposerDraft(target)?.images.map(({ id }) => id)).toEqual(["restored"]); }); }); - -describe("waitingMessageCanResend", () => { - const ready = { - waitingDraftId: "draft-1", - draftId: "draft-1", - isLocalDraftThread: true, - onSandbox: true, - canOperateThread: true, - isSendBusy: false, - isRevertingCheckpoint: false, - threadDetailLoading: false, - clientSettingsHydrated: true, - needsLoadBalancing: false, - activeEnvironmentUnavailable: false, - hasPendingUserInput: false, - feedbackUploading: false, - }; - - it("resends once the draft is idle", () => { - expect(waitingMessageCanResend(ready)).toBe(true); - }); - - // A sandbox paired a moment ago can show its project before its session grants this app any - // scope; a send then would be dropped while the message no longer waits. - it("waits until the draft's sandbox lets this app start threads", () => { - expect(waitingMessageCanResend({ ...ready, canOperateThread: false })).toBe(false); - expect(waitingMessageCanResend({ ...ready, onSandbox: false, canOperateThread: false })).toBe( - true, - ); - }); - - it("waits only for its own draft", () => { - expect(waitingMessageCanResend({ ...ready, draftId: "draft-2" })).toBe(false); - expect(waitingMessageCanResend({ ...ready, waitingDraftId: null })).toBe(false); - }); -}); diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx index 3ea19f2380c4a..0b9bcc943b76e 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx @@ -4,7 +4,6 @@ import { EnvironmentId, ProviderDriverKind, ProviderInstanceId, - SANDBOX_BRIDGE_INSTANCE_ID, type ProviderAuthState, type ServerProvider, type UnifiedSettings, @@ -384,34 +383,6 @@ describe("EnvironmentProviderSettings routing", () => { ]); }); - it("leaves out the internal sandbox bridge instance", async () => { - await setup(); - const bridgeId = ProviderInstanceId.make(SANDBOX_BRIDGE_INSTANCE_ID); - state.settings = { - ...DEFAULT_UNIFIED_SETTINGS, - providerInstances: { - [customId]: { - driver: ProviderDriverKind.make("codex"), - enabled: true, - displayName: "Work", - }, - [bridgeId]: { - driver: ProviderDriverKind.make("acpRegistry"), - enabled: true, - displayName: "Sandboxes", - config: { source: "local", commandPath: "/t3", commandArgs: ["sandbox-bridge"] }, - }, - }, - }; - await setProviders([ - provider(), - { ...provider(), instanceId: bridgeId, driver: ProviderDriverKind.make("acpRegistry") }, - ]); - await using _screen = await render(panel()); - await expect.element(page.getByRole("switch", { name: "Enable Work" }).first()).toBeVisible(); - await expect.element(page.getByText("Sandboxes")).not.toBeInTheDocument(); - }); - it("routes explicit ACP browser authentication consent to the selected environment", async () => { await setup(); const instanceId = ProviderInstanceId.make("acpRegistry_antigravity"); diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.environment.sandbox.browser.test.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.environment.sandbox.browser.test.tsx new file mode 100644 index 0000000000000..842b571223117 --- /dev/null +++ b/apps/web/src/components/settings/ProviderSettingsPanel.environment.sandbox.browser.test.tsx @@ -0,0 +1,279 @@ +import { RegistryContext } from "@effect/atom-react"; +import { + DEFAULT_UNIFIED_SETTINGS, + EnvironmentId, + ProviderDriverKind, + ProviderInstanceId, + SANDBOX_BRIDGE_INSTANCE_ID, + type ProviderAuthState, + type ServerProvider, + type UnifiedSettings, +} from "@t3tools/contracts"; +import { AsyncResult, type Atom } from "effect/reactivity"; +import type { ReactNode } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import "~/index.css"; +import { act, render } from "../../../test/render"; + +const state = vi.hoisted(() => ({ + providers: null as unknown as Atom.Writable>, + providerAuthQuery: null as unknown, + providerAuth: null as ProviderAuthState | null, + settings: null as unknown as UnifiedSettings, + canManageProviders: true, + canWriteSettings: true, + searchTargetId: null as string | null, + readEnvironmentIds: [] as string[], + updateEnvironmentIds: [] as string[], + mutationEnvironmentIds: [] as string[], + refresh: vi.fn(), + updateProvider: vi.fn(), + uninstall: vi.fn(), + acceptUrlAuth: vi.fn(), + updateSettings: vi.fn(), + updateModelPreferences: vi.fn(), + toggleFavorite: vi.fn(), + mutateProviderInstance: vi.fn(), + confirm: vi.fn<() => Promise>(), +})); + +vi.mock(import("../../state/server"), async (original) => { + const actual = await original(); + const { Atom } = await import("effect/reactivity"); + const providers = Atom.make>([]).pipe(Atom.keepAlive); + state.providers = providers; + const config = Atom.make(null); + const providerAuth = Atom.make(null); + state.providerAuthQuery = providerAuth; + const commandLabels = { + refreshProviders: "refresh", + updateProvider: "update", + uninstallAcpRegistryManagedBinary: "uninstall", + acceptAcpRegistryUrlAuth: "accept-url-auth", + } as const; + const labelled = Object.fromEntries( + Object.entries(commandLabels).map(([key, label]) => [ + key, + { ...actual.serverEnvironment[key as keyof typeof commandLabels], label }, + ]), + ); + return { + ...actual, + providersIgnoringCheckedAtAtom: (() => providers) as never, + serverEnvironment: { + ...actual.serverEnvironment, + ...labelled, + configValueAtom: (() => config) as never, + providerAuthState: (() => providerAuth) as never, + providersValueAtom: (() => providers) as never, + } as never, + }; +}); +vi.mock(import("../../state/use-atom-command"), async (original) => ({ + ...(await original()), + useAtomCommand: ((command: { label?: string }) => + ({ + refresh: state.refresh, + update: state.updateProvider, + uninstall: state.uninstall, + "accept-url-auth": state.acceptUrlAuth, + })[command.label ?? ""] ?? vi.fn()) as never, +})); +vi.mock(import("~/localApi"), async (original) => { + const api = { dialogs: { confirm: state.confirm } }; + return { + ...(await original()), + readLocalApi: (() => api) as never, + ensureLocalApi: (() => api) as never, + }; +}); +vi.mock(import("../../state/query"), async (original) => ({ + ...(await original()), + useEnvironmentQuery: ((query: unknown) => ({ + data: query === state.providerAuthQuery ? state.providerAuth : null, + error: null, + isPending: false, + refresh: vi.fn(), + })) as never, +})); +vi.mock(import("../../hooks/useSettings"), async (original) => ({ + ...(await original()), + useEnvironmentSettings: ((environmentId: string) => { + state.readEnvironmentIds.push(environmentId); + return state.settings; + }) as never, + useUpdateEnvironmentSettings: ((environmentId: string) => { + state.updateEnvironmentIds.push(environmentId); + return state.updateSettings; + }) as never, + useUpdateEnvironmentModelPreferences: (() => state.updateModelPreferences) as never, + useToggleEnvironmentModelFavorite: (() => state.toggleFavorite) as never, + usePersistEnvironmentProviderInstanceMutation: ((environmentId: string) => { + state.mutationEnvironmentIds.push(environmentId); + return state.mutateProviderInstance; + }) as never, +})); +vi.mock(import("../../state/session"), async (original) => { + const scope = (environmentId: string, requested: string) => + environmentId === "remote-device" && + (requested === "providers:manage" + ? state.canManageProviders + : requested === "settings:write" + ? state.canWriteSettings + : requested === "orchestration:read"); + return { + ...(await original()), + useEnvironmentScope: scope as never, + readEnvironmentScope: scope as never, + }; +}); +vi.mock(import("../../state/entities"), async (original) => ({ + ...(await original()), + useProjects: (() => []) as never, +})); +vi.mock(import("./settingsLayout"), async (original) => ({ + ...(await original()), + useSettingsSearchTargetId: () => state.searchTargetId, + SettingsRow: (({ + id, + title, + description, + status, + control, + children, + }: { + id?: string; + title: ReactNode; + description?: ReactNode; + status?: ReactNode; + control?: ReactNode; + children?: ReactNode; + }) => ( +
+

{title}

+ {description} + {status} + {control} + {children} +
+ )) as never, +})); +vi.mock(import("./UsageProviderSettings"), async (original) => ({ + ...(await original()), + UsageProviderSettings: (() => null) as never, +})); +vi.mock(import("../ProviderUpdatesAction"), async (original) => ({ + ...(await original()), + ProviderUpdatesAction: (() => null) as never, +})); + +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { EnvironmentProviderSettings } from "./ProviderSettingsPanel"; + +const environmentId = EnvironmentId.make("remote-device"); +const codexId = ProviderInstanceId.make("codex"); +const customId = ProviderInstanceId.make("codex_work"); + +function provider(): ServerProvider { + return { + instanceId: codexId, + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-07-24T12:00:00.000Z", + models: [{ slug: "chosen", name: "Chosen", isCustom: false, capabilities: null }], + slashCommands: [], + skills: [], + versionAdvisory: { + status: "behind_latest", + currentVersion: "1.0.0", + latestVersion: "1.1.0", + updateCommand: "pnpm add -g @openai/codex@latest", + canUpdate: true, + checkedAt: "2026-07-24T12:00:00.000Z", + message: "Update available.", + }, + }; +} + +const setProviders = (providers: ReadonlyArray) => + act(async () => appAtomRegistry.set(state.providers, providers)); + +function panel(options?: { + readonly readOnly?: boolean; + readonly targetInstanceId?: ProviderInstanceId; +}) { + return ( + +
+ +
+
+ ); +} + +// The section header and the end of the provider list both offer Add provider. + +async function setup() { + await page.viewport(1280, 900); + state.settings = DEFAULT_UNIFIED_SETTINGS; + state.canManageProviders = true; + state.canWriteSettings = true; + state.searchTargetId = null; + state.providerAuth = null; + state.readEnvironmentIds = []; + state.updateEnvironmentIds = []; + state.mutationEnvironmentIds = []; + state.updateSettings.mockReset(); + state.updateModelPreferences.mockReset(); + state.toggleFavorite.mockReset(); + state.mutateProviderInstance.mockReset().mockResolvedValue(AsyncResult.success({})); + state.confirm.mockReset().mockResolvedValue(false); + state.refresh.mockReset().mockResolvedValue(AsyncResult.success(undefined)); + state.updateProvider.mockReset().mockResolvedValue(AsyncResult.success(undefined)); + state.uninstall.mockReset().mockResolvedValue(AsyncResult.success({})); + state.acceptUrlAuth.mockReset().mockResolvedValue(AsyncResult.success({ accepted: true })); + await setProviders([]); +} + +describe("EnvironmentProviderSettings routing with sandboxes", () => { + it("leaves out the internal sandbox bridge instance", async () => { + await setup(); + const bridgeId = ProviderInstanceId.make(SANDBOX_BRIDGE_INSTANCE_ID); + state.settings = { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [customId]: { + driver: ProviderDriverKind.make("codex"), + enabled: true, + displayName: "Work", + }, + [bridgeId]: { + driver: ProviderDriverKind.make("acpRegistry"), + enabled: true, + displayName: "Sandboxes", + config: { source: "local", commandPath: "/t3", commandArgs: ["sandbox-bridge"] }, + }, + }, + }; + await setProviders([ + provider(), + { ...provider(), instanceId: bridgeId, driver: ProviderDriverKind.make("acpRegistry") }, + ]); + await using _screen = await render(panel()); + await expect.element(page.getByRole("switch", { name: "Enable Work" }).first()).toBeVisible(); + await expect.element(page.getByText("Sandboxes")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/components/settings/scopedSettings.sandbox.test.ts b/apps/web/src/components/settings/scopedSettings.sandbox.test.ts new file mode 100644 index 0000000000000..aac5393d46727 --- /dev/null +++ b/apps/web/src/components/settings/scopedSettings.sandbox.test.ts @@ -0,0 +1,192 @@ +import { + DEFAULT_SERVER_SETTINGS, + EnvironmentId, + ProjectId, + ProviderInstanceId, + type ServerSettings, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; +import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; + +import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; +import { persistScopedSettingsPatch, planScopedSettingsPatch } from "./scopedSettings"; +import { resolveSettingsScope } from "./settingsScope"; + +function environment( + id: string, + options: { + connected?: boolean; + loaded?: boolean; + settings?: Partial; + } = {}, +) { + return { + environmentId: EnvironmentId.make(id), + label: id, + connection: { + phase: options.connected === false ? ("offline" as const) : ("connected" as const), + }, + serverConfig: + options.loaded === false + ? null + : { + settings: { ...DEFAULT_SERVER_SETTINGS, ...options.settings }, + }, + }; +} + +const laptop = environment("Laptop"); +const server = environment("Server"); +const offline = environment("Offline", { connected: false }); +const loading = environment("Loading", { loaded: false }); +const environments = [laptop, server, offline, loading]; + +const projectId = ProjectId.make("project"); +const laptopProjectId = ProjectId.make("laptop-project"); +const member = { + id: projectId, + environmentId: server.environmentId, + title: "Project", + workspaceRoot: "/repo", + physicalProjectKey: `${server.environmentId}:/repo`, + environmentLabel: server.label, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-09-07T00:00:00.000Z", + updatedAt: "2026-09-07T00:00:00.000Z", +}; +const laptopMember = { + ...member, + id: laptopProjectId, + environmentId: laptop.environmentId, + physicalProjectKey: `${laptop.environmentId}:/repo`, + environmentLabel: laptop.label, +}; +const group: SidebarProjectSnapshot = { + ...member, + projectKey: "project-group", + displayName: "Project", + memberProjects: [member, laptopMember], + memberProjectRefs: [ + { environmentId: server.environmentId, projectId }, + { environmentId: laptop.environmentId, projectId: laptopProjectId }, + ], + groupedProjectCount: 2, + environmentPresence: "remote-only", + allRemoteMembersAreDesktopLocal: false, + allRemoteMembersAreWsl: false, + remoteEnvironmentLabels: [server.label, laptop.label], + pinned: false, + archived: false, +}; + +describe("sandbox followers", () => { + const sandbox = environment("Sandbox"); + const sandboxProjectId = ProjectId.make("sandbox-clone"); + const sandboxes = { + hostEnvironmentId: laptop.environmentId, + followers: [ + { + environmentId: sandbox.environmentId, + hostProjectId: laptopProjectId, + projectId: sandboxProjectId, + }, + ], + }; + const patch = { branchNamePrefix: "ada", worktreesDirectory: "/Users/ada/trees" }; + + it("repeats the host's followed settings on its sandboxes and reports only the host's", () => { + const scope = resolveSettingsScope({}, [], environments, sandboxes); + const plan = planScopedSettingsPatch(scope, environments, patch, { + followerEnvironments: [sandbox], + }); + expect(plan.serverWrites.map((write) => write.environmentId)).toEqual([ + laptop.environmentId, + server.environmentId, + ]); + expect(plan.followerWrites).toEqual([ + expect.objectContaining({ + environmentId: sandbox.environmentId, + patch: { branchNamePrefix: "ada" }, + }), + ]); + // A setting that stays on the host, or a scope without the host, reaches no sandbox. + expect( + planScopedSettingsPatch( + scope, + environments, + { worktreesDirectory: "/x" }, + { followerEnvironments: [sandbox] }, + ).followerWrites, + ).toEqual([]); + expect( + planScopedSettingsPatch( + resolveSettingsScope({ machine: server.environmentId }, [], environments, sandboxes), + environments, + patch, + { followerEnvironments: [sandbox] }, + ).followerWrites, + ).toEqual([]); + }); + + it("repeats a host project's override on the sandbox's clone of it", () => { + const scope = resolveSettingsScope( + { project: group.projectKey }, + [group], + environments, + sandboxes, + ); + expect( + planScopedSettingsPatch( + scope, + environments, + { branchNamePrefix: "ada" }, + { followerEnvironments: [sandbox] }, + ).followerWrites, + ).toEqual([ + expect.objectContaining({ + environmentId: sandbox.environmentId, + patch: { projectSettingsOverrides: { [sandboxProjectId]: { branchNamePrefix: "ada" } } }, + }), + ]); + // Pi owns a sandbox's default model. + expect( + planScopedSettingsPatch( + scope, + environments, + { defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt" } }, + { followerEnvironments: [sandbox] }, + ).followerWrites, + ).toEqual([]); + }); + + it("never waits for or reports a sandbox's write", async () => { + const scope = resolveSettingsScope({}, [], [laptop], sandboxes); + const plan = planScopedSettingsPatch( + scope, + [laptop], + { branchNamePrefix: "ada" }, + { followerEnvironments: [sandbox] }, + ); + const writes: EnvironmentId[] = []; + const result = await persistScopedSettingsPatch( + plan, + async ({ environmentId, input }) => { + writes.push(environmentId); + // A sandbox that went away answers only when it reconnects, if ever. + return environmentId === sandbox.environmentId + ? new Promise(() => {}) + : { + _tag: "Success" as const, + value: applyServerSettingsPatch(laptop.serverConfig!.settings, input.patch), + }; + }, + () => {}, + ); + expect(writes).toContain(sandbox.environmentId); + expect(result.failedEnvironments).toEqual([]); + expect(result.savedEnvironments.map((write) => write.environmentId)).toEqual([ + laptop.environmentId, + ]); + }); +}); diff --git a/apps/web/src/components/settings/scopedSettings.test.ts b/apps/web/src/components/settings/scopedSettings.test.ts index bd40e30851ea0..cba475fa01ed5 100644 --- a/apps/web/src/components/settings/scopedSettings.test.ts +++ b/apps/web/src/components/settings/scopedSettings.test.ts @@ -992,114 +992,3 @@ describe("model selection patches at project scope", () => { ).toEqual({ ...saved, options }); }); }); - -describe("sandbox followers", () => { - const sandbox = environment("Sandbox"); - const sandboxProjectId = ProjectId.make("sandbox-clone"); - const sandboxes = { - hostEnvironmentId: laptop.environmentId, - followers: [ - { - environmentId: sandbox.environmentId, - hostProjectId: laptopProjectId, - projectId: sandboxProjectId, - }, - ], - }; - const patch = { branchNamePrefix: "ada", worktreesDirectory: "/Users/ada/trees" }; - - it("repeats the host's followed settings on its sandboxes and reports only the host's", () => { - const scope = resolveSettingsScope({}, [], environments, sandboxes); - const plan = planScopedSettingsPatch(scope, environments, patch, { - followerEnvironments: [sandbox], - }); - expect(plan.serverWrites.map((write) => write.environmentId)).toEqual([ - laptop.environmentId, - server.environmentId, - ]); - expect(plan.followerWrites).toEqual([ - expect.objectContaining({ - environmentId: sandbox.environmentId, - patch: { branchNamePrefix: "ada" }, - }), - ]); - // A setting that stays on the host, or a scope without the host, reaches no sandbox. - expect( - planScopedSettingsPatch( - scope, - environments, - { worktreesDirectory: "/x" }, - { followerEnvironments: [sandbox] }, - ).followerWrites, - ).toEqual([]); - expect( - planScopedSettingsPatch( - resolveSettingsScope({ machine: server.environmentId }, [], environments, sandboxes), - environments, - patch, - { followerEnvironments: [sandbox] }, - ).followerWrites, - ).toEqual([]); - }); - - it("repeats a host project's override on the sandbox's clone of it", () => { - const scope = resolveSettingsScope( - { project: group.projectKey }, - [group], - environments, - sandboxes, - ); - expect( - planScopedSettingsPatch( - scope, - environments, - { branchNamePrefix: "ada" }, - { followerEnvironments: [sandbox] }, - ).followerWrites, - ).toEqual([ - expect.objectContaining({ - environmentId: sandbox.environmentId, - patch: { projectSettingsOverrides: { [sandboxProjectId]: { branchNamePrefix: "ada" } } }, - }), - ]); - // Pi owns a sandbox's default model. - expect( - planScopedSettingsPatch( - scope, - environments, - { defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt" } }, - { followerEnvironments: [sandbox] }, - ).followerWrites, - ).toEqual([]); - }); - - it("never waits for or reports a sandbox's write", async () => { - const scope = resolveSettingsScope({}, [], [laptop], sandboxes); - const plan = planScopedSettingsPatch( - scope, - [laptop], - { branchNamePrefix: "ada" }, - { followerEnvironments: [sandbox] }, - ); - const writes: EnvironmentId[] = []; - const result = await persistScopedSettingsPatch( - plan, - async ({ environmentId, input }) => { - writes.push(environmentId); - // A sandbox that went away answers only when it reconnects, if ever. - return environmentId === sandbox.environmentId - ? new Promise(() => {}) - : { - _tag: "Success" as const, - value: applyServerSettingsPatch(laptop.serverConfig!.settings, input.patch), - }; - }, - () => {}, - ); - expect(writes).toContain(sandbox.environmentId); - expect(result.failedEnvironments).toEqual([]); - expect(result.savedEnvironments.map((write) => write.environmentId)).toEqual([ - laptop.environmentId, - ]); - }); -}); diff --git a/apps/web/src/components/settings/settingsScope.sandbox.test.ts b/apps/web/src/components/settings/settingsScope.sandbox.test.ts new file mode 100644 index 0000000000000..2ea2f50d3869d --- /dev/null +++ b/apps/web/src/components/settings/settingsScope.sandbox.test.ts @@ -0,0 +1,104 @@ +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import type { + SidebarProjectGroupMember, + SidebarProjectSnapshot, +} from "../../sidebarProjectGrouping"; +import { normalizeSandboxScopeSearch, resolveSettingsScope } from "./settingsScope"; + +const laptopId = EnvironmentId.make("laptop"); +const serverId = EnvironmentId.make("server"); +const environments = [ + { environmentId: laptopId, label: "Laptop" }, + { environmentId: serverId, label: "Server" }, +]; + +function member(id: string, environmentId: EnvironmentId): SidebarProjectGroupMember { + return { + id: ProjectId.make(id), + environmentId, + title: "T3 Code", + workspaceRoot: `/repos/${id}`, + physicalProjectKey: `${environmentId}:/repos/${id}`, + environmentLabel: + environments.find((environment) => environment.environmentId === environmentId)?.label ?? + null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-09-07T00:00:00.000Z", + updatedAt: "2026-09-07T00:00:00.000Z", + }; +} + +const first = member("first", laptopId); +const second = member("second", laptopId); +const third = member("third", serverId); +const other = member("other", serverId); + +function group( + projectKey: string, + members: readonly SidebarProjectGroupMember[], +): SidebarProjectSnapshot { + return { + ...members[0]!, + projectKey, + displayName: projectKey, + memberProjects: members, + memberProjectRefs: members.map((project) => ({ + environmentId: project.environmentId, + projectId: project.id, + })), + groupedProjectCount: members.length, + environmentPresence: "mixed", + allRemoteMembersAreDesktopLocal: false, + allRemoteMembersAreWsl: false, + remoteEnvironmentLabels: [], + pinned: false, + archived: false, + }; +} + +const groups = [group("t3code", [first, second, third]), group("other", [other])]; + +describe("sandboxes in the settings scope", () => { + const sandboxId = EnvironmentId.make("sandbox"); + const clone = member("clone", sandboxId); + const sandboxes = { + hostEnvironmentId: laptopId, + followers: [{ environmentId: sandboxId, hostProjectId: first.id, projectId: clone.id }], + }; + // Sandbox checkouts are left out of the groups the scope sees, but links may still name them. + const withSandbox = () => [ + group("t3code", [first, second, third, clone]), + group("other", [other]), + ]; + const separate = () => [...groups, group("clone-only", [clone])]; + const normalize = (search: object, hidden = withSandbox) => + normalizeSandboxScopeSearch(search, groups, hidden, sandboxes); + + it("opens the host instead of a sandbox, and leaves other remotes alone", () => { + expect(normalize({ machine: sandboxId })).toEqual({ machine: laptopId }); + expect(normalize({ project: "t3code", machine: serverId })).toEqual({ + project: "t3code", + machine: serverId, + }); + expect(normalize({ project: "t3code", checkout: clone.physicalProjectKey })).toEqual({ + project: "t3code", + machine: laptopId, + }); + expect(normalize({ project: "clone-only" }, separate)).toEqual({ project: "t3code" }); + }); + + it("makes the host's sandboxes followers of every scope that writes to the host", () => { + const resolve = (search: object) => + resolveSettingsScope(search, groups, environments, sandboxes).followers; + expect(resolve({})).toEqual([{ environmentId: sandboxId, projectId: null }]); + expect(resolve({ machine: laptopId })).toEqual([{ environmentId: sandboxId, projectId: null }]); + expect(resolve({ machine: serverId })).toEqual([]); + expect(resolve({ project: "t3code" })).toEqual([ + { environmentId: sandboxId, projectId: clone.id }, + ]); + expect(resolve({ project: "t3code", checkout: second.physicalProjectKey })).toEqual([]); + }); +}); diff --git a/apps/web/src/components/settings/settingsScope.test.ts b/apps/web/src/components/settings/settingsScope.test.ts index 250d2285e3ab3..60e69b7714f11 100644 --- a/apps/web/src/components/settings/settingsScope.test.ts +++ b/apps/web/src/components/settings/settingsScope.test.ts @@ -5,11 +5,7 @@ import type { SidebarProjectGroupMember, SidebarProjectSnapshot, } from "../../sidebarProjectGrouping"; -import { - normalizeSandboxScopeSearch, - resolveSettingsScope, - validateSettingsScopeSearch, -} from "./settingsScope"; +import { resolveSettingsScope, validateSettingsScopeSearch } from "./settingsScope"; const laptopId = EnvironmentId.make("laptop"); const serverId = EnvironmentId.make("server"); @@ -164,45 +160,3 @@ describe("settings scope resolution", () => { }); }); }); - -describe("sandboxes in the settings scope", () => { - const sandboxId = EnvironmentId.make("sandbox"); - const clone = member("clone", sandboxId); - const sandboxes = { - hostEnvironmentId: laptopId, - followers: [{ environmentId: sandboxId, hostProjectId: first.id, projectId: clone.id }], - }; - // Sandbox checkouts are left out of the groups the scope sees, but links may still name them. - const withSandbox = () => [ - group("t3code", [first, second, third, clone]), - group("other", [other]), - ]; - const separate = () => [...groups, group("clone-only", [clone])]; - const normalize = (search: object, hidden = withSandbox) => - normalizeSandboxScopeSearch(search, groups, hidden, sandboxes); - - it("opens the host instead of a sandbox, and leaves other remotes alone", () => { - expect(normalize({ machine: sandboxId })).toEqual({ machine: laptopId }); - expect(normalize({ project: "t3code", machine: serverId })).toEqual({ - project: "t3code", - machine: serverId, - }); - expect(normalize({ project: "t3code", checkout: clone.physicalProjectKey })).toEqual({ - project: "t3code", - machine: laptopId, - }); - expect(normalize({ project: "clone-only" }, separate)).toEqual({ project: "t3code" }); - }); - - it("makes the host's sandboxes followers of every scope that writes to the host", () => { - const resolve = (search: object) => - resolveSettingsScope(search, groups, environments, sandboxes).followers; - expect(resolve({})).toEqual([{ environmentId: sandboxId, projectId: null }]); - expect(resolve({ machine: laptopId })).toEqual([{ environmentId: sandboxId, projectId: null }]); - expect(resolve({ machine: serverId })).toEqual([]); - expect(resolve({ project: "t3code" })).toEqual([ - { environmentId: sandboxId, projectId: clone.id }, - ]); - expect(resolve({ project: "t3code", checkout: second.physicalProjectKey })).toEqual([]); - }); -}); diff --git a/apps/web/src/components/threadActionMenu.logic.sandbox.test.ts b/apps/web/src/components/threadActionMenu.logic.sandbox.test.ts new file mode 100644 index 0000000000000..5bf68d5488753 --- /dev/null +++ b/apps/web/src/components/threadActionMenu.logic.sandbox.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { buildThreadActionMenuItems, type ThreadActionMenuState } from "./threadActionMenu.logic"; + +const baseState: ThreadActionMenuState = { + canOperate: true, + branch: null, + projectFilter: null, + isPinned: false, + isSettled: false, + autoSettleEnabled: true, + isSnoozed: false, + canSnoozeNow: true, + isRegeneratingTitle: false, + isRunning: false, + supports: { + settlement: true, + autoSettleOptOut: true, + snooze: true, + pinning: true, + titleRegeneration: true, + }, + snoozePresets: [ + { id: "hour", label: "In 1 hour", whenLabel: "3:00 PM", snoozedUntil: "2026-08-07T15:00:00Z" }, + ], +}; + +describe("buildThreadActionMenuItems on sandboxes", () => { + it("says why a sandbox thread cannot change and offers deleting its sandbox", () => { + const items = buildThreadActionMenuItems({ + ...baseState, + canOperate: false, + sandboxUnavailable: "The sandbox no longer exists", + }); + expect(items[0]).toEqual({ + id: "sandbox-unavailable", + label: "The sandbox no longer exists", + disabled: true, + }); + expect(items[1]).toMatchObject({ id: "pin", disabled: true, separatorBefore: true }); + expect(items.at(-1)).toMatchObject({ id: "delete-sandbox", label: "Delete sandbox…" }); + expect(items.at(-1)?.disabled).not.toBe(true); + expect(items.find((item) => item.id === "delete")?.disabled).toBe(true); + }); + + it("leaves an operable thread's menu as it was, sandbox or not", () => { + expect( + buildThreadActionMenuItems({ ...baseState, sandboxUnavailable: "The sandbox is stopped" }), + ).toEqual(buildThreadActionMenuItems(baseState)); + expect( + buildThreadActionMenuItems({ ...baseState, canOperate: false, sandboxUnavailable: null }), + ).toEqual(buildThreadActionMenuItems({ ...baseState, canOperate: false })); + }); +}); diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts index d505425d47163..bd9dfdcdcc4b6 100644 --- a/apps/web/src/components/threadActionMenu.logic.test.ts +++ b/apps/web/src/components/threadActionMenu.logic.test.ts @@ -74,30 +74,4 @@ describe("buildThreadActionMenuItems", () => { expect(items.find((item) => item.id === "archive")?.disabled).toBe(true); expect(items.find((item) => item.id === "turn-into-project")?.disabled).toBe(true); }); - - it("says why a sandbox thread cannot change and offers deleting its sandbox", () => { - const items = buildThreadActionMenuItems({ - ...baseState, - canOperate: false, - sandboxUnavailable: "The sandbox no longer exists", - }); - expect(items[0]).toEqual({ - id: "sandbox-unavailable", - label: "The sandbox no longer exists", - disabled: true, - }); - expect(items[1]).toMatchObject({ id: "pin", disabled: true, separatorBefore: true }); - expect(items.at(-1)).toMatchObject({ id: "delete-sandbox", label: "Delete sandbox…" }); - expect(items.at(-1)?.disabled).not.toBe(true); - expect(items.find((item) => item.id === "delete")?.disabled).toBe(true); - }); - - it("leaves an operable thread's menu as it was, sandbox or not", () => { - expect( - buildThreadActionMenuItems({ ...baseState, sandboxUnavailable: "The sandbox is stopped" }), - ).toEqual(buildThreadActionMenuItems(baseState)); - expect( - buildThreadActionMenuItems({ ...baseState, canOperate: false, sandboxUnavailable: null }), - ).toEqual(buildThreadActionMenuItems({ ...baseState, canOperate: false })); - }); }); diff --git a/apps/web/src/environmentGrouping.sandbox.test.ts b/apps/web/src/environmentGrouping.sandbox.test.ts new file mode 100644 index 0000000000000..217ccd213f2c8 --- /dev/null +++ b/apps/web/src/environmentGrouping.sandbox.test.ts @@ -0,0 +1,96 @@ +import { EnvironmentId, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { buildSidebarProjectSnapshots } from "./sidebarProjectGrouping"; +import type { Project } from "./types"; + +const primaryEnvironmentId = EnvironmentId.make("env-primary"); + +const repositoryIdentity = { + canonicalKey: "github.com/example/shared-repo", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "https://github.com/example/shared-repo.git", + }, +}; +const defaultGroupingSettings = { + sidebarProjectGroupingMode: "repository" as const, + sidebarProjectGroupingOverrides: {}, +}; + +function makeProject(overrides: Partial = {}): Project { + return { + id: ProjectId.make("project-1"), + environmentId: primaryEnvironmentId, + title: "shared-repo", + workspaceRoot: "/tmp/shared-repo", + repositoryIdentity: null, + defaultModelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + }, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + scripts: [], + ...overrides, + }; +} + +describe("environment grouping with sandboxes", () => { + it("leaves out sandbox placeholder projects unless asked to keep one", () => { + const real = makeProject({ title: "hello", workspaceRoot: "/work/hello" }); + const placeholder = makeProject({ + id: ProjectId.make("placeholder"), + title: "hello", + workspaceRoot: "/Users/me/.t3/userdata/sandbox-projects/octo/hello", + // Newest, so it would otherwise win its group. + updatedAt: "2026-02-01T00:00:00.000Z", + }); + const input = { + projects: [real, placeholder], + settings: defaultGroupingSettings, + primaryEnvironmentId, + resolveEnvironmentLabel: () => null, + }; + + expect(buildSidebarProjectSnapshots(input).map((group) => group.id)).toEqual([real.id]); + const kept = buildSidebarProjectSnapshots({ + ...input, + keepSandboxPlaceholder: (project) => project.id === placeholder.id, + }); + expect(kept.map((group) => group.id)).toEqual([real.id, placeholder.id]); + }); + + it("never lets a sandbox placeholder stand for the real project it is grouped with", () => { + const real = makeProject({ + title: "shared-repo", + workspaceRoot: "/work/shared-repo", + repositoryIdentity, + }); + // A placeholder inside a checkout resolves to that checkout's repository. + const placeholder = makeProject({ + id: ProjectId.make("placeholder"), + title: "octo-hello", + workspaceRoot: "/work/shared-repo/.t3/userdata/sandbox-projects/octo/hello", + repositoryIdentity, + projectIcon: { kind: "lucide", name: "cloud", color: "sky" }, + }); + const [group, ...rest] = buildSidebarProjectSnapshots({ + projects: [placeholder, real], + settings: defaultGroupingSettings, + primaryEnvironmentId, + resolveEnvironmentLabel: () => null, + keepSandboxPlaceholder: () => true, + }); + + expect(rest).toEqual([]); + expect(group).toMatchObject({ + id: real.id, + workspaceRoot: "/work/shared-repo", + displayName: "shared-repo", + groupedProjectCount: 2, + }); + expect(group).not.toHaveProperty("projectIcon"); + }); +}); diff --git a/apps/web/src/environmentGrouping.test.ts b/apps/web/src/environmentGrouping.test.ts index 1c6fef4d5d6c3..6a93f2d266078 100644 --- a/apps/web/src/environmentGrouping.test.ts +++ b/apps/web/src/environmentGrouping.test.ts @@ -107,62 +107,6 @@ describe("environment grouping", () => { }, ); - it("leaves out sandbox placeholder projects unless asked to keep one", () => { - const real = makeProject({ title: "hello", workspaceRoot: "/work/hello" }); - const placeholder = makeProject({ - id: ProjectId.make("placeholder"), - title: "hello", - workspaceRoot: "/Users/me/.t3/userdata/sandbox-projects/octo/hello", - // Newest, so it would otherwise win its group. - updatedAt: "2026-02-01T00:00:00.000Z", - }); - const input = { - projects: [real, placeholder], - settings: defaultGroupingSettings, - primaryEnvironmentId, - resolveEnvironmentLabel: () => null, - }; - - expect(buildSidebarProjectSnapshots(input).map((group) => group.id)).toEqual([real.id]); - const kept = buildSidebarProjectSnapshots({ - ...input, - keepSandboxPlaceholder: (project) => project.id === placeholder.id, - }); - expect(kept.map((group) => group.id)).toEqual([real.id, placeholder.id]); - }); - - it("never lets a sandbox placeholder stand for the real project it is grouped with", () => { - const real = makeProject({ - title: "shared-repo", - workspaceRoot: "/work/shared-repo", - repositoryIdentity, - }); - // A placeholder inside a checkout resolves to that checkout's repository. - const placeholder = makeProject({ - id: ProjectId.make("placeholder"), - title: "octo-hello", - workspaceRoot: "/work/shared-repo/.t3/userdata/sandbox-projects/octo/hello", - repositoryIdentity, - projectIcon: { kind: "lucide", name: "cloud", color: "sky" }, - }); - const [group, ...rest] = buildSidebarProjectSnapshots({ - projects: [placeholder, real], - settings: defaultGroupingSettings, - primaryEnvironmentId, - resolveEnvironmentLabel: () => null, - keepSandboxPlaceholder: () => true, - }); - - expect(rest).toEqual([]); - expect(group).toMatchObject({ - id: real.id, - workspaceRoot: "/work/shared-repo", - displayName: "shared-repo", - groupedProjectCount: 2, - }); - expect(group).not.toHaveProperty("projectIcon"); - }); - it("prefers an existing ordinary repository scope over a scratch alias", () => { const scratch = makeProject({ isScratch: true, repositoryIdentity }); const ordinary = makeProject({ diff --git a/apps/web/src/modelSelection.sandbox.test.ts b/apps/web/src/modelSelection.sandbox.test.ts new file mode 100644 index 0000000000000..8889c22d9c313 --- /dev/null +++ b/apps/web/src/modelSelection.sandbox.test.ts @@ -0,0 +1,82 @@ +import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts"; +import { DEFAULT_UNIFIED_SETTINGS, type UnifiedSettings } from "@t3tools/contracts/settings"; +import { describe, expect, it } from "vite-plus/test"; +import { resolveAppModelSelectionForInstance } from "./modelSelection"; + +function provider(input: { + provider?: ProviderDriverKind; + instanceId: string; + models?: ReadonlyArray; + supportsTextGeneration?: boolean; +}): ServerProvider { + const driver = + input.provider ?? + (input.instanceId.startsWith("claude_") + ? ProviderDriverKind.make("claudeAgent") + : ProviderDriverKind.make("codex")); + return { + instanceId: ProviderInstanceId.make(input.instanceId), + driver, + ...(input.supportsTextGeneration === undefined + ? {} + : { supportsTextGeneration: input.supportsTextGeneration }), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-01-01T00:00:00.000Z", + models: (input.models ?? []).map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: {}, + })), + slashCommands: [], + skills: [], + }; +} + +function settingsWithProviderInstances(): UnifiedSettings { + return { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [ProviderInstanceId.make("claudeAgent")]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { customModels: [] }, + }, + [ProviderInstanceId.make("claude_openrouter")]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { customModels: ["openai/gpt-5.5"] }, + }, + }, + }; +} + +describe("instance-scoped model selection on the sandbox bridge", () => { + it("keeps a sandbox chat's own model on the sandbox bridge, which lists only its placeholder", () => { + const acp = ProviderDriverKind.make("acpRegistry"); + const providers = [ + provider({ provider: acp, instanceId: "sandboxes", models: ["sandbox"] }), + provider({ provider: acp, instanceId: "kimi", models: ["kimi-k3"] }), + ]; + const settings = settingsWithProviderInstances(); + expect( + resolveAppModelSelectionForInstance( + ProviderInstanceId.make("sandboxes"), + settings, + providers, + "claude-fable-5-2", + ), + ).toBe("claude-fable-5-2"); + // Another agent on the same driver still falls back to a model it lists. + expect( + resolveAppModelSelectionForInstance( + ProviderInstanceId.make("kimi"), + settings, + providers, + "claude-fable-5-2", + ), + ).toBe("kimi-k3"); + }); +}); diff --git a/apps/web/src/modelSelection.test.ts b/apps/web/src/modelSelection.test.ts index 121208973d636..7df4c4d339a9e 100644 --- a/apps/web/src/modelSelection.test.ts +++ b/apps/web/src/modelSelection.test.ts @@ -246,32 +246,6 @@ describe("instance-scoped model selection", () => { ).toContain("openai/gpt-5.5"); }); - it("keeps a sandbox chat's own model on the sandbox bridge, which lists only its placeholder", () => { - const acp = ProviderDriverKind.make("acpRegistry"); - const providers = [ - provider({ provider: acp, instanceId: "sandboxes", models: ["sandbox"] }), - provider({ provider: acp, instanceId: "kimi", models: ["kimi-k3"] }), - ]; - const settings = settingsWithProviderInstances(); - expect( - resolveAppModelSelectionForInstance( - ProviderInstanceId.make("sandboxes"), - settings, - providers, - "claude-fable-5-2", - ), - ).toBe("claude-fable-5-2"); - // Another agent on the same driver still falls back to a model it lists. - expect( - resolveAppModelSelectionForInstance( - ProviderInstanceId.make("kimi"), - settings, - providers, - "claude-fable-5-2", - ), - ).toBe("kimi-k3"); - }); - it("preserves a custom slug that collides with a provider alias", () => { const providers = [ provider({ diff --git a/packages/client-runtime/src/handoff.sandbox.test.ts b/packages/client-runtime/src/handoff.sandbox.test.ts new file mode 100644 index 0000000000000..cca683b205559 --- /dev/null +++ b/packages/client-runtime/src/handoff.sandbox.test.ts @@ -0,0 +1,49 @@ +import { + ProviderInstanceId, + RunId, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; +import { resolvePendingHandoff, type HandoffTimelineRun } from "./handoff.ts"; + +const from = ProviderInstanceId.make("codex_personal"); +const to = ProviderInstanceId.make("claudeAgent"); +const run = ( + id: string, + ordinal: number, + instanceId: ProviderInstanceId, + model: string, +): HandoffTimelineRun => ({ + id: RunId.make(id), + ordinal, + providerInstanceId: instanceId, + modelSelection: { instanceId, model }, +}); + +const projection = { + runs: [ + { + ...run("source", 1, from, "source"), + status: "completed", + contextHandoffId: null, + startedAt: "2026-10-11T00:00:00Z", + }, + ], + visibleTurnItems: [{ item: { type: "user_message" } }], +} as unknown as OrchestrationV2ThreadProjection; + +describe("pending context handoff on the sandbox bridge", () => { + it("stays hidden for a switch onto or off the sandbox bridge, which carries no history", () => { + const bridge = ProviderInstanceId.make("sandboxes"); + const sandboxChat = { + ...projection, + runs: [{ ...projection.runs[0]!, ...run("source", 1, bridge, "claude-opus-5-5") }], + }; + expect( + resolvePendingHandoff(sandboxChat, { instanceId: to, model: "claude-opus-5-5" }, []), + ).toBeNull(); + expect( + resolvePendingHandoff(projection, { instanceId: bridge, model: "claude-opus-5-5" }, []), + ).toBeNull(); + }); +}); diff --git a/packages/client-runtime/src/handoff.test.ts b/packages/client-runtime/src/handoff.test.ts index 13ab4ee000670..d2f5fb4e78903 100644 --- a/packages/client-runtime/src/handoff.test.ts +++ b/packages/client-runtime/src/handoff.test.ts @@ -151,19 +151,6 @@ describe("pending context handoff", () => { expect(resolvePendingHandoff(projection, { instanceId: from, model: "source" }, [])).toBeNull(); expect(resolvePendingHandoff(projection, { instanceId: from, model: "other" }, [])).toBeNull(); }); - it("stays hidden for a switch onto or off the sandbox bridge, which carries no history", () => { - const bridge = ProviderInstanceId.make("sandboxes"); - const sandboxChat = { - ...projection, - runs: [{ ...projection.runs[0]!, ...run("source", 1, bridge, "claude-opus-5-5") }], - }; - expect( - resolvePendingHandoff(sandboxChat, { instanceId: to, model: "claude-opus-5-5" }, []), - ).toBeNull(); - expect( - resolvePendingHandoff(projection, { instanceId: bridge, model: "claude-opus-5-5" }, []), - ).toBeNull(); - }); it("stays hidden while the thread's timeline is empty", () => { const empty = { ...projection, visibleTurnItems: [] }; expect(resolvePendingHandoff(empty, { instanceId: to, model: "first" }, [])).toBeNull(); diff --git a/packages/client-runtime/src/state/runtime.sandbox.test.ts b/packages/client-runtime/src/state/runtime.sandbox.test.ts new file mode 100644 index 0000000000000..8f42191c55db0 --- /dev/null +++ b/packages/client-runtime/src/state/runtime.sandbox.test.ts @@ -0,0 +1,195 @@ +import { describe, expect, it } from "@effect/vitest"; +import { + DEFAULT_SERVER_SETTINGS, + EnvironmentId, + type ServerSettings, + WS_METHODS, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; + +import { + AVAILABLE_CONNECTION_STATE, + PrimaryConnectionTarget, + type PreparedConnection, + type SupervisorConnectionState, +} from "../connection/model.ts"; +import * as EnvironmentRegistry from "../connection/registry.ts"; +import * as EnvironmentSupervisor from "../connection/supervisor.ts"; +import type * as RpcSession from "../rpc/session.ts"; +import { createSandboxEnvironmentAtoms } from "./sandboxes.ts"; +import type * as Persistence from "../platform/persistence.ts"; +import type { QueryPersistence } from "./queryPersistence.ts"; +import { createEnvironmentQueryAtomFamily, type QueryAnswerHandler } from "./runtime.ts"; + +const QUERY_ENVIRONMENT = new PrimaryConnectionTarget({ + environmentId: EnvironmentId.make("query-environment"), + label: "Query environment", + httpBaseUrl: "https://query.example.test", + wsBaseUrl: "wss://query.example.test", +}); + +const QUERY_RPC_SESSION = {} as RpcSession.RpcSession; + +function queryConnectionState( + overrides: Partial = {}, +): SupervisorConnectionState { + return { + ...AVAILABLE_CONNECTION_STATE, + desired: true, + network: "online", + phase: "connected", + attempt: 1, + generation: 1, + ...overrides, + }; +} + +const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness")(function* ( + execute: Effect.Effect, + { + refreshTrigger, + idleTtlMs, + persistence, + initialState, + rpcSession, + isFinal, + onAnswer, + }: { + readonly refreshTrigger?: Atom.Atom; + readonly onAnswer?: QueryAnswerHandler; + readonly isFinal?: (value: A) => boolean; + readonly idleTtlMs?: number; + readonly persistence?: QueryPersistence; + readonly initialState?: SupervisorConnectionState; + readonly rpcSession?: RpcSession.RpcSession; + } = {}, +) { + const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState()); + const supervisorSession = yield* SubscriptionRef.make( + Option.some(rpcSession ?? QUERY_RPC_SESSION), + ); + const streamGeneration = yield* SubscriptionRef.make(0); + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target: QUERY_ENVIRONMENT, + state: supervisorState, + session: supervisorSession, + prepared: yield* SubscriptionRef.make>(Option.none()), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); + const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_environmentId, effect) => + Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor); + const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = ( + _environmentId, + stream, + ) => + SubscriptionRef.changes(streamGeneration).pipe( + Stream.switchMap(() => + Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + ), + ); + const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({ + run, + followStream, + stateChanges: () => SubscriptionRef.changes(supervisorState), + } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); + const runtime = Atom.runtime( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), + ); + const family = createEnvironmentQueryAtomFamily(runtime, { + label: "test.environment-query", + staleTimeMs: 60_000, + ...(persistence === undefined ? {} : { persistence }), + execute: () => execute, + ...(refreshTrigger === undefined ? {} : { refreshTrigger: () => refreshTrigger }), + ...(idleTtlMs === undefined ? {} : { idleTtlMs }), + ...(isFinal === undefined ? {} : { isFinal }), + ...(onAnswer === undefined ? {} : { onAnswer }), + }); + + return { + runtime, + family, + atom: family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }), + supervisorSession, + supervisorState, + streamGeneration, + }; +}); + +/** + * `getResult` resumes from inside the query's listener, so it only unsubscribes + * once the reader yields. + */ +const readEnvironmentQuery = ( + registry: AtomRegistry.AtomRegistry, + atom: Atom.Atom>, +) => + AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true }).pipe( + Effect.tap(() => Effect.yieldNow), + ); + +const mountEnvironmentQuery = Effect.fn("TestEnvironmentQuery.mount")(function* ( + atom: Atom.Atom>, +) { + const registry = AtomRegistry.make(); + const unmount = registry.mount(atom); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + unmount(); + registry.dispose(); + }), + ); + return registry; +}); + +describe("sandbox host facts", () => { + it.effect("refetch when a setting they come from changes, and only then", () => + Effect.scoped( + Effect.gen(function* () { + let fetches = 0; + const harness = yield* makeEnvironmentQueryHarness(Effect.void, { + rpcSession: { + client: { + [WS_METHODS.sandboxesProviders]: () => Effect.sync(() => ++fetches), + }, + } as unknown as RpcSession.RpcSession, + }); + const settings = Atom.make(DEFAULT_SERVER_SETTINGS).pipe( + Atom.keepAlive, + ); + // Host facts never read the query cache. + const runtime = harness.runtime as unknown as Atom.AtomRuntime< + EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore + >; + const atom = createSandboxEnvironmentAtoms(runtime, () => settings).sandboxesProviders({ + environmentId: QUERY_ENVIRONMENT.environmentId, + input: undefined, + }); + const registry = yield* mountEnvironmentQuery(atom); + expect(yield* readEnvironmentQuery(registry, atom)).toBe(1); + + // Saving the Northflank token in Settings, from this client or another one. + registry.set(settings, { + ...DEFAULT_SERVER_SETTINGS, + sandboxTooling: { ...DEFAULT_SERVER_SETTINGS.sandboxTooling, northflankToken: "••••" }, + }); + expect(yield* readEnvironmentQuery(registry, atom)).toBe(2); + + registry.set(settings, { + ...DEFAULT_SERVER_SETTINGS, + sandboxTooling: { ...DEFAULT_SERVER_SETTINGS.sandboxTooling, northflankToken: "••••" }, + hideTaggedThreads: !DEFAULT_SERVER_SETTINGS.hideTaggedThreads, + }); + expect(registry.get(atom).waiting).toBe(false); + expect(fetches).toBe(2); + }), + ), + ); +}); diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index e7549b2a8fa47..97b5750872986 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -4,12 +4,10 @@ import * as NodeVM from "node:vm"; import { vi } from "vite-plus/test"; import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES, - DEFAULT_SERVER_SETTINGS, EnvironmentId, type FilesystemBrowseEntry, ORCHESTRATION_V2_WS_METHODS, type OrchestrationV2ArchivedShellSnapshot, - type ServerSettings, ThreadId, ProjectId, type ReviewDiffPreviewInput, @@ -52,10 +50,8 @@ import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import type * as RpcSession from "../rpc/session.ts"; import { createOrchestrationEnvironmentAtoms } from "./orchestration.ts"; import { createReviewEnvironmentAtoms } from "./review.ts"; -import { createSandboxEnvironmentAtoms } from "./sandboxes.ts"; import { createPreviewEnvironmentAtoms } from "./preview.ts"; import { createFilesystemEnvironmentAtoms } from "./filesystem.ts"; -import type * as Persistence from "../platform/persistence.ts"; import type { QueryPersistence } from "./queryPersistence.ts"; import type { EnvironmentShellState } from "./shell.ts"; import { v2Now, v2Project, v2ThreadId, v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; @@ -1459,51 +1455,6 @@ describe("environment query lifecycle", () => { ); }); -describe("sandbox host facts", () => { - it.effect("refetch when a setting they come from changes, and only then", () => - Effect.scoped( - Effect.gen(function* () { - let fetches = 0; - const harness = yield* makeEnvironmentQueryHarness(Effect.void, { - rpcSession: { - client: { - [WS_METHODS.sandboxesProviders]: () => Effect.sync(() => ++fetches), - }, - } as unknown as RpcSession.RpcSession, - }); - const settings = Atom.make(DEFAULT_SERVER_SETTINGS).pipe( - Atom.keepAlive, - ); - // Host facts never read the query cache. - const runtime = harness.runtime as unknown as Atom.AtomRuntime< - EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore - >; - const atom = createSandboxEnvironmentAtoms(runtime, () => settings).sandboxesProviders({ - environmentId: QUERY_ENVIRONMENT.environmentId, - input: undefined, - }); - const registry = yield* mountEnvironmentQuery(atom); - expect(yield* readEnvironmentQuery(registry, atom)).toBe(1); - - // Saving the Northflank token in Settings, from this client or another one. - registry.set(settings, { - ...DEFAULT_SERVER_SETTINGS, - sandboxTooling: { ...DEFAULT_SERVER_SETTINGS.sandboxTooling, northflankToken: "••••" }, - }); - expect(yield* readEnvironmentQuery(registry, atom)).toBe(2); - - registry.set(settings, { - ...DEFAULT_SERVER_SETTINGS, - sandboxTooling: { ...DEFAULT_SERVER_SETTINGS.sandboxTooling, northflankToken: "••••" }, - hideTaggedThreads: !DEFAULT_SERVER_SETTINGS.hideTaggedThreads, - }); - expect(registry.get(atom).waiting).toBe(false); - expect(fetches).toBe(2); - }), - ), - ); -}); - describe("executeAtomQuery", () => { it("keeps concurrent query results correlated to their atoms", async () => { const firstLatch = Latch.makeUnsafe(); diff --git a/packages/provider-acp-registry/src/server/driver.sandbox.test.ts b/packages/provider-acp-registry/src/server/driver.sandbox.test.ts new file mode 100644 index 0000000000000..0773eb7c0d422 --- /dev/null +++ b/packages/provider-acp-registry/src/server/driver.sandbox.test.ts @@ -0,0 +1,210 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + ProviderInstanceId, + SANDBOX_BRIDGE_INSTANCE_ID, + SANDBOX_BRIDGE_MODEL, + type ServerProvider, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; +import { 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 Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { AcpRegistrySettings } from "../settings.ts"; +import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; +import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; +import { AcpRegistryDriver } from "./driver.ts"; +import { normalizeAcpRegistryLiveConfiguration } from "./probe.ts"; + +const decodeSettings = Schema.decodeSync(AcpRegistrySettings); + +function catalogWithInspection( + inspection: AcpRegistrySupport.AcpRegistryInspection, +): AcpRegistrySupport.AcpRegistryCatalog["Service"] { + return { + search: () => Effect.die("unused search"), + prepare: () => Effect.die("unused prepare"), + inspect: () => Effect.succeed(inspection), + resolve: () => Effect.die("unused resolve"), + uninstallManagedBinary: () => Effect.die("unused uninstall"), + }; +} + +const fakeAgentSource = ` +import { readFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n"); +createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method } = JSON.parse(line); + if (id === undefined) return; + if (method === "initialize") { + send({ + id, + result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [], agentInfo: { name: "fake", version: "1.5.9" } }, + }); + } else if (method === "session/new") { + const modelIds = JSON.parse(readFileSync(process.argv[2], "utf8")); + send({ + id, + result: { + sessionId: "probe-session", + models: { + currentModelId: modelIds[0], + availableModels: modelIds.map((modelId) => ({ modelId, name: modelId })), + }, + }, + }); + send({ + method: "session/update", + params: { + sessionId: "probe-session", + update: { sessionUpdate: "available_commands_update", availableCommands: [] }, + }, + }); + } else { + send({ id, result: {} }); + } +}); +`; + +const driverLayer = TestProviderHost.layer({ runBackgroundWork: false }).pipe( + Layer.provideMerge(AcpRegistryRuntimeCoordinator.layer), + Layer.provideMerge(IdAllocator.layer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provideMerge( + Layer.succeed( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), +); + +it.layer(driverLayer, { excludeTestServices: true })( + "AcpRegistryDriver for sandbox chats", + (it) => { + it.effect( + "lists what every sandbox chat reported, without the placeholder, across a restart", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-" }); + const agentPath = path.join(directory, "agent.mjs"); + const modelsPath = path.join(directory, "models.json"); + yield* fileSystem.writeFileString(agentPath, fakeAgentSource); + // As the bridge's probe session does: only its placeholder. + yield* fileSystem.writeFileString(modelsPath, JSON.stringify([SANDBOX_BRIDGE_MODEL])); + const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; + const start = (instanceId: ProviderInstanceId) => + AcpRegistryDriver.create({ + instanceId, + displayName: "Sandboxes", + enabled: true, + environment: [], + config: decodeSettings({ source: "local", commandPath: "agent" }), + }).pipe( + Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { + ...catalogWithInspection({ + status: "ready", + agentId: "agent", + version: null, + distribution: "local", + }), + resolve: () => + Effect.succeed({ + distribution: "local" as const, + spawn: { command: process.execPath, args: [agentPath, modelsPath] }, + }), + }), + ); + const report = ( + models: ReadonlyArray, + levels: ReadonlyArray = [], + defaultModelId?: string, + ) => ({ + ...normalizeAcpRegistryLiveConfiguration([ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: models[0] ?? SANDBOX_BRIDGE_MODEL, + options: models.map((model) => ({ value: model, name: model })), + }, + ...levels.slice(0, 1).map((currentValue) => ({ + id: "effort", + name: "Effort", + category: "thought_level" as const, + type: "select" as const, + currentValue, + options: levels.map((level) => ({ value: level, name: level })), + })), + ]), + ...(defaultModelId === undefined ? {} : { defaultModelId }), + }); + const listing = (snapshot: ServerProvider) => + snapshot.models + .map((model) => { + const effort = model.capabilities?.optionDescriptors?.find( + (descriptor) => descriptor.id === "effort", + ); + const levels = + effort?.type === "select" + ? `(${effort.options.map((choice) => choice.id).join("|")})` + : ""; + return `${model.slug}${model.isDefault ? "*" : ""}${levels}`; + }) + .join(); + const reportAndList = Effect.fn(function* ( + instanceId: ProviderInstanceId, + instance: Effect.Success>, + configuration: ReturnType, + ) { + yield* coordinator.publishLiveConfiguration(instanceId, configuration); + yield* instance.snapshot.refresh; + return listing(yield* instance.snapshot.getSnapshot); + }); + const first = report(["opus", "sonnet", SANDBOX_BRIDGE_MODEL], ["low", "high"], "sonnet"); + const second = report(["opus", "haiku", SANDBOX_BRIDGE_MODEL], ["medium", "max"]); + + const sandboxes = ProviderInstanceId.make(SANDBOX_BRIDGE_INSTANCE_ID); + const host = yield* start(sandboxes); + yield* host.snapshot.refresh; + expect(yield* reportAndList(sandboxes, host, first)).toBe("opus(low|high),sonnet*"); + // A sandbox that did not answer, then a session that only has the placeholder. + expect(yield* reportAndList(sandboxes, host, report([]))).toBe("opus(low|high),sonnet*"); + expect(yield* reportAndList(sandboxes, host, report([SANDBOX_BRIDGE_MODEL]))).toBe( + "opus(low|high),sonnet*", + ); + // Another sandbox's chat adds its models and has the newest word on the ones they share. + expect(yield* reportAndList(sandboxes, host, second)).toBe( + "opus(medium|max),sonnet*,haiku", + ); + yield* host.invalidateCaches ?? Effect.void; + + const restarted = yield* start(sandboxes); + yield* restarted.snapshot.refresh; + expect(listing(yield* restarted.snapshot.getSnapshot)).toBe( + "opus(medium|max),sonnet*,haiku", + ); + + // Any other ACP agent lists what its newest session reported, as before. + const otherId = ProviderInstanceId.make("acpRegistry_other"); + const other = yield* start(otherId); + yield* other.snapshot.refresh; + yield* reportAndList(otherId, other, first); + expect(yield* reportAndList(otherId, other, second)).toBe( + `opus*(medium|max),haiku,${SANDBOX_BRIDGE_MODEL}`, + ); + }), + ); + }, +); diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 37ba6b6219f05..2f9352bbdbfe0 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -3,8 +3,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { AcpRegistryOperationError, ProviderInstanceId, - SANDBOX_BRIDGE_INSTANCE_ID, - SANDBOX_BRIDGE_MODEL, type ServerProvider, } from "@t3tools/contracts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -1110,121 +1108,4 @@ it.layer(driverLayer, { excludeTestServices: true })("AcpRegistryDriver", (it) = ); }), ); - - it.effect( - "lists what every sandbox chat reported, without the placeholder, across a restart", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "acp-driver-" }); - const agentPath = path.join(directory, "agent.mjs"); - const modelsPath = path.join(directory, "models.json"); - yield* fileSystem.writeFileString(agentPath, fakeAgentSource); - // As the bridge's probe session does: only its placeholder. - yield* fileSystem.writeFileString(modelsPath, JSON.stringify([SANDBOX_BRIDGE_MODEL])); - const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; - const start = (instanceId: ProviderInstanceId) => - AcpRegistryDriver.create({ - instanceId, - displayName: "Sandboxes", - enabled: true, - environment: [], - config: decodeSettings({ source: "local", commandPath: "agent" }), - }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, { - ...catalogWithInspection({ - status: "ready", - agentId: "agent", - version: null, - distribution: "local", - }), - resolve: () => - Effect.succeed({ - distribution: "local" as const, - spawn: { command: process.execPath, args: [agentPath, modelsPath] }, - }), - }), - ); - const report = ( - models: ReadonlyArray, - levels: ReadonlyArray = [], - defaultModelId?: string, - ) => ({ - ...normalizeAcpRegistryLiveConfiguration([ - { - id: "model", - name: "Model", - category: "model", - type: "select", - currentValue: models[0] ?? SANDBOX_BRIDGE_MODEL, - options: models.map((model) => ({ value: model, name: model })), - }, - ...levels.slice(0, 1).map((currentValue) => ({ - id: "effort", - name: "Effort", - category: "thought_level" as const, - type: "select" as const, - currentValue, - options: levels.map((level) => ({ value: level, name: level })), - })), - ]), - ...(defaultModelId === undefined ? {} : { defaultModelId }), - }); - const listing = (snapshot: ServerProvider) => - snapshot.models - .map((model) => { - const effort = model.capabilities?.optionDescriptors?.find( - (descriptor) => descriptor.id === "effort", - ); - const levels = - effort?.type === "select" - ? `(${effort.options.map((choice) => choice.id).join("|")})` - : ""; - return `${model.slug}${model.isDefault ? "*" : ""}${levels}`; - }) - .join(); - const reportAndList = Effect.fn(function* ( - instanceId: ProviderInstanceId, - instance: Effect.Success>, - configuration: ReturnType, - ) { - yield* coordinator.publishLiveConfiguration(instanceId, configuration); - yield* instance.snapshot.refresh; - return listing(yield* instance.snapshot.getSnapshot); - }); - const first = report(["opus", "sonnet", SANDBOX_BRIDGE_MODEL], ["low", "high"], "sonnet"); - const second = report(["opus", "haiku", SANDBOX_BRIDGE_MODEL], ["medium", "max"]); - - const sandboxes = ProviderInstanceId.make(SANDBOX_BRIDGE_INSTANCE_ID); - const host = yield* start(sandboxes); - yield* host.snapshot.refresh; - expect(yield* reportAndList(sandboxes, host, first)).toBe("opus(low|high),sonnet*"); - // A sandbox that did not answer, then a session that only has the placeholder. - expect(yield* reportAndList(sandboxes, host, report([]))).toBe("opus(low|high),sonnet*"); - expect(yield* reportAndList(sandboxes, host, report([SANDBOX_BRIDGE_MODEL]))).toBe( - "opus(low|high),sonnet*", - ); - // Another sandbox's chat adds its models and has the newest word on the ones they share. - expect(yield* reportAndList(sandboxes, host, second)).toBe( - "opus(medium|max),sonnet*,haiku", - ); - yield* host.invalidateCaches ?? Effect.void; - - const restarted = yield* start(sandboxes); - yield* restarted.snapshot.refresh; - expect(listing(yield* restarted.snapshot.getSnapshot)).toBe( - "opus(medium|max),sonnet*,haiku", - ); - - // Any other ACP agent lists what its newest session reported, as before. - const otherId = ProviderInstanceId.make("acpRegistry_other"); - const other = yield* start(otherId); - yield* other.snapshot.refresh; - yield* reportAndList(otherId, other, first); - expect(yield* reportAndList(otherId, other, second)).toBe( - `opus*(medium|max),haiku,${SANDBOX_BRIDGE_MODEL}`, - ); - }), - ); }); From 921149a272adf25c1471785bfcd6e2a445373f7e Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Tue, 17 Nov 2026 17:22:11 -0600 Subject: [PATCH 3/4] docs: sandbox environments get their own user guide page The sandbox sections move from remote-access.md, which now matches upstream, to sandboxes.md. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/user/remote-access.md | 414 ------------------------------------- docs/user/sandboxes.md | 413 ++++++++++++++++++++++++++++++++++++ 3 files changed, 414 insertions(+), 414 deletions(-) create mode 100644 docs/user/sandboxes.md diff --git a/docs/README.md b/docs/README.md index 264d509d97642..952226ed4f8ea 100644 --- a/docs/README.md +++ b/docs/README.md @@ -22,6 +22,7 @@ - [Secrets](./user/secrets.md) - [Product usage data](./user/telemetry.md) - [Remote access](./user/remote-access.md) +- [Sandbox environments](./user/sandboxes.md) - [Guest links](./user/guest-links.md) - [T3 Connect troubleshooting](./user/t3-connect-troubleshooting.md) - [Outside agents (MCP)](./user/outside-agents.md) diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index c7a2cb3ceffde..ad0fcb12503e1 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -3,420 +3,6 @@ Connect a phone, browser, or another desktop app to T3 Code running on a different machine. That machine must stay running and reachable while you work. -## Sandbox environments - -A sandbox gives a thread its own cloud machine, with its own T3 Code server and a fresh clone of -the project. Each thread you start on a sandbox gets a different machine, so threads never share -files, processes, or ports. - -### Add a sandbox config - -A config says how each thread's machine is made. Open **Settings → Environments → Add -environment**, choose **Sandbox**, pick Boat, Celesto, Daytona, Upstash, or Vercel, and enter the -provider's API key. Then choose a name, a machine size (or a template to start from), and what each -sandbox gets from this machine. **Add sandbox config** saves it; no machine is made and nothing -bills until a thread starts on it. Edit or delete configs in **Settings → Connections → -Sandboxes**. Deleting a config leaves the sandboxes already made from it running until you delete -them. - -The key is saved on the T3 Code server that keeps the configs (this machine, or the first server -you paired on the hosted web app), not on the client. Each sandbox bills the provider account that -owns the key. - -A sandbox gets none of this machine's logins unless the config asks. **Agent access** lists only -what this machine has set up, with a switch each; connect more under **Settings → Connections → -Sandboxes → Add integration**. **Claude** appears when Claude here talks to a custom endpoint, and -points Claude in each sandbox at the same one. If that endpoint is a [CLIProxyAPI hub you connected](./usage.md#connect-a-cliproxyapi-hub), -each sandbox gets its own key on the hub, which T3 Code removes when you delete the sandbox; -otherwise this machine's Claude token is copied, and it stays valid after the sandbox is gone. The -sandbox must be able to reach that endpoint. When it only answers on your tailnet or local network, -each sandbox [joins your tailnet](#private-endpoints-tailscale) on its own once Tailscale is set -up; without Tailscale, T3 Code refuses to start the sandbox and points you to its setup. You can -also expose the endpoint publicly instead (for example with Tailscale Funnel or Cloudflare Tunnel). -With a hub, **Pi** also installs the [Pi agent](./providers-pi.md) -in each sandbox with the hub's non-Claude models, on that same key, and **Start new chats on** can -make new chats on the config start on Pi with one of them instead of Claude. -**GitHub** lets `gh` and `git` in each sandbox clone private repositories and push, with a -token from the [GitHub App](#github-in-a-sandbox) or this machine's own. Without it a sandbox can -clone public repositories only. -[**Let the agent use Boat**](#let-the-agent-use-boat) signs the `boat` CLI in on each Boat sandbox -with a key scoped to it. T3 Code also -installs git, the GitHub CLI, and Claude Code when the provider's image lacks them; sign Codex in -from the sandbox's **Settings → Providers**. - -Every sandbox's Claude also gets a skill from T3 Code, `t3-sandbox-files`, whether or not you copy -any skills of your own. A stop empties the sandbox's `/tmp`, so the skill tells the agent to keep -screenshots, drafts, logs, downloads and extra git worktrees under its home folder (for example -`~/scratch//`) instead. A launch writes it; a resume adds it when it is missing, so sandboxes -made before it get it too. A sandbox where it could not be written still works and shows a warning. -Codex agents on a sandbox do not get it. - -**Projects** limits which repositories can start a thread on the config. It lists the github.com -repositories of projects on every connected machine, once each, so a project that lives only on a -paired machine counts too: the sandbox clones from GitHub, not from that machine. With none picked, -any project with a github.com remote can. Configs saved by older versions, which named projects on -this server, keep working and switch to repositories the next time you save them. Under -**Advanced**: - -- **Running limit** (8 hours by default) stops a sandbox that has run that long since its last - start. Its disk stays, so **Resume** brings it back with the thread's files. Boat sandboxes show - **Stop when idle** and an optional **Hard limit** instead (see - [Boat sandboxes stay on while they work](#boat-sandboxes-stay-on-while-they-work)). -- **Files copied from this machine** chooses, per repository, which git-ignored files go into the - clone. They come from the repository's copy on the server that keeps the configs, so a project - open only on another machine gets none. By default each sandbox gets that copy's env files - (`.env` files, `.envrc`, `.dev.vars`). They are written into the clone with owner-only - permissions and never appear in a provider's command history. -- **Reach it only through my tailnet** shows only on a config that already has it, so you can turn - it off. Such a sandbox has no public URL: this app connects over your tailnet, so the machine - running it has to be on your tailnet too, and the hosted web app cannot reach it. - -### Start a thread on a sandbox - -In a new thread, open the **Run on** picker under the composer. Below your machines, the -**Sandbox** group lists the configs this project can start on, with the provider's logo; choose one. -Any project with a github.com remote qualifies, on whichever connected machine it lives. With no -config yet, the group offers **New sandbox config…**, which opens the same form as Settings. Write -your message and send it: the message waits in the composer while a card shows the sandbox being -made. - -1. **Check limits and access** reads the provider's limits, so a start it would refuse costs - nothing. -2. **Create machine** creates and exposes it. -3. **Install T3 Code and tools**: git, the GitHub CLI, and Claude Code where missing. -4. **Set up credentials**: Claude, GitHub, and Tailscale, as the config asks. -5. **Start T3 Code**. -6. **Clone repository** from GitHub into `~/work/` and add it as a project there. -7. **Copy env files**. -8. **Connect and start thread** pairs this app with the sandbox and starts the thread on this - computer, under the **Sandboxes** provider, so your phone can follow it (see - [Drive a sandbox thread from your phone](#drive-a-sandbox-thread-from-your-phone)). The message - waits until this computer shows that provider in the project, usually a few seconds. If this - computer cannot take the thread, the thread starts on the sandbox itself, as it did before, and - a notice says your phone cannot drive it. - -Once connected, the thread starts with your message. A failure in steps 1 to 5 -deletes the machine, and **Start a new sandbox** tries again from scratch. A failed clone or -connection keeps the machine, so **Retry** runs just that step again, and **Discard sandbox** -deletes it. A setup step that fails, such as a GitHub sign-in, or an env file that could not be -copied, shows as a warning and leaves a working sandbox. **Cancel** stops the launch at any point and -deletes everything it made: the machine, its hub key, and its tailnet device. - -The thread's sandbox appears under its config in **Settings → Connections → Sandboxes**, not in the -list of environments you paired. - -### Manage sandboxes - -**Settings → Connections → Sandboxes** groups sandboxes under the config they came from. Each row -shows the thread (with **Open thread**), the project, the machine size, its state, how long it has -been running against its running limit, and Boat's monthly cost. Stop, resume, and delete -sandboxes there; deleting removes the machine and its disk at the provider and forgets the sandbox's -connection in this app. Work you have not pushed is lost with it. - -That list follows the provider: a sandbox you stop or delete in the provider's dashboard shows up as -stopped or deleted within a minute. A stopped sandbox shows how long its disk has been kept. Boat -keeps a stopped sandbox's disk for 14 days and then shows it as expired; three days before that the -row recommends deleting it. T3 Code never deletes a sandbox you did not ask it to, except one whose -launch was cut short when this server stopped, which it deletes once it is running again. A row -also says when the thread it belonged to was deleted. - -### Drive a sandbox thread from your phone - -A sandbox thread also appears on this computer under the **Sandboxes** provider, in the project it -came from (or a small project named after the repository when the repository is not on this -computer). The T3 Code app reaches it there through this computer, without pairing with the sandbox. -Sending a message forwards it to the sandbox, its answer streams back, and the sandbox's approvals -and questions appear as usual. Threads launched this way start there, Supervised. - -A sandbox chat starts only from T3 Code on this computer (**Run on → Sandbox**), where the sandbox -configs live; a new thread started from the phone gets a reply saying so. Once it has started, you -can keep the conversation going from the phone. - -The small project is an empty folder, not the repository, so it offers no git actions, scripts, -files, or terminal. The repository's files, diffs, terminals and previews are on the sandbox. This -computer connects to a running sandbox on its own when you open its chat; otherwise **Connect to -the sandbox** (in the side panel, the thread details, or the sandbox menu in the thread's header) -connects it, resuming a stopped sandbox first, and the chat then shows the sandbox's own thread. If -a connection fails, the reason shows under that button. The phone does -not connect to sandboxes, so there these are available only from a computer. **Settings → -Connections → Sandboxes** has **Connect** and **Disconnect** for each chat's sandbox; after -**Disconnect**, this device stays disconnected until you connect again, and the chat stays here. - -- Keep the thread **Supervised**. In another mode the sandbox's approvals cannot reach you: the - request waits on the sandbox and the thread says so. -- While the sandbox is stopped or starting, this computer shows the chat as its thread under - **Sandboxes**. A message sent then waits there, marked "Starting sandbox", resumes the sandbox, - and goes out once it is up, even if you switch chats or close the app. Messages after it queue - behind it. Once the sandbox is running and connected, the chat shows the sandbox's own thread - again. -- Attachments and images are not forwarded yet. -- The thread under **Sandboxes** shows what was sent through it, and the replies the sandbox's - agent gives on its own, such as when a background task or subagent finishes; messages sent to - the sandbox directly appear on the sandbox's own thread. -- The **Sandboxes** provider shows only in projects that hold a sandbox thread. - -### Settle or delete a sandbox chat - -A thread that runs through the **Sandboxes** provider keeps its conversation on this computer, so -deleting its sandbox keeps the conversation. What goes is the sandbox's disk: work not committed -and pushed from it is lost, and the thread needs a new sandbox to continue. A sandbox thread started -before this, or one that could not start on this computer, is stored only on its sandbox, so -deleting the sandbox deletes the conversation too. Every prompt that can delete a sandbox says -which case it is. - -**When a chat is settled**, in the sandbox config, says what settling a thread does to its sandbox. -It applies however the chat is settled: from the computer, the phone, an agent, a scheduled task, -or automatic settling. - -- **Ask me** (the default) asks: **Keep snapshot** or **Delete sandbox…**. The question waits on - the sandbox under **Settings → Sandboxes** (**Keep** or **Delete…**) and on the chat's row - ("Keep sandbox?"), and pops up on a computer that has the app open. Tick **Remember for** the - config's name to make that choice the config's setting. Keep, from any device, stops a running - sandbox and keeps its disk. Un-settling the chat drops the question. -- **Keep a snapshot** stops the sandbox and keeps its disk. The provider bills for the stopped disk - (Boat keeps it for 14 days). Sending a message in the thread resumes the sandbox, from any - device; the first answer can take a few minutes. Un-settling the thread resumes it too. -- **Delete without asking** waits 10 seconds after the settle; **Undo**, or un-settling the - thread another way, keeps the sandbox. Then it checks the clone for uncommitted files and commits - not on a remote. With nothing to lose, it deletes the sandbox. While the chat's agents or tasks - still run, with work to lose, when the sandbox does not answer within about 10 seconds, or when - it is stopped, it asks as **Ask me** does. Copied env files count as uncommitted when the repository does not ignore them. - -A thread the sandbox settles on its own, and a thread stored only on its sandbox, leave the -sandbox as it is. Deleting a sandbox thread asks first, names the sandbox ("Also deletes sandbox bx_46wr on -Boat"), and shows the same check. Deleting a thread that runs through the **Sandboxes** provider -also deletes the sandbox's copy of it. A stopped sandbox is not started just to check, so its -prompt says the check could not run. - -The thread's header shows its sandbox: its state, **Stop and keep its disk** or **Resume**, -**Open sandbox thread** (for a thread under the **Sandboxes** provider), **Open in Sandboxes -list**, and **Delete sandbox…**. A warning icon there means the provider will -soon drop the stopped disk. - -**Not tracked by T3 Code** lists sandboxes that carry this server's tag but have no record, for -example after a crash. They may still bill; delete the ones you do not need. Only Boat reports -these. Forks an agent made of its sandbox show under that sandbox instead (see -[Let the agent use Boat](#let-the-agent-use-boat)). - -Each provider also stops sandboxes on its own, as a backstop for the running limit. Boat is the -exception: its own auto-stop is what stops a thread's sandbox once its work ends, as the next -section explains. - -For Vercel, create an access token at vercel.com/account/settings/tokens; T3 Code uses your only -team and a `t3-sandboxes` project unless you fill in **Team** or **Project** (a change applies to -new sandboxes; existing ones stay where they were created), and a sandbox on the -Hobby plan stops after 45 minutes, so resume it from the Sandboxes list to keep working. - -Upstash is new. Create a Box API key in the Upstash Console at console.upstash.com. Upstash pauses -a box after an hour idle (six hours on paid plans) and may not count a running agent as activity, -so a long turn can stop partway and the sandbox then shows as stopped. Opening the sandbox's URL or -choosing **Resume** wakes it, and T3 Code starts again on it. Medium and Large boxes need a paid -plan. Upstash sandboxes cannot be saved as templates and show no cost. - -Celesto is new. Create an API key in the Celesto console under **Settings → Security**; a scoped -key needs all three computer permissions (see, create and run, delete). Celesto never stops a -sandbox on its own, so the running limit is the only thing that stops one, and a sandbox keeps -billing while this T3 Code server is off. The free trial runs Micro only and keeps one sandbox, -stopped ones included, so delete it before you start another thread on it. Celesto keeps a stopped -sandbox's disk for 30 days. Celesto can also move a running sandbox to another machine on its own, -and does not promise to keep the sandbox's files when it does, so push work you want to keep. If a -sandbox stops answering after such a move, delete it. Celesto sandboxes cannot be saved as templates -and show no cost. - -Daytona deletes a sandbox, files included, a day after its running limit, so copy out anything you -need before then. - -### Boat sandboxes stay on while they work - -A thread's Boat sandbox has no running limit while its agents work. It stops on its own once they -have been idle for the config's **Stop when idle** time (30 minutes by default). - -- Every 5 minutes the sandbox checks whether any thread on it, subagents included, is queued, - starting or running, is waiting on background work it will pick up again (a subagent, or a - command or monitor it waits on), or has had any activity since the last check, such as a short - turn or your answer to a question. If so, it moves Boat's auto-stop to the idle time plus 5 - minutes from now. A thread left waiting on you, for an approval or an answer, counts as idle. -- Background commands no agent waits on, such as a dev server, keep the sandbox on too, but only - for 8 hours after the sandbox last started. - The check log in `~/.t3/userdata/sandbox-keepalive/log` shows each decision and how many threads - had background work. -- The sandbox does this itself, so it keeps working while this machine sleeps or the app is - closed. With no work, nothing moves the auto-stop, and Boat stops the sandbox when it passes. - Its disk stays, and sending a message resumes it. -- **Hard limit** (off by default) still stops a sandbox that has run that long since its last start, - even mid-work. -- For this, T3 Code mints a Boat key named `t3-keepalive--`, scoped to that one - sandbox with only `sandbox.read` and `sandbox.update`. It travels in a private file, never in a - command, and only the sandbox keeps it, under `~/.t3/userdata/sandbox-keepalive/`. It lasts 30 - days, is replaced on a resume once it has less than a week left, and is revoked when you delete - the sandbox. -- A Boat sandbox made before this gets its key the next time it resumes. If the key cannot be set - up, the setup card or the resume says so, and that sandbox stops at its running limit as before. -- On a Boat trial the idle time is capped at two hours, Boat's longest trial auto-stop. - -### GitHub in a sandbox - -With **Sign in with → GitHub App (recommended)**, each sandbox gets an hour-long token from the -app, which T3 Code renews while the sandbox runs and revokes when you delete it. - -- The token covers **every repository the app is installed on**, not just the sandbox's own, so an - agent can clone, push, and open pull requests on another of your repositories in the same - thread. It is the app's installation that decides this, so the app must still be installed on the - sandbox's own repository, or the launch warns with a link to install it. -- Choose those repositories on GitHub: **Settings → Applications → Installed GitHub Apps → - Configure** next to the app (for an organization, the organization's **Settings → GitHub - Apps**), under **Repository access**. **Install on repositories** in the app's menu under - **Settings → Connections → Sandboxes** opens the same page. A running sandbox picks up a - change with its next token, at most about 40 minutes later; a resumed sandbox gets a new token - as it starts. Because every sandbox reaches every repository on that list, keep it to the - repositories you want agents to push to. -- The app asks to write contents, pull requests, issues and workflows, and to read checks, - statuses and actions. Without Workflows, GitHub refuses a push that changes - `.github/workflows/`; without Issues, an agent cannot open or comment on issues. An app created - before T3 Code asked for one of these lacks it: open the app's settings on GitHub - (**Settings → Developer settings → GitHub Apps → Edit**), set **Permissions → Repository - permissions → Workflows** and **Issues** to **Read and write**, and save. GitHub then asks each - installation to approve the change; until you accept it under **Installed GitHub Apps → - Configure**, tokens keep the old permissions. - -### Let the agent use Boat - -Off by default, and offered only for Boat. With it on, the agent in each sandbox can run `boat` -against its own machine: fork it, host its ports, stop it, and delete the forks it made. Forks bill -like new sandboxes, and they count against Boat's start limits. - -- At launch T3 Code makes a Boat environment for that sandbox alone, named - `t3-sandbox--`, with **Safe for third parties** on and no GitHub token, secrets, - sandbox credentials or agent logins passed. The sandbox starts in it, and so do its forks. That is - also why the option needs **No credentials** as the Boat environment under **Advanced**. -- Once the sandbox exists, T3 Code mints a scoped key with the same name, limited to that sandbox - and its environment, and signs `boat` in with it. The key travels in a private file, never in a - command, and only the sandbox keeps it, in `boat`'s own config. Its actions are - `sandbox.create` (forking makes a sandbox), `sandbox.read`, `sandbox.stop`, `sandbox.fork`, - `sandbox.delete-own`, `exec`, `file.read`, `file.write` and `host`. It cannot read or delete any - other sandbox on your account, or the sandbox it runs on. -- The key expires after the config's running limit (8 hours by default), counted from launch, even - if the sandbox was stopped in between or kept itself running past it. After that `boat` on that sandbox stops working; start a new thread for a new - key. -- Before anything bills, T3 Code checks that your Boat key can mint scoped keys. A key that cannot - stops the launch with "Your Boat key can't create scoped keys; use an admin key or turn off Let - the agent use Boat". -- Forks appear under their sandbox in the Sandboxes list, each with its own delete. Deleting the - sandbox revokes its key, deletes its forks, and then deletes its environment. T3 Code never - deletes a fork on its own: a launch cut short by a restart loses its key and machine, but any - fork stays, with its environment, for you to delete in Boat. - -### Sandboxes for subagents - -An agent on this machine can give a subagent its own sandbox when the task needs more CPU, RAM or -disk than its machine has, or runs heavy builds in parallel: `delegate_task` with -`target.sandbox`. The child then runs there as a task in a linked environment, so **Linked -environments** has to be on under **Settings → Labs**; the agent says so when it is off. - -- The sandbox comes from the parent thread's own sandbox config when the parent is a sandbox chat. - Otherwise it comes from the config this project's sandbox chats last used, or the only config - there is. It clones the project at the parent's branch once that branch is pushed (the default - branch otherwise), with the same env files, tools and keep-alive as a thread's sandbox. -- `target.sandbox.size` can be the config's size or one size larger. A config that starts from a - template keeps the template's size. -- Each config limits how many run at once: **Subagent sandboxes per thread** (2 by default) and - **in total** across every thread (4 by default), under **Machine**. Sandboxes still starting - count. 0 turns them off. Past a limit the agent gets a `concurrency_full` error. -- When the task ends or is cancelled, T3 Code checks the sandbox for uncommitted files and - unpushed commits. A clean one is deleted. One with work, or one it could not check, is stopped - and kept, and the task's result says which sandbox and folder hold the work. -- In the Sandboxes list they sit under the thread that delegated their tasks. - -Agents on a sandbox can ask too. The sandbox runs the official T3 Code, whose `delegate_task` has no -`target.sandbox`, so T3 Code installs a small helper there that gives Claude two tools: -`sandbox_delegate` asks for a sandbox and `sandbox_task_status` reports on it. The request goes to -this machine, which starts the sandbox the same way: from the same config, within the same limits -and sizes, and ended the same way when the task is done. The task shows under the sandbox's chat -on this machine. - -- **This machine must be awake** and running T3 Code, since it holds the configs and provider - keys. It checks each running sandbox for requests every 15 seconds while that sandbox's chat - works, and every minute otherwise. When nothing picks a request up within about 45 seconds, the - helper withdraws it and tells the agent to do the work on its own sandbox. -- The request is recorded on the chat's running turn on this machine, so it works when the - conversation goes through T3 Code here or on your phone. Each request has an id, and asking - again with the same id never starts a second sandbox. A result is passed back to the agent when - it asks for the status, and a result that arrives after its turn has ended starts a new turn, - as a subagent's result does here. -- Refusals reach the agent with the reason: a limit reached (`concurrency_full`), **Linked - environments** off, no config to start from, or a size too large. A config whose limits are 0 - still gets the helper, and every request from it is refused with that reason. -- Sandboxes get the helper when they start, and older sandboxes get it when they resume. A - subagent's own sandbox does not get it. The helper is for Claude; other agents on a sandbox do - not see it. Saving a template removes it, with any pending requests. - -### Templates - -A template starts each sandbox with your tools and dependencies already installed. Save one from a -sandbox that belongs to no thread, with **Save as template…** in the Sandboxes list; a thread's -sandbox cannot be saved, because saving deletes the source machine. Then choose the template under -**Start from** in a config. Saving resets T3 Code on the source so each copy connects as a new -environment. Its files live on in the template, `.env` files included, so leave out secrets you do -not want in every copy; T3 Code removes only its own identity and the Claude, GitHub, and Tailscale -logins it set up. - -### Private endpoints (Tailscale) - -A sandbox can join your tailnet to reach an endpoint that is only on it, such as a CLIProxyAPI -server, without exposing that endpoint publicly. Each sandbox joins as its own ephemeral device, -tagged `tag:t3-sandbox`, with a single-use key; deleting the sandbox removes the device. A sandbox -that stays stopped for more than about an hour drops off the tailnet and rejoins as a new device -when you resume it. - -**Settings → Connections → Sandboxes → Add integration → Tailscale** walks through the same three steps, -with the policy snippet filled in for this server's Claude endpoint. - -1. Add the tag and an access rule. Open the - [policy file](https://login.tailscale.com/admin/acls/file) and merge in: - - ```jsonc - "tagOwners": { - "tag:t3-sandbox": ["autogroup:admin"], - }, - "grants": [ - // Sandboxes reach the Claude endpoint and nothing else. - { "src": ["tag:t3-sandbox"], "dst": ["100.x.y.z"], "ip": ["tcp:443"] }, - // Replace the default allow-all grant ("src": ["*"]) with this one: - // { "src": ["autogroup:member"], "dst": ["*"], "ip": ["*"] }, - ], - ``` - - Use your endpoint's tailnet IP for `100.x.y.z`, and its port if it is not 443. Tailscale's - default grant lets every device reach every other, sandboxes included, so narrow it to the - commented one. - -2. Create the OAuth client. Open - [Trust credentials](https://login.tailscale.com/admin/settings/trust-credentials), then: - 1. Select **Credential**, then **OAuth**. - 2. Under **Scopes**, choose **Custom scopes**. - 3. Expand **Devices** and set **Core** to **Write**. - 4. Expand **Keys** and set **Auth Keys** to **Write**. - 5. Pick `tag:t3-sandbox` as the tag for both. - 6. Select **Generate credential** and copy the secret. Tailscale shows it only once. -3. Paste the secret (`tskey-client-…`) into the Tailscale card and save. T3 Code reads the client - ID from it and signs in once, asking for the tag, before saving. When something is missing it - says what, for example `Missing Keys → Auth Keys: Write for tag:t3-sandbox`, or that Tailscale - won't give the client the tag, which means the tag is not in `tagOwners` yet (step 1) or was not - selected on the client. If your secret has another form, enter the client ID under - **Advanced**, where you can also change the tag. The secret stays on this server; sandboxes - never get it. - -A sandbox joins your tailnet on its own whenever Claude's endpoint resolves to a private or tailnet -address. That is decided each time a sandbox starts, so configs saved before Tailscale was set up -work too. For other endpoints, check **Join my tailnet** in the config to join anyway. If the -sandbox still cannot reach Claude after it starts, T3 Code stops the setup and deletes the sandbox -rather than starting a thread that would wait forever. - -Most sandboxes get a full Tailscale connection. One that cannot create a network device runs -Tailscale in userspace instead: T3 Code then points Claude at Tailscale's local proxy, and other -programs in the sandbox reach the tailnet only through `http://localhost:1055`. Tailscale needs root -or passwordless sudo on the sandbox, which Boat, Upstash, and Vercel provide. - ## T3 Connect T3 Connect makes an environment available to your other devices without setting diff --git a/docs/user/sandboxes.md b/docs/user/sandboxes.md new file mode 100644 index 0000000000000..5169bbf1f4e8f --- /dev/null +++ b/docs/user/sandboxes.md @@ -0,0 +1,413 @@ +# Sandbox environments + +A sandbox gives a thread its own cloud machine, with its own T3 Code server and a fresh clone of +the project. Each thread you start on a sandbox gets a different machine, so threads never share +files, processes, or ports. + +## Add a sandbox config + +A config says how each thread's machine is made. Open **Settings → Environments → Add +environment**, choose **Sandbox**, pick Boat, Celesto, Daytona, Upstash, or Vercel, and enter the +provider's API key. Then choose a name, a machine size (or a template to start from), and what each +sandbox gets from this machine. **Add sandbox config** saves it; no machine is made and nothing +bills until a thread starts on it. Edit or delete configs in **Settings → Connections → +Sandboxes**. Deleting a config leaves the sandboxes already made from it running until you delete +them. + +The key is saved on the T3 Code server that keeps the configs (this machine, or the first server +you paired on the hosted web app), not on the client. Each sandbox bills the provider account that +owns the key. + +A sandbox gets none of this machine's logins unless the config asks. **Agent access** lists only +what this machine has set up, with a switch each; connect more under **Settings → Connections → +Sandboxes → Add integration**. **Claude** appears when Claude here talks to a custom endpoint, and +points Claude in each sandbox at the same one. If that endpoint is a [CLIProxyAPI hub you connected](./usage.md#connect-a-cliproxyapi-hub), +each sandbox gets its own key on the hub, which T3 Code removes when you delete the sandbox; +otherwise this machine's Claude token is copied, and it stays valid after the sandbox is gone. The +sandbox must be able to reach that endpoint. When it only answers on your tailnet or local network, +each sandbox [joins your tailnet](#private-endpoints-tailscale) on its own once Tailscale is set +up; without Tailscale, T3 Code refuses to start the sandbox and points you to its setup. You can +also expose the endpoint publicly instead (for example with Tailscale Funnel or Cloudflare Tunnel). +With a hub, **Pi** also installs the [Pi agent](./providers-pi.md) +in each sandbox with the hub's non-Claude models, on that same key, and **Start new chats on** can +make new chats on the config start on Pi with one of them instead of Claude. +**GitHub** lets `gh` and `git` in each sandbox clone private repositories and push, with a +token from the [GitHub App](#github-in-a-sandbox) or this machine's own. Without it a sandbox can +clone public repositories only. +[**Let the agent use Boat**](#let-the-agent-use-boat) signs the `boat` CLI in on each Boat sandbox +with a key scoped to it. T3 Code also +installs git, the GitHub CLI, and Claude Code when the provider's image lacks them; sign Codex in +from the sandbox's **Settings → Providers**. + +Every sandbox's Claude also gets a skill from T3 Code, `t3-sandbox-files`, whether or not you copy +any skills of your own. A stop empties the sandbox's `/tmp`, so the skill tells the agent to keep +screenshots, drafts, logs, downloads and extra git worktrees under its home folder (for example +`~/scratch//`) instead. A launch writes it; a resume adds it when it is missing, so sandboxes +made before it get it too. A sandbox where it could not be written still works and shows a warning. +Codex agents on a sandbox do not get it. + +**Projects** limits which repositories can start a thread on the config. It lists the github.com +repositories of projects on every connected machine, once each, so a project that lives only on a +paired machine counts too: the sandbox clones from GitHub, not from that machine. With none picked, +any project with a github.com remote can. Configs saved by older versions, which named projects on +this server, keep working and switch to repositories the next time you save them. Under +**Advanced**: + +- **Running limit** (8 hours by default) stops a sandbox that has run that long since its last + start. Its disk stays, so **Resume** brings it back with the thread's files. Boat sandboxes show + **Stop when idle** and an optional **Hard limit** instead (see + [Boat sandboxes stay on while they work](#boat-sandboxes-stay-on-while-they-work)). +- **Files copied from this machine** chooses, per repository, which git-ignored files go into the + clone. They come from the repository's copy on the server that keeps the configs, so a project + open only on another machine gets none. By default each sandbox gets that copy's env files + (`.env` files, `.envrc`, `.dev.vars`). They are written into the clone with owner-only + permissions and never appear in a provider's command history. +- **Reach it only through my tailnet** shows only on a config that already has it, so you can turn + it off. Such a sandbox has no public URL: this app connects over your tailnet, so the machine + running it has to be on your tailnet too, and the hosted web app cannot reach it. + +## Start a thread on a sandbox + +In a new thread, open the **Run on** picker under the composer. Below your machines, the +**Sandbox** group lists the configs this project can start on, with the provider's logo; choose one. +Any project with a github.com remote qualifies, on whichever connected machine it lives. With no +config yet, the group offers **New sandbox config…**, which opens the same form as Settings. Write +your message and send it: the message waits in the composer while a card shows the sandbox being +made. + +1. **Check limits and access** reads the provider's limits, so a start it would refuse costs + nothing. +2. **Create machine** creates and exposes it. +3. **Install T3 Code and tools**: git, the GitHub CLI, and Claude Code where missing. +4. **Set up credentials**: Claude, GitHub, and Tailscale, as the config asks. +5. **Start T3 Code**. +6. **Clone repository** from GitHub into `~/work/` and add it as a project there. +7. **Copy env files**. +8. **Connect and start thread** pairs this app with the sandbox and starts the thread on this + computer, under the **Sandboxes** provider, so your phone can follow it (see + [Drive a sandbox thread from your phone](#drive-a-sandbox-thread-from-your-phone)). The message + waits until this computer shows that provider in the project, usually a few seconds. If this + computer cannot take the thread, the thread starts on the sandbox itself, as it did before, and + a notice says your phone cannot drive it. + +Once connected, the thread starts with your message. A failure in steps 1 to 5 +deletes the machine, and **Start a new sandbox** tries again from scratch. A failed clone or +connection keeps the machine, so **Retry** runs just that step again, and **Discard sandbox** +deletes it. A setup step that fails, such as a GitHub sign-in, or an env file that could not be +copied, shows as a warning and leaves a working sandbox. **Cancel** stops the launch at any point and +deletes everything it made: the machine, its hub key, and its tailnet device. + +The thread's sandbox appears under its config in **Settings → Connections → Sandboxes**, not in the +list of environments you paired. + +## Manage sandboxes + +**Settings → Connections → Sandboxes** groups sandboxes under the config they came from. Each row +shows the thread (with **Open thread**), the project, the machine size, its state, how long it has +been running against its running limit, and Boat's monthly cost. Stop, resume, and delete +sandboxes there; deleting removes the machine and its disk at the provider and forgets the sandbox's +connection in this app. Work you have not pushed is lost with it. + +That list follows the provider: a sandbox you stop or delete in the provider's dashboard shows up as +stopped or deleted within a minute. A stopped sandbox shows how long its disk has been kept. Boat +keeps a stopped sandbox's disk for 14 days and then shows it as expired; three days before that the +row recommends deleting it. T3 Code never deletes a sandbox you did not ask it to, except one whose +launch was cut short when this server stopped, which it deletes once it is running again. A row +also says when the thread it belonged to was deleted. + +## Drive a sandbox thread from your phone + +A sandbox thread also appears on this computer under the **Sandboxes** provider, in the project it +came from (or a small project named after the repository when the repository is not on this +computer). The T3 Code app reaches it there through this computer, without pairing with the sandbox. +Sending a message forwards it to the sandbox, its answer streams back, and the sandbox's approvals +and questions appear as usual. Threads launched this way start there, Supervised. + +A sandbox chat starts only from T3 Code on this computer (**Run on → Sandbox**), where the sandbox +configs live; a new thread started from the phone gets a reply saying so. Once it has started, you +can keep the conversation going from the phone. + +The small project is an empty folder, not the repository, so it offers no git actions, scripts, +files, or terminal. The repository's files, diffs, terminals and previews are on the sandbox. This +computer connects to a running sandbox on its own when you open its chat; otherwise **Connect to +the sandbox** (in the side panel, the thread details, or the sandbox menu in the thread's header) +connects it, resuming a stopped sandbox first, and the chat then shows the sandbox's own thread. If +a connection fails, the reason shows under that button. The phone does +not connect to sandboxes, so there these are available only from a computer. **Settings → +Connections → Sandboxes** has **Connect** and **Disconnect** for each chat's sandbox; after +**Disconnect**, this device stays disconnected until you connect again, and the chat stays here. + +- Keep the thread **Supervised**. In another mode the sandbox's approvals cannot reach you: the + request waits on the sandbox and the thread says so. +- While the sandbox is stopped or starting, this computer shows the chat as its thread under + **Sandboxes**. A message sent then waits there, marked "Starting sandbox", resumes the sandbox, + and goes out once it is up, even if you switch chats or close the app. Messages after it queue + behind it. Once the sandbox is running and connected, the chat shows the sandbox's own thread + again. +- Attachments and images are not forwarded yet. +- The thread under **Sandboxes** shows what was sent through it, and the replies the sandbox's + agent gives on its own, such as when a background task or subagent finishes; messages sent to + the sandbox directly appear on the sandbox's own thread. +- The **Sandboxes** provider shows only in projects that hold a sandbox thread. + +## Settle or delete a sandbox chat + +A thread that runs through the **Sandboxes** provider keeps its conversation on this computer, so +deleting its sandbox keeps the conversation. What goes is the sandbox's disk: work not committed +and pushed from it is lost, and the thread needs a new sandbox to continue. A sandbox thread started +before this, or one that could not start on this computer, is stored only on its sandbox, so +deleting the sandbox deletes the conversation too. Every prompt that can delete a sandbox says +which case it is. + +**When a chat is settled**, in the sandbox config, says what settling a thread does to its sandbox. +It applies however the chat is settled: from the computer, the phone, an agent, a scheduled task, +or automatic settling. + +- **Ask me** (the default) asks: **Keep snapshot** or **Delete sandbox…**. The question waits on + the sandbox under **Settings → Sandboxes** (**Keep** or **Delete…**) and on the chat's row + ("Keep sandbox?"), and pops up on a computer that has the app open. Tick **Remember for** the + config's name to make that choice the config's setting. Keep, from any device, stops a running + sandbox and keeps its disk. Un-settling the chat drops the question. +- **Keep a snapshot** stops the sandbox and keeps its disk. The provider bills for the stopped disk + (Boat keeps it for 14 days). Sending a message in the thread resumes the sandbox, from any + device; the first answer can take a few minutes. Un-settling the thread resumes it too. +- **Delete without asking** waits 10 seconds after the settle; **Undo**, or un-settling the + thread another way, keeps the sandbox. Then it checks the clone for uncommitted files and commits + not on a remote. With nothing to lose, it deletes the sandbox. While the chat's agents or tasks + still run, with work to lose, when the sandbox does not answer within about 10 seconds, or when + it is stopped, it asks as **Ask me** does. Copied env files count as uncommitted when the repository does not ignore them. + +A thread the sandbox settles on its own, and a thread stored only on its sandbox, leave the +sandbox as it is. Deleting a sandbox thread asks first, names the sandbox ("Also deletes sandbox bx_46wr on +Boat"), and shows the same check. Deleting a thread that runs through the **Sandboxes** provider +also deletes the sandbox's copy of it. A stopped sandbox is not started just to check, so its +prompt says the check could not run. + +The thread's header shows its sandbox: its state, **Stop and keep its disk** or **Resume**, +**Open sandbox thread** (for a thread under the **Sandboxes** provider), **Open in Sandboxes +list**, and **Delete sandbox…**. A warning icon there means the provider will +soon drop the stopped disk. + +**Not tracked by T3 Code** lists sandboxes that carry this server's tag but have no record, for +example after a crash. They may still bill; delete the ones you do not need. Only Boat reports +these. Forks an agent made of its sandbox show under that sandbox instead (see +[Let the agent use Boat](#let-the-agent-use-boat)). + +Each provider also stops sandboxes on its own, as a backstop for the running limit. Boat is the +exception: its own auto-stop is what stops a thread's sandbox once its work ends, as the next +section explains. + +For Vercel, create an access token at vercel.com/account/settings/tokens; T3 Code uses your only +team and a `t3-sandboxes` project unless you fill in **Team** or **Project** (a change applies to +new sandboxes; existing ones stay where they were created), and a sandbox on the +Hobby plan stops after 45 minutes, so resume it from the Sandboxes list to keep working. + +Upstash is new. Create a Box API key in the Upstash Console at console.upstash.com. Upstash pauses +a box after an hour idle (six hours on paid plans) and may not count a running agent as activity, +so a long turn can stop partway and the sandbox then shows as stopped. Opening the sandbox's URL or +choosing **Resume** wakes it, and T3 Code starts again on it. Medium and Large boxes need a paid +plan. Upstash sandboxes cannot be saved as templates and show no cost. + +Celesto is new. Create an API key in the Celesto console under **Settings → Security**; a scoped +key needs all three computer permissions (see, create and run, delete). Celesto never stops a +sandbox on its own, so the running limit is the only thing that stops one, and a sandbox keeps +billing while this T3 Code server is off. The free trial runs Micro only and keeps one sandbox, +stopped ones included, so delete it before you start another thread on it. Celesto keeps a stopped +sandbox's disk for 30 days. Celesto can also move a running sandbox to another machine on its own, +and does not promise to keep the sandbox's files when it does, so push work you want to keep. If a +sandbox stops answering after such a move, delete it. Celesto sandboxes cannot be saved as templates +and show no cost. + +Daytona deletes a sandbox, files included, a day after its running limit, so copy out anything you +need before then. + +## Boat sandboxes stay on while they work + +A thread's Boat sandbox has no running limit while its agents work. It stops on its own once they +have been idle for the config's **Stop when idle** time (30 minutes by default). + +- Every 5 minutes the sandbox checks whether any thread on it, subagents included, is queued, + starting or running, is waiting on background work it will pick up again (a subagent, or a + command or monitor it waits on), or has had any activity since the last check, such as a short + turn or your answer to a question. If so, it moves Boat's auto-stop to the idle time plus 5 + minutes from now. A thread left waiting on you, for an approval or an answer, counts as idle. +- Background commands no agent waits on, such as a dev server, keep the sandbox on too, but only + for 8 hours after the sandbox last started. + The check log in `~/.t3/userdata/sandbox-keepalive/log` shows each decision and how many threads + had background work. +- The sandbox does this itself, so it keeps working while this machine sleeps or the app is + closed. With no work, nothing moves the auto-stop, and Boat stops the sandbox when it passes. + Its disk stays, and sending a message resumes it. +- **Hard limit** (off by default) still stops a sandbox that has run that long since its last start, + even mid-work. +- For this, T3 Code mints a Boat key named `t3-keepalive--`, scoped to that one + sandbox with only `sandbox.read` and `sandbox.update`. It travels in a private file, never in a + command, and only the sandbox keeps it, under `~/.t3/userdata/sandbox-keepalive/`. It lasts 30 + days, is replaced on a resume once it has less than a week left, and is revoked when you delete + the sandbox. +- A Boat sandbox made before this gets its key the next time it resumes. If the key cannot be set + up, the setup card or the resume says so, and that sandbox stops at its running limit as before. +- On a Boat trial the idle time is capped at two hours, Boat's longest trial auto-stop. + +## GitHub in a sandbox + +With **Sign in with → GitHub App (recommended)**, each sandbox gets an hour-long token from the +app, which T3 Code renews while the sandbox runs and revokes when you delete it. + +- The token covers **every repository the app is installed on**, not just the sandbox's own, so an + agent can clone, push, and open pull requests on another of your repositories in the same + thread. It is the app's installation that decides this, so the app must still be installed on the + sandbox's own repository, or the launch warns with a link to install it. +- Choose those repositories on GitHub: **Settings → Applications → Installed GitHub Apps → + Configure** next to the app (for an organization, the organization's **Settings → GitHub + Apps**), under **Repository access**. **Install on repositories** in the app's menu under + **Settings → Connections → Sandboxes** opens the same page. A running sandbox picks up a + change with its next token, at most about 40 minutes later; a resumed sandbox gets a new token + as it starts. Because every sandbox reaches every repository on that list, keep it to the + repositories you want agents to push to. +- The app asks to write contents, pull requests, issues and workflows, and to read checks, + statuses and actions. Without Workflows, GitHub refuses a push that changes + `.github/workflows/`; without Issues, an agent cannot open or comment on issues. An app created + before T3 Code asked for one of these lacks it: open the app's settings on GitHub + (**Settings → Developer settings → GitHub Apps → Edit**), set **Permissions → Repository + permissions → Workflows** and **Issues** to **Read and write**, and save. GitHub then asks each + installation to approve the change; until you accept it under **Installed GitHub Apps → + Configure**, tokens keep the old permissions. + +## Let the agent use Boat + +Off by default, and offered only for Boat. With it on, the agent in each sandbox can run `boat` +against its own machine: fork it, host its ports, stop it, and delete the forks it made. Forks bill +like new sandboxes, and they count against Boat's start limits. + +- At launch T3 Code makes a Boat environment for that sandbox alone, named + `t3-sandbox--`, with **Safe for third parties** on and no GitHub token, secrets, + sandbox credentials or agent logins passed. The sandbox starts in it, and so do its forks. That is + also why the option needs **No credentials** as the Boat environment under **Advanced**. +- Once the sandbox exists, T3 Code mints a scoped key with the same name, limited to that sandbox + and its environment, and signs `boat` in with it. The key travels in a private file, never in a + command, and only the sandbox keeps it, in `boat`'s own config. Its actions are + `sandbox.create` (forking makes a sandbox), `sandbox.read`, `sandbox.stop`, `sandbox.fork`, + `sandbox.delete-own`, `exec`, `file.read`, `file.write` and `host`. It cannot read or delete any + other sandbox on your account, or the sandbox it runs on. +- The key expires after the config's running limit (8 hours by default), counted from launch, even + if the sandbox was stopped in between or kept itself running past it. After that `boat` on that sandbox stops working; start a new thread for a new + key. +- Before anything bills, T3 Code checks that your Boat key can mint scoped keys. A key that cannot + stops the launch with "Your Boat key can't create scoped keys; use an admin key or turn off Let + the agent use Boat". +- Forks appear under their sandbox in the Sandboxes list, each with its own delete. Deleting the + sandbox revokes its key, deletes its forks, and then deletes its environment. T3 Code never + deletes a fork on its own: a launch cut short by a restart loses its key and machine, but any + fork stays, with its environment, for you to delete in Boat. + +## Sandboxes for subagents + +An agent on this machine can give a subagent its own sandbox when the task needs more CPU, RAM or +disk than its machine has, or runs heavy builds in parallel: `delegate_task` with +`target.sandbox`. The child then runs there as a task in a linked environment, so **Linked +environments** has to be on under **Settings → Labs**; the agent says so when it is off. + +- The sandbox comes from the parent thread's own sandbox config when the parent is a sandbox chat. + Otherwise it comes from the config this project's sandbox chats last used, or the only config + there is. It clones the project at the parent's branch once that branch is pushed (the default + branch otherwise), with the same env files, tools and keep-alive as a thread's sandbox. +- `target.sandbox.size` can be the config's size or one size larger. A config that starts from a + template keeps the template's size. +- Each config limits how many run at once: **Subagent sandboxes per thread** (2 by default) and + **in total** across every thread (4 by default), under **Machine**. Sandboxes still starting + count. 0 turns them off. Past a limit the agent gets a `concurrency_full` error. +- When the task ends or is cancelled, T3 Code checks the sandbox for uncommitted files and + unpushed commits. A clean one is deleted. One with work, or one it could not check, is stopped + and kept, and the task's result says which sandbox and folder hold the work. +- In the Sandboxes list they sit under the thread that delegated their tasks. + +Agents on a sandbox can ask too. The sandbox runs the official T3 Code, whose `delegate_task` has no +`target.sandbox`, so T3 Code installs a small helper there that gives Claude two tools: +`sandbox_delegate` asks for a sandbox and `sandbox_task_status` reports on it. The request goes to +this machine, which starts the sandbox the same way: from the same config, within the same limits +and sizes, and ended the same way when the task is done. The task shows under the sandbox's chat +on this machine. + +- **This machine must be awake** and running T3 Code, since it holds the configs and provider + keys. It checks each running sandbox for requests every 15 seconds while that sandbox's chat + works, and every minute otherwise. When nothing picks a request up within about 45 seconds, the + helper withdraws it and tells the agent to do the work on its own sandbox. +- The request is recorded on the chat's running turn on this machine, so it works when the + conversation goes through T3 Code here or on your phone. Each request has an id, and asking + again with the same id never starts a second sandbox. A result is passed back to the agent when + it asks for the status, and a result that arrives after its turn has ended starts a new turn, + as a subagent's result does here. +- Refusals reach the agent with the reason: a limit reached (`concurrency_full`), **Linked + environments** off, no config to start from, or a size too large. A config whose limits are 0 + still gets the helper, and every request from it is refused with that reason. +- Sandboxes get the helper when they start, and older sandboxes get it when they resume. A + subagent's own sandbox does not get it. The helper is for Claude; other agents on a sandbox do + not see it. Saving a template removes it, with any pending requests. + +## Templates + +A template starts each sandbox with your tools and dependencies already installed. Save one from a +sandbox that belongs to no thread, with **Save as template…** in the Sandboxes list; a thread's +sandbox cannot be saved, because saving deletes the source machine. Then choose the template under +**Start from** in a config. Saving resets T3 Code on the source so each copy connects as a new +environment. Its files live on in the template, `.env` files included, so leave out secrets you do +not want in every copy; T3 Code removes only its own identity and the Claude, GitHub, and Tailscale +logins it set up. + +## Private endpoints (Tailscale) + +A sandbox can join your tailnet to reach an endpoint that is only on it, such as a CLIProxyAPI +server, without exposing that endpoint publicly. Each sandbox joins as its own ephemeral device, +tagged `tag:t3-sandbox`, with a single-use key; deleting the sandbox removes the device. A sandbox +that stays stopped for more than about an hour drops off the tailnet and rejoins as a new device +when you resume it. + +**Settings → Connections → Sandboxes → Add integration → Tailscale** walks through the same three steps, +with the policy snippet filled in for this server's Claude endpoint. + +1. Add the tag and an access rule. Open the + [policy file](https://login.tailscale.com/admin/acls/file) and merge in: + + ```jsonc + "tagOwners": { + "tag:t3-sandbox": ["autogroup:admin"], + }, + "grants": [ + // Sandboxes reach the Claude endpoint and nothing else. + { "src": ["tag:t3-sandbox"], "dst": ["100.x.y.z"], "ip": ["tcp:443"] }, + // Replace the default allow-all grant ("src": ["*"]) with this one: + // { "src": ["autogroup:member"], "dst": ["*"], "ip": ["*"] }, + ], + ``` + + Use your endpoint's tailnet IP for `100.x.y.z`, and its port if it is not 443. Tailscale's + default grant lets every device reach every other, sandboxes included, so narrow it to the + commented one. + +2. Create the OAuth client. Open + [Trust credentials](https://login.tailscale.com/admin/settings/trust-credentials), then: + 1. Select **Credential**, then **OAuth**. + 2. Under **Scopes**, choose **Custom scopes**. + 3. Expand **Devices** and set **Core** to **Write**. + 4. Expand **Keys** and set **Auth Keys** to **Write**. + 5. Pick `tag:t3-sandbox` as the tag for both. + 6. Select **Generate credential** and copy the secret. Tailscale shows it only once. +3. Paste the secret (`tskey-client-…`) into the Tailscale card and save. T3 Code reads the client + ID from it and signs in once, asking for the tag, before saving. When something is missing it + says what, for example `Missing Keys → Auth Keys: Write for tag:t3-sandbox`, or that Tailscale + won't give the client the tag, which means the tag is not in `tagOwners` yet (step 1) or was not + selected on the client. If your secret has another form, enter the client ID under + **Advanced**, where you can also change the tag. The secret stays on this server; sandboxes + never get it. + +A sandbox joins your tailnet on its own whenever Claude's endpoint resolves to a private or tailnet +address. That is decided each time a sandbox starts, so configs saved before Tailscale was set up +work too. For other endpoints, check **Join my tailnet** in the config to join anyway. If the +sandbox still cannot reach Claude after it starts, T3 Code stops the setup and deletes the sandbox +rather than starting a thread that would wait forever. + +Most sandboxes get a full Tailscale connection. One that cannot create a network device runs +Tailscale in userspace instead: T3 Code then points Claude at Tailscale's local proxy, and other +programs in the sandbox reach the tailnet only through `http://localhost:1055`. Tailscale needs root +or passwordless sudo on the sandbox, which Boat, Upstash, and Vercel provide. From c936bebcf87b0fe0b6878b4661afe78459f5d3a4 Mon Sep 17 00:00:00 2001 From: OmarAlex24 Date: Tue, 17 Nov 2026 17:23:10 -0600 Subject: [PATCH 4/4] revert: drop the steer secret-card fix, upstream #34634 covers it This reverts commit a21d2032ef0a725cc3c3b648c18177e82fc7945f. Upstream pingdotgg/t3code#34634 fixes the same bug, and this copy would conflict with it in Orchestrator.ts once it merges. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/McpHttpServer.test.ts | 72 ------------------- .../src/orchestration-v2/Orchestrator.ts | 62 +--------------- .../SteeringCompletion.integration.test.ts | 62 ---------------- .../server/src/secrets/SecretRequests.test.ts | 23 +----- apps/server/src/secrets/SecretRequests.ts | 8 +-- 5 files changed, 6 insertions(+), 221 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index a62d61db4d239..5801a210ba6cf 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -20,7 +20,6 @@ import { import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; @@ -52,7 +51,6 @@ import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import * as ServerConfig from "../config.ts"; import * as ServerHttp from "../http.ts"; import * as ServerSettings from "../serverSettings.ts"; -import { mcpToolSession } from "./AcpMcpStdioBridge.ts"; import { advertisedJsonSchema } from "./advertisedJsonSchema.ts"; import * as McpHttpServer from "./McpHttpServer.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; @@ -2058,73 +2056,3 @@ it.effect("lists optional tools to a deferring client only after tool_search loa }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); - -it.effect("interrupts a tool handler when its HTTP caller drops the call", () => - Effect.scoped( - Effect.gen(function* () { - const token = "providerTokenWithoutDots"; - const scope: McpInvocationContext.McpThreadInvocationScope = { - environmentId, - requestNamespace: "provider-session", - thread: { - threadId: ThreadId.make("thread-provider"), - providerSessionId: "provider-session", - providerInstanceId: ProviderInstanceId.make("codex"), - }, - client: undefined, - capabilities: new Set(["orchestration"]), - issuedAt: 1, - }; - const started = yield* Deferred.make(); - const interrupted = yield* Deferred.make(); - const WaitsToolkit = Toolkit.make( - Tool.make("waits", { - description: "Waits until its caller goes away.", - success: Schema.Struct({}), - failure: OrchestratorMcpFailure, - failureMode: "return", - }), - ); - const serverLayer = McpHttpServer.layerMcpTransport( - McpHttpServer.toolkitRegistration( - WaitsToolkit, - McpToolAccess.toLayer(WaitsToolkit, { - waits: McpToolAccess.reads(() => - Deferred.succeed(started, undefined).pipe( - Effect.andThen(Effect.never), - Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)), - ), - ), - }), - ), - ).pipe( - Layer.provide(ServerSettings.layerTest()), - Layer.provide(McpToolAccessTestkit.liveThreadsLayer), - Layer.provide( - Layer.mock(McpSessionRegistry.McpSessionRegistry)({ - resolve: (presented) => Effect.succeed(presented === token ? scope : undefined), - }), - ), - ); - yield* HttpRouter.serve(serverLayer, { - disableListenLog: true, - disableLogger: true, - }).pipe(Layer.build); - const { address } = yield* HttpServer.HttpServer; - if (address._tag === "UnixPathAddress") return yield* Effect.die("expected TCP"); - - const call = yield* mcpToolSession({ - endpoint: `http://127.0.0.1:${address.port}/mcp`, - authorization: `Bearer ${token}`, - clientName: "probe", - }).pipe( - Effect.flatMap((session) => session.call("waits", {})), - Effect.scoped, - Effect.forkChild, - ); - yield* Deferred.await(started); - yield* Fiber.interrupt(call); - yield* Deferred.await(interrupted); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), -); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 2d0b662dcbe39..92f441fd5bae3 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -6620,13 +6620,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...currentAttempt, status: "superseded", completedAt: now }, }); } - yield* closePendingSecretRequests({ - command: input.command, - events: input.events, - threadId: input.command.threadId, - nodeId: rootNodeId, - now, - }); if (currentRootNode !== undefined) { yield* emitEvent({ type: "node.updated", @@ -10578,18 +10571,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); const run = projection.runs.find((candidate) => candidate.id === command.runId); - const existing = projection.turnItems.find((item) => item.id === command.turnItemId); - // A card whose node a steer replaced can still be closed, never answered. - const closesExisting = - existing?.nodeId === command.nodeId && - (command.secretStatus === "declined" || command.secretStatus === "cancelled"); - if (run === undefined || (run.rootNodeId !== command.nodeId && !closesExisting)) { + if (run === undefined || run.rootNodeId !== command.nodeId) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, cause: `Node ${command.nodeId} is not the root of run ${command.runId}.`, }); } + const existing = projection.turnItems.find((item) => item.id === command.turnItemId); if (existing !== undefined && existing.type !== "secret_request") { return yield* new OrchestratorDispatchError({ commandId: command.commandId, @@ -10910,53 +10899,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, ); - /** - * Closes the secret cards a stopped root node asked. Only the `request_secret` - * call in that node's provider turn could hand the agent the answer. - */ - const closePendingSecretRequests = Effect.fn("orchestrationV2.closePendingSecretRequests")( - function* (input: { - readonly command: OrchestrationV2ServerCommand; - readonly events: Ref.Ref>; - readonly threadId: ThreadId; - readonly nodeId: NodeId; - readonly now: DateTime.Utc; - }) { - const { turnItems } = yield* projectionStore - .getThreadRecords(input.threadId, ["turnItems"], { - turnItemTypes: ["secret_request"], - turnItemStatuses: ["waiting"], - messageRoles: [], - }) - .pipe(mapDispatchError(input.command)); - for (const item of turnItems) { - if ( - item.type !== "secret_request" || - item.secretStatus !== "pending" || - item.nodeId !== input.nodeId - ) - continue; - yield* emit( - input.events, - input.command, - )({ - type: "turn-item.updated", - threadId: input.threadId, - ...(item.runId === null ? {} : { runId: item.runId }), - nodeId: item.nodeId, - occurredAt: input.now, - payload: { - ...item, - status: "cancelled", - secretStatus: "cancelled", - completedAt: input.now, - updatedAt: input.now, - }, - }); - } - }, - ); - const dispatchRuntimeRequestRespond = Effect.fn("Orchestrator.dispatchRuntimeRequestRespond")( function* ( command: Extract, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 8960e78ffb38f..11b36aeb148eb 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1345,68 +1345,6 @@ it.effect("restarts the turn for an image when native steering takes text only", }), ); -it.effect("a steer that restarts the turn closes the secret card the stopped turn asked", () => - Effect.scoped( - Effect.gen(function* () { - const { layer, startFirstTurn } = yield* nextTurnSelectionHarness( - "steering-closes-secret-card", - true, - false, - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = yield* startFirstTurn; - const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; - const turnItemId = TurnItemId.make("turn-item:secret-request:steered"); - const record = (secretStatus: "pending" | "cancelled" | "saved") => - orchestrator.dispatch({ - type: "secret_request.record", - commandId: CommandId.make(`secret-request:${secretStatus}`), - threadId, - runId: run.id, - nodeId: run.rootNodeId!, - turnItemId, - label: "Gateway key", - reason: "Signs the payment gateway calls.", - delivery: "file", - secretStatus, - }); - const card = orchestrator - .getThreadProjection(threadId) - .pipe( - Effect.map((projection) => projection.turnItems.find((item) => item.id === turnItemId)), - ); - yield* record("pending"); - - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("steer-past-secret"), - threadId, - messageId: MessageId.make("message:steer-past-secret"), - text: "skip the gateway for now", - attachments: [], - modelSelection: runSelection, - dispatchMode: { type: "steer_active", targetRunId: run.id }, - createdBy: "user", - creationSource: "web", - }); - yield* worker.drain(); - const restarted = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; - assert.equal(restarted.id, run.id); - assert.notEqual(restarted.rootNodeId, run.rootNodeId); - assert.deepInclude(yield* card, { status: "cancelled", secretStatus: "cancelled" }); - - // The interrupted `request_secret` call still closes its card; nothing can save into it. - yield* record("cancelled"); - const saved = yield* record("saved").pipe(Effect.flip); - assert.include(String(saved.cause), "is not the root of run"); - assert.deepInclude(yield* card, { secretStatus: "cancelled" }); - }).pipe(Effect.provide(layer)); - }), - ), -); - it.effect("starts a steer that missed the turn on the saved next-turn selection", () => Effect.gen(function* () { const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( diff --git a/apps/server/src/secrets/SecretRequests.test.ts b/apps/server/src/secrets/SecretRequests.test.ts index e8577d8a3f8a6..026b9775b52d1 100644 --- a/apps/server/src/secrets/SecretRequests.test.ts +++ b/apps/server/src/secrets/SecretRequests.test.ts @@ -77,7 +77,6 @@ const withService = ( readonly delivery?: "file"; readonly directory?: string; readonly runStatus?: string; - readonly rootNodeId?: string; readonly removeFails?: boolean; readonly closedFirst?: boolean; readonly failedRecords?: number; @@ -138,13 +137,7 @@ const withService = ( getThreadRecords: () => Effect.succeed({ thread: { projectId }, - runs: [ - { - id: "run-1", - status: options.runStatus ?? "running", - rootNodeId: options.rootNodeId ?? "node-root", - }, - ], + runs: [{ id: "run-1", status: options.runStatus ?? "running" }], turnItems: [ { id: turnItemId, @@ -435,10 +428,7 @@ it.effect("works in threads with long ids, such as a delegated subagent's", () = ); }); -it.effect.each([ - { stopped: "the run ended", runStatus: "completed" }, - { stopped: "a steer restarted the run", rootNodeId: "node-after-steer" }, -])("refuses a value once the agent that asked has stopped ($stopped), but can decline", (state) => +it.effect("refuses an answer once the agent that asked has stopped", () => withService( ({ service, stored, dispatched }) => Effect.gen(function* () { @@ -448,15 +438,8 @@ it.effect.each([ assert.include(late.message, "has stopped"); assert.deepEqual(valuesOf(stored), []); assert.equal(dispatched.length, 0); - yield* service.answer({ threadId, turnItemId, answer: { type: "decline" } }); - assert.deepEqual( - dispatched.map((command) => - command.type === "secret_request.record" ? command.secretStatus : command.type, - ), - ["declined"], - ); }), - state, + { runStatus: "completed" }, ), ); diff --git a/apps/server/src/secrets/SecretRequests.ts b/apps/server/src/secrets/SecretRequests.ts index 6edc25d2605c0..cef9191bbf3dc 100644 --- a/apps/server/src/secrets/SecretRequests.ts +++ b/apps/server/src/secrets/SecretRequests.ts @@ -129,13 +129,7 @@ const make = Effect.gen(function* () { return yield* new SecretRequestError({ reason: "already_answered" }); } const run = records.runs.find((candidate) => candidate.id === item.runId); - // Declining only closes the card, so it works after the asking turn is gone. - if ( - input.answer.type !== "decline" && - (run === undefined || - ThreadManagementService.isTerminalRunStatus(run.status) || - run.rootNodeId !== item.nodeId) - ) { + if (run === undefined || ThreadManagementService.isTerminalRunStatus(run.status)) { return yield* new SecretRequestError({ reason: "agent_stopped" }); } const secret =