diff --git a/.vite-hooks/pre-push b/.vite-hooks/pre-push index bc58b85e3f2f7..d0b57a919ef8e 100755 --- a/.vite-hooks/pre-push +++ b/.vite-hooks/pre-push @@ -52,4 +52,5 @@ if [ -n "$(git status --porcelain --untracked-files=no)" ]; then fi # With no base found, check:changed falls back to the nearest remote main. echo "pre-push: vp run check:changed ${base:-}" +unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_COMMON_DIR GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES vp run check:changed ${base:+"$base"} diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 9cf2d604dbc8d..ce2c87d5d12bc 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1350,7 +1350,7 @@ export const layerPullRequestsToolkit = toolkitRegistration( PullRequestsHandlers.layer, ).pipe(Layer.provide(PullRequestWatchService.layer)); -export const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe( +const layerEventsToolkit = toolkitRegistration(EventsToolkit, EventsHandlers.layer).pipe( Layer.provide(PullRequestWatchService.layer), ); diff --git a/apps/server/src/orchestration-v2/contextBoundary.ts b/apps/server/src/orchestration-v2/contextBoundary.ts index 1d9ca8d552fa2..ff918a0126554 100644 --- a/apps/server/src/orchestration-v2/contextBoundary.ts +++ b/apps/server/src/orchestration-v2/contextBoundary.ts @@ -3,7 +3,7 @@ import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3too import { cancelledBeforeStart } from "./RestartBackgroundNote.ts"; /** A fresh-session schedule run starts a side conversation; the thread's own one continues past it. */ -export function isScheduledFreshRun( +function isScheduledFreshRun( run: Pick, turnItems: OrchestrationV2ThreadProjection["turnItems"], ): boolean { diff --git a/apps/server/src/orchestration-v2/eventSubscription.ts b/apps/server/src/orchestration-v2/eventSubscription.ts index fcb871fe5643d..be2ba0a0cc4f9 100644 --- a/apps/server/src/orchestration-v2/eventSubscription.ts +++ b/apps/server/src/orchestration-v2/eventSubscription.ts @@ -40,23 +40,20 @@ export const emptyCursor = (): SubscriptionCursor => ({ deliveredSignatures: {}, }); -export function canonicalAuthor(login: string): string { +function canonicalAuthor(login: string): string { return login .trim() .toLowerCase() .replace(/\[bot\]$/i, ""); } -export function authorIgnored( - login: string | null | undefined, - ignore: readonly string[], -): boolean { +function authorIgnored(login: string | null | undefined, ignore: readonly string[]): boolean { if (login == null || login.trim() === "") return false; const key = canonicalAuthor(login); return ignore.some((entry) => canonicalAuthor(entry) === key); } -export function normalizePullRequestUrl(raw: string): string { +function normalizePullRequestUrl(raw: string): string { const url = new URL(raw); url.hash = ""; url.search = ""; @@ -95,7 +92,7 @@ export interface DeliveryInput { readonly maxWakesPerHour?: number | null | undefined; } -export function normalizeDelivery( +function normalizeDelivery( input: DeliveryInput | undefined, ): | { readonly ok: true; readonly delivery: EventDeliveryPolicy } @@ -159,7 +156,7 @@ function validateQuietHours(hours: QuietHours): string | null { } /** Minutes from midnight in the zone. Throws when the zone is invalid. */ -export function minutesInZone(nowMs: number, timeZone: string): number { +function minutesInZone(nowMs: number, timeZone: string): number { const parts = new Intl.DateTimeFormat("en-US", { timeZone, hour: "2-digit", diff --git a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts index d90886835a234..18c904b158129 100644 --- a/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ThreadFork.integration.test.ts @@ -11,10 +11,6 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; -import * as PlatformError from "effect/PlatformError"; -import * as Schema from "effect/Schema"; -import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { ClaudeOrchestratorReplayHarness } from "../Adapters/ClaudeAdapterV2.testkit.ts"; import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts"; @@ -32,6 +28,7 @@ import { decodeProviderReplayNdjson, materializeReplayTranscriptWorkspace, } from "@t3tools/provider-testing/replayTranscript"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; const CODEX_MODEL_SELECTION = { instanceId: ProviderInstanceId.make("codex"), @@ -54,51 +51,6 @@ const CODEX_READ_ONLY_NEVER_POLICY = { }, } as const; -class ThreadForkGitCommandError extends Schema.TaggedError()( - "ThreadForkGitCommandError", - { - command: Schema.String, - exitCode: Schema.Number, - }, -) { - override get message(): string { - return `${this.command} failed with exit ${this.exitCode}.`; - } -} - -function runGit( - cwd: string, - args: ReadonlyArray, -): Effect.Effect< - void, - ThreadForkGitCommandError | PlatformError.PlatformError, - ChildProcessSpawner.ChildProcessSpawner -> { - return Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd })); - if (Number(exitCode) !== 0) { - return yield* new ThreadForkGitCommandError({ - command: `git ${args.join(" ")}`, - exitCode: Number(exitCode), - }); - } - }); -} - -const makeCheckpointWorkspace = Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cwd = yield* fs.makeTempDirectory({ prefix: "t3-orchestrator-v2-thread-fork-" }); - yield* runGit(cwd, ["init"]); - yield* runGit(cwd, ["config", "user.name", "T3 Code Test"]); - yield* runGit(cwd, ["config", "user.email", "t3code-test@example.com"]); - yield* fs.writeFileString(path.join(cwd, "README.md"), "# thread fork\n"); - yield* runGit(cwd, ["add", "README.md"]); - yield* runGit(cwd, ["commit", "-m", "initial"]); - return cwd; -}); - function readTranscript(transcriptPath: string) { return Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -145,12 +97,7 @@ describe("orchestration V2 thread fork", () => { const rawTranscript = yield* readTranscript(CLAUDE_TRANSCRIPT_PATH); const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript); const forkedNativeSessionId = metadataString(transcript, "forkedNativeSessionId"); - const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) => - Effect.service(FileSystem.FileSystem).pipe( - Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })), - Effect.orDie, - ), - ); + const cwd = yield* checkpointWorkspace("thread-fork"); const materialized = yield* Effect.gen(function* () { const ids = yield* IdAllocator.IdAllocatorV2; @@ -283,12 +230,7 @@ describe("orchestration V2 thread fork", () => { it.effect("forks a Codex native thread at the selected native turn boundary", () => Effect.gen(function* () { const rawTranscript = yield* readTranscript(PRIOR_TURN_TRANSCRIPT_PATH); - const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) => - Effect.service(FileSystem.FileSystem).pipe( - Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })), - Effect.orDie, - ), - ); + const cwd = yield* checkpointWorkspace("thread-fork"); const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript( materializeReplayTranscriptWorkspace(rawTranscript, cwd), ); @@ -469,12 +411,7 @@ describe("orchestration V2 thread fork", () => { transcript, "sourceAssistantMessageUuids", ); - const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) => - Effect.service(FileSystem.FileSystem).pipe( - Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })), - Effect.orDie, - ), - ); + const cwd = yield* checkpointWorkspace("thread-fork"); const materialized = yield* Effect.gen(function* () { const ids = yield* IdAllocator.IdAllocatorV2; @@ -678,12 +615,7 @@ describe("orchestration V2 thread fork", () => { throw new Error("Claude fork-local rollback transcript is missing expected prompts."); } - const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) => - Effect.service(FileSystem.FileSystem).pipe( - Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })), - Effect.orDie, - ), - ); + const cwd = yield* checkpointWorkspace("thread-fork"); const materialized = yield* Effect.gen(function* () { const ids = yield* IdAllocator.IdAllocatorV2; diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index a071e682881e3..385996c985c17 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 61564 + "mcpToolListJsonBytes": 61917 } diff --git a/apps/server/src/testUtils/gitConfig.setup.test.ts b/apps/server/src/testUtils/gitConfig.setup.test.ts new file mode 100644 index 0000000000000..5d727c1ed8c7f --- /dev/null +++ b/apps/server/src/testUtils/gitConfig.setup.test.ts @@ -0,0 +1,133 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { afterEach, describe, expect, it, vi } from "@effect/vitest"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import { configureTestGitEnv } from "./gitConfig.setup.ts"; + +const runCleanGit = (cwd: string, args: ReadonlyArray) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const env: NodeJS.ProcessEnv = { ...process.env }; + configureTestGitEnv(env); + const handle = yield* spawner.spawn( + ChildProcess.make("git", args, { cwd, env, extendEnv: false }), + ); + const [stdout, exitCode] = yield* Effect.all( + [ + Stream.runCollect(handle.stdout).pipe( + Effect.map((chunks) => Buffer.concat(chunks).toString("utf8").trim()), + ), + handle.exitCode, + ], + { concurrency: "unbounded" }, + ); + expect(Number(exitCode)).toBe(0); + return stdout; + }).pipe(Effect.scoped); + +describe("git test environment scrub", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("strips inherited GIT_* variables and sets deterministic fixture git config", () => { + const env: NodeJS.ProcessEnv = { + PATH: "/usr/bin", + GIT_DIR: "/scratch/.git", + GIT_WORK_TREE: "/scratch", + GIT_INDEX_FILE: "/scratch/.git/index", + GIT_COMMON_DIR: "/scratch/.git", + git_object_directory: "/scratch/.git/objects", + GIT_CONFIG_PARAMETERS: "'user.name=Leaked'", + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: "user.name", + GIT_CONFIG_VALUE_0: "Leaked", + }; + + configureTestGitEnv(env); + + expect(env.PATH).toBe("/usr/bin"); + expect(env.GIT_DIR).toBeUndefined(); + expect(env.GIT_WORK_TREE).toBeUndefined(); + expect(env.GIT_INDEX_FILE).toBeUndefined(); + expect(env.GIT_COMMON_DIR).toBeUndefined(); + expect(env.git_object_directory).toBeUndefined(); + expect(env.GIT_CONFIG_PARAMETERS).toBeUndefined(); + expect(env.GIT_CONFIG_COUNT).toBe("6"); + expect(env.GIT_CONFIG_KEY_0).toBe("core.autocrlf"); + expect(env.GIT_CONFIG_VALUE_0).toBe("false"); + expect(env.GIT_CONFIG_KEY_3).toBe("commit.gpgsign"); + expect(env.GIT_CONFIG_VALUE_3).toBe("false"); + expect(env.GIT_CONFIG_KEY_5).toBe("init.defaultBranch"); + expect(env.GIT_CONFIG_VALUE_5).toBe("main"); + }); + + it.effect( + "prevents checkpointWorkspace from leaking into a scratch non-bare repo under GIT_DIR and GIT_INDEX_FILE", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const scratchDir = yield* fs.makeTempDirectoryScoped({ + prefix: "t3-git-scrub-non-bare-", + }); + yield* runCleanGit(scratchDir, ["init"]); + yield* runCleanGit(scratchDir, ["config", "user.name", "Scratch Owner"]); + yield* runCleanGit(scratchDir, ["config", "user.email", "scratch@example.invalid"]); + yield* fs.writeFileString(path.join(scratchDir, "scratch.txt"), "baseline\n"); + yield* runCleanGit(scratchDir, ["add", "scratch.txt"]); + yield* runCleanGit(scratchDir, ["commit", "-m", "scratch baseline"]); + + const beforeHead = yield* runCleanGit(scratchDir, ["rev-parse", "HEAD"]); + const scratchGitDir = path.join(scratchDir, ".git"); + vi.stubEnv("GIT_DIR", scratchGitDir); + vi.stubEnv("GIT_WORK_TREE", scratchDir); + vi.stubEnv("GIT_COMMON_DIR", scratchGitDir); + vi.stubEnv("GIT_INDEX_FILE", path.join(scratchGitDir, "index")); + + const workspace = yield* checkpointWorkspace("scrub-non-bare"); + + expect(yield* runCleanGit(workspace, ["log", "-1", "--format=%s"])).toBe("initial"); + expect(yield* runCleanGit(scratchDir, ["rev-parse", "HEAD"])).toBe(beforeHead); + expect(yield* runCleanGit(scratchDir, ["rev-list", "--count", "HEAD"])).toBe("1"); + expect(yield* runCleanGit(scratchDir, ["config", "--local", "user.name"])).toBe( + "Scratch Owner", + ); + expect(yield* runCleanGit(scratchDir, ["config", "--local", "user.email"])).toBe( + "scratch@example.invalid", + ); + expect(yield* runCleanGit(scratchDir, ["status", "--porcelain"])).toBe(""); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect( + "prevents checkpointWorkspace from leaking into a scratch bare repo under GIT_DIR and GIT_INDEX_FILE", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const bareDir = yield* fs.makeTempDirectoryScoped({ + prefix: "t3-git-scrub-bare-", + }); + yield* runCleanGit(bareDir, ["init", "--bare"]); + + const scratchIndex = path.join(bareDir, "index"); + vi.stubEnv("GIT_DIR", bareDir); + vi.stubEnv("GIT_INDEX_FILE", scratchIndex); + + const workspace = yield* checkpointWorkspace("scrub-bare"); + + expect(yield* runCleanGit(workspace, ["log", "-1", "--format=%s"])).toBe("initial"); + expect(yield* runCleanGit(bareDir, ["for-each-ref"])).toBe(""); + expect(yield* runCleanGit(bareDir, ["config", "--local", "--list"])).not.toContain( + "T3 Code Test", + ); + expect(yield* fs.exists(scratchIndex)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/testUtils/gitConfig.setup.ts b/apps/server/src/testUtils/gitConfig.setup.ts index f2ad4a83e2d54..089555194af9c 100644 --- a/apps/server/src/testUtils/gitConfig.setup.ts +++ b/apps/server/src/testUtils/gitConfig.setup.ts @@ -1,4 +1,3 @@ -// Override inherited autocrlf, signing and init-branch settings through env so every git child gets stable fixtures. const entries: ReadonlyArray = [ ["core.autocrlf", "false"], ["core.filemode", "false"], @@ -8,9 +7,17 @@ const entries: ReadonlyArray = [ ["init.defaultBranch", "main"], ]; -const existing = Number(process.env.GIT_CONFIG_COUNT ?? "0"); -process.env.GIT_CONFIG_COUNT = String(existing + entries.length); -entries.forEach(([key, value], index) => { - process.env[`GIT_CONFIG_KEY_${existing + index}`] = key; - process.env[`GIT_CONFIG_VALUE_${existing + index}`] = value; -}); +export function configureTestGitEnv(env: NodeJS.ProcessEnv): void { + for (const key of Object.keys(env)) { + if (key.toUpperCase().startsWith("GIT_")) { + delete env[key]; + } + } + env.GIT_CONFIG_COUNT = String(entries.length); + entries.forEach(([key, value], index) => { + env[`GIT_CONFIG_KEY_${index}`] = key; + env[`GIT_CONFIG_VALUE_${index}`] = value; + }); +} + +configureTestGitEnv(process.env); diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index addd7e3752bda..7bbd46edef0e2 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -630,22 +630,6 @@ export const setThreadStanding = Effect.fn("EnvironmentCommands.setThreadStandin }); }); -export interface SetThreadDelegationNudgeInput extends ThreadCommandInput { - readonly enabled: boolean; - readonly thresholds?: ReadonlyArray; -} -export const setThreadDelegationNudge = Effect.fn("EnvironmentCommands.setThreadDelegationNudge")( - function* (input: SetThreadDelegationNudgeInput) { - return yield* dispatch({ - type: "thread.delegation-nudge.set", - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - enabled: input.enabled, - ...(input.thresholds === undefined ? {} : { thresholds: [...input.thresholds] }), - }); - }, -); - export interface SetThreadAutoSettleInput extends ThreadCommandInput { readonly enabled: boolean; } diff --git a/packages/provider-testing/src/replayWorkspace.ts b/packages/provider-testing/src/replayWorkspace.ts index 4216ebaedc53f..8e1d42c933355 100644 --- a/packages/provider-testing/src/replayWorkspace.ts +++ b/packages/provider-testing/src/replayWorkspace.ts @@ -1,4 +1,5 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -19,6 +20,30 @@ class ReplayFixtureGitCommandError extends Schema.TaggedError = [ + ["core.autocrlf", "false"], + ["core.filemode", "false"], + ["core.longpaths", "true"], + ["commit.gpgsign", "false"], + ["tag.gpgsign", "false"], + ["init.defaultBranch", "main"], +]; + +function cleanGitEnv(inherited: NodeJS.ProcessEnv): Record { + return { + ...Object.fromEntries( + Object.entries(inherited).filter(([name]) => !name.toUpperCase().startsWith("GIT_")), + ), + GIT_CONFIG_COUNT: String(REPLAY_GIT_CONFIG.length), + ...Object.fromEntries( + REPLAY_GIT_CONFIG.flatMap(([key, value], index) => [ + [`GIT_CONFIG_KEY_${index}`, key], + [`GIT_CONFIG_VALUE_${index}`, value], + ]), + ), + }; +} + function runGit( cwd: string, args: ReadonlyArray, @@ -29,7 +54,10 @@ function runGit( > { return Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd })); + const inherited = yield* HostProcess.Environment; + const exitCode = yield* spawner.exitCode( + ChildProcess.make("git", args, { cwd, env: cleanGitEnv(inherited), extendEnv: false }), + ); if (Number(exitCode) !== 0) { return yield* new ReplayFixtureGitCommandError({ command: `git ${args.join(" ")}`, diff --git a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts index 064f04fb92924..e6e59dd00b720 100644 --- a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts +++ b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts @@ -1,54 +1,17 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import * as NodeWS from "@effect/platform-node/NodeWS"; -import { - CommandId, - ORCHESTRATION_PROTOCOL_VERSION, - ThreadId, - WsRpcGroup, -} from "@t3tools/contracts"; +import { CommandId, ThreadId } from "@t3tools/contracts"; import { expect } from "e2e"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import { RpcClient, RpcSerialization } from "effect/rpc"; -import { Socket } from "effect/socket"; import { T3_HOME } from "../e2e.config.ts"; import { SECOND_HOME, startSecondServer } from "./second-server.ts"; -import { makeState, runPromise, test, WEB } from "./t3.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; // A shell keeps an environment's 25 newest settled threads; older ones come from search. const NEWER_SETTLED = 25; -/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ -const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { - const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); - const { ticket } = yield* HttpClient.execute( - HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( - HttpClientRequest.bearerToken(issued.stdout.trim()), - ), - ).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), - Effect.provide(FetchHttpClient.layer), - ); - // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. - const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( - Layer.provide( - Socket.layerWebSocket( - `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, - ), - ), - Layer.provide(RpcSerialization.layerJson), - Layer.provide(NodeWS.layerWebSocketConstructor), - ), - ); - return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); -}); - const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4()); const decodePairing = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), diff --git a/scripts/scenarios/t3.ts b/scripts/scenarios/t3.ts index 113916cf94081..c3800c74ad321 100644 --- a/scripts/scenarios/t3.ts +++ b/scripts/scenarios/t3.ts @@ -1,14 +1,19 @@ // `test` for web scenarios: e2e's web test plus `t3`, which seeds state and opens the signed-in // app. `t3-mobile.ts` is the same for the iOS app. import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeWS from "@effect/platform-node/NodeWS"; import { test as base } from "@e2e-dev/web"; +import { ORCHESTRATION_PROTOCOL_VERSION, WsRpcGroup } from "@t3tools/contracts"; import { expect } from "e2e"; import * as HostProcess from "@t3tools/shared/HostProcess"; 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 { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { RpcClient, RpcSerialization } from "effect/rpc"; +import { Socket } from "effect/socket"; import { APP_DIR, T3_HOME } from "../e2e.config.ts"; import { run } from "./shell.ts"; @@ -149,6 +154,33 @@ const environmentId = (baseUrl: string) => Effect.provide(FetchHttpClient.layer), ); +/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ +export const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { + const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); + const { ticket } = yield* HttpClient.execute( + HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), + Effect.provide(FetchHttpClient.layer), + ); + // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. + const protocol = yield* Layer.build( + RpcClient.layerProtocolSocket().pipe( + Layer.provide( + Socket.layerWebSocket( + `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, + ), + ), + Layer.provide(RpcSerialization.layerJson), + Layer.provide(NodeWS.layerWebSocketConstructor), + ), + ); + return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); +}); + export const test = base.extend<{ t3: T3 }>({ t3: async ({ app, browser }, use) => { const { state, cleanup } = makeState(T3_HOME);