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.

13.2 KB
Raw Blame
import { Match, Predicate } from "effect";
import type { AuthSessionState } from "@akeru/contracts";
import type { MessageKey } from "@akeru/client-runtime/i18n";
import type { HostedPairingRequest } from "@akeru/shared/remote";
import { squashAtomCommandFailure } from "@akeru/client-runtime/state/runtime";
import React, { startTransition, useEffect, useRef, useState, useCallback } from "react";

import {
  isPrimaryEnvironmentPairingCredentialRejectedError,
  peekPairingTokenFromUrl,
  PrimaryEnvironmentPairingCredentialRejectedError,
  readPrimaryEnvironmentDescriptor,
  resolveInitialPrimaryEnvironmentDescriptor,
  stripPairingTokenFromUrl,
  submitServerAuthCredential,
} from "../../environments/primary";
import { isPrimaryEnvironmentPairingCredentialRequiredError } from "../../environments/primary/auth";
import { connectPairing } from "../../connection/onboarding";
import {
  listenForPairingHash,
  type PairingHashOptions,
  readHostedPairingLink,
  runHostedPairing,
  takePairingHash,
} from "../../hostedPairing";
import { useI18n } from "../../i18n";
import { useAtomCommand } from "../../state/use-atom-command";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Spinner } from "../ui/spinner";
import {
  type PairingEnvironmentSummary,
  PairingPanel,
  type PairingPanelStatus,
} from "./PairingPanel";

export function PairingPendingSurface() {
  const environment = usePrimaryEnvironmentSummary();

  return <PairingPanel environment={environment} status={{ kind: "checking" }} />;
}

type PairingError =
  | { readonly kind: "rejected" }
  | { readonly kind: "missing-token"; readonly message: string }
  | { readonly kind: "failed"; readonly message: string };

const REJECTED_TOKEN_MESSAGE = new PrimaryEnvironmentPairingCredentialRejectedError({
  providedLength: 0,
  cause: null,
}).message;

/** Sorts a pairing failure into the state the page shows for it. */
export function pairingErrorFromUnknown(cause: unknown): PairingError {
  if (isPrimaryEnvironmentPairingCredentialRejectedError(cause)) {
    return { kind: "rejected" };
  }

  if (isPrimaryEnvironmentPairingCredentialRequiredError(cause)) {
    return { kind: "missing-token", message: cause.message };
  }

  return pairingErrorFromMessage(errorMessageFromUnknown(cause));
}

/** Bootstrap hands the route only a message, so match the rejection by its text. */
export function pairingErrorFromMessage(message: string): PairingError {
  return message === REJECTED_TOKEN_MESSAGE ? { kind: "rejected" } : { kind: "failed", message };
}

export function PairingRouteSurface({
  auth,
  initialErrorMessage,
  onAuthenticated,
}: {
  auth: AuthSessionState["auth"];
  initialErrorMessage?: string;
  onAuthenticated: () => void;
}) {
  const { t } = useI18n();
  const environment = usePrimaryEnvironmentSummary();
  const autoPairTokenRef = useRef<string | null>(peekPairingTokenFromUrl());
  const [credential, setCredential] = useState(() => autoPairTokenRef.current ?? "");

  const [pairingError, setPairingError] = useState<PairingError | null>(() =>
    initialErrorMessage ? pairingErrorFromMessage(initialErrorMessage) : null,
  );

  const [isSubmitting, setIsSubmitting] = useState(false);
  const autoSubmitAttemptedRef = useRef(false);
  const submittingRef = useRef(false);
  const hashOptionsRef = useRef<PairingHashOptions<string> | null>(null);

  const submitCredential = useCallback(
    async (nextCredential: string) => {
      if (submittingRef.current) return;
      submittingRef.current = true;
      setIsSubmitting(true);
      setPairingError(null);

      const submitError = await submitServerAuthCredential(nextCredential).then(
        () => null,
        (error) => pairingErrorFromUnknown(error),
      );

      submittingRef.current = false;
      setIsSubmitting(false);

      if (submitError) {
        setPairingError(submitError);

        // A link opened while this one was in flight waited in the address bar.
        if (hashOptionsRef.current) takePairingHash(hashOptionsRef.current);

        return;
      }

      startTransition(() => {
        onAuthenticated();
      });
    },
    [onAuthenticated],
  );

  const handleSubmit = useCallback(
    async (event?: React.SubmitEvent<HTMLFormElement>) => {
      event?.preventDefault();
      await submitCredential(credential);
    },
    [submitCredential, credential],
  );

  useEffect(() => {
    const token = autoPairTokenRef.current;

    if (!token || autoSubmitAttemptedRef.current) {
      return;
    }

    autoSubmitAttemptedRef.current = true;
    stripPairingTokenFromUrl();
    void submitCredential(token);
  }, [submitCredential]);

  // Opening the same link with its #token in this tab is a same-document
  // navigation, so read the token again rather than keep the first verdict.
  useEffect(() => {
    const options: PairingHashOptions<string> = {
      read: peekPairingTokenFromUrl,
      isBusy: () => submittingRef.current,
      strip: stripPairingTokenFromUrl,
      submit: (token) => {
        setCredential(token);
        void submitCredential(token);
      },
    };

    hashOptionsRef.current = options;

    return listenForPairingHash(window, options);
  }, [submitCredential]);

  const supportedMethodsNote = describeSupportedMethods(auth.bootstrapMethods);

  const status: PairingPanelStatus = isSubmitting
    ? { kind: "submitting" }
    : pairingError?.kind === "rejected"
      ? { kind: "rejected" }
      : pairingError?.kind === "failed"
        ? { kind: "failed", message: pairingError.message }
        : { kind: "ready" };

  return (
    <PairingPanel
      environment={environment}
      readyDescription={t(describeAuthGate(auth.bootstrapMethods))}
      status={status}
    >
      <PairingTokenForm
        credential={credential}
        fieldError={pairingError?.kind === "missing-token" ? pairingError.message : null}
        isSubmitting={isSubmitting}
        onCredentialChange={setCredential}
        onSubmit={(event) => void handleSubmit(event)}
        showReload={pairingError?.kind === "failed"}
        submitLabel={pairingError?.kind === "failed" ? t("Try again") : t("Pair this browser")}
        tokenLabel={pairingError?.kind === "rejected" ? t("New pairing token") : t("Pairing token")}
      />
      {supportedMethodsNote ? (
        <p className="mt-4 text-xs leading-relaxed text-muted-foreground">
          {t(supportedMethodsNote)}
        </p>
      ) : null}
    </PairingPanel>
  );
}

/**
 * Opens a hosted pairing link (`/pair?host=…#token=…`): saves the remote server
 * named by `host` in this browser, whatever origin served the page. The token
 * is stripped from the address bar before it is submitted, and only once.
 */
export function HostedPairingRouteSurface() {
  const { t } = useI18n();
  const connect = useAtomCommand(connectPairing, { reportFailure: false });
  const requestRef = useRef(readHostedPairingLink(window.location.href));

  const [status, setStatus] = useState<PairingPanelStatus>(() =>
    requestRef.current ? { kind: "checking" } : { kind: "incomplete" },
  );

  const startedRef = useRef(false);
  const pairingRef = useRef(false);
  const hashOptionsRef = useRef<PairingHashOptions<HostedPairingRequest> | null>(null);

  const pair = useCallback(async () => {
    if (pairingRef.current) return;
    pairingRef.current = true;
    setStatus({ kind: "submitting" });
    let next: PairingPanelStatus = { kind: "checking" };

    try {
      next = await runHostedPairing(requestRef.current, async (input) => {
        const result = await connect(input);

        if (Predicate.isTagged(result, "Success")) return { ok: true };

        return {
          ok: false,
          message: `${errorMessageFromUnknown(squashAtomCommandFailure(result))} ${t(
            "If the server accepted this one-time token, get a new pairing link before trying again.",
          )}`,
        };
      });
      setStatus(next);
    } finally {
      pairingRef.current = false;
    }

    // A link opened while this one was in flight waited in the address bar.
    if (next.kind === "failed" && hashOptionsRef.current) takePairingHash(hashOptionsRef.current);
  }, [connect, t]);

  useEffect(() => {
    if (startedRef.current) return;
    startedRef.current = true;
    stripPairingTokenFromUrl();

    if (requestRef.current) void pair();
  }, [pair]);

  // Opening the same link with its #token in this tab is a same-document
  // navigation, so read the link again rather than keep the first verdict.
  useEffect(() => {
    const options: PairingHashOptions<HostedPairingRequest> = {
      read: () => readHostedPairingLink(window.location.href),
      isBusy: () => pairingRef.current,
      strip: stripPairingTokenFromUrl,
      submit: (next) => {
        requestRef.current = next;
        void pair();
      },
    };

    hashOptionsRef.current = options;

    return listenForPairingHash(window, options);
  }, [pair]);

  const request = requestRef.current;

  return (
    <PairingPanel
      environment={{ name: request?.label || null, address: request?.host ?? null }}
      status={status}
    >
      {Match.value(status).pipe(
        Match.when({ kind: "failed" }, () => (
          <Button className="w-full" onClick={() => void pair()} size="lg">
            {t("Try again")}
          </Button>
        )),
        Match.when({ kind: "paired" }, () => (
          <Button className="w-full" onClick={() => window.location.assign("/")} size="lg">
            {t("Open app")}
          </Button>
        )),
        Match.orElse(() => null),
      )}
    </PairingPanel>
  );
}

export function PairingTokenForm({
  credential,
  fieldError,
  isSubmitting,
  onCredentialChange,
  onSubmit,
  showReload,
  submitLabel,
  tokenLabel,
}: {
  readonly credential: string;
  readonly fieldError: string | null;
  readonly isSubmitting: boolean;
  readonly onCredentialChange: (value: string) => void;
  readonly onSubmit: (event: React.SubmitEvent<HTMLFormElement>) => void;
  readonly showReload: boolean;
  readonly submitLabel: string;
  readonly tokenLabel: string;
}) {
  const { t } = useI18n();

  return (
    <form className="space-y-3" onSubmit={onSubmit}>
      <div className="space-y-1.5">
        <label className="text-sm font-medium" htmlFor="pairing-token">
          {tokenLabel}
        </label>
        <Input
          id="pairing-token"
          aria-describedby={fieldError ? "pairing-token-error" : undefined}
          aria-invalid={fieldError ? true : undefined}
          autoCapitalize="none"
          autoComplete="off"
          autoCorrect="off"
          variant="mono"
          disabled={isSubmitting}
          nativeInput
          onChange={(event) => onCredentialChange(event.currentTarget.value)}
          placeholder={t("Paste a token")}
          spellCheck={false}
          value={credential}
        />
        {fieldError ? (
          <p className="text-xs text-destructive-foreground" id="pairing-token-error">
            {fieldError}
          </p>
        ) : null}
      </div>

      <div className="flex flex-col gap-2 pt-1">
        <Button className="w-full" disabled={isSubmitting} size="lg" type="submit">
          {isSubmitting ? (
            <>
              <Spinner className="size-4" />
              {t("Pairing")}
            </>
          ) : (
            submitLabel
          )}
        </Button>
        {showReload ? (
          <Button
            className="w-full"
            disabled={isSubmitting}
            onClick={() => window.location.reload()}
            size="lg"
            variant="ghost"
          >
            {t("Reload page")}
          </Button>
        ) : null}
      </div>
    </form>
  );
}

/**
 * Names the environment this page pairs with. The descriptor endpoint is
 * public, so it resolves before pairing; the address falls back to the page
 * host until then.
 */
function usePrimaryEnvironmentSummary(): PairingEnvironmentSummary {
  const [name, setName] = useState(() => readPrimaryEnvironmentDescriptor()?.label ?? null);

  useEffect(() => {
    if (name) {
      return;
    }

    let cancelled = false;
    resolveInitialPrimaryEnvironmentDescriptor().then(
      (descriptor) => {
        if (!cancelled) {
          setName(descriptor.label);
        }
      },
      () => undefined,
    );

    return () => {
      cancelled = true;
    };
  }, [name]);

  return { name, address: typeof window === "undefined" ? null : window.location.host || null };
}

function errorMessageFromUnknown(cause: unknown): string {
  if (cause instanceof Error && cause.message.trim().length > 0) {
    return cause.message;
  }

  if (Predicate.isString(cause) && cause.trim().length > 0) {
    return cause;
  }

  return "Authentication failed.";
}

function describeAuthGate(bootstrapMethods: ReadonlyArray<string>): MessageKey {
  if (bootstrapMethods.includes("desktop-bootstrap")) {
    return "Paste the pairing credential from the desktop app to connect.";
  }

  return "Paste the pairing token from your link to connect.";
}

function describeSupportedMethods(bootstrapMethods: ReadonlyArray<string>): MessageKey | null {
  if (!bootstrapMethods.includes("desktop-bootstrap")) {
    return null;
  }

  if (bootstrapMethods.includes("one-time-token")) {
    return "This environment accepts desktop pairing and one-time pairing tokens.";
  }

  return "The desktop app manages this environment. Open it there, or paste a credential it issued.";
}