File size: 5,487 Bytes
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
816fa8a
 
 
 
 
 
 
dec006b
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useRef, useState } from "react";
import { intelligenceProblem } from "./intelligenceApi";
import type { IntelligenceApi, IntelligenceFile, IntelligenceProposal } from "./intelligenceApi";

const statusText = { pending: "Waiting for approval", approving: "Saving approval", approved: "Approved",
  rejected: "Declined", stale: "File changed" };

function sourceInteractions(row: IntelligenceProposal): string[] {
  const value = "sourceInteractions" in row ? row.sourceInteractions : null;
  return Array.isArray(value) && value.length === 3
    && value.every((id): id is string => typeof id === "string" && /^[A-Za-z0-9_-]{8,96}$/.test(id)) ? value : [];
}

export default function Proposals({ path, api, onApproved, onLoaded }: {
  path: string; api: IntelligenceApi; onApproved: (file: IntelligenceFile) => void;
  onLoaded?: (rows: IntelligenceProposal[] | null) => void;
}) {
  const [rows, setRows] = useState<IntelligenceProposal[]>([]);
  const [problem, setProblem] = useState("");
  const [busy, setBusy] = useState("");
  const [retry, setRetry] = useState(0);
  const writing = useRef(false);
  const alive = useRef(false);
  const request = useRef<AbortController | null>(null);
  useEffect(() => {
    alive.current = true;
    const abort = new AbortController();
    request.current = abort;
    setProblem(""); setRows([]); onLoaded?.(null);
    void api.listProposals(path, abort.signal).then((value) => {
      if (!abort.signal.aborted) { setRows(value); onLoaded?.(value); }
    }).catch((error: unknown) => {
      if (!abort.signal.aborted) setProblem(intelligenceProblem(error, "Proposals could not be read. Try again."));
    });
    return () => { alive.current = false; abort.abort(); onLoaded?.(null); };
  }, [api, path, retry, onLoaded]);

  async function decide(row: IntelligenceProposal, decision: "approve" | "reject") {
    if (writing.current) return;
    const started = request.current;
    const currentRequest = () => alive.current && request.current === started;
    writing.current = true; setBusy(row.id); setProblem("");
    try {
      const result = await api.decideProposal(row.id, decision);
      if (!currentRequest()) return;
      setRows((current) => current.map((item) => item.id === row.id ? result.proposal : item));
      if (result.file) onApproved(result.file);
      const current = await api.listProposals(path);
      if (currentRequest()) { setRows(current); onLoaded?.(current); }
    } catch (error) {
      if (currentRequest()) {
        onLoaded?.(null);
        setProblem(intelligenceProblem(error, "The decision could not be confirmed. Reload and try again."));
        // A stale refusal still persists the stale state on the server.
        try {
          const current = await api.listProposals(path);
          if (currentRequest()) { setRows(current); onLoaded?.(current); }
        } catch { /* The decision error remains visible until Retry. */ }
      }
    } finally {
      writing.current = false;
      if (alive.current) setBusy("");
    }
  }

  if (!rows.length && !problem) return null;
  return <section className="intelligence-proposals" aria-label="Proposed changes" aria-busy={!!busy}>
    {problem ? <div className="intelligence-feedback" role="alert"><span>{problem}</span>
      <button className="intelligence-button" type="button" disabled={!!busy} onClick={() => setRetry((value) => value + 1)}>Retry</button></div> : null}
    {rows.map((row) => <article key={row.id} data-testid="intelligence-proposal" data-status={row.status}>
      <h3>{statusText[row.status]}</h3>
      <p className="intelligence-meta">{!row.agent && !row.onBehalfOf ? row.author : `${row.author} for ${row.onBehalfOf}`}</p>
      {sourceInteractions(row).length ? <p className="intelligence-meta" data-testid="intelligence-learning-sources"
        style={{ overflowWrap: "anywhere" }}>
        Source interactions: {sourceInteractions(row).join(", ")}</p> : null}
      <p className="intelligence-meta">{row.approvedBy.length} of {row.policy.approvals_needed} approvals
        {row.status === "approved" ? ` · Version ${row.approvedVersion}` : ` · Base version ${row.baseVersion}`}</p>
      {row.status === "pending" ? <p className="intelligence-meta">Approvers: {row.recipients.join(", ")}</p> : null}
      {row.approvedBy.length ? <p className="intelligence-meta">Approved by {row.approvedBy.join(", ")}</p> : null}
      {row.status === "stale" ? <p className="intelligence-meta">Request a new proposal</p> : null}
      <details open={row.status === "pending" || row.status === "stale"}>
        <summary>Changes</summary>
        <pre className="intelligence-diff" tabIndex={0} aria-label="Proposed diff">{row.diff.split("\n").map((line, index) =>
          <span key={index} className={line.startsWith("+") && !line.startsWith("+++") ? "intelligence-diff-add"
            : line.startsWith("-") && !line.startsWith("---") ? "intelligence-diff-remove" : undefined}>{line}{"\n"}</span>)}</pre>
      </details>
      {row.canDecide ? <div className="intelligence-proposal-actions">
        <button className="intelligence-button" type="button" disabled={!!busy} onClick={() => void decide(row, "reject")}>Decline</button>
        <button className="intelligence-button intelligence-primary" type="button" disabled={!!busy}
          onClick={() => void decide(row, "approve")}>{busy === row.id ? "Saving…" : "Approve"}</button>
      </div> : null}
    </article>)}
  </section>;
}