File size: 7,425 Bytes
fba6beb
 
 
 
 
89af3b2
fba6beb
 
 
e174d2c
89af3b2
fba6beb
 
 
 
 
 
89af3b2
fba6beb
89af3b2
 
fba6beb
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
fba6beb
 
 
 
 
 
 
 
 
 
89af3b2
 
 
 
 
 
 
 
fba6beb
89af3b2
 
 
fba6beb
 
 
89af3b2
 
 
fba6beb
 
 
 
 
89af3b2
 
fba6beb
 
 
 
89af3b2
fba6beb
 
89af3b2
 
 
 
 
 
 
 
fba6beb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
fba6beb
 
 
 
 
89af3b2
 
fba6beb
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
fba6beb
 
 
 
 
 
e174d2c
fba6beb
 
 
89af3b2
fba6beb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
// ---------------------------------------------------------------------------
// customer-grid / FieldAgentChat.tsx β€” owner item 10's chat (W36-T07, R6, R11).
//
// β›” NOTHING IS CREATED UNTIL THE USER ACCEPTS, and that is the ticket's own `done-when`. The
// proposal is a PROPOSAL: it sits on screen with its reasoning, the user may correct it in
// another turn, and only the acceptance button reaches `onAccept`. A chat that created a column on
// the first sentence would be faster and would be the wrong product β€” the owner asked for this
// precisely so they *"can further align request"* first.
//
// ⚠ ITS OWN MODULE because `ColumnMenu.tsx` is 180k and pulls the whole
// grid, so node probes emit this surface and inject its history transport.
// ⚠ The composer wears the `cg-agent-*` classes W36-T05 already introduced. That is deliberate
// reuse of ONE shape (bordered card, foot row inside the border, circular send) rather than a
// second chat look β€” the same parity D-16 measured between the Assistant and the agent chat.
// ---------------------------------------------------------------------------

import { useMemo, useState } from "react";
import { logExchange } from "../assistant/dockClient";
import { proposalReady, proposeField } from "./fieldAgent";
import type { AgentKind, FieldAgentTarget, FieldProposal } from "./fieldAgent";
import type { Field } from "./types";

/** Plain words for the kinds this agent proposes, so the card never shows an internal key. */
const KIND_WORDS: Partial<Record<AgentKind, string>> = {
  text: "Free text",
  currency: "Money",
  pct: "Percentage",
  int: "Whole number",
  date: "Date",
  checkbox: "Yes or no",
  rating: "Rating",
  email: "Email",
  phone: "Phone",
  url: "Web address",
  link: "Link to another record",
  select: "One choice from a list",
  multiselect: "Several choices from a list",
  user: "Person",
  measure: "Metric",
};

export function kindWord(kind: AgentKind): string {
  return KIND_WORDS[kind] ?? String(kind);
}

export function fieldProposalSummary(proposal: FieldProposal): string {
  const label = proposal.label.replace(/\s+/g, " ");
  const target = proposal.linkTarget?.label.replace(/\s+/g, " ");
  return proposal.existingField
    ? `Use existing field: "${label}" (${kindWord(proposal.kind)}).`
    : `Proposed column: "${label}" (${kindWord(proposal.kind)})${target ? `, linked to "${target}"` : ""}.`;
}

export function FieldAgentChat({
  existing = [],
  linkTargets = [],
  database,
  onAccept,
  onCancel,
}: {
  existing?: readonly Field[];
  linkTargets?: readonly FieldAgentTarget[];
  database?: string;
  onAccept: (proposal: FieldProposal) => void;
  onCancel: () => void;
}) {
  const [turns, setTurns] = useState<string[]>([]);
  const [draft, setDraft] = useState("");
  const proposal = useMemo(() => (turns.length ? proposeField(turns, existing, linkTargets) : null),
    [turns, existing, linkTargets]);
  const ready = proposal !== null && proposalReady(proposal);
  const send = () => {
    const said = draft.trim();
    if (!said) return;
    const next = proposeField([...turns, said], existing, linkTargets);
    setTurns((t) => [...t, said]);
    setDraft("");
    // History failure must leave the proposal available for review and acceptance.
    try {
      void logExchange({
        question: said,
        answer: [...next.why, ...next.missing, fieldProposalSummary(next)].join("\n"),
        context: { surface: "field", ...(database ? { database } : {}) },
      }).catch(() => {});
    } catch { /* A synchronous transport failure is best effort too. */ }
  };
  return (
    <div className="cg-fagent" aria-label="Field agent">
      <div className="cg-fagent-body">
        {turns.length === 0 ? (
          <div className="cg-agent-empty">
            <span className="cg-agent-mark" aria-hidden="true" />
            <p className="cg-agent-ask">What should this column hold?</p>
          </div>
        ) : (
          <ol className="cg-fagent-turns">
            {turns.map((turn, i) => (
              <li className="cg-fagent-turn" key={i}>
                <span className="cg-fagent-said">{turn}</span>
              </li>
            ))}
          </ol>
        )}

        {proposal !== null && (
          <div className="cg-fagent-card">
            <p className="cg-fagent-card-head">{proposal.existingField ? "Existing field" : "Proposed column"}</p>
            <dl className="cg-fagent-def">
              <dt>Name</dt>
              <dd>{proposal.label}</dd>
              <dt>Kind</dt>
              <dd>{kindWord(proposal.kind)}</dd>
              {proposal.linkTarget ? <dt>Database</dt> : null}
              {proposal.linkTarget ? <dd>{proposal.linkTarget.label}</dd> : null}
              {proposal.options ? <dt>Values</dt> : null}
              {proposal.options ? <dd>{proposal.options.join(", ")}</dd> : null}
            </dl>
            {proposal.why.length > 0 ? (
              <ul className="cg-fagent-why">
                {proposal.why.map((line, i) => <li key={i}>{line}</li>)}
              </ul>
            ) : null}
            {proposal.missing.length > 0 ? (
              <ul className="cg-fagent-missing">
                {proposal.missing.map((line, i) => <li key={i}>{line}</li>)}
              </ul>
            ) : null}
            <div className="cg-fagent-actions">
              <button type="button" className="cg-fagent-cancel" onClick={onCancel}>
                Cancel
              </button>
              {/* β›” THE ONLY PATH TO CREATION. Disabled while anything is still open, so the
                  agent asks rather than inventing an answer nobody gave it. */}
              <button
                type="button"
                className="cg-fagent-create"
                disabled={!ready}
                onClick={() => proposal && onAccept(proposal)}
              >
                {proposal.existingField ? "Use existing field" : "Create this field"}
              </button>
            </div>
          </div>
        )}
      </div>

      <div className="cg-agent-composer">
        <textarea
          className="cg-agent-input"
          value={draft}
          rows={2}
          placeholder={turns.length === 0
            ? "Describe the column you want"
            : "Correct anything above, or add what is missing"}
          aria-label="Describe the column you want"
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter" && !e.shiftKey) {
              e.preventDefault();
              send();
            }
          }}
        />
        <div className="cg-agent-composer-foot">
          <span className="cg-agent-pill">Nothing is created until you accept</span>
          <span className="cg-agent-spacer" />
          <button
            type="button"
            className="cg-agent-send"
            onClick={send}
            disabled={draft.trim() === ""}
            aria-label="Send this to the field agent"
            title="Send this to the field agent"
          >
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path d="M8 12.6V3.8M4.4 7.2 8 3.6l3.6 3.6" stroke="currentColor" strokeWidth="1.5"
                    strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}