Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

8.5 KB
Raw Blame
"use client";

import { useMemo, useState, useEffect, useRef } from "react";
import { Plug } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { FormDrawer, openWindow } from "@/features/appshell";
import { channelAction } from "../lib/api";
import type { ChannelsSnapshot, ChannelProviderId, ChannelView, WorkflowOption } from "../types";

const selectClass = "h-9 w-full rounded-md border bg-background px-2 text-sm";
const credentialValue = (user: string, connection: string) => `${user}::${connection}`;

type GroupOption = { id: string; name: string };

export function ChannelEditor({
  open,
  onOpenChange,
  row,
  snapshot,
  workflows,
  onSaved,
}: {
  open: boolean;
  onOpenChange: (value: boolean) => void;
  row: ChannelView | null;
  snapshot: ChannelsSnapshot;
  workflows: WorkflowOption[];
  onSaved: () => Promise<void>;
}) {
  const initialProvider = row?.provider ?? "telegram";
  const initialCredential = row
    ? credentialValue(row.credential.user, row.credential.connection)
    : (() => {
        const first = snapshot.credentials.find((item) => item.provider === initialProvider);
        return first ? credentialValue(first.user, first.id) : "";
      })();

  const [name, setName] = useState(row?.name ?? "");
  const [provider, setProvider] = useState<ChannelProviderId>(initialProvider);
  const [credential, setCredential] = useState(initialCredential);
  const [target, setTarget] = useState(row?.defaultTarget ?? "");
  const [workflowId, setWorkflowId] = useState(row?.workflowId ?? "");
  const [agentGroupId, setAgentGroupId] = useState(row?.agentGroupId ?? "");
  const [groups, setGroups] = useState<GroupOption[]>([]);
  const [enabled, setEnabled] = useState(row?.enabled ?? true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const saving = useRef(false);
  const [baseRevision, setBaseRevision] = useState(snapshot.revision);
  const initialDraft = useRef(JSON.stringify([name, provider, credential, target, workflowId, agentGroupId, enabled]));
  const close = (next: boolean) => {
    if (!next && (busy || (JSON.stringify([name, provider, credential, target, workflowId, agentGroupId, enabled]) !== initialDraft.current && !window.confirm("Discard unsaved changes?")))) return;
    onOpenChange(next);
  };

  useEffect(() => {
    if (!open) return;
    fetch("/api/v1/agent-groups", { cache: "no-store" })
      .then((response) => response.json())
      .then((body: { groups?: GroupOption[] }) => setGroups(body.groups ?? []))
      .catch(() => setGroups([]));
  }, [open]);

  const credentials = useMemo(
    () => snapshot.credentials.filter((item) => item.provider === provider),
    [provider, snapshot.credentials],
  );

  const changeProvider = (next: ChannelProviderId) => {
    setProvider(next);
    const first = snapshot.credentials.find((item) => item.provider === next);
    setCredential(first ? credentialValue(first.user, first.id) : "");
  };

  const save = async () => {
    if (saving.current) return;
    const [user, connection] = credential.split("::");
    if (!user || !connection) { setError("Choose an Integration connection first."); return; }
    saving.current = true; setBusy(true); setError("");
    try {
      const data = {
        name,
        provider,
        credential: { user, connection },
        enabled,
        defaultTarget: target,
        workflowId,
        agentGroupId,
      };
      await channelAction(row
        ? { action: "update", id: row.id, expectedRevision: baseRevision, data }
        : { action: "create", data });
      await onSaved();
      onOpenChange(false);
    } catch (cause) {
      await onSaved().catch(() => undefined);
      setError((cause instanceof Error ? cause.message : "Could not save channel.") + " Your draft is preserved; close and reopen to load the latest version.");
    } finally { saving.current = false; setBusy(false); }
  };

  return <FormDrawer open={open} onOpenChange={close} size="md">
    <FormDrawer.Header>
      <FormDrawer.Title>{row ? "Edit channel" : "Add channel"}</FormDrawer.Title>
      <FormDrawer.Description>
        Channel configuration stores only connection references. Bot tokens remain in Integrations.
      </FormDrawer.Description>
    </FormDrawer.Header>
    <FormDrawer.Body className="space-y-4">
      <Field label="Name"><Input value={name} maxLength={120} placeholder="Support bot" onChange={(event) => setName(event.target.value)}/></Field>
      <Field label="Provider">
        <select className={selectClass} value={provider} onChange={(event) => changeProvider(event.target.value as ChannelProviderId)}>
          <option value="telegram">Telegram</option><option value="discord">Discord</option>
        </select>
      </Field>
      <Field label="Integration connection">
        {credentials.length ? <select className={selectClass} value={credential} onChange={(event) => setCredential(event.target.value)}>
          {credentials.map((item) => <option key={`${item.user}:${item.id}`} value={credentialValue(item.user, item.id)}>
            {item.userLabel} / {item.label} · {item.state}
          </option>)}
        </select> : <div className="rounded-lg border border-dashed p-3">
          <p className="text-xs text-muted-foreground">No {provider} bot connection exists yet.</p>
          <Button className="mt-2" size="sm" variant="outline" onClick={() => openWindow("integrations", "Integrations")}><Plug className="mr-2 size-3"/>Open Integrations</Button>
        </div>}
      </Field>
      <Field label={provider === "telegram" ? "Default chat ID / @channel" : "Default channel ID"}>
        <Input value={target} placeholder={provider === "telegram" ? "-1001234567890" : "123456789012345678"} onChange={(event) => setTarget(event.target.value)}/>
      </Field>
      <Field label="Inbound workflow">
        <select className={selectClass} value={workflowId} onChange={(event) => setWorkflowId(event.target.value)}>
          <option value="">Receive only (no workflow)</option>
          {workflows.map((workflow) => <option key={workflow.id} value={workflow.id}>{workflow.name}</option>)}
        </select>
      </Field>
      <Field label="Agent group (Telegram discussion)">
        <select className={selectClass} value={agentGroupId} onChange={(event) => setAgentGroupId(event.target.value)}>
          <option value="">Not linked</option>
          {groups.map((group) => <option key={group.id} value={group.id}>{group.name}</option>)}
        </select>
      </Field>
      <label className="flex items-center justify-between rounded-lg border p-3">
        <span><span className="block text-sm font-medium">Enabled</span><span className="text-xs text-muted-foreground">Allow send and verified inbound events.</span></span>
        <Switch checked={enabled} onCheckedChange={setEnabled}/>
      </label>
      <div className="rounded-lg bg-muted/40 p-3 text-xs text-muted-foreground">
        {provider === "telegram"
          ? "Inbound Telegram requires a webhook secret on the selected Integration connection."
          : "Inbound Discord uses the application public key to verify signed Interactions. Gateway message ingestion is intentionally not enabled."}
      </div>
      {error ? <p role="alert" className="text-xs text-destructive">{error}</p> : null}
      {error && row && snapshot.revision !== baseRevision ? <div className="space-y-2 rounded border p-2 text-xs">
        <p>The saved channel changed. Compare it with your draft above before choosing to overwrite its fields.</p>
        <pre className="max-h-40 overflow-auto whitespace-pre-wrap break-all">{JSON.stringify(snapshot.channels.filter(item => item.id === row.id).map(({ name, provider, credential, enabled, defaultTarget, workflowId, agentGroupId }) => ({ name, provider, credential, enabled, defaultTarget, workflowId, agentGroupId })), null, 2)}</pre>
        <Button variant="outline" size="sm" onClick={() => { setBaseRevision(snapshot.revision); setError(""); }}>Use latest revision for this draft</Button>
      </div> : null}
    </FormDrawer.Body>
    <FormDrawer.Footer>
      <Button variant="ghost" onClick={() => close(false)}>Cancel</Button>
      <Button disabled={busy || !name.trim() || !credential} onClick={() => void save()}>{busy ? "Saving…" : "Save channel"}</Button>
    </FormDrawer.Footer>
  </FormDrawer>;
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return <label className="block space-y-1.5"><span className="text-xs font-medium">{label}</span>{children}</label>;
}