Skip to content

The open-source app everyone uses to manage agents at work

80.4 KB
Raw Blame
import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import { adapterAuthSessions, companies, createDb, environmentLeases, environments } from "@paperclipai/db";
import type { AgentAdapterType } from "@paperclipai/shared";
import { DEVICE_LOGIN_URL } from "@paperclipai/adapter-codex-local/server";
import {
  getEmbeddedPostgresTestSupport,
  startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import {
  AdapterAuthSessionConflictError,
  buildSandboxLoginDriver,
  DEVICE_LOGIN_TIMEOUT_MS,
  DISPLAYED_CODE_ADAPTER_TYPES,
  DISPLAYED_CODE_PROFILES,
  LOGIN_LEASE_SESSION_TAG_KEY,
  createDeviceLoginService,
  createDbAdapterAuthSessionStore,
  sessionLoginHomePath,
  sessionCredentialPath,
  type AcquireLoginLeaseInput,
  type AdapterAuthSessionRow,
  type AdapterAuthSessionStore,
  type CredentialPromotion,
  type LoginSessionActivityEvent,
  type LoginSessionLease,
  type LoginSessionRuntime,
  type SandboxDeleteResult,
} from "../services/device-login-service.ts";
import {
  createDeviceLoginReaper,
  createProductionLoginSessionReaperRuntime,
  type LoginSessionCleanupRuntime,
} from "../services/device-login-reaper.ts";

// A cleanup runtime for the reaper. It confirms every delete and reports no
// tagged lease, so the reaper only reclaims the seeded session rows.
function createReaperRuntime() {
  const deletes: string[] = [];
  const runtime: LoginSessionCleanupRuntime = {
    async deleteSandbox(ref) {
      deletes.push(ref.providerLeaseId);
      return { outcome: "deleted" };
    },
    async listTaggedLeases() {
      return [];
    },
  };
  return { runtime, deletes };
}

// A passing promotion for the lifecycle tests. The mandatory promotion is a
// required dependency, so a test that does not exercise the credential write
// still supplies a promotion that accepts the credential.
const passingPromotion: CredentialPromotion = { promote: () => {} };

// Build the service with the passing promotion by default, applied to every
// adapter type. A test that checks the promotion path passes its own
// `promotion` to override the default for every adapter type, or its own
// `promotionByAdapterType` to give each adapter type a distinct promotion (for
// example, to prove a `grok_local` login never runs the Codex promotion).
type ServiceDeps = Parameters<typeof createDeviceLoginService>[0];
function makeService(
  deps: Omit<ServiceDeps, "promotionByAdapterType"> & {
    promotion?: CredentialPromotion;
    promotionByAdapterType?: ServiceDeps["promotionByAdapterType"];
  },
) {
  const { promotion, promotionByAdapterType, ...rest } = deps;
  return createDeviceLoginService({
    promotionByAdapterType:
      promotionByAdapterType ?? {
        codex_local: promotion ?? passingPromotion,
        grok_local: promotion ?? passingPromotion,
      },
    ...rest,
  });
}

const ADAPTER_TYPE: AgentAdapterType = "codex_local";
const OWNER_A = "user-a";
const OWNER_B = "user-b";

// Poll the store until the row reaches the wanted status. The login run writes
// the status through a serialized tail, so a test waits for the write to land
// before it drives the next step.
async function waitForStatus(
  store: {
    getByPublicId(publicSessionId: string, companyId: string): Promise<AdapterAuthSessionRow | null>;
  },
  publicSessionId: string,
  companyId: string,
  status: AdapterAuthSessionRow["status"],
): Promise<void> {
  for (let attempt = 0; attempt < 1000; attempt += 1) {
    const row = await store.getByPublicId(publicSessionId, companyId);
    if (row?.status === status) return;
    await new Promise((resolve) => setImmediate(resolve));
  }
  throw new Error(`the session did not reach status ${status}`);
}

// A valid device-login output. The parser accepts the exact URL and a code of
// four characters, a hyphen, and five characters, on a dedicated line after the
// "one-time code" preamble.
const PROMPT_OUTPUT = `Open ${DEVICE_LOGIN_URL} in your browser.\nEnter the one-time code below:\nABCD-EFGHI\n`;
const PROMPT_CODE = "ABCD-EFGHI";

// A valid Grok device-login output. The Grok parser requires the `user_code`
// query to equal the code that stands alone on its own line after the
// preamble. The Codex parser accepts none of this shape.
const GROK_CODE = "WXYZ-ABCD";
const GROK_DEVICE_LOGIN_URL = `https://accounts.x.ai/oauth2/device?user_code=${GROK_CODE}`;
const GROK_PROMPT_OUTPUT = [
  "To sign in, open this URL in your browser:",
  `  ${GROK_DEVICE_LOGIN_URL}`,
  "Confirm this code in your browser:",
  `  ${GROK_CODE}`,
].join("\n");

type ExecController = { onStdout: (chunk: string) => void; input: AcquireLoginLeaseInput };
type ExecBehavior = (c: ExecController) => Promise<{ exitCode: number | null }>;

const execSuccess: ExecBehavior = async ({ onStdout }) => {
  onStdout(PROMPT_OUTPUT);
  return { exitCode: 0 };
};

const execFailure: ExecBehavior = async ({ onStdout }) => {
  onStdout(PROMPT_OUTPUT);
  return { exitCode: 1 };
};

const execDriverError: ExecBehavior = async ({ onStdout }) => {
  onStdout(PROMPT_OUTPUT);
  throw new Error("driver stream errored");
};

// Emit the prompt, then never resolve. The host timeout or the cancellation
// signal ends the run.
const execHang: ExecBehavior = ({ onStdout }) => {
  onStdout(PROMPT_OUTPUT);
  return new Promise<{ exitCode: number | null }>(() => {});
};

interface FakeRuntimeOptions {
  exec: ExecBehavior;
  authBytes?: Buffer;
  /** When set, the descriptor-bound read rejects with this error on success. */
  readError?: Error;
  delete?: () => Promise<SandboxDeleteResult>;
}

function createFakeRuntime(opts: FakeRuntimeOptions) {
  const acquisitions: AcquireLoginLeaseInput[] = [];
  const deleteCalls: string[] = [];
  const releaseCalls: string[] = [];
  const deleteImpl = opts.delete ?? (async (): Promise<SandboxDeleteResult> => ({ outcome: "deleted" }));
  const runtime: LoginSessionRuntime = {
    async acquireLoginLease(input) {
      acquisitions.push(input);
      const lease: LoginSessionLease = {
        providerLeaseId: `lease-${input.sessionId}`,
        authPath: sessionCredentialPath(input.sessionId),
        driver: {
          start: (_command, onData) => opts.exec({ onStdout: onData, input }),
          readFile: async () => {
            if (opts.readError) throw opts.readError;
            return opts.authBytes ?? Buffer.from("{}");
          },
          dispose: async () => {},
        },
        deleteSandbox: async () => {
          deleteCalls.push(input.sessionId);
          return await deleteImpl();
        },
        release: async () => {
          releaseCalls.push(input.sessionId);
        },
      };
      return lease;
    },
  };
  return { runtime, acquisitions, deleteCalls, releaseCalls };
}

// An in-memory store. It mimics the active company-adapter slot, so most tests
// run with no database. The concurrency test uses the database-backed store, so
// the real partial unique index maps the conflict to a 409.
function createMemoryStore(): AdapterAuthSessionStore & {
  rows: Map<string, AdapterAuthSessionRow>;
} {
  const rows = new Map<string, AdapterAuthSessionRow>();
  const activeSlots = new Set<string>();
  // The active company credential slot is scoped to the company, the owner, and
  // the adapter, so two owners in one company hold independent slots.
  const slotKey = (companyId: string, startedByUserId: string, adapterType: string) =>
    `${companyId}|${startedByUserId}|${adapterType}`;
  const isActive = (status: AdapterAuthSessionRow["status"]) =>
    status === "starting" || status === "waiting_for_user" || status === "promoting";
  return {
    rows,
    async insert(input) {
      const key = slotKey(input.companyId, input.startedByUserId, input.adapterType);
      if (activeSlots.has(key)) throw new AdapterAuthSessionConflictError();
      activeSlots.add(key);
      rows.set(input.id, {
        id: input.id,
        publicSessionId: input.publicSessionId,
        companyId: input.companyId,
        environmentId: input.environmentId,
        adapterType: input.adapterType,
        startedByUserId: input.startedByUserId,
        providerLeaseId: null,
        status: "starting",
        expiresAt: input.expiresAt,
        promotionExpiresAt: null,
        finishedAt: null,
        failureReason: null,
      });
    },
    async recordLeaseAcquired(input) {
      const row = rows.get(input.sessionId);
      if (row) row.providerLeaseId = input.providerLeaseId;
    },
    async setStatus(input) {
      const row = rows.get(input.sessionId);
      if (!row) return;
      row.status = input.status;
      if (input.failureReason !== undefined) row.failureReason = input.failureReason;
      if (input.finishedAt !== undefined) row.finishedAt = input.finishedAt;
      if (input.promotionExpiresAt !== undefined) row.promotionExpiresAt = input.promotionExpiresAt;
      if (!isActive(input.status))
        activeSlots.delete(slotKey(row.companyId, row.startedByUserId, row.adapterType));
    },
    async compareAndSetStatus(input) {
      const row = rows.get(input.sessionId);
      if (!row || !input.expectedStatuses.includes(row.status)) return false;
      row.status = input.status;
      if (input.failureReason !== undefined) row.failureReason = input.failureReason;
      if (input.finishedAt !== undefined) row.finishedAt = input.finishedAt;
      if (input.promotionExpiresAt !== undefined) row.promotionExpiresAt = input.promotionExpiresAt;
      if (!isActive(input.status))
        activeSlots.delete(slotKey(row.companyId, row.startedByUserId, row.adapterType));
      return true;
    },
    async get(sessionId) {
      const row = rows.get(sessionId);
      return row ? { ...row } : null;
    },
    async getByPublicId(publicSessionId, companyId) {
      // Scope the read to the company and the public session id, so a
      // foreign-company lookup reads nothing and the internal id never matches.
      for (const row of rows.values()) {
        if (row.publicSessionId === publicSessionId && row.companyId === companyId) {
          return { ...row };
        }
      }
      return null;
    },
    async getActiveByOwner(companyId, startedByUserId, adapterType) {
      for (const row of rows.values()) {
        if (
          row.companyId === companyId &&
          row.startedByUserId === startedByUserId &&
          row.adapterType === adapterType &&
          isActive(row.status)
        ) {
          return { ...row };
        }
      }
      return null;
    },
    async withCompanyAdapterPromotionLock(_companyId, _startedByUserId, _adapterType, fn) {
      // The in-memory store runs on a single event loop, so it needs no real
      // lock. The pass-through keeps the store contract satisfied.
      return fn();
    },
  };
}

describe("device login service", () => {
  it("inserts the session row before it acquires the lease", async () => {
    const store = createMemoryStore();
    let rowPresentAtAcquire = false;
    const runtime: LoginSessionRuntime = {
      async acquireLoginLease(input) {
        rowPresentAtAcquire = (await store.get(input.sessionId)) !== null;
        return {
          providerLeaseId: `lease-${input.sessionId}`,
          authPath: sessionCredentialPath(input.sessionId),
          driver: {
            start: (_command, onData) => execSuccess({ onStdout: onData, input }),
            readFile: async () => Buffer.from("{}"),
            dispose: async () => {},
          },
          deleteSandbox: async () => ({ outcome: "deleted" }),
          release: async () => {},
        };
      },
    };
    const service = makeService({ store, runtime });
    const { session, completed } = await service.start({
      companyId: randomUUID(),
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });
    expect(rowPresentAtAcquire).toBe(true);
    expect(session.status).toBe("starting");
    expect(session.expiresAt).not.toBeNull();
    await completed;
  });

  it("delivers the prompt to the owner, promotes, deletes the sandbox, and authenticates", async () => {
    const store = createMemoryStore();
    const activity: LoginSessionActivityEvent[] = [];
    const promoted: Buffer[] = [];
    const promotionContexts: { sessionId: string; companyId: string }[] = [];
    // Gate the login after the prompt surfaces, so the row stays in
    // `waiting_for_user` long enough for the test to read the prompt (twice)
    // before it releases the gate and lets the login race to `authenticated`.
    let releaseGate!: () => void;
    const gate = new Promise<void>((resolve) => {
      releaseGate = resolve;
    });
    const execGated: ExecBehavior = async ({ onStdout }) => {
      onStdout(PROMPT_OUTPUT);
      await gate;
      return { exitCode: 0 };
    };
    const { runtime, deleteCalls } = createFakeRuntime({
      exec: execGated,
      authBytes: Buffer.from('{"token":"secret"}'),
    });
    const companyId = randomUUID();
    const service = makeService({
      store,
      runtime,
      recordActivity: (event) => activity.push(event),
      promotion: {
        promote: (bytes, context) => {
          promoted.push(bytes);
          promotionContexts.push({ sessionId: context.sessionId, companyId: context.companyId });
        },
      },
    });
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });

    // The prompt is surfaced only after the conditional move to
    // `waiting_for_user` wins, so wait for that surface, then drain the microtask
    // that retains the prompt before the owner reads it.
    await waitForStatus(store, session.sessionId, companyId, "waiting_for_user");
    await new Promise((resolve) => setImmediate(resolve));

    // The owner reads the one-time prompt through the owner read path.
    const owner = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(owner?.prompt).toEqual({ url: DEVICE_LOGIN_URL, code: PROMPT_CODE });
    // The read returns the public session id, never the internal row id.
    expect(owner?.sessionId).toBe(session.sessionId);

    // A non-owner never reads the prompt.
    const other = await service.readOwnerSession(session.sessionId, companyId, OWNER_B);
    expect(other?.prompt).toBeNull();

    // The prompt survives a repeated read while the session is still active. The
    // read never consumes it, so a page reload does not lose the code.
    const repeatWhileActive = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(repeatWhileActive?.prompt).toEqual({ url: DEVICE_LOGIN_URL, code: PROMPT_CODE });

    // Release the gate, so the login proceeds to the promotion and the
    // authenticated terminal.
    releaseGate();
    const outcome = await completed;
    expect(outcome.status).toBe("authenticated");
    expect(outcome.cleanupPending).toBe(false);
    expect(outcome.sandboxDeleteObserved).toBe(true);
    expect(deleteCalls).toHaveLength(1);
    expect(promoted).toHaveLength(1);
    // The promotion runs with the internal session id and the company context, so
    // it resolves the company scope and the sole-active-owner check for this exact
    // session. The internal id is not the public session id.
    const internalRow = await store.getByPublicId(session.sessionId, companyId);
    expect(promotionContexts).toEqual([{ sessionId: internalRow?.id, companyId }]);
    expect(internalRow?.id).not.toBe(session.sessionId);

    // The session is now terminal (authenticated). A read after a terminal
    // transition returns a null prompt, and it carries `Cache-Control:
    // no-store, private` at the route layer (see agent-device-login-routes.test.ts).
    const afterTerminal = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(afterTerminal?.prompt).toBeNull();

    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("authenticated");
    expect(row?.finishedAt).not.toBeNull();

    // Every activity record carries only non-secret fields.
    expect(activity.length).toBeGreaterThan(0);
    for (const event of activity) {
      expect(Object.keys(event).sort()).toEqual([
        "adapterType",
        "companyId",
        "environmentId",
        "phase",
        "sessionId",
      ]);
    }
    // The prompt phase records the surface, not the URL or the code.
    expect(activity.map((event) => event.phase)).toContain("prompt_surfaced");
    expect(JSON.stringify(activity)).not.toContain(DEVICE_LOGIN_URL);
    expect(JSON.stringify(activity)).not.toContain(PROMPT_CODE);
  });

  it("wraps the terminal authenticated commit in a promotion's runTerminalCommit", async () => {
    // A promotion that defines `runTerminalCommit` gets the chance to wrap the
    // service's own terminal write, so it can hold a lock across a check it
    // already ran once earlier in `promote` and the write that publishes
    // `authenticated`.
    const store = createMemoryStore();
    const { runtime } = createFakeRuntime({
      exec: execSuccess,
      authBytes: Buffer.from('{"token":"secret"}'),
    });
    const companyId = randomUUID();
    const wrapCalls: unknown[] = [];
    const service = makeService({
      store,
      runtime,
      promotion: {
        promote: () => {},
        async runTerminalCommit(commit, context) {
          wrapCalls.push(context);
          return commit();
        },
      },
    });
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });

    const outcome = await completed;
    expect(outcome.status).toBe("authenticated");
    expect(wrapCalls).toHaveLength(1);
    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("authenticated");
  });

  it("records a failed terminal, and never authenticates, when runTerminalCommit rejects", async () => {
    // A promotion's `runTerminalCommit` rejects when its own re-check, run
    // immediately before the terminal write, finds the value it validated
    // earlier no longer holds (for example, a rotation landed in the gap).
    // The service must fail the login the same way a `promote` rejection
    // does, never publishing `authenticated` for the stale value.
    const store = createMemoryStore();
    const { runtime, deleteCalls } = createFakeRuntime({
      exec: execSuccess,
      authBytes: Buffer.from('{"token":"secret"}'),
    });
    const companyId = randomUUID();
    const service = makeService({
      store,
      runtime,
      promotion: {
        promote: () => {},
        async runTerminalCommit() {
          // A real promotion would run its re-check here, find the bound
          // value stale, and throw before ever calling `commit`.
          throw new Error("the bound value no longer matches");
        },
      },
    });
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });

    const outcome = await completed;
    expect(outcome.status).toBe("failed");
    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("failed");
    expect(row?.failureReason).toBe("promotion_failed");
    // The service still deletes the sandbox on this failure path, the same
    // as a `promote` rejection.
    expect(deleteCalls).toHaveLength(1);
  });

  it("gives a Grok prompt to a grok_local session, and the session surfaces the Grok code and URL", async () => {
    // This proves the Grok parser ran: the profile map resolves the parser from
    // the trusted adapter type, so a `grok_local` session runs the Grok parser,
    // not the Codex parser.
    const store = createMemoryStore();
    // Gate the login after the prompt surfaces, so the row stays in
    // `waiting_for_user` long enough for the test to read the prompt before the
    // login races to its own terminal.
    let releaseGate!: () => void;
    const gate = new Promise<void>((resolve) => {
      releaseGate = resolve;
    });
    const execGrokGatedSuccess: ExecBehavior = async ({ onStdout }) => {
      onStdout(GROK_PROMPT_OUTPUT);
      await gate;
      return { exitCode: 0 };
    };
    const { runtime } = createFakeRuntime({ exec: execGrokGatedSuccess, authBytes: Buffer.from("{}") });
    const companyId = randomUUID();
    const service = makeService({ store, runtime });
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: "grok_local",
      startedByUserId: OWNER_A,
    });

    await waitForStatus(store, session.sessionId, companyId, "waiting_for_user");
    await new Promise((resolve) => setImmediate(resolve));

    const owner = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(owner?.prompt).toEqual({ url: GROK_DEVICE_LOGIN_URL, code: GROK_CODE });

    releaseGate();
    await completed;
  });

  it("gives the same Grok prompt to a codex_local session, and the session surfaces no prompt", async () => {
    // This proves the Codex parser stays strict: a Grok-shaped prompt never
    // satisfies the Codex parser's origin, path, and code-length rules, so the
    // row never leaves `starting` and the owner read carries no prompt.
    const store = createMemoryStore();
    let releaseGate!: () => void;
    const gate = new Promise<void>((resolve) => {
      releaseGate = resolve;
    });
    const execGrokGated: ExecBehavior = async ({ onStdout }) => {
      onStdout(GROK_PROMPT_OUTPUT);
      await gate;
      return { exitCode: 0 };
    };
    const { runtime } = createFakeRuntime({ exec: execGrokGated, authBytes: Buffer.from("{}") });
    const companyId = randomUUID();
    const service = makeService({ store, runtime });
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });

    // Give the run several event-loop turns. The row must never reach
    // `waiting_for_user`, because the Codex parser never matches the Grok
    // prompt.
    for (let attempt = 0; attempt < 20; attempt += 1) {
      await new Promise((resolve) => setImmediate(resolve));
    }
    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("starting");

    const owner = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(owner?.prompt).toBeNull();

    releaseGate();
    await completed;
  });

  it("runs the Grok promotion (never the Codex one) for a grok_local login, and the Codex promotion (never the Grok one) for a codex_local login", async () => {
    // This proves the promotion dispatch is adapter-scoped: `resolveProfile`
    // must pick the promotion for the login's own adapter type, not always the
    // same injected value. A test that only asserts the map carries a
    // `grok_local` member would not prove this — it follows the value all the
    // way to the call that runs it.
    const codexPromoteCalls: string[] = [];
    const grokPromoteCalls: string[] = [];
    const service = makeService({
      store: createMemoryStore(),
      runtime: createFakeRuntime({ exec: execSuccess, authBytes: Buffer.from("{}") }).runtime,
      promotionByAdapterType: {
        codex_local: {
          promote: (_bytes, context) => {
            codexPromoteCalls.push(context.sessionId);
          },
        },
        grok_local: {
          promote: (_bytes, context) => {
            grokPromoteCalls.push(context.sessionId);
          },
        },
      },
    });

    const grokRun = await service.start({
      companyId: randomUUID(),
      environmentId: randomUUID(),
      adapterType: "grok_local",
      startedByUserId: OWNER_A,
    });
    await grokRun.completed;
    expect(grokPromoteCalls).toHaveLength(1);
    expect(codexPromoteCalls).toHaveLength(0);

    const codexRun = await service.start({
      companyId: randomUUID(),
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });
    await codexRun.completed;
    expect(codexPromoteCalls).toHaveLength(1);
    expect(grokPromoteCalls).toHaveLength(1);
  });

  it("holds no prompt value, account email, or credential byte in an activity record, an API response, or a database row for a Grok session", async () => {
    // A realistic Grok auth.json: the composite <issuer>::<uuid> identity key,
    // a refresh token, and the personal fields the payload carries (email,
    // name, ids). None of these may reach the service's own generic surfaces:
    // the activity record, the session/owner API responses, or the database
    // row. (The promotion's own log lines are proven redacted separately, in
    // the grok-local `adapter-auth-promotion.test.ts` suite.)
    const grokIssuer = "https://issuer.x.ai";
    const grokUuid = "3fa85f64-5717-4562-b3fc-2c963f66afa6";
    const grokEmail = "[email protected]";
    const refreshTokenSentinel = "SENTINEL_GROK_REFRESH_TOKEN";
    const grokAuthBytes = Buffer.from(
      JSON.stringify({
        [`${grokIssuer}::${grokUuid}`]: {
          key: "api-key-value",
          refresh_token: refreshTokenSentinel,
          expires_at: "2026-01-01T00:00:00Z",
          oidc_issuer: grokIssuer,
          oidc_client_id: "client-1",
          email: grokEmail,
          first_name: "Test",
          last_name: "User",
          user_id: "user-1",
          principal_id: "principal-1",
          team_id: "team-1",
        },
      }),
    );

    const store = createMemoryStore();
    const activity: LoginSessionActivityEvent[] = [];
    // Gate the login after the prompt surfaces, so the row stays in
    // `waiting_for_user` long enough for the test to read the prompt before the
    // login races to its own terminal.
    let releaseGate!: () => void;
    const gate = new Promise<void>((resolve) => {
      releaseGate = resolve;
    });
    const { runtime } = createFakeRuntime({
      exec: async ({ onStdout }) => {
        onStdout(GROK_PROMPT_OUTPUT);
        await gate;
        return { exitCode: 0 };
      },
      authBytes: grokAuthBytes,
    });
    const companyId = randomUUID();
    const service = makeService({
      store,
      runtime,
      recordActivity: (event) => activity.push(event),
      promotionByAdapterType: { grok_local: { promote: () => {} } },
    });

    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: "grok_local",
      startedByUserId: OWNER_A,
    });
    await waitForStatus(store, session.sessionId, companyId, "waiting_for_user");
    await new Promise((resolve) => setImmediate(resolve));

    const owner = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    releaseGate();
    const outcome = await completed;
    expect(outcome.status).toBe("authenticated");

    const forbidden = [grokEmail, refreshTokenSentinel, "api-key-value", grokUuid];
    const activityText = JSON.stringify(activity);
    const sessionText = JSON.stringify(session);
    const ownerText = JSON.stringify(owner);
    const outcomeText = JSON.stringify(outcome);
    const row = await store.getByPublicId(session.sessionId, companyId);
    const rowText = JSON.stringify(row);
    for (const secret of forbidden) {
      expect(activityText).not.toContain(secret);
      expect(sessionText).not.toContain(secret);
      expect(ownerText).not.toContain(secret);
      expect(outcomeText).not.toContain(secret);
      expect(rowText).not.toContain(secret);
    }
    // The owner read still carries the (non-secret) device-login prompt.
    expect(owner?.prompt).toEqual({ url: GROK_DEVICE_LOGIN_URL, code: GROK_CODE });
  });

  it("fails closed and never promotes when a success outcome carries no credential", async () => {
    const store = createMemoryStore();
    let promoteCalls = 0;
    const { runtime, deleteCalls } = createFakeRuntime({
      // The login command exits 0, but the sandbox produced no credential bytes.
      exec: execSuccess,
      authBytes: Buffer.alloc(0),
    });
    const service = makeService({
      store,
      runtime,
      promotion: {
        promote: () => {
          promoteCalls += 1;
        },
      },
    });
    const companyId = randomUUID();
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });
    const outcome = await completed;
    // A success outcome with no credential never authenticates and never runs
    // the promotion write. The service still deletes the sandbox.
    expect(outcome.status).toBe("failed");
    expect(promoteCalls).toBe(0);
    expect(deleteCalls).toHaveLength(1);
    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("failed");
    const failed = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(failed?.failure?.reason).toBe("promotion_failed");
  });

  it("deletes the sandbox and records a failed terminal on a non-zero exit", async () => {
    const store = createMemoryStore();
    const { runtime, deleteCalls } = createFakeRuntime({ exec: execFailure });
    const service = makeService({ store, runtime });
    const companyId = randomUUID();
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });
    const outcome = await completed;
    expect(outcome.status).toBe("failed");
    expect(outcome.sandboxDeleteObserved).toBe(true);
    expect(deleteCalls).toHaveLength(1);
    const failed = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(failed?.status).toBe("failed");
    expect(failed?.failure?.reason).toBe("login_command_failed");
  });

  it("deletes the sandbox and records a failed terminal on a driver error", async () => {
    const store = createMemoryStore();
    const { runtime, deleteCalls } = createFakeRuntime({ exec: execDriverError });
    const service = makeService({ store, runtime });
    const { completed } = await service.start({
      companyId: randomUUID(),
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });
    const outcome = await completed;
    expect(outcome.status).toBe("failed");
    expect(deleteCalls).toHaveLength(1);
  });

  it("fails closed and deletes the sandbox when the descriptor-bound read fails", async () => {
    const store = createMemoryStore();
    let promoteCalls = 0;
    const { runtime, deleteCalls } = createFakeRuntime({
      // The login command exits 0, but the descriptor-bound read rejects. The
      // runner converts the read error to a fixed driver error, so the run fails.
      exec: execSuccess,
      readError: new Error("device login failed: the sandbox credential read errored."),
    });
    const service = makeService({
      store,
      runtime,
      promotion: {
        promote: () => {
          promoteCalls += 1;
        },
      },
    });
    const companyId = randomUUID();
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });
    const outcome = await completed;
    // A failed read never promotes a credential and still deletes the sandbox.
    expect(outcome.status).toBe("failed");
    expect(promoteCalls).toBe(0);
    expect(deleteCalls).toHaveLength(1);
    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("failed");
  });

  it("fails closed and deletes the sandbox when the credential schema is malformed", async () => {
    const store = createMemoryStore();
    const { runtime, deleteCalls } = createFakeRuntime({
      // The read returns a well-formed file, but the promotion rejects the shape.
      // A malformed schema fails the same way as a failed check: no authenticate,
      // and a sandbox delete.
      exec: execSuccess,
      authBytes: Buffer.from('{"not":"a subscription auth"}', "utf8"),
    });
    const service = makeService({
      store,
      runtime,
      promotion: {
        promote: () => {
          throw new Error("malformed credential schema");
        },
      },
    });
    const companyId = randomUUID();
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });
    const outcome = await completed;
    expect(outcome.status).toBe("failed");
    expect(deleteCalls).toHaveLength(1);
    const failed = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(failed?.status).toBe("failed");
    expect(failed?.failure?.reason).toBe("promotion_failed");
  });

  it("deletes the sandbox and records a cancelled terminal on a cancellation", async () => {
    const store = createMemoryStore();
    const { runtime, deleteCalls } = createFakeRuntime({ exec: execHang });
    const service = makeService({ store, runtime });
    const controller = new AbortController();
    const companyId = randomUUID();
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
      signal: controller.signal,
    });
    controller.abort();
    const outcome = await completed;
    expect(outcome.status).toBe("cancelled");
    expect(outcome.sandboxDeleteObserved).toBe(true);
    expect(deleteCalls).toHaveLength(1);
    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("cancelled");
  });

  it("clears the prompt on a cancellation, so the owner read returns a null prompt with Cache-Control set at the route layer", async () => {
    const store = createMemoryStore();
    const { runtime } = createFakeRuntime({ exec: execHang });
    const service = makeService({ store, runtime });
    const controller = new AbortController();
    const companyId = randomUUID();
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
      signal: controller.signal,
    });

    await waitForStatus(store, session.sessionId, companyId, "waiting_for_user");
    await new Promise((resolve) => setImmediate(resolve));

    // The prompt is present while the session is active.
    const whileActive = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(whileActive?.prompt).toEqual({ url: DEVICE_LOGIN_URL, code: PROMPT_CODE });

    controller.abort();
    await completed;

    // The session is now terminal (cancelled). The prompt is gone.
    const afterCancel = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(afterCancel?.status).toBe("cancelled");
    expect(afterCancel?.prompt).toBeNull();
  });

  it("releases the lease when a transition fails after acquisition", async () => {
    const store = createMemoryStore();
    // A rejecting `recordLeaseAcquired` forces a transition failure right after
    // the acquisition.
    const failingStore: AdapterAuthSessionStore = {
      ...store,
      async recordLeaseAcquired() {
        throw new Error("transition write failed");
      },
    };
    const { runtime, releaseCalls, deleteCalls } = createFakeRuntime({ exec: execSuccess });
    const service = makeService({ store: failingStore, runtime });
    const companyId = randomUUID();
    await expect(
      service.start({
        companyId,
        environmentId: randomUUID(),
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
      }),
    ).rejects.toThrow("transition write failed");
    expect(releaseCalls).toHaveLength(1);
    // The service never runs the login command, so it never deletes a sandbox.
    expect(deleteCalls).toHaveLength(0);
    const rows = [...store.rows.values()].filter((row) => row.companyId === companyId);
    expect(rows).toHaveLength(1);
    expect(rows[0]?.status).toBe("failed");
  });

  // The rejecting-delete matrix. A delete failure on every terminal path records
  // the durable internal `cleanup_pending` state and never returns a false-clean
  // terminal outcome.
  const rejectingDelete = async (): Promise<SandboxDeleteResult> => {
    throw new Error("provider delete rejected");
  };

  it.each([
    { name: "success", exec: execSuccess, terminal: "authenticated" as const, cancel: false },
    { name: "failure", exec: execFailure, terminal: "failed" as const, cancel: false },
    { name: "cancellation", exec: execHang, terminal: "cancelled" as const, cancel: true },
  ])(
    "records cleanup_pending on a delete failure for the $name path",
    async ({ exec, terminal, cancel }) => {
      const store = createMemoryStore();
      const { runtime, deleteCalls } = createFakeRuntime({
        exec,
        authBytes: Buffer.from("{}"),
        delete: rejectingDelete,
      });
      const service = makeService({ store, runtime });
      const controller = new AbortController();
      const companyId = randomUUID();
      const { session, completed } = await service.start({
        companyId,
        environmentId: randomUUID(),
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
        signal: controller.signal,
      });
      if (cancel) controller.abort();
      const outcome = await completed;
      expect(outcome.status).toBe(terminal);
      expect(outcome.cleanupPending).toBe(true);
      expect(outcome.sandboxDeleteObserved).toBe(true);
      expect(deleteCalls).toHaveLength(1);
      const row = await store.getByPublicId(session.sessionId, companyId);
      expect(row?.status).toBe("cleanup_pending");
      // The public read resolves the retained terminal, never a false-clean.
      const publicRead = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
      expect(publicRead?.status).toBe(terminal);
    },
  );

  it("records cleanup_pending on a delete failure after a promotion failure", async () => {
    const store = createMemoryStore();
    const { runtime, deleteCalls } = createFakeRuntime({
      exec: execSuccess,
      authBytes: Buffer.from("{}"),
      delete: rejectingDelete,
    });
    const service = makeService({
      store,
      runtime,
      promotion: {
        promote: () => {
          throw new Error("promotion write failed");
        },
      },
    });
    const companyId = randomUUID();
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });
    const outcome = await completed;
    // The promotion write failed, so the terminal is `failed`, not
    // `authenticated`. The delete also failed, so the row holds cleanup_pending.
    expect(outcome.status).toBe("failed");
    expect(outcome.cleanupPending).toBe(true);
    expect(outcome.sandboxDeleteObserved).toBe(true);
    expect(deleteCalls).toHaveLength(1);
    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("cleanup_pending");
    const publicRead = await service.readOwnerSession(session.sessionId, companyId, OWNER_A);
    expect(publicRead?.status).toBe("failed");
    expect(publicRead?.failure?.reason).toBe("promotion_failed");
  });

  it("treats a provider not_found result as an idempotent confirmed delete", async () => {
    const store = createMemoryStore();
    const { runtime } = createFakeRuntime({
      exec: execSuccess,
      authBytes: Buffer.from("{}"),
      delete: async () => ({ outcome: "not_found" }),
    });
    const service = makeService({ store, runtime });
    const companyId = randomUUID();
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });
    const outcome = await completed;
    expect(outcome.status).toBe("authenticated");
    expect(outcome.cleanupPending).toBe(false);
    expect(outcome.sandboxDeleteObserved).toBe(true);
    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("authenticated");
  });

  it("never promotes or authenticates when the reaper wins the slot before the claim", async () => {
    const store = createMemoryStore();
    let releaseGate!: () => void;
    const gate = new Promise<void>((resolve) => {
      releaseGate = resolve;
    });
    // Emit the prompt, then hold the login until the test releases the gate. The
    // test uses the hold to terminate the row before the promotion claim runs.
    const execGatedSuccess: ExecBehavior = async ({ onStdout }) => {
      onStdout(PROMPT_OUTPUT);
      await gate;
      return { exitCode: 0 };
    };
    const { runtime, deleteCalls } = createFakeRuntime({
      exec: execGatedSuccess,
      authBytes: Buffer.from("{}"),
    });
    const promote = vi.fn(() => {});
    const service = makeService({ store, runtime, promotion: { promote } });
    const companyId = randomUUID();
    const { session, completed } = await service.start({
      companyId,
      environmentId: randomUUID(),
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });

    // The prompt moves the row to the active `waiting_for_user` state.
    await waitForStatus(store, session.sessionId, companyId, "waiting_for_user");

    // The reaper wins the slot: it terminates the row before the promotion claim.
    // The status write keys on the internal id, not the public session id.
    const seededRow = await store.getByPublicId(session.sessionId, companyId);
    await store.setStatus({
      sessionId: seededRow!.id,
      status: "timed_out",
      at: new Date(),
      finishedAt: new Date(),
    });

    // Release the login. The success outcome now reaches the promotion claim, but
    // the row no longer holds an active pre-promotion status.
    releaseGate();
    const outcome = await completed;

    // The lost claim writes no credential and never authenticates.
    expect(promote).not.toHaveBeenCalled();
    expect(outcome.status).not.toBe("authenticated");
    const row = await store.getByPublicId(session.sessionId, companyId);
    expect(row?.status).toBe("timed_out");
    // The service still deletes its own sandbox on the lost-claim path.
    expect(deleteCalls).toHaveLength(1);
  });

  describe("durable cancel", () => {
    it("cancels a waiting session, releases the slot, and hands cleanup to the reaper", async () => {
      const store = createMemoryStore();
      let releaseGate!: () => void;
      const gate = new Promise<void>((resolve) => {
        releaseGate = resolve;
      });
      // Emit the prompt, then hold the login. The hold keeps the row in the active
      // `waiting_for_user` state while the test cancels it.
      const execGated: ExecBehavior = async ({ onStdout }) => {
        onStdout(PROMPT_OUTPUT);
        await gate;
        return { exitCode: 0 };
      };
      const { runtime } = createFakeRuntime({ exec: execGated, authBytes: Buffer.from("{}") });
      const service = makeService({ store, runtime });
      const companyId = randomUUID();
      const environmentId = randomUUID();
      const { session, completed } = await service.start({
        companyId,
        environmentId,
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
      });
      await waitForStatus(store, session.sessionId, companyId, "waiting_for_user");

      // A non-owner cannot cancel the session.
      expect(await service.cancelOwnerSession(session.sessionId, companyId, OWNER_B)).toBeNull();

      // The owner cancel resolves the public terminal status at once.
      const cancelled = await service.cancelOwnerSession(session.sessionId, companyId, OWNER_A);
      expect(cancelled?.status).toBe("cancelled");

      // The row holds the internal cleanup_pending state that encodes the
      // cancelled terminal, so the reaper deletes the sandbox and finalizes it.
      const row = await store.getByPublicId(session.sessionId, companyId);
      expect(row?.status).toBe("cleanup_pending");
      expect(row?.finishedAt).not.toBeNull();

      // The durable write released the company slot, so a fresh start for the same
      // company and adapter wins. This proves the cancel does not depend on the
      // in-flight run ending.
      const second = await service.start({
        companyId,
        environmentId,
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
      });
      expect(second.session.sessionId).not.toBe(session.sessionId);

      // Release the held runs, so both `completed` promises settle and clear their
      // timers.
      releaseGate();
      await completed;
      await second.completed;
    });

    it("does not cancel a session whose promotion is in flight", async () => {
      const store = createMemoryStore();
      let releasePromotion!: () => void;
      const promotionGate = new Promise<void>((resolve) => {
        releasePromotion = resolve;
      });
      // A promotion that resolves only when the test releases it, so the row stays
      // in the `promoting` state while the test tries to cancel it.
      const promote = vi.fn(async () => {
        await promotionGate;
      });
      const { runtime } = createFakeRuntime({ exec: execSuccess, authBytes: Buffer.from("{}") });
      const service = makeService({ store, runtime, promotion: { promote } });
      const companyId = randomUUID();
      const { session, completed } = await service.start({
        companyId,
        environmentId: randomUUID(),
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
      });
      await waitForStatus(store, session.sessionId, companyId, "promoting");

      // The cancel skips the promoting row, so the credential write finishes. The
      // public projection of a promoting row is `waiting_for_user`.
      const result = await service.cancelOwnerSession(session.sessionId, companyId, OWNER_A);
      expect(result?.status).toBe("waiting_for_user");
      const row = await store.getByPublicId(session.sessionId, companyId);
      expect(row?.status).toBe("promoting");

      // Release the promotion, so the run reaches its own terminal.
      releasePromotion();
      const outcome = await completed;
      expect(outcome.status).toBe("authenticated");
    });
  });

  describe("active session lookup", () => {
    it("finds the caller's active session for a company and adapter, with no session id", async () => {
      const store = createMemoryStore();
      const { runtime } = createFakeRuntime({ exec: execHang });
      const service = makeService({ store, runtime });
      const controller = new AbortController();
      const companyId = randomUUID();
      const { session, completed } = await service.start({
        companyId,
        environmentId: randomUUID(),
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
        signal: controller.signal,
      });
      await waitForStatus(store, session.sessionId, companyId, "waiting_for_user");
      await new Promise((resolve) => setImmediate(resolve));

      const active = await service.readActiveOwnerSession(companyId, ADAPTER_TYPE, OWNER_A);
      expect(active?.sessionId).toBe(session.sessionId);
      expect(active?.prompt).toEqual({ url: DEVICE_LOGIN_URL, code: PROMPT_CODE });

      controller.abort();
      await completed;
    });

    it("returns null for another owner, another company, and another adapter", async () => {
      const store = createMemoryStore();
      const { runtime } = createFakeRuntime({ exec: execHang });
      const service = makeService({ store, runtime });
      const controller = new AbortController();
      const companyId = randomUUID();
      await service.start({
        companyId,
        environmentId: randomUUID(),
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
        signal: controller.signal,
      });

      expect(await service.readActiveOwnerSession(companyId, ADAPTER_TYPE, OWNER_B)).toBeNull();
      expect(
        await service.readActiveOwnerSession(randomUUID(), ADAPTER_TYPE, OWNER_A),
      ).toBeNull();
      expect(await service.readActiveOwnerSession(companyId, "grok_local", OWNER_A)).toBeNull();

      controller.abort();
    });

    it("returns null once the caller's session has no active row", async () => {
      const store = createMemoryStore();
      const { runtime } = createFakeRuntime({ exec: execHang });
      const service = makeService({ store, runtime });
      const controller = new AbortController();
      const companyId = randomUUID();
      const { completed } = await service.start({
        companyId,
        environmentId: randomUUID(),
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
        signal: controller.signal,
      });

      // No active session for this owner before any start ever ran.
      expect(await service.readActiveOwnerSession(companyId, ADAPTER_TYPE, OWNER_A)).not.toBeNull();

      controller.abort();
      await completed;

      // The session is now terminal, so it no longer counts as active.
      expect(await service.readActiveOwnerSession(companyId, ADAPTER_TYPE, OWNER_A)).toBeNull();
    });
  });

  describe("five-minute host timeout", () => {
    it("holds the session active until exactly five minutes, then times out and deletes", async () => {
      vi.useFakeTimers();
      try {
        const store = createMemoryStore();
        const { runtime, deleteCalls } = createFakeRuntime({ exec: execHang });
        const service = makeService({ store, runtime });
        const companyId = randomUUID();
        const { session, completed } = await service.start({
          companyId,
          environmentId: randomUUID(),
          adapterType: ADAPTER_TYPE,
          startedByUserId: OWNER_A,
        });
        let settled = false;
        void completed.then(() => {
          settled = true;
        });

        // One millisecond before five minutes: the run still holds the active
        // claim.
        await vi.advanceTimersByTimeAsync(DEVICE_LOGIN_TIMEOUT_MS - 1);
        expect(settled).toBe(false);
        const midRow = await store.getByPublicId(session.sessionId, companyId);
        expect(["starting", "waiting_for_user"]).toContain(midRow?.status);

        // The last millisecond fires the timeout.
        await vi.advanceTimersByTimeAsync(1);
        const outcome = await completed;
        expect(outcome.status).toBe("timed_out");
        expect(outcome.sandboxDeleteObserved).toBe(true);
        expect(deleteCalls).toHaveLength(1);
        const row = await store.getByPublicId(session.sessionId, companyId);
        expect(row?.status).toBe("timed_out");
      } finally {
        vi.useRealTimers();
      }
    });

    it("records cleanup_pending on a delete failure at the five-minute timeout", async () => {
      vi.useFakeTimers();
      try {
        const store = createMemoryStore();
        const { runtime, deleteCalls } = createFakeRuntime({
          exec: execHang,
          delete: async () => {
            throw new Error("provider delete rejected");
          },
        });
        const service = makeService({ store, runtime });
        const companyId = randomUUID();
        const { session, completed } = await service.start({
          companyId,
          environmentId: randomUUID(),
          adapterType: ADAPTER_TYPE,
          startedByUserId: OWNER_A,
        });
        await vi.advanceTimersByTimeAsync(DEVICE_LOGIN_TIMEOUT_MS);
        const outcome = await completed;
        expect(outcome.status).toBe("timed_out");
        expect(outcome.cleanupPending).toBe(true);
        expect(outcome.sandboxDeleteObserved).toBe(true);
        expect(deleteCalls).toHaveLength(1);
        const row = await store.getByPublicId(session.sessionId, companyId);
        expect(row?.status).toBe("cleanup_pending");
      } finally {
        vi.useRealTimers();
      }
    });
  });

  it("runs the login over the shared pseudo-terminal and reads the credential with the descriptor-bound read", async () => {
    const sessionId = randomUUID();
    const sessionHome = sessionLoginHomePath(sessionId);
    const authPath = sessionCredentialPath(sessionId);

    // The fake pseudo-terminal session streams the prompt and exits with code
    // zero. It records the command the transport opened.
    let openedCommand: string | null = null;
    let closed = false;
    const openPtySession = async (command: string) => {
      openedCommand = command;
      return {
        onData(listener: (chunk: string) => void) {
          listener(PROMPT_OUTPUT);
        },
        write() {},
        async wait() {
          return { exitCode: 0 };
        },
        kill() {},
        async close() {
          closed = true;
        },
      };
    };

    // The fake runtime runs only the descriptor-bound read. It records the fixed,
    // no-follow helper shape and returns the base64 of the credential bytes.
    const execCalls: { command: string; args?: string[]; bypassSession?: boolean }[] = [];
    const credential = '{"tokens":{"refresh_token":"r"}}';
    const environmentRuntime = {
      execute: async (input: { command: string; args?: string[]; bypassSession?: boolean }) => {
        execCalls.push({
          command: input.command,
          args: input.args,
          bypassSession: input.bypassSession,
        });
        return {
          exitCode: 0,
          stdout: Buffer.from(credential, "utf8").toString("base64"),
          stderr: "",
        };
      },
    };

    const driver = buildSandboxLoginDriver({
      openPtySession,
      environmentRuntime: environmentRuntime as never,
      environment: { id: "env", driver: "sandbox" } as never,
      lease: { id: "lease" } as never,
      sessionHome,
      timeoutMs: DEVICE_LOGIN_TIMEOUT_MS,
    });

    const chunks: string[] = [];
    const result = await driver.start("codex login --device-auth", (chunk) => chunks.push(chunk));
    expect(result.exitCode).toBe(0);
    expect(openedCommand).toBe("codex login --device-auth");
    expect(chunks.join("")).toContain(DEVICE_LOGIN_URL);
    // The login runs over the pseudo-terminal, so the descriptor read did not run
    // during the login.
    expect(execCalls.length).toBe(0);

    // The runner path passes the credential path, but the descriptor-bound read
    // ignores it and reads the fixed file under the verified session home.
    const authBytes = await driver.readFile(authPath);
    expect(authBytes.toString("utf8")).toBe(credential);
    expect(execCalls.length).toBe(1);
    // The read runs the fixed no-follow helper as a one-shot, non-session command.
    expect(execCalls[0].command).toBe("node");
    expect(execCalls[0].bypassSession).toBe(true);
    expect(execCalls[0].args?.[0]).toBe("-e");
    // The third argument is the verified session home the helper opens no-follow.
    expect(execCalls[0].args?.[2]).toBe(sessionHome);

    await driver.dispose();
    expect(closed).toBe(true);
  });
});

const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;

if (!embeddedPostgresSupport.supported) {
  console.warn(
    `Skipping codex device login concurrency tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
  );
}

describeEmbeddedPostgres("device login service concurrency (embedded postgres)", () => {
  let stopDb: (() => Promise<void>) | undefined;
  let db!: ReturnType<typeof createDb>;

  beforeAll(async () => {
    const started = await startEmbeddedPostgresTestDatabase("device-login");
    stopDb = started.stop;
    db = createDb(started.connectionString);
  });

  afterEach(async () => {
    await db.delete(adapterAuthSessions);
    await db.delete(environments);
    await db.delete(companies);
  });

  afterAll(async () => {
    await stopDb?.();
  });

  async function seedCompanyEnvironment(): Promise<{ companyId: string; environmentId: string }> {
    const companyId = randomUUID();
    const environmentId = randomUUID();
    await db.insert(companies).values({
      id: companyId,
      name: "Acme",
      status: "active",
      createdAt: new Date(),
      updatedAt: new Date(),
    });
    await db.insert(environments).values({
      id: environmentId,
      name: `sandbox-${environmentId.slice(0, 8)}`,
      driver: "sandbox",
      status: "active",
      config: { provider: "fake" },
      createdAt: new Date(),
      updatedAt: new Date(),
    });
    return { companyId, environmentId };
  }

  async function seedEnvironment(companyId: string): Promise<string> {
    const environmentId = randomUUID();
    await db.insert(environments).values({
      id: environmentId,
      name: `sandbox-${environmentId.slice(0, 8)}`,
      driver: "sandbox",
      status: "active",
      config: { provider: "fake" },
      createdAt: new Date(),
      updatedAt: new Date(),
    });
    return environmentId;
  }

  it("lets two owners in one company each hold an active session", async () => {
    // The active slot is scoped to the company, the owner, and the adapter. Two
    // owners in one company hold independent slots, so both concurrent starts
    // succeed and each acquires one lease.
    const { companyId, environmentId } = await seedCompanyEnvironment();
    const store = createDbAdapterAuthSessionStore(db);
    const { runtime, acquisitions } = createFakeRuntime({ exec: execHang });
    const service = makeService({ store, runtime });
    const controller = new AbortController();

    const results = await Promise.allSettled([
      service.start({
        companyId,
        environmentId,
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
        signal: controller.signal,
      }),
      service.start({
        companyId,
        environmentId,
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_B,
        signal: controller.signal,
      }),
    ]);

    const fulfilled = results.filter(
      (result): result is PromiseFulfilledResult<Awaited<ReturnType<typeof service.start>>> =>
        result.status === "fulfilled",
    );
    expect(fulfilled).toHaveLength(2);
    expect(acquisitions).toHaveLength(2);
    const rows = await db
      .select()
      .from(adapterAuthSessions)
      .where(eq(adapterAuthSessions.companyId, companyId));
    expect(rows).toHaveLength(2);

    // Release the surviving runs so the hanging login commands end.
    controller.abort();
    await Promise.all(fulfilled.map((result) => result.value.completed));
  });

  it("returns one session, one lease, and one 409 when one owner starts twice", async () => {
    // One owner starting twice in two environments conflicts on the active slot.
    // The slot dropped the environment term, so the second environment does not
    // grant a second active session.
    const { companyId, environmentId: environmentA } = await seedCompanyEnvironment();
    const environmentB = await seedEnvironment(companyId);

    const store = createDbAdapterAuthSessionStore(db);
    const { runtime, acquisitions } = createFakeRuntime({ exec: execHang });
    const service = makeService({ store, runtime });
    const controller = new AbortController();

    const results = await Promise.allSettled([
      service.start({
        companyId,
        environmentId: environmentA,
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
        signal: controller.signal,
      }),
      service.start({
        companyId,
        environmentId: environmentB,
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
        signal: controller.signal,
      }),
    ]);

    const fulfilled = results.filter(
      (result): result is PromiseFulfilledResult<Awaited<ReturnType<typeof service.start>>> =>
        result.status === "fulfilled",
    );
    const rejected = results.filter(
      (result): result is PromiseRejectedResult => result.status === "rejected",
    );
    expect(fulfilled).toHaveLength(1);
    expect(rejected).toHaveLength(1);
    const conflict = rejected[0]!.reason;
    expect(conflict).toBeInstanceOf(AdapterAuthSessionConflictError);
    expect(conflict.statusCode).toBe(409);

    // Exactly one start acquired a lease; the losing start never acquired.
    expect(acquisitions).toHaveLength(1);
    const rows = await db
      .select()
      .from(adapterAuthSessions)
      .where(eq(adapterAuthSessions.companyId, companyId));
    expect(rows).toHaveLength(1);

    // Release the surviving run so the hanging login command ends.
    controller.abort();
    await fulfilled[0]!.value.completed;
  });

  it("rejects the same owner's second start with a 409 while the first holds the promotion claim", async () => {
    const { companyId, environmentId } = await seedCompanyEnvironment();
    const store = createDbAdapterAuthSessionStore(db);
    const { runtime } = createFakeRuntime({ exec: execSuccess, authBytes: Buffer.from("{}") });

    // A promotion that never resolves. The first login stays in `promoting`, so
    // it holds the active slot through the claim window.
    let releasePromotion!: () => void;
    const promotionGate = new Promise<void>((resolve) => {
      releasePromotion = resolve;
    });
    const service = makeService({
      store,
      runtime,
      promotion: { promote: () => promotionGate },
    });

    const first = await service.start({
      companyId,
      environmentId,
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
    });

    // The first login reaches the `promoting` claim and holds it.
    await waitForStatus(store, first.session.sessionId, companyId, "promoting");

    // A second start for the same company, owner, and adapter conflicts on the
    // active slot, even though the first login is mid-promotion.
    await expect(
      service.start({
        companyId,
        environmentId,
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
      }),
    ).rejects.toBeInstanceOf(AdapterAuthSessionConflictError);

    // Release the first promotion so the run ends and no timer survives.
    releasePromotion();
    const outcome = await first.completed;
    expect(outcome.status).toBe("authenticated");
  });

  // Insert a `promoting` row whose promotion claim already expired, so the reaper
  // scan selects it. The tests below race the reaper reclaim against the
  // promotion critical section through the real advisory lock.
  async function seedStalePromotingRow(companyId: string, environmentId: string): Promise<string> {
    const sessionId = randomUUID();
    const past = new Date(Date.now() - 5 * 60_000);
    await db.insert(adapterAuthSessions).values({
      id: sessionId,
      companyId,
      environmentId,
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
      publicSessionId: randomUUID(),
      providerLeaseId: `lease-${sessionId}`,
      status: "promoting",
      expiresAt: past,
      promotionExpiresAt: past,
      createdAt: past,
      updatedAt: past,
    });
    return sessionId;
  }

  it("holds the promotion lock so the reaper cannot reclaim a live credential write", async () => {
    const { companyId, environmentId } = await seedCompanyEnvironment();
    const store = createDbAdapterAuthSessionStore(db);
    const sessionId = await seedStalePromotingRow(companyId, environmentId);

    const { runtime } = createReaperRuntime();
    const reaper = createDeviceLoginReaper({ store, runtime, now: () => new Date() });

    // Run the ownership check and the credential write inside the promotion lock.
    // The write flag stands in for the filesystem credential write. A gate holds
    // the section open, so the test can start the reaper while the lock is held.
    let wroteCredential = false;
    let releaseSection!: () => void;
    const sectionGate = new Promise<void>((resolve) => {
      releaseSection = resolve;
    });
    let markSectionActive!: () => void;
    const sectionActive = new Promise<void>((resolve) => {
      markSectionActive = resolve;
    });
    const promotion = store.withCompanyAdapterPromotionLock(companyId, OWNER_A, ADAPTER_TYPE, async () => {
      markSectionActive();
      await sectionGate;
      // Decision H: the write proceeds only while the session still owns the slot.
      const row = await store.get(sessionId);
      if (row?.status === "promoting" && row.companyId === companyId) {
        wroteCredential = true;
      }
    });

    // The promotion holds the lock now. Start the reaper. It must block on the
    // advisory lock, so it cannot reclaim the row while the write section runs.
    await sectionActive;
    const reaped = reaper.sweep();
    await new Promise((resolve) => setTimeout(resolve, 100));
    expect((await store.get(sessionId))?.status).toBe("promoting");

    // Release the section. The ownership check sees the live claim and writes.
    releaseSection();
    await promotion;
    const sweep = await reaped;

    // The credential write stood, because the session owned the slot at the
    // write. The reaper reclaimed the row only after the write finished.
    expect(wroteCredential).toBe(true);
    expect(sweep.expiredTimedOut).toBe(1);
    expect((await store.get(sessionId))?.status).toBe("timed_out");
  });

  it("skips the credential write when the reaper reclaimed the stale slot first", async () => {
    const { companyId, environmentId } = await seedCompanyEnvironment();
    const store = createDbAdapterAuthSessionStore(db);
    const sessionId = await seedStalePromotingRow(companyId, environmentId);

    const { runtime } = createReaperRuntime();
    const reaper = createDeviceLoginReaper({ store, runtime, now: () => new Date() });

    // The reaper reclaims the stale row first and times it out.
    const sweep = await reaper.sweep();
    expect(sweep.expiredTimedOut).toBe(1);
    expect((await store.get(sessionId))?.status).toBe("timed_out");

    // A delayed promotion now runs its section. The ownership check reads the
    // reclaimed row, so it writes no credential and the terminal claim fails.
    let wroteCredential = false;
    await store.withCompanyAdapterPromotionLock(companyId, OWNER_A, ADAPTER_TYPE, async () => {
      const row = await store.get(sessionId);
      if (row?.status === "promoting" && row.companyId === companyId) {
        wroteCredential = true;
      }
    });
    expect(wroteCredential).toBe(false);

    const authenticated = await store.compareAndSetStatus({
      sessionId,
      expectedStatuses: ["promoting"],
      status: "authenticated",
      at: new Date(),
    });
    expect(authenticated).toBe(false);
    expect((await store.get(sessionId))?.status).toBe("timed_out");
  });

  it("does not resurrect a reaped starting row when a delayed prompt arrives", async () => {
    const { companyId, environmentId } = await seedCompanyEnvironment();
    const store = createDbAdapterAuthSessionStore(db);

    // The login emits the prompt only after the test opens the gate, so the
    // reaper reclaims the expired `starting` row before the prompt arrives.
    let releasePrompt!: () => void;
    const promptGate = new Promise<void>((resolve) => {
      releasePrompt = resolve;
    });
    const execGatedPrompt: ExecBehavior = async ({ onStdout }) => {
      await promptGate;
      onStdout(PROMPT_OUTPUT);
      return new Promise<{ exitCode: number | null }>(() => {});
    };
    const { runtime } = createFakeRuntime({ exec: execGatedPrompt });
    const service = makeService({ store, runtime });

    const controller = new AbortController();
    const started = await service.start({
      companyId,
      environmentId,
      adapterType: ADAPTER_TYPE,
      startedByUserId: OWNER_A,
      signal: controller.signal,
    });
    const publicSessionId = started.session.sessionId;
    await waitForStatus(store, publicSessionId, companyId, "starting");

    // The reaper reclaims the expired row and times it out.
    const { runtime: reaperRuntime } = createReaperRuntime();
    const reaper = createDeviceLoginReaper({
      store,
      runtime: reaperRuntime,
      now: () => new Date(Date.now() + DEVICE_LOGIN_TIMEOUT_MS + 60_000),
    });
    const sweep = await reaper.sweep();
    expect(sweep.expiredTimedOut).toBe(1);
    expect((await store.getByPublicId(publicSessionId, companyId))?.status).toBe("timed_out");

    // The delayed prompt arrives now. The conditional transition must not revive
    // the reaped row, and the owner must not read a prompt for it.
    releasePrompt();
    await new Promise((resolve) => setImmediate(resolve));
    await new Promise((resolve) => setImmediate(resolve));

    const owner = await service.readOwnerSession(publicSessionId, companyId, OWNER_A);
    expect((await store.getByPublicId(publicSessionId, companyId))?.status).toBe("timed_out");
    expect(owner?.prompt ?? null).toBeNull();

    // End the run so no timer survives.
    controller.abort();
    await started.completed;
  });

  describe("public session id lookup", () => {
    // Start one session and read its rows. The service returns the public session
    // id, and the store keeps the internal id private.
    async function startOneSession(companyId: string, environmentId: string) {
      const store = createDbAdapterAuthSessionStore(db);
      const controller = new AbortController();
      const { runtime } = createFakeRuntime({ exec: execHang });
      const service = makeService({ store, runtime });
      const started = await service.start({
        companyId,
        environmentId,
        adapterType: ADAPTER_TYPE,
        startedByUserId: OWNER_A,
        signal: controller.signal,
      });
      const publicSessionId = started.session.sessionId;
      const row = await store.getByPublicId(publicSessionId, companyId);
      return { store, service, controller, started, publicSessionId, row };
    }

    it("reads a session by its public id in the same company", async () => {
      const { companyId, environmentId } = await seedCompanyEnvironment();
      const { store, controller, started, publicSessionId, row } = await startOneSession(
        companyId,
        environmentId,
      );

      // The lookup by the public id succeeds in the same company.
      expect(row).not.toBeNull();
      expect(row?.publicSessionId).toBe(publicSessionId);
      // The internal primary-key id is a distinct value, never the public id.
      expect(row?.id).toBeTruthy();
      expect(row?.id).not.toBe(publicSessionId);
      // The API-facing row read stays scoped: the same public id resolves the
      // same row on a second read.
      const again = await store.getByPublicId(publicSessionId, companyId);
      expect(again?.id).toBe(row?.id);

      controller.abort();
      await started.completed;
    });

    it("does not read a session for a foreign company", async () => {
      const { companyId, environmentId } = await seedCompanyEnvironment();
      const { store, controller, started, publicSessionId } = await startOneSession(
        companyId,
        environmentId,
      );

      // A different company id never resolves the row, even with the exact public
      // session id. The predicate carries the company id, so a query never keys on
      // the public session id alone.
      const foreignCompanyId = randomUUID();
      expect(await store.getByPublicId(publicSessionId, foreignCompanyId)).toBeNull();

      controller.abort();
      await started.completed;
    });

    it("never accepts the internal row id as an API identifier", async () => {
      const { companyId, environmentId } = await seedCompanyEnvironment();
      const { store, service, controller, started, publicSessionId, row } =
        await startOneSession(companyId, environmentId);
      const internalId = row!.id;

      // The store never resolves a row by the internal id through the public-id
      // path, even within the same company.
      expect(await store.getByPublicId(internalId, companyId)).toBeNull();

      // The owner read returns the public session id, never the internal id.
      const owner = await service.readOwnerSession(publicSessionId, companyId, OWNER_A);
      expect(owner?.sessionId).toBe(publicSessionId);
      expect(owner?.sessionId).not.toBe(internalId);

      // The owner read rejects the internal id as an API identifier.
      expect(await service.readOwnerSession(internalId, companyId, OWNER_A)).toBeNull();

      controller.abort();
      await started.completed;
    });
  });

  describe("the displayed-code adapter scope", () => {
    it("reads a session row of a second displayed-code adapter by its public id", async () => {
      const { companyId, environmentId } = await seedCompanyEnvironment();
      const store = createDbAdapterAuthSessionStore(db);
      const publicSessionId = randomUUID();
      await db.insert(adapterAuthSessions).values({
        id: randomUUID(),
        companyId,
        environmentId,
        adapterType: "grok_local",
        startedByUserId: OWNER_A,
        publicSessionId,
        status: "starting",
        expiresAt: new Date(Date.now() + 60_000),
        createdAt: new Date(),
        updatedAt: new Date(),
      });

      const row = await store.getByPublicId(publicSessionId, companyId);
      expect(row).not.toBeNull();
      expect(row?.adapterType).toBe("grok_local");
    });

    it("the expiry scan and the cleanup scan include a row of a second displayed-code adapter", async () => {
      const { companyId, environmentId } = await seedCompanyEnvironment();
      const store = createDbAdapterAuthSessionStore(db);
      const past = new Date(Date.now() - 60_000);
      const expiredId = randomUUID();
      await db.insert(adapterAuthSessions).values({
        id: expiredId,
        companyId,
        environmentId,
        adapterType: "grok_local",
        startedByUserId: OWNER_A,
        publicSessionId: randomUUID(),
        status: "starting",
        expiresAt: past,
        createdAt: past,
        updatedAt: past,
      });
      const pendingId = randomUUID();
      await db.insert(adapterAuthSessions).values({
        id: pendingId,
        companyId,
        environmentId,
        adapterType: "grok_local",
        startedByUserId: OWNER_A,
        publicSessionId: randomUUID(),
        status: "cleanup_pending",
        failureReason: "failed|login_command_failed",
        finishedAt: past,
        createdAt: past,
        updatedAt: past,
      });

      const expired = await store.listExpiredActiveSessions(new Date());
      expect(expired.map((row) => row.id)).toContain(expiredId);

      const pending = await store.listCleanupPendingSessions();
      expect(pending.map((row) => row.id)).toContain(pendingId);
    });

    it("the orphan lease scan includes a session row of a second displayed-code adapter, and excludes a Claude setup-token row", async () => {
      const { companyId, environmentId } = await seedCompanyEnvironment();
      const reaperRuntime = createProductionLoginSessionReaperRuntime({
        db,
        // The orphan scan under test reads only the store and the lease list; it
        // never reaches the environment runtime driver.
        environmentRuntime: {} as never,
      });

      // A grok_local session row that still owns its lease. `grok_local` is in
      // the displayed-code adapter set, so the scan's candidate query reaches
      // this row's environment.
      const grokSessionId = randomUUID();
      await db.insert(adapterAuthSessions).values({
        id: randomUUID(),
        companyId,
        environmentId,
        adapterType: "grok_local",
        startedByUserId: OWNER_A,
        publicSessionId: randomUUID(),
        providerLeaseId: "grok-lease-1",
        status: "waiting_for_user",
        expiresAt: new Date(Date.now() + 60_000),
        createdAt: new Date(),
        updatedAt: new Date(),
      });
      await db.insert(environmentLeases).values({
        companyId,
        environmentId,
        status: "active",
        providerLeaseId: "grok-lease-1",
        metadata: { [LOGIN_LEASE_SESSION_TAG_KEY]: grokSessionId },
      });

      // A Claude setup-token row in a second environment, in the shared
      // `cleanup_pending` state the two login flows both use. `claude_local` is
      // outside the displayed-code adapter set, and no other row makes this
      // second environment a scan candidate, so the scan must never read it.
      const claudeEnvironmentId = await seedEnvironment(companyId);
      const claudeSessionId = randomUUID();
      await db.insert(adapterAuthSessions).values({
        id: randomUUID(),
        companyId,
        environmentId: claudeEnvironmentId,
        adapterType: "claude_local",
        startedByUserId: OWNER_B,
        publicSessionId: randomUUID(),
        providerLeaseId: "claude-lease-1",
        status: "cleanup_pending",
        failureReason: "failed",
        finishedAt: new Date(),
        createdAt: new Date(),
        updatedAt: new Date(),
      });
      await db.insert(environmentLeases).values({
        companyId,
        environmentId: claudeEnvironmentId,
        status: "active",
        providerLeaseId: "claude-lease-1",
        metadata: { [LOGIN_LEASE_SESSION_TAG_KEY]: claudeSessionId },
      });

      const tagged = await reaperRuntime.listTaggedLeases();
      const taggedProviderLeaseIds = tagged.map((lease) => lease.providerLeaseId);
      expect(taggedProviderLeaseIds).not.toContain("grok-lease-1");
      expect(taggedProviderLeaseIds).not.toContain("claude-lease-1");
      await db.update(adapterAuthSessions).set({ status: "failed", providerLeaseId: null })
        .where(eq(adapterAuthSessions.providerLeaseId, "grok-lease-1"));
      const orphaned = await reaperRuntime.listTaggedLeases();
      expect(orphaned.map(lease => lease.providerLeaseId)).toEqual(["grok-lease-1"]);
    });

    it("carries the CODEX_HOME variable name on the codex_local profile", () => {
      // The home variable name has no consuming call site yet in this phase; the
      // profile only carries it, ready for a later phase to read it.
      expect(DISPLAYED_CODE_PROFILES.codex_local?.homeEnvVar).toBe("CODEX_HOME");
    });

    it("runLogin and the start ttl read the command, the parser, and the timeout from the resolved profile", async () => {
      const { companyId, environmentId } = await seedCompanyEnvironment();
      const store = createDbAdapterAuthSessionStore(db);
      const originalProfile = DISPLAYED_CODE_PROFILES.codex_local!;
      const customPrompt = { url: "https://example.test/device", code: "ZZZZ-99999" };
      const customTimeoutMs = 12_345_000;
      const capturedCommands: string[] = [];
      // The map is a plain object at runtime; only its TypeScript type reads
      // `Readonly`. Mutate the one entry for this test, then restore it, so no
      // other test in this file observes the override.
      const profiles = DISPLAYED_CODE_PROFILES as Record<string, typeof originalProfile>;
      profiles.codex_local = {
        ...originalProfile,
        command: "custom-login-command",
        timeoutMs: customTimeoutMs,
        parsePrompt: (output) => (output.includes("MARKER") ? customPrompt : null),
      };
      try {
        const runtime: LoginSessionRuntime = {
          async acquireLoginLease(input) {
            return {
              providerLeaseId: `lease-${input.sessionId}`,
              authPath: sessionCredentialPath(input.sessionId),
              driver: {
                start: (command, onData) => {
                  capturedCommands.push(command);
                  onData("a MARKER line\n");
                  return new Promise<{ exitCode: number | null }>(() => {});
                },
                readFile: async () => Buffer.from("{}"),
                dispose: async () => {},
              },
              deleteSandbox: async () => ({ outcome: "deleted" }),
              release: async () => {},
            };
          },
        };
        const service = makeService({ store, runtime });
        const controller = new AbortController();
        const started = await service.start({
          companyId,
          environmentId,
          adapterType: ADAPTER_TYPE,
          startedByUserId: OWNER_A,
          signal: controller.signal,
        });

        // The start ttl read: `session.expiresAt` reflects the profile's
        // `timeoutMs`, not the fixed `DEVICE_LOGIN_TIMEOUT_MS`.
        const expectedExpiresAt = Date.now() + customTimeoutMs;
        expect(Math.abs(new Date(started.session.expiresAt).getTime() - expectedExpiresAt)).toBeLessThan(
          5000,
        );

        // `runLogin`: the driver received the profile's command, and the
        // profile's parser produced the owner-visible prompt.
        await waitForStatus(store, started.session.sessionId, companyId, "waiting_for_user");
        const owner = await service.readOwnerSession(started.session.sessionId, companyId, OWNER_A);
        expect(capturedCommands).toEqual(["custom-login-command"]);
        expect(owner?.prompt).toEqual(customPrompt);

        controller.abort();
        await started.completed;
      } finally {
        profiles.codex_local = originalProfile;
      }
    });
  });
});