Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

2.4 KB
Raw Blame
import { vi } from 'vitest';
import { changed } from './until';

type Fetch = (url: string, options: RequestInit) => Promise<Response>;

/** What a host sent to the `/agent-sessions` routes, in order. */
export type AgentSessionsCall = { method: string; path: string; body: unknown };

/**
 * Stubs `fetch` with `server`, answering the `/agent-sessions` routes itself:
 * activity and approval writes are accepted, and `outcomes` (settable per
 * test) is what `GET /agent-sessions/approvals/outcomes` returns. `server`
 * never sees those calls, so a test counting its own requests is unaffected.
 * Setting `state.unavailable` answers every such call with 503, as an
 * unreachable Switch would, and `state.refusesUsage` refuses an activity row
 * carrying usage with 422, as a server that predates it does.
 * `state.startUnknown` answers a session start report with a bare 404, as a
 * server that predates that route does, and `state.startRefused` refuses one
 * with 422.
 */
export function stubSwitchFetch(server: Fetch, outcomes: unknown[] = []) {
  const calls: AgentSessionsCall[] = [];
  const state = {
    outcomes,
    unavailable: false,
    refusesUsage: false,
    startUnknown: false,
    startRefused: false,
  };
  vi.stubGlobal('fetch', async (url: string, options: RequestInit = {}) => {
    const path = new URL(url).pathname;
    if (!path.includes('/agent-sessions/')) return server(url, options);
    const method = options.method ?? 'GET';
    calls.push({
      method,
      path,
      body: typeof options.body === 'string' ? JSON.parse(options.body) : null,
    });
    changed();
    if (state.unavailable) return new Response('unavailable', { status: 503 });
    if (path.endsWith('/approvals/outcomes')) {
      const listed = state.outcomes;
      return Response.json(listed);
    }
    if (path.endsWith('/started')) {
      if (state.startUnknown) return Response.json({ detail: 'Not Found' }, { status: 404 });
      if (state.startRefused)
        return Response.json({ detail: [{ type: 'literal_error' }] }, { status: 422 });
      return Response.json({ reported: true });
    }
    if (path.endsWith('/activity')) {
      const body = calls.at(-1)!.body as Record<string, unknown>;
      if (state.refusesUsage && 'usage' in body)
        return Response.json({ detail: [{ type: 'extra_forbidden' }] }, { status: 422 });
      return Response.json({ recorded: true });
    }
    return Response.json({});
  });
  return { calls, state };
}