Catalyst / admin/Apex 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Apex

public

Bid Management and Orchestration Tool with AI Capability

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Apex / Synapse-Apexv2 / frontend / src / components / AssistantCloud.tsx 6720 B · main
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { useEffect, useRef, useState } from "react";
import { api } from "../lib/api";

interface Suggestion {
  id: number; kind: string; target_ref: string; advice: string[];
  proposed_text: string; guardrail: any; status: string;
}

const soundKey = "apex_assistant_sound";

function ping(on: boolean) {
  if (!on) return;
  try {
    const AC = (window.AudioContext || (window as any).webkitAudioContext) as typeof AudioContext;
    const ctx = new AC();
    const o = ctx.createOscillator();
    const g = ctx.createGain();
    o.connect(g); g.connect(ctx.destination);
    o.type = "sine";
    o.frequency.setValueAtTime(880, ctx.currentTime);
    o.frequency.setValueAtTime(1320, ctx.currentTime + 0.12);
    g.gain.setValueAtTime(0.0001, ctx.currentTime);
    g.gain.exponentialRampToValueAtTime(0.18, ctx.currentTime + 0.02);
    g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.34);
    o.start();
    o.stop(ctx.currentTime + 0.36);
    o.onended = () => ctx.close();
  } catch {
    /* audio blocked — ignore */
  }
}

export default function AssistantCloud({ bidId, active, onView }: { bidId: number; active: boolean; onView: () => void }) {
  const [sugs, setSugs] = useState<Suggestion[]>([]);
  const [shown, setShown] = useState<Suggestion | null>(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [soundOn, setSoundOn] = useState(() => localStorage.getItem(soundKey) !== "off");
  const acked = useRef<Set<number>>(new Set(JSON.parse(localStorage.getItem(`apex_ack_${bidId}`) || "[]")));
  const lastPinged = useRef<number | null>(null);

  function persistAck() {
    localStorage.setItem(`apex_ack_${bidId}`, JSON.stringify([...acked.current]));
  }

  async function load() {
    if (!active) return;
    try { setSugs(await api.get(`/bids/${bidId}/assistant/suggestions`)); } catch { /* ignore */ }
  }

  // poll while the assistant is active on this bid
  useEffect(() => {
    if (!active) { setShown(null); return; }
    load();
    const t = setInterval(load, 6000);
    return () => clearInterval(t);
  }, [active, bidId]);

  // decide what (if anything) the cloud should surface
  useEffect(() => {
    if (!active) return;
    const proposed = sugs.filter((s) => s.status === "proposed");
    const fresh = proposed.find((s) => !acked.current.has(s.id));
    if (fresh) {
      if (!shown || shown.id !== fresh.id) {
        setShown(fresh);
        if (lastPinged.current !== fresh.id) { ping(soundOn); lastPinged.current = fresh.id; } // "sound a ping when it appears"
      }
    } else if (shown && !proposed.some((s) => s.id === shown.id)) {
      setShown(null); // the shown one was applied/dismissed elsewhere
    }
  }, [sugs, active]);

  if (!active) return null;

  const anyProposed = sugs.some((s) => s.status === "proposed");

  function toggleSound() {
    const next = !soundOn;
    setSoundOn(next);
    localStorage.setItem(soundKey, next ? "on" : "off");
  }

  function acknowledge() {
    if (shown) { acked.current.add(shown.id); persistAck(); }
    setShown(null); // "disappear once user has acknowledged it"
  }

  async function summon() {
    // "reappear ... when the user calls for it"
    setErr("");
    const latest = sugs.find((s) => s.status === "proposed");
    if (latest) { setShown(latest); return; }
    setBusy(true);
    try {
      await api.post(`/bids/${bidId}/assistant/advise`);
      await load();
    } catch (e: any) {
      setErr(e.message || "The Assistant could not respond. Check the AI status on the dashboard.");
    }
    setBusy(false);
  }

  async function apply() {
    if (!shown) return;
    try { await api.post(`/bids/assistant/suggestions/${shown.id}/apply`); } catch (e: any) { alert(e.message); return; }
    acked.current.add(shown.id); persistAck();
    setShown(null); load();
  }

  const g = shown?.guardrail;
  const canApply = shown && (shown.kind === "response_enhance" || shown.kind === "framework_align") && shown.proposed_text;

  return (
    <>
      {busy && (
        <div className="thought-cloud" role="status">
          <div className="tc-title"> Bid Assistant</div>
          <div className="tc-body" style={{ marginTop: 6 }}>Thinking gathering guidance from this bid's data.</div>
        </div>
      )}
      {!busy && err && (
        <div className="thought-cloud" role="alert">
          <div className="tc-head">
            <span className="tc-title"> Bid Assistant</span>
            <button className="tc-icon" title="Dismiss" onClick={() => setErr("")}></button>
          </div>
          <div className="tc-body" style={{ color: "var(--danger)", marginTop: 6 }}>{err}</div>
        </div>
      )}
      {!busy && !err && shown && (
        <div className="thought-cloud" role="dialog" aria-label="Bid Assistant suggestion">
          <div className="tc-head">
            <span className="tc-title"> Bid Assistant</span>
            <span>
              <button className="tc-icon" title={soundOn ? "Mute assistant sound" : "Unmute assistant sound"} onClick={toggleSound}>
                {soundOn ? "🔊" : "🔇"}
              </button>
              <button className="tc-icon" title="Acknowledge" onClick={acknowledge}></button>
            </span>
          </div>
          <div className="tc-body">
            <div style={{ fontSize: 12, color: "#6b7280", marginBottom: 4 }}>
              {shown.kind === "bid_advice" ? "Bid-level advice"
                : shown.kind === "framework_align" ? `Framework alignment · ${shown.target_ref}`
                : `Enhancement · ${shown.target_ref}`}
            </div>
            {shown.advice?.slice(0, 3).map((a, i) => <div key={i} style={{ marginBottom: 4 }}> {a}</div>)}
            {g && (
              <div style={{ marginTop: 6 }}>
                {g.checked === false
                  ? <span className="chip" title="AI off — no self-check ran"> Self-check unavailable</span>
                  : <span className="chip ok" title={(g.claims || []).join("\n") || "No unsupported claims"}> Hallucination self-check{g.removed > 0 ? ` — ${g.removed} removed` : " — clean"}</span>}
              </div>
            )}
          </div>
          <div className="tc-actions">
            {canApply && <button onClick={apply}>Approve &amp; apply</button>}
            <button className="secondary" onClick={() => { onView(); acknowledge(); }}>View</button>
            <button className="ghost" onClick={acknowledge}>Got it</button>
          </div>
        </div>
      )}
      <button className={"assistant-fab" + (anyProposed && !shown ? " nudge" : "")} title="Call the Bid Assistant" onClick={summon}></button>
    </>
  );
}