Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

6.6 KB
Raw Blame
/* ═══════════════════════════════════════════════════════════════
   App state. Views are all mounted at once and switched by `view`, so
   moving between Chat, Code, Bots, Plugins and Skills is a state change,
   never a page load.
   ═══════════════════════════════════════════════════════════════ */

import { create } from "zustand";
import type { BotActivityEvent, BotStatus, ChatThread, PendingPrompt, BotApproval } from "~/api/types";

export type View = "chat" | "artifacts" | "code" | "bots" | "brain" | "plugins" | "skills" | "settings";

/** What the agent is doing right now; drives the StateOrb everywhere. */
export type AgentState = "idle" | "thinking" | "streaming" | "working" | "needs-you" | "offline";

interface UiState {
  view: View;
  setView(view: View): void;
  /** Chat is showing the live Optimus voice session instead of a thread. */
  voiceOpen: boolean;
  setVoiceOpen(open: boolean): void;
  sidebar: boolean;
  toggleSidebar(): void;
  /** A Settings section to open next (e.g. "models" from the Cloud banner); Settings consumes it. */
  settingsSection: string | null;
  openSettings(section: string): void;
  clearSettingsSection(): void;
  /** A plugin whose linking panel Plugins should open (e.g. WhatsApp from Settings → Channels). */
  pluginFocus: string | null;
  openPlugin(id: string): void;
  clearPluginFocus(): void;
  /** What Bots should show next: a bot's page, or "inbox" (from a notification). */
  botFocus: string | null;
  openBot(target: string): void;
  clearBotFocus(): void;
}

export const useUi = create<UiState>((set) => ({
  view: "chat",
  setView: (view) => set({ view }),
  voiceOpen: false,
  setVoiceOpen: (voiceOpen) => set({ voiceOpen }),
  sidebar: true,
  toggleSidebar: () => set((s) => ({ sidebar: !s.sidebar })),
  settingsSection: null,
  openSettings: (section) => set({ view: "settings", settingsSection: section }),
  clearSettingsSection: () => set({ settingsSection: null }),
  pluginFocus: null,
  openPlugin: (id) => set({ view: "plugins", pluginFocus: id }),
  clearPluginFocus: () => set({ pluginFocus: null }),
  botFocus: null,
  openBot: (target) => set({ view: "bots", botFocus: target }),
  clearBotFocus: () => set({ botFocus: null }),
}));

interface RuntimeState {
  connected: boolean;
  agent: AgentState;
  provider: string;
  model: string;
  step: { total: number; current: number; tool: string } | null;
  prompts: PendingPrompt[];
  /** Ask Me (false) or Allow All (true); null until known. One copy for every toggle on screen. */
  allowAll: boolean | null;
  setConnected(connected: boolean): void;
  setAgent(agent: AgentState): void;
  setProvider(provider: string, model: string): void;
  setStep(step: RuntimeState["step"]): void;
  addPrompt(prompt: PendingPrompt): void;
  removePrompt(id: string): void;
  setAllowAll(allowAll: boolean): void;
}

export const useRuntimeState = create<RuntimeState>((set, get) => ({
  connected: false,
  agent: "offline",
  provider: "",
  model: "",
  step: null,
  prompts: [],
  allowAll: null,
  setAllowAll: (allowAll) => set({ allowAll }),
  setConnected: (connected) => set({ connected, agent: connected ? (get().agent === "offline" ? "idle" : get().agent) : "offline" }),
  setAgent: (agent) => set({ agent }),
  setProvider: (provider, model) => set({ provider, model }),
  setStep: (step) => set({ step }),
  addPrompt: (prompt) => set((s) => ({ prompts: [...s.prompts.filter((p) => p.id !== prompt.id), prompt], agent: "needs-you" })),
  removePrompt: (id) => set((s) => {
    const prompts = s.prompts.filter((p) => p.id !== id);
    return { prompts, agent: prompts.length === 0 && s.agent === "needs-you" ? "working" : s.agent };
  }),
}));

interface ThreadsState {
  /** Every session the runtime has; each surface filters its own. */
  threads: ChatThread[];
  setThreads(threads: ChatThread[]): void;
}

export const useChat = create<ThreadsState>((set) => ({
  threads: [],
  setThreads: (threads) => set({ threads }),
}));

interface BotsState {
  bots: BotStatus[];
  available: boolean;
  activity: Record<string, string>;
  /** Unread inbox entries across every bot. */
  unread: number;
  /** Bumped when an inbox entry arrives, so open lists reload. */
  inboxVersion: number;
  /** Bots waiting for your answer right now. */
  approvals: BotApproval[];
  setApprovals(approvals: BotApproval[]): void;
  setBots(bots: BotStatus[], available: boolean, unread?: number): void;
  inboxChanged(unread?: number): void;
  setActivity(botId: string, label: string | null): void;
  /** The live feed: recent bot events, oldest first, capped (LIVE_CAP). */
  live: BotActivityEvent[];
  /** Add events (from the stream or the history endpoint); duplicates are dropped. */
  addLive(events: BotActivityEvent[]): void;
}

/** How many live events the app keeps (the whole fleet). */
export const LIVE_CAP = 2000;

/** One key per distinct event: the same event from history and the stream counts once. */
export function liveKey(e: BotActivityEvent): string {
  return `${e.jobId ?? ""}|${e.kind}|${e.stepIndex ?? 0}|${e.label}|${e.status ?? ""}|${e.at ?? 0}`;
}

/** Merge events into the feed: dedupe, keep only the latest thinking preview per run, sort by time, cap. */
export function mergeLive(current: BotActivityEvent[], incoming: BotActivityEvent[]): BotActivityEvent[] {
  const seen = new Set(current.map(liveKey));
  let next = current.slice();
  for (const e of incoming) {
    const k = liveKey(e);
    if (seen.has(k)) continue;
    seen.add(k);
    if (e.kind === "thinking") next = next.filter((x) => !(x.kind === "thinking" && x.jobId === e.jobId && (x.at ?? 0) <= (e.at ?? 0)));
    next.push(e);
  }
  next.sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
  return next.length > LIVE_CAP ? next.slice(next.length - LIVE_CAP) : next;
}

export const useBots = create<BotsState>((set) => ({
  bots: [],
  available: true,
  activity: {},
  unread: 0,
  inboxVersion: 0,
  approvals: [],
  setApprovals: (approvals) => set({ approvals }),
  setBots: (bots, available, unread) => set(unread === undefined ? { bots, available } : { bots, available, unread }),
  inboxChanged: (unread) => set((s) => ({ inboxVersion: s.inboxVersion + 1, ...(unread === undefined ? {} : { unread }) })),
  live: [],
  addLive: (events) => set((s) => ({ live: mergeLive(s.live, events) })),
  setActivity: (botId, label) => set((s) => {
    const activity = { ...s.activity };
    if (label === null) delete activity[botId];
    else activity[botId] = label;
    return { activity };
  }),
}));