Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

5.7 KB
Raw Blame
// A server connected by hand, before the window goes there: the window goes only to a server that answers; one that
// doesn't (its name no longer resolves, nothing listens) is the person's choice: try again, remove it, or stay.

import nativeText from "./native-text.cjs";

/** How long a server has to answer before it counts as not answering. */
export const SERVER_LOOK_MS = 3_000;

/** Whether anything answers at `origin` (any HTTP status but a 5xx from a proxy in front of a stopped app). */
export async function serverAnswers(origin, fetchImpl, timeoutMs = SERVER_LOOK_MS) {
  try {
    const response = await fetchImpl(`${origin}/.well-known/openmausbot/environment`, {
      cache: "no-store", redirect: "manual", credentials: "omit", signal: AbortSignal.timeout(timeoutMs), headers: { accept: "application/json" },
    });
    return response.status < 500;
  } catch {
    return false;
  }
}

/**
 * True when the window may go to `entry` now. A server that doesn't answer asks the person, in one dialog: Try again
 * (looks once more), Remove from list (`forget(entry.id)`, then false), or Cancel (false: the window stays where it is).
 * @param {{ id: string, name: string, origin: string }} entry
 * @param {{ fetch: typeof fetch, dialog: { showMessageBox(options: object): Promise<{ response: number }> }, forget: (id: string) => unknown, timeoutMs?: number }} deps
 */
export async function serverOpens(entry, { fetch: fetchImpl, dialog, forget, timeoutMs = SERVER_LOOK_MS, t = nativeText.englishText.t }) {
  for (;;) {
    if (await serverAnswers(entry.origin, fetchImpl, timeoutMs)) return true;
    const { response } = await dialog.showMessageBox({
      type: "warning", buttons: [t("cloudHome.tryAgain"), t("rail.remove"), t("native.common.cancel")], defaultId: 0, cancelId: 2,
      message: t("native.server.notAnswering", { name: entry.name }),
      detail: t("native.server.notAnsweringDetail", { host: new URL(entry.origin).host }),
    });
    if (response === 1) { await forget(entry.id); return false; }
    if (response !== 0) return false;
  }
}

/**
 * What a server saved by hand is to this app at launch, before the window goes there unasked: "in" when this app has a
 * session there (its page opens signed in), "own" when it is this computer's own server under another address,
 * "sign-in" when it answers but its page would ask this window to pair, "gone" when nothing answers. Only a session
 * counts as in: this process isn't a browser, so a server on this machine lets it in where the window's page would not.
 * @param {string} origin
 * @param {{ fetch: typeof fetch, ownEnvironmentId(): Promise<string | null>, timeoutMs?: number }} deps
 * @returns {Promise<"in" | "own" | "sign-in" | "gone">}
 */
export async function savedServerLook(origin, { fetch: fetchImpl, ownEnvironmentId, timeoutMs = SERVER_LOOK_MS }) {
  const read = async (route, credentials) => {
    try {
      const response = await fetchImpl(`${origin}${route}`, {
        cache: "no-store", redirect: "manual", credentials, signal: AbortSignal.timeout(timeoutMs), headers: { accept: "application/json" },
      });
      return { status: response.status, body: await response.json().catch(() => null) };
    } catch {
      return null;
    }
  };
  const [described, session] = await Promise.all([read("/.well-known/openmausbot/environment", "omit"), read("/api/auth/session", "include")]);
  if (!described || described.status >= 500) return "gone";
  const own = await ownEnvironmentId().catch(() => null);
  if (typeof own === "string" && own && [described.body?.environmentId, session?.body?.environmentId].includes(own)) return "own";
  return session?.status === 200 && session.body?.kind === "session" ? "in" : "sign-in";
}

/**
 * The launch's way back to the server saved by hand that was on screen when the app closed: the window goes there only
 * when this app is signed in there (savedServerLook). True when it went; false when the server isn't saved any more or
 * doesn't answer; "own" or "sign-in" when it answers but isn't a place to open unasked (`declined()` is told first).
 * @param {{ id: string, origin: string }} entry
 * @param {{ saved(): Array<{ id: string }>, fetch: typeof fetch, ownEnvironmentId(): Promise<string | null>, opened(entry: object): unknown, declined?(): unknown, timeoutMs?: number }} deps
 * @returns {Promise<boolean | "own" | "sign-in">}
 */
export async function reopenSavedServerAtLaunch(entry, { saved, fetch: fetchImpl, ownEnvironmentId, opened, declined = () => {}, timeoutMs }) {
  const look = await savedServerLook(entry.origin, { fetch: fetchImpl, ownEnvironmentId, timeoutMs });
  if (look === "gone" || !saved().some((candidate) => candidate.id === entry.id)) return false;
  if (look !== "in") { await declined(); return look; }
  return Boolean(await opened(entry));
}

/**
 * The window's way back to a server this computer's bots moved to: opens it again as the Server menu does, without that
 * menu's dialog, because this is the app putting itself right and the screen it lands on has Try again. False when the
 * server isn't saved here any more, nothing answers at it, or `still()` says a newer `show()` took over.
 * @param {{ origin: string | null }} place
 * @param {{ saved(): Array<{ id: string, origin: string }>, fetch: typeof fetch, still?(): boolean, opened(entry: object): unknown }} deps
 */
export async function reopenSavedServer({ origin }, { saved, fetch: fetchImpl, still = () => true, opened }) {
  const entry = origin ? saved().find((candidate) => candidate.origin === origin) ?? null : null;
  if (!entry) return false;
  if (!(await serverAnswers(entry.origin, fetchImpl))) return false;
  if (!saved().some((candidate) => candidate.id === entry.id)) return false;
  if (!still()) return false;
  return Boolean(await opened(entry));
}