Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

5.9 KB
Raw Blame
import { testRpcClient, testEnvironmentRegistry } from "../test-support/services.ts";
import { EnvironmentId, ThreadId, WS_METHODS } from "@akeru/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { vi } from "vite-plus/test";

import {
  AVAILABLE_CONNECTION_STATE,
  PrimaryConnectionTarget,
  type PreparedConnection,
  type SupervisorConnectionState,
} from "../connection/model.ts";
import * as EnvironmentRegistry from "../connection/registry.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";

import type { RpcSession } from "../rpc/session.ts";
import { createMemoryEnvironmentAtoms } from "./memory.ts";

const environmentId = EnvironmentId.make("memory-environment");

it.effect("routes memory commands and refreshes inspection after changes", () =>
  Effect.scoped(
    Effect.gen(function* () {
      const calls: string[] = [];

      const client = testRpcClient({
        [WS_METHODS.memoryExport]: () =>
          Effect.sync(() => calls.push(WS_METHODS.memoryExport)).pipe(
            Effect.as({ schemaVersion: 2 } as never),
          ),
        [WS_METHODS.memoryFactMutate]: () =>
          Effect.sync(() => calls.push(WS_METHODS.memoryFactMutate)).pipe(
            Effect.as({ kind: "deleted", memoryId: "root-1" } as never),
          ),
        [WS_METHODS.memoryFactsList]: () => Effect.succeed({ facts: [] } as never),
        [WS_METHODS.memoryObservationsClear]: () =>
          Effect.sync(() => calls.push(WS_METHODS.memoryObservationsClear)).pipe(
            Effect.as(undefined as never),
          ),
      });

      const session: RpcSession = {
        client,
        initialConfig: Effect.never,
        ready: Effect.void,
        probe: Effect.void,
        closed: Effect.never,
      };

      const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
        target: new PrimaryConnectionTarget({
          environmentId,
          label: "Memory environment",
          httpBaseUrl: "https://memory.example.test",
          wsBaseUrl: "wss://memory.example.test",
        }),
        state: yield* SubscriptionRef.make<SupervisorConnectionState>({
          ...AVAILABLE_CONNECTION_STATE,
          desired: true,
          network: "online",
          phase: "connected",
          attempt: 1,
          generation: 1,
        }),
        session: yield* SubscriptionRef.make(Option.some(session)),
        prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
        connect: Effect.void,
        disconnect: Effect.void,
        retryNow: Effect.void,
        retryIfDesired: Effect.void,
      } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);

      const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_id, effect) =>
        Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);

      const atoms = createMemoryEnvironmentAtoms(
        Atom.runtime(
          Layer.succeed(
            EnvironmentRegistry.EnvironmentRegistry,
            testEnvironmentRegistry({
              run,
            }),
          ),
        ),
      );

      const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (value) =>
        Effect.sync(() => value.dispose()),
      );

      const refresh = vi.spyOn(registry, "refresh");
      const threadId = ThreadId.make("thread-memory");

      // Another chat's mounted list shares bot and project facts with this chat.
      const otherThreadId = ThreadId.make("thread-memory-other");

      const otherProjectList = atoms.listFacts({
        environmentId,
        input: { threadId: otherThreadId, target: "project" },
      });

      const unmount = registry.mount(otherProjectList);
      yield* Effect.addFinalizer(() => Effect.sync(unmount));
      const unmountedOtherThreadId = ThreadId.make("thread-memory-unmounted");
      atoms.listFacts({
        environmentId,
        input: { threadId: unmountedOtherThreadId, target: "project" },
      });

      const exported = yield* Effect.promise(() =>
        atoms.exportArchive.run(registry, {
          environmentId,
          input: { threadId, target: "thread", complete: true },
        }),
      );

      const cleared = yield* Effect.promise(() =>
        atoms.clearObservations.run(registry, {
          environmentId,
          input: { threadId },
        }),
      );

      const deleted = yield* Effect.promise(() =>
        atoms.mutateFact.run(registry, {
          environmentId,
          input: {
            threadId,
            mutation: {
              operation: "fact.delete",
              memoryId: "root-1" as never,
              expectedRevision: 2,
            },
          },
        }),
      );

      expect(AsyncResult.isSuccess(exported)).toBe(true);
      expect(AsyncResult.isSuccess(cleared)).toBe(true);
      expect(AsyncResult.isSuccess(deleted)).toBe(true);
      expect(calls).toEqual([
        WS_METHODS.memoryExport,
        WS_METHODS.memoryObservationsClear,
        WS_METHODS.memoryFactMutate,
      ]);

      // A mutation can move a fact between scopes, so every listed scope refreshes.
      for (const target of ["thread", "bot", "project"] as const) {
        expect(refresh).toHaveBeenCalledWith(
          atoms.listFacts({ environmentId, input: { threadId, target } }),
        );
      }

      expect(refresh).toHaveBeenCalledWith(otherProjectList);
      expect(refresh).not.toHaveBeenCalledWith(
        atoms.listFacts({
          environmentId,
          input: { threadId: unmountedOtherThreadId, target: "project" },
        }),
      );
      expect(refresh).toHaveBeenCalledWith(
        atoms.inspectDocuments({
          environmentId,
          input: { threadId },
        }),
      );
    }),
  ),
);