sailfork / t3code-github / packages/ provider-acp/ src/ server/ clientTerminals.test.ts

import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Sink from "effect/Sink";
import * as TestClock from "effect/testing/TestClock";
import * as Result from "effect/Result";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as HostProcess from "@t3tools/shared/HostProcess";

import {
  makeAcpClientTerminals,
  resolveEmbeddedTerminalContent,
  type AcpClientTerminals,
} from "./clientTerminals.ts";

const withTerminals = <A, E>(use: (terminals: AcpClientTerminals) => Effect.Effect<A, E>) =>
  Effect.gen(function* () {
    const terminals = yield* makeAcpClientTerminals({
      defaultCwd: process.cwd(),
    });
    return yield* use(terminals).pipe(Effect.ensuring(terminals.disposeAll));
  }).pipe(Effect.provide(NodeServices.layer), Effect.scoped);

describe("AcpClientTerminals", () => {
  it.live("runs a command, buffers output, and reports the exit status", () =>
    withTerminals((terminals) =>
      Effect.gen(function* () {
        const created = yield* terminals.create({
          sessionId: "session",
          command: process.execPath,
          args: ["-e", "console.log('hello from acp'); process.exit(3);"],
        });

        const exit = yield* terminals.waitForExit({
          sessionId: "session",
          terminalId: created.terminalId,
        });
        expect(exit.exitCode).toBe(3);

        const output = yield* terminals.output({
          sessionId: "session",
          terminalId: created.terminalId,
        });
        expect(output.output).toContain("hello from acp");
        expect(output.truncated).toBe(false);
        expect(output.exitStatus?.exitCode).toBe(3);
      }),
    ),
  );

  it.live("resolves terminal environment from the requesting ACP session", () =>
    Effect.gen(function* () {
      const terminals = yield* makeAcpClientTerminals({
        defaultCwd: process.cwd(),
        environmentForSession: (sessionId) => ({
          T3_TEST_ACP_SESSION_TOKEN: sessionId === "session-a" ? "token-a" : "token-b",
        }),
      });
      yield* Effect.addFinalizer(() => terminals.disposeAll);

      for (const [sessionId, expected] of [
        ["session-a", "token-a"],
        ["session-b", "token-b"],
      ] as const) {
        const created = yield* terminals.create({
          sessionId,
          command: process.execPath,
          args: ["-e", "process.stdout.write(process.env.T3_TEST_ACP_SESSION_TOKEN ?? '')"],
        });
        yield* terminals.waitForExit({ sessionId, terminalId: created.terminalId });
        const output = yield* terminals.output({ sessionId, terminalId: created.terminalId });
        expect(output.output).toBe(expected);
      }
    }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
  );

  it.live("runs Devin shell source with arguments, pipes, and session fallback variables", () =>
    Effect.gen(function* () {
      const terminals = yield* makeAcpClientTerminals({
        defaultCwd: process.cwd(),
        shellCommands: true,
        environmentForSession: () => ({ T3_ACP_MCP_NODE: "mailbox-probe" }),
      });
      yield* Effect.addFinalizer(() => terminals.disposeAll);
      const terminal = yield* terminals.create({
        sessionId: "devin",
        command: 'printf "%s\\n" "$T3_ACP_MCP_NODE" | tr a-z A-Z',
      });
      const exit = yield* terminals.waitForExit({ sessionId: "devin", ...terminal });
      const output = yield* terminals.output({ sessionId: "devin", ...terminal });
      expect(exit.exitCode).toBe(0);
      expect(output.output.trim()).toBe("MAILBOX-PROBE");
    }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
  );

  it.live("truncates buffered output from the beginning at the byte limit", () =>
    withTerminals((terminals) =>
      Effect.gen(function* () {
        const created = yield* terminals.create({
          sessionId: "session",
          command: process.execPath,
          args: ["-e", "process.stdout.write('a'.repeat(64) + 'TAIL');"],
          outputByteLimit: 16,
        });
        yield* terminals.waitForExit({ sessionId: "session", terminalId: created.terminalId });

        const output = yield* terminals.output({
          sessionId: "session",
          terminalId: created.terminalId,
        });
        expect(output.truncated).toBe(true);
        expect(output.output.endsWith("TAIL")).toBe(true);
        expect(output.output.length).toBeLessThanOrEqual(16);
      }),
    ),
  );

  it.live("kills long-running commands and rejects released terminal handles", () =>
    withTerminals((terminals) =>
      Effect.gen(function* () {
        const created = yield* terminals.create({
          sessionId: "session",
          command: process.execPath,
          args: ["-e", "setInterval(() => {}, 1000);"],
        });
        yield* terminals.kill({ sessionId: "session", terminalId: created.terminalId });
        const exit = yield* terminals.waitForExit({
          sessionId: "session",
          terminalId: created.terminalId,
        });
        expect(exit.exitCode === 0 ? null : exit.exitCode).not.toBe(0);
        // Windows has no signals: a killed process only reports an exit code.
        if (yield* HostProcess.isWindows) {
          expect(exit.signal).toBeNull();
        } else {
          expect(exit.signal).toBe("SIGTERM");
        }

        yield* terminals.release({ sessionId: "session", terminalId: created.terminalId });
        const rejected = yield* Effect.flip(
          terminals.output({ sessionId: "session", terminalId: created.terminalId }),
        );
        expect(rejected.message).toContain("unknown terminal ID");

        expect(terminals.readOutputSnapshot("session", created.terminalId)).toBeDefined();
      }),
    ),
  );

  it.effect.each([
    { deadline: "default", forceKillAfter: undefined, deadlineMillis: 5000 },
    { deadline: "configured", forceKillAfter: "250 millis" as const, deadlineMillis: 250 },
  ])(
    "waits for the $deadline deadline before force-killing a SIGTERM-ignoring terminal",
    ({ forceKillAfter, deadlineMillis }) =>
      Effect.gen(function* () {
        const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
        const child = ChildProcessSpawner.makeHandle({
          pid: ChildProcessSpawner.ProcessId(1),
          exitCode: Deferred.await(exited),
          isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
          // Model a process that only exits when the spawner escalates after its deadline.
          kill: (options) =>
            options?.forceKillAfter === undefined
              ? Deferred.await(exited).pipe(Effect.asVoid)
              : Effect.sleep(options.forceKillAfter).pipe(
                  Effect.andThen(Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137))),
                  Effect.asVoid,
                ),
          stdin: Sink.drain,
          stdout: Stream.empty,
          stderr: Stream.empty,
          all: Stream.empty,
          getInputFd: () => Sink.drain,
          getOutputFd: () => Stream.empty,
          unref: Effect.succeed(Effect.void),
        });
        const terminals = yield* makeAcpClientTerminals({
          defaultCwd: process.cwd(),
          ...(forceKillAfter === undefined ? {} : { forceKillAfter }),
        }).pipe(
          Effect.provideService(
            ChildProcessSpawner.ChildProcessSpawner,
            ChildProcessSpawner.make(() => Effect.succeed(child)),
          ),
        );
        yield* Effect.addFinalizer(() =>
          Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137)).pipe(
            Effect.andThen(terminals.disposeAll),
          ),
        );
        const terminal = yield* terminals.create({
          sessionId: "session",
          command: "ignores-SIGTERM",
        });
        const request = { sessionId: "session", ...terminal };
        const killing = yield* terminals.kill(request).pipe(Effect.forkChild);
        const waiting = yield* terminals.waitForExit(request).pipe(Effect.forkChild);

        yield* TestClock.adjust(deadlineMillis - 1);
        expect(yield* child.isRunning).toBe(true);
        expect(killing.pollUnsafe()).toBeUndefined();
        expect(waiting.pollUnsafe()).toBeUndefined();
        yield* TestClock.adjust("1 millis");
        expect(yield* child.isRunning).toBe(false);
        yield* Fiber.join(killing);
        expect(yield* Fiber.join(waiting)).toEqual({ exitCode: 137, signal: null });
      }).pipe(Effect.scoped),
  );

  it.live("force-kills commands that ignore SIGTERM and resolves wait_for_exit", () =>
    Effect.gen(function* () {
      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
      const ready = yield* Deferred.make<void>();
      const spawned = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>();
      let stdout = "";
      const terminals = yield* makeAcpClientTerminals({
        defaultCwd: process.cwd(),
        forceKillAfter: "50 millis",
      }).pipe(
        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, {
          ...spawner,
          spawn: (command) =>
            spawner.spawn(command).pipe(
              Effect.tap((child) => Deferred.succeed(spawned, child)),
              Effect.map((child) => ({
                ...child,
                stdout: child.stdout.pipe(
                  Stream.tap((chunk) => {
                    stdout += Buffer.from(chunk).toString("utf8");
                    return stdout.includes("ready")
                      ? Deferred.succeed(ready, undefined)
                      : Effect.void;
                  }),
                ),
              })),
            ),
        }),
      );
      yield* Effect.addFinalizer(() => terminals.disposeAll);
      const terminal = yield* terminals.create({
        sessionId: "session",
        command: process.execPath,
        args: [
          "-e",
          "process.on('SIGTERM', () => {}); console.log('ready'); setInterval(() => {}, 1000);",
        ],
      });
      const child = yield* Deferred.await(spawned);
      // Reap only this test's captured child, including when the regression fails.
      yield* Effect.addFinalizer(() => child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore));
      yield* Deferred.await(ready);

      const request = { sessionId: "session", ...terminal };
      yield* terminals.kill(request);
      const exit = yield* terminals.waitForExit(request);
      // Windows has no signals: the command is terminated without a signal name.
      if (!(yield* HostProcess.isWindows)) {
        expect(exit).toEqual({ exitCode: null, signal: "SIGKILL" });
      }
      expect(yield* child.isRunning).toBe(false);
    }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
  );

  it.live("reserves terminal capacity across concurrent creates", () =>
    withTerminals((terminals) =>
      Effect.gen(function* () {
        const results = yield* Effect.all(
          Array.from({ length: 17 }, () =>
            terminals
              .create({
                sessionId: "session",
                command: process.execPath,
                args: ["-e", "setInterval(() => {}, 1000);"],
              })
              .pipe(Effect.result),
          ),
          { concurrency: "unbounded" },
        );

        expect(results.filter(Result.isSuccess)).toHaveLength(16);
        expect(results.filter(Result.isFailure)).toHaveLength(1);
      }),
    ),
  );

  it.live("bounds unreleased terminal handles without invalidating existing ids", () =>
    withTerminals((terminals) =>
      Effect.gen(function* () {
        const terminalIds: string[] = [];
        for (let index = 0; index < 64; index += 1) {
          const created = yield* terminals.create({
            sessionId: "session",
            command: process.execPath,
            args: ["-e", `process.stdout.write('${index}');`],
          });
          yield* terminals.waitForExit({
            sessionId: "session",
            terminalId: created.terminalId,
          });
          terminalIds.push(created.terminalId);
        }

        const rejected = yield* terminals
          .create({
            sessionId: "session",
            command: process.execPath,
            args: ["-e", ""],
          })
          .pipe(Effect.result);
        expect(Result.isFailure(rejected)).toBe(true);
        expect(terminals.readOutputSnapshot("session", terminalIds[0]!)).toBeDefined();
        expect(terminals.readOutputSnapshot("session", terminalIds.at(-1)!)).toBeDefined();
      }),
    ),
  );

  it.live("bounds aggregate output retained across unreleased terminals", () =>
    withTerminals((terminals) =>
      Effect.gen(function* () {
        const terminalIds: string[] = [];
        for (let index = 0; index < 3; index += 1) {
          const created = yield* terminals.create({
            sessionId: "session",
            command: process.execPath,
            args: ["-e", "process.stdout.write('x'.repeat(8 * 1024 * 1024));"],
            outputByteLimit: 8 * 1024 * 1024,
          });
          yield* terminals.waitForExit({
            sessionId: "session",
            terminalId: created.terminalId,
          });
          terminalIds.push(created.terminalId);
        }

        const snapshots = terminalIds.map((terminalId) =>
          terminals.readOutputSnapshot("session", terminalId)!,
        );
        const retainedBytes = snapshots.reduce(
          (total, snapshot) => total + Buffer.byteLength(snapshot.output),
          0,
        );
        expect(retainedBytes).toBeLessThanOrEqual(16 * 1024 * 1024);
        expect(snapshots.some((snapshot) => snapshot.truncated)).toBe(true);
      }),
    ),
  );

  it.live("rejects terminal handles from a different ACP session", () =>
    withTerminals((terminals) =>
      Effect.gen(function* () {
        const created = yield* terminals.create({
          sessionId: "owner-session",
          command: process.execPath,
          args: ["-e", "process.stdout.write('owned');"],
        });
        const foreignRequest = {
          sessionId: "foreign-session",
          terminalId: created.terminalId,
        };
        const results = yield* Effect.forEach(
          [
            terminals.output(foreignRequest),
            terminals.waitForExit(foreignRequest),
            terminals.kill(foreignRequest),
            terminals.release(foreignRequest),
          ],
          (effect) => effect.pipe(Effect.result),
          { concurrency: "unbounded" },
        );

        expect(results.every(Result.isFailure)).toBe(true);
        expect(terminals.readOutputSnapshot("foreign-session", created.terminalId)).toBeUndefined();
        expect(terminals.readOutputSnapshot("owner-session", created.terminalId)).toBeDefined();
      }),
    ),
  );
});

describe("resolveEmbeddedTerminalContent", () => {
  it("rewrites terminal content into text from the buffered snapshot", () => {
    const notification = {
      sessionId: "session",
      update: {
        sessionUpdate: "tool_call_update" as const,
        toolCallId: "call-1",
        content: [
          { type: "content" as const, content: { type: "text" as const, text: "before" } },
          { type: "terminal" as const, terminalId: "t3-term-1" },
          { type: "terminal" as const, terminalId: "t3-term-unknown" },
        ],
      },
    };

    const resolved = resolveEmbeddedTerminalContent(notification, (sessionId, terminalId) =>
      sessionId === "session" && terminalId === "t3-term-1"
        ? { output: "compiled 3 files", truncated: false, exitStatus: undefined }
        : undefined,
    );

    expect(resolved.update).toMatchObject({
      content: [
        { type: "content", content: { type: "text", text: "before" } },
        { type: "content", content: { type: "text", text: "compiled 3 files" } },
        { type: "content", content: { type: "text", text: "[terminal t3-term-unknown]" } },
      ],
    });
  });
});