Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
20.6 KB
Raw Blame
"use client";

import { useEffect, useRef, type ReactNode } from "react";
import {useQuery} from "@tanstack/react-query";
import {runtimeModelsOptions} from "@multica/core/runtimes";
import {findModelCapabilityEntry,thinkingLevelRequiredForProvider} from "../components/inspector/model-capability";
import {
  AGENT_DESCRIPTION_MAX_LENGTH,
  agentDescriptionLength,
  applyDraftModelChange,
  applyDraftRuntimeChange,
  type AgentDraft,
  type AgentPermissionScope,
} from "@multica/core/agents";
import { useConfigStore } from "@multica/core/config";
import { usePaidFeatureAccess } from "@multica/core/billing";
import { useWorkspaceId } from "@multica/core/hooks";
import type { MemberWithUser, RuntimeDevice } from "@multica/core/types";
import { Checkbox } from "@multica/ui/components/ui/checkbox";
import { Input } from "@multica/ui/components/ui/input";
import { Textarea } from "@multica/ui/components/ui/textarea";
import { cn } from "@multica/ui/lib/utils";
import { ActorAvatar } from "../../common/actor-avatar";
import { PaidFeatureNotice, PaidFeatureUpgradeBadge } from "../../billing";
import { AvatarUploadControl } from "../../common/avatar-upload-control";
import { useT } from "../../i18n";
import {
  SettingsCard,
  SettingsSection,
} from "../../settings/components/settings-layout";
import { CharCounter } from "../components/char-counter";
import { ServiceTierSettingField } from "../components/inspector/service-tier-setting-field";
import { ThinkingSettingField } from "../components/inspector/thinking-prop-row";
import { ModelDropdown } from "../components/model-dropdown";
import { QoderAgentSelect } from "../components/qoder-agent-select";
import { RuntimePicker } from "../components/runtime-picker";
import { SkillMultiSelect } from "../components/skill-multi-select";
import { ConversationStartersEditor } from "../components/conversation-starters-editor";

const PERMISSION_SCOPES: AgentPermissionScope[] = [
  "private",
  "workspace",
  "members",
];

export function AgentConfigurationPanel({
  draft,
  onChange,
  onAutomaticChange = onChange,
  runtimes,
  runtimesLoading,
  members,
  currentUserId,
  nameError,
  onNameChange,
  compact = false,
  onRuntimeSelect,
  runtimeSwitchPending = false,
  runtimeSwitchInFlight = false,
  runtimeSummary,
}: {
  draft: AgentDraft;
  onChange: (draft: AgentDraft) => void;
  /** Value cleanup without user interaction, such as an unsupported model. */
  onAutomaticChange?: (draft: AgentDraft) => void;
  runtimes: RuntimeDevice[];
  runtimesLoading: boolean;
  members: MemberWithUser[];
  currentUserId: string | null;
  nameError: string | null;
  onNameChange: (name: string) => void;
  compact?: boolean;
  /** Builder sessions rebind the server-side carrier instead of only editing
   *  the draft. Absent for the plain create flows, where the draft is the only
   *  state that exists. */
  onRuntimeSelect?: (runtimeId: string) => void;
  /** A builder reply is in flight, so the server would refuse the rebind. */
  runtimeSwitchPending?: boolean;
  /** A rebind request is in flight. */
  runtimeSwitchInFlight?: boolean;
  /** Replaces the runtime picker when the runtime was chosen in an earlier
   *  step and changing it means going back there. */
  runtimeSummary?: ReactNode;
}) {
  const { t } = useT("agents");
  const conversationStartersSupported = useConfigStore(
    (state) => state.agentConversationStartersSupported,
  );
  const selectedRuntime =
    runtimes.find((runtime) => runtime.id === draft.runtimeId) ?? null;
  const set = <K extends keyof AgentDraft>(key: K, value: AgentDraft[K]) =>
    onChange({ ...draft, [key]: value });
  const otherMembers = members.filter(
    (member) => member.user_id !== currentUserId,
  );
  const runtimeLocked = runtimeSwitchPending || runtimeSwitchInFlight;
  // The agent does not exist yet, so a plan without member access makes the
  // option unavailable. A draft that already picked people (restored, or
  // seeded before the plan changed) can still drop them or switch away.
  const wsId = useWorkspaceId();
  const invocationMembers = usePaidFeatureAccess(wsId, "agent_invocation_members", {
    hasExistingConfig: false,
  });
  const canAddMembers = invocationMembers.canAdd;
  // The Qoder bridge refuses tasks from agents with skills or per-agent
  // config, so the fields that would produce them are not offered.
  const qoderRuntime = selectedRuntime?.provider === "qoder_cloud";
  const handleRuntimeSelect = (id: string) => {
    if (id === draft.runtimeId) return;
    if (onRuntimeSelect) {
      onRuntimeSelect(id);
      return;
    }
    // Model is per-runtime; clear it — and the per-model thinking / speed
    // overrides — on runtime change so the new runtime resolves its own
    // defaults instead of stale values.
    onChange(applyDraftRuntimeChange(draft, id));
  };

  return (
    <div className={cn("space-y-8", compact && "space-y-6")}>
      <SettingsSection
        title={t(($) => $.creation_studio.sections.identity)}
      >
        <SettingsCard>
          <DraftFieldRow
            compact={compact}
            label={t(($) => $.create_dialog.avatar.change_aria)}
          >
            <div className={cn(!compact && "sm:flex sm:justify-end")}>
              <AvatarUploadControl
                variant="agent"
                value={draft.avatarUrl}
                name={draft.name}
                size={compact ? 52 : 56}
                onUploaded={(url) => set("avatarUrl", url)}
                onEmojiSelected={(value) => set("avatarUrl", value)}
                onClear={() => set("avatarUrl", null)}
              />
            </div>
          </DraftFieldRow>
          <AgentNameField
            compact={compact}
            name={draft.name}
            error={nameError}
            onChange={onNameChange}
          />
          <DraftFieldRow
            compact={compact}
            align="start"
            label={t(($) => $.create_dialog.description_label)}
            htmlFor="agent-create-description"
          >
            <div>
              <Textarea
                id="agent-create-description"
                name="agent-description"
                autoComplete="off"
                aria-label={t(($) => $.create_dialog.description_label)}
                value={draft.description}
                onChange={(event) => set("description", event.target.value)}
                placeholder={t(($) => $.create_dialog.description_placeholder)}
                rows={compact ? 3 : 4}
                // The create API rejects >255 code points with a 400. No
                // maxLength (UTF-16 units, wrong for emoji): the counter shows
                // the limit and Create stays disabled past it, matching the
                // settings page.
                className="resize-y"
              />
              <CharCounter
                length={agentDescriptionLength(draft.description)}
                max={AGENT_DESCRIPTION_MAX_LENGTH}
              />
            </div>
          </DraftFieldRow>
          {conversationStartersSupported ? (
            <DraftFieldRow
              compact={compact}
              align="start"
              label={t(($) => $.conversation_starters.label)}
              description={t(($) => $.conversation_starters.create_hint)}
            >
              <ConversationStartersEditor
                value={draft.conversationStarters}
                onChange={(value) => set("conversationStarters", value)}
              />
            </DraftFieldRow>
          ) : null}
        </SettingsCard>
      </SettingsSection>

      <SettingsSection
        title={t(($) => $.creation_studio.sections.behavior)}
      >
        <SettingsCard>
          <DraftFieldRow
            compact
            label={t(($) => $.create_dialog.instructions.label)}
            htmlFor="agent-create-instructions"
          >
            <Textarea
              id="agent-create-instructions"
              name="agent-instructions"
              autoComplete="off"
              aria-label={t(($) => $.create_dialog.instructions.label)}
              value={draft.instructions}
              onChange={(event) => set("instructions", event.target.value)}
              placeholder={t(
                ($) => $.create_dialog.instructions.editor_placeholder,
              )}
              rows={compact ? 9 : 12}
              className="min-h-44 resize-y font-mono text-label leading-6"
            />
          </DraftFieldRow>
          {qoderRuntime ? (
            <p className="px-4 py-3 text-caption text-muted-foreground">
              {t(($) => $.creation_studio.cloud_fields_note)}
            </p>
          ) : (
            <div className="px-4 py-4">
              <SkillMultiSelect
                selectedIds={draft.skillIds}
                onChange={(ids) => set("skillIds", ids)}
              />
            </div>
          )}
        </SettingsCard>
      </SettingsSection>

      <SettingsSection
        title={t(($) => $.creation_studio.sections.execution)}
        description={t(($) => $.creation_studio.sections.execution_hint)}
      >
        <SettingsCard>
          <div
            className={cn("grid gap-4 px-4 py-4", !compact && "sm:grid-cols-2")}
          >
            <div className="min-w-0">
              {runtimeSummary ?? (
              <RuntimePicker
                runtimes={runtimes}
                runtimesLoading={runtimesLoading}
                members={members}
                currentUserId={currentUserId}
                selectedRuntimeId={draft.runtimeId}
                onSelect={handleRuntimeSelect}
                disabled={runtimeLocked}
                autoSelect={!onRuntimeSelect}
              />
              )}
              {/* A silently greyed-out picker is the worst version of this: the
                  user reaches for it exactly when the current runtime has gone
                  wrong, so say what unblocks it instead of just refusing. */}
              {runtimeSwitchPending && (
                <p className="mt-1.5 text-caption text-muted-foreground">
                  {t(($) => $.creation_studio.builder.switch_runtime_pending)}
                </p>
              )}
            </div>
            {qoderRuntime ? (
              <QoderAgentSelect
                value={draft.qoderAgentId}
                onChange={(value) => set("qoderAgentId", value)}
                disabled={runtimeLocked}
              />
            ) : (
              <ModelDropdown
                runtimeId={selectedRuntime?.id ?? null}
                runtimeOnline={selectedRuntime?.status === "online"}
                value={draft.model}
                onChange={(value) =>
                  onChange(applyDraftModelChange(draft, value))
                }
                onAutomaticChange={(value) =>
                  onAutomaticChange(applyDraftModelChange(draft, value))
                }
                // A successful switch clears the model, so an edit made while the
                // rebind is in flight would be silently discarded.
                disabled={!selectedRuntime || runtimeSwitchInFlight}
              />
            )}
          </div>
          {/* Both fields fail closed: they render only when the exact selected
              model's live catalog advertises the capability (or a value is
              already set and needs clearing), so an offline runtime, a failed
              discovery or an empty model shows nothing instead of an input
              that cannot be honoured. */}
          <AgentExecutionOverrides
            draft={draft}
            runtime={selectedRuntime}
            disabled={runtimeLocked}
            onChange={onChange}
          />
        </SettingsCard>
      </SettingsSection>

      <SettingsSection
        title={t(($) => $.creation_studio.sections.access)}
      >
        <SettingsCard>
          <div
            className="space-y-1 p-2"
            role="radiogroup"
            aria-label={t(($) => $.creation_studio.sections.access)}
          >
            {PERMISSION_SCOPES.map((scope) => {
              // The badge is a sibling of the radio, not inside it, so it keeps
              // its own focus and name and never selects the option.
              const showBadge =
                scope === "members" && invocationMembers.state === "unavailable";
              return (
                <div key={scope} className="relative">
                  <button
                    type="button"
                    role="radio"
                    aria-checked={draft.permissionScope === scope}
                    disabled={
                      scope === "members" &&
                      !canAddMembers &&
                      draft.permissionScope !== "members"
                    }
                    onClick={() => set("permissionScope", scope)}
                    className={cn(
                      "flex w-full items-start gap-3 rounded-md px-3 py-2.5 text-left transition-colors",
                      "hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
                      "disabled:cursor-default disabled:opacity-60 disabled:hover:bg-transparent",
                      draft.permissionScope === scope && "bg-muted",
                      showBadge && "pr-28",
                    )}
                  >
                    <span
                      className={cn(
                        "mt-1 flex size-3.5 shrink-0 items-center justify-center rounded-full border",
                        draft.permissionScope === scope && "border-primary",
                      )}
                      aria-hidden="true"
                    >
                      {draft.permissionScope === scope ? (
                        <span className="size-1.5 rounded-full bg-primary" />
                      ) : null}
                    </span>
                    <span className="min-w-0">
                      <span className="block text-body font-medium">
                        {t(($) => $.creation_studio.access[scope].title)}
                      </span>
                      <span className="mt-0.5 block text-caption leading-5 text-muted-foreground">
                        {t(($) => $.creation_studio.access[scope].description)}
                      </span>
                    </span>
                  </button>
                  {showBadge ? (
                    <PaidFeatureUpgradeBadge
                      feature="agent_invocation_members"
                      className="absolute top-3 right-3"
                    />
                  ) : null}
                </div>
              );
            })}
          </div>
          {invocationMembers.state === "unavailable" ? (
            <PaidFeatureNotice state="unavailable" className="px-5 pb-3" />
          ) : null}
          {draft.permissionScope === "members" ? (
            <div className="max-h-48 overflow-y-auto p-2">
              {otherMembers.map((member) => {
                const checked = draft.memberIds.has(member.user_id);
                return (
                  <label
                    key={member.user_id}
                    className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 hover:bg-muted"
                  >
                    <Checkbox
                      checked={checked}
                      disabled={!checked && !canAddMembers}
                      onCheckedChange={(value) => {
                        const next = new Set(draft.memberIds);
                        if (value === true) next.add(member.user_id);
                        else next.delete(member.user_id);
                        set("memberIds", next);
                      }}
                    />
                    <ActorAvatar
                      actorType="member"
                      actorId={member.user_id}
                      size="sm"
                    />
                    <span className="min-w-0 flex-1 truncate text-body">
                      {member.name}
                    </span>
                  </label>
                );
              })}
              {draft.memberIds.size === 0 ? (
                <p className="px-2 py-1 text-caption text-destructive">
                  {t(($) => $.creation_studio.access.members.required)}
                </p>
              ) : null}
            </div>
          ) : null}
        </SettingsCard>
      </SettingsSection>
    </div>
  );
}

export function AgentNameField({
  name,
  error,
  onChange,
  compact = false,
}: {
  name: string;
  error: string | null;
  onChange: (name: string) => void;
  compact?: boolean;
}) {
  const { t } = useT("agents");
  const errorId = "agent-create-name-error";
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (!error) return;
    inputRef.current?.focus();
    inputRef.current?.select();
  }, [error]);

  return (
    <DraftFieldRow
      compact={compact}
      label={t(($) => $.create_dialog.name_label)}
      htmlFor="agent-create-name"
    >
      <div className="space-y-1.5">
        <Input
          ref={inputRef}
          id="agent-create-name"
          name="agent-name"
          autoComplete="off"
          aria-label={t(($) => $.create_dialog.name_label)}
          aria-invalid={!!error}
          aria-describedby={error ? errorId : undefined}
          value={name}
          onChange={(event) => onChange(event.target.value)}
          placeholder={t(($) => $.create_dialog.name_placeholder)}
        />
        {error ? (
          <p id={errorId} className="text-caption text-destructive">
            {error}
          </p>
        ) : null}
      </div>
    </DraftFieldRow>
  );
}

/**
 * Per-model execution overrides (thinking level + Codex speed) for the create
 * flow. Capability comes from the exact selected model's live catalog on the
 * selected runtime, so nothing renders while that cannot be resolved — an
 * offline runtime, failed discovery, or an empty "use the runtime default"
 * model. That is the same fail-closed rule the settings page follows, and it is
 * why no value can be sent that the daemon would refuse to honour.
 */
export function AgentExecutionOverrides({
  draft,
  runtime,
  disabled = false,
  onChange,
}: {
  draft: AgentDraft;
  runtime: RuntimeDevice | null;
  disabled?: boolean;
  onChange: (draft: AgentDraft) => void;
}) {
  const { t } = useT("agents");
  const runtimeOnline = runtime?.status === "online";
  const modelsQuery = useQuery(runtimeModelsOptions(runtimeOnline && thinkingLevelRequiredForProvider(runtime?.provider ?? "") ? runtime?.id ?? null : null));
  useEffect(() => {
    if (disabled || !thinkingLevelRequiredForProvider(runtime?.provider ?? "")) return;
    if (draft.thinkingLevel || !draft.model || !modelsQuery.isSuccess || !modelsQuery.data?.supported) return;
    const entry = findModelCapabilityEntry(modelsQuery.data.models, draft.model, runtime?.provider ?? "");
    const level = entry?.thinking?.default_level ?? entry?.thinking?.supported_levels[0]?.value;
    if (level) onChange({ ...draft, thinkingLevel: level });
  }, [disabled, draft, modelsQuery.data, modelsQuery.isSuccess, onChange, runtime?.provider]);

  return (
    <>
      <ThinkingSettingField
        label={t(($) => $.creation_studio.thinking_label)}
        runtimeId={runtime?.id ?? null}
        runtimeOnline={runtimeOnline}
        provider={runtime?.provider ?? ""}
        model={draft.model}
        value={draft.thinkingLevel}
        canEdit={!disabled}
        onChange={(thinkingLevel) => onChange({ ...draft, thinkingLevel })}
      />
      <ServiceTierSettingField
        label={t(($) => $.creation_studio.speed_label)}
        runtimeId={runtime?.id ?? null}
        runtimeOnline={runtimeOnline}
        provider={runtime?.provider ?? ""}
        model={draft.model}
        value={draft.serviceTier}
        canEdit={!disabled}
        onChange={(serviceTier) => onChange({ ...draft, serviceTier })}
      />
    </>
  );
}

function DraftFieldRow({
  label,
  description,
  children,
  compact = false,
  align = "center",
  htmlFor,
}: {
  label: string;
  description?: string;
  children: ReactNode;
  compact?: boolean;
  align?: "center" | "start";
  htmlFor?: string;
}) {
  return (
    <div
      className={cn(
        "gap-3 px-4 py-4",
        compact
          ? "flex flex-col"
          : "grid sm:grid-cols-[minmax(0,1fr)_minmax(280px,1.2fr)] sm:gap-8",
        !compact && (align === "center" ? "sm:items-center" : "sm:items-start"),
      )}
    >
      <div className="min-w-0">
        {htmlFor ? (
          <label htmlFor={htmlFor} className="text-body font-medium">
            {label}
          </label>
        ) : (
          <div className="text-body font-medium">{label}</div>
        )}
        {description ? (
          <p className="mt-0.5 text-caption leading-5 text-muted-foreground">
            {description}
          </p>
        ) : null}
      </div>
      <div className="min-w-0">{children}</div>
    </div>
  );
}