@ia-qa/pal 1.11.1 β†’ 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ui/page.js CHANGED
@@ -117,6 +117,14 @@ figcaption code{display:block;margin:2px 0 6px}
117
117
  .decOut{margin-top:10px;padding:10px 12px;border-radius:10px;border-left:4px solid var(--warn);background:var(--code);white-space:pre-wrap}
118
118
  .decOut.good{border-left-color:var(--ok)}.decOut.bad{border-left-color:var(--bad)}
119
119
  .decOut pre{max-height:220px;overflow:auto;font-size:12px}
120
+ .tabs{display:flex;gap:8px;margin:16px 0 0;flex-wrap:wrap}
121
+ .tab{border-radius:999px;font-weight:700}
122
+ .tab.on{background:linear-gradient(120deg,var(--accent),var(--accent2));border-color:transparent;color:#fff}
123
+ .aiAct{border-top:1px dashed var(--line);padding:12px 0}.aiAct:first-child{border-top:0}
124
+ .aiAct pre{max-height:260px;overflow:auto;font-size:12px;white-space:pre-wrap;background:var(--code);border-radius:8px;padding:8px}
125
+ .aiAct details{margin:4px 0}.aiAct summary{cursor:pointer}
126
+ .aiBadge{border:2px solid var(--info);border-radius:10px;padding:6px 10px;margin:6px 0;background:#8b5cf60f}
127
+ figure.suggested{outline:3px solid var(--info);outline-offset:4px;border-radius:8px}
120
128
  @media (prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important}}
121
129
  </style></head>
122
130
  <body><div id="confetti"></div><main>
@@ -132,6 +140,55 @@ figcaption code{display:block;margin:2px 0 6px}
132
140
  <div class="where" id="where">loading…</div>
133
141
  </header>
134
142
 
143
+ <nav class="tabs" role="tablist">
144
+ <button class="tab on" id="tabBtnMain" role="tab" aria-selected="true">🧭 Tour</button>
145
+ <button class="tab" id="tabBtnAi" role="tab" aria-selected="false">πŸ€– AI suggestions</button>
146
+ </nav>
147
+
148
+ <div id="tabAi" class="hidden">
149
+ <section class="card" id="aiModeCard">
150
+ <h2><span class="ic">🎚️</span>How far a model may go in this project</h2>
151
+ <div class="choices">
152
+ <label><input type="radio" name="aiMode" value="local"> <b>πŸ”’ Local</b> β€” deterministic only. Nothing is ever sent to a model, even if one is set up below. The tour, the checks and the repairs all work.</label>
153
+ <label><input type="radio" name="aiMode" value="hybrid"> <b>🀝 Hybrid</b> β€” a model suggests; you decide. Nothing leaves before you see its preview, nothing is applied without your click.</label>
154
+ <label><input type="radio" name="aiMode" value="agent"> <b>πŸ€– Agent</b> β€” as hybrid, and the model's most confident repairs may be committed <b>onto a new git branch</b> for you to review. Never onto your working tree, never merged, never a CI gate.</label>
155
+ </div>
156
+ <p class="muted">Saved as <code>"mode"</code> in <code>.ia-qa/config.json</code> β€” the one setting heal, discovery and pal all read, from the CLI, the MCP and this page alike.</p>
157
+ <div id="aiModeNotice" class="notice hidden"></div>
158
+ </section>
159
+
160
+ <section class="card" id="aiSetupCard">
161
+ <h2><span class="ic">πŸ”Œ</span>Connect a model β€” your key, your account</h2>
162
+ <p class="muted" id="aiIntro">Optional. A model can suggest which element a broken test meant, what each page is for, and what someone comes to do there. It proposes; you decide; nothing is applied without your click. Everything else pal does works without it.</p>
163
+ <div id="aiCurrent" class="notice hidden"></div>
164
+ <div class="row"><span class="muted">Provider</span><select id="aiProvider"></select><button id="aiLocal">🏠 Model on this machine (Ollama)</button></div>
165
+ <div class="row" id="aiUrlRow"><span class="muted">Endpoint</span><input type="url" id="aiBaseUrl" list="aiUrls" placeholder="https://api.deepseek.com/v1 or http://localhost:11434/v1" spellcheck="false"><datalist id="aiUrls"></datalist></div>
166
+ <div class="row"><span class="muted">Model</span><input type="text" id="aiModel" list="aiModels" placeholder="e.g. gpt-4o-mini" spellcheck="false" autocomplete="off"><datalist id="aiModels"></datalist></div>
167
+ <div id="aiKeyRows">
168
+ <div class="row"><span class="muted">Key variable</span><input type="text" id="aiKeyName" maxlength="128" placeholder="OPENAI_API_KEY" spellcheck="false" autocomplete="off"></div>
169
+ <div class="row"><span class="muted">Key value</span><input type="password" id="aiKeyValue" placeholder="optional β€” stored on this machine only" autocomplete="new-password" spellcheck="false"></div>
170
+ <p class="muted">The config files get the variable's <b>name</b>, never the key. A value typed here goes to this machine's credential store and nowhere else; a variable set in your shell still wins.</p>
171
+ </div>
172
+ <p class="muted hidden" id="aiLocalNote">🏠 A model on this machine needs no key, and nothing leaves it.</p>
173
+ <div class="row"><button class="primary" id="aiSave">πŸ’Ύ Save</button></div>
174
+ <div id="aiSaveNotice" class="notice hidden"></div>
175
+ </section>
176
+
177
+ <section class="card hidden" id="aiAskCard">
178
+ <h2><span class="ic">✨</span>Ask the model</h2>
179
+ <p class="muted">Each question starts with its preview: exactly what would be sent, and where. Nothing leaves before you look at it and press send.</p>
180
+ <div id="aiActions"></div>
181
+ <div id="aiJob" class="decOut"></div>
182
+ </section>
183
+
184
+ <section class="card hidden" id="aiReadCard">
185
+ <h2><span class="ic">πŸ“–</span>What the model said</h2>
186
+ <p class="muted">A model's reading, never an observation: each carries the model and the date, and is marked <span class="pill warn">older capture</span> once what it read has been captured again.</p>
187
+ <div id="aiReadings"></div>
188
+ </section>
189
+ </div>
190
+
191
+ <div id="tabMain">
135
192
  <div id="browserBox" class="notice hidden"></div>
136
193
 
137
194
  <section class="card hidden" id="setupCard">
@@ -269,8 +326,9 @@ figcaption code{display:block;margin:2px 0 6px}
269
326
  <p class="muted hidden" id="noStore">This machine has no credential store β€” export the variable in the shell that starts the console, or use <code id="setCmd"></code> where one exists.</p>
270
327
  <div class="notice hidden" id="secretNotice"></div>
271
328
  </section>
329
+ </div>
272
330
 
273
- <footer>🏠 Local only · 127.0.0.1 · nothing on this page is sent anywhere · it stops by itself when you close the tab</footer>
331
+ <footer>🏠 Local only · 127.0.0.1 · nothing leaves this machine unless you send it from the AI tab, after its preview · it stops by itself when you close the tab</footer>
274
332
  </main>
275
333
  <script>
276
334
  (() => {
@@ -757,10 +815,20 @@ figcaption code{display:block;margin:2px 0 6px}
757
815
  const lab = el('label', null, 'check'); watch = document.createElement('input'); watch.type = 'checkbox';
758
816
  lab.appendChild(watch); lab.appendChild(el('span', 'πŸ‘€ Show me the browser while the test re-runs')); card.appendChild(lab);
759
817
  }
818
+ // A model's reading marks a choice; it never adds one. Its button is the same "βœ… This one".
819
+ const sg = d.suggestion;
820
+ if (sg) {
821
+ const b = el('div', null, 'aiBadge');
822
+ b.appendChild(el('div', 'πŸ€– Suggested by the model: ' + (sg.name ? '"' + sg.name + '" ' : '') + sg.selector + ' β€” ' + Math.round(sg.confidence * 100) + '/100 by its own estimate' + (sg.stale ? ' Β· read from an older capture' : '')));
823
+ b.appendChild(el('div', '↳ ' + sg.rationale, 'muted'));
824
+ b.appendChild(el('div', sg.inChoices ? 'A suggestion, not a verdict: the choice below is still yours (' + sg.model + ').' : 'That element is not one of the choices below, so it cannot be applied from here β€” read it as a remark (' + sg.model + ').', 'muted'));
825
+ card.appendChild(b);
826
+ }
760
827
  card.appendChild(el('div', 'Which one did the test mean?', 'q'));
761
828
  const figs = el('div', null, 'figs'); const out = el('div', null, 'decOut');
762
829
  for (const c of d.candidates) {
763
830
  const fig = document.createElement('figure'); fig.appendChild(crop(d.page, c.crop));
831
+ if (sg && sg.inChoices && sg.selector === c.selector) fig.className = 'suggested';
764
832
  const cap = document.createElement('figcaption'); cap.appendChild(el('b', c.label)); cap.appendChild(el('code', c.selector));
765
833
  const pick = el('button', 'βœ… This one', 'pickBtn');
766
834
  pick.onclick = async () => {
@@ -783,6 +851,8 @@ figcaption code{display:block;margin:2px 0 6px}
783
851
  for (const l of items) {
784
852
  const row = el('div', null, 'decRow');
785
853
  row.appendChild(el('span', l.label)); row.appendChild(el('code', l.sites.map((x) => x.file + ':' + x.line).join(', ')));
854
+ // Information only: nothing is rewritten towards an element that is gone.
855
+ if (l.suggestion) row.appendChild(el('div', 'πŸ€– The model thinks ' + (l.suggestion.name ? '"' + l.suggestion.name + '" ' : '') + l.suggestion.selector + ' replaced it (' + Math.round(l.suggestion.confidence * 100) + '/100 by its own estimate' + (l.suggestion.stale ? ', older capture' : '') + ') β€” ' + l.suggestion.rationale + ' If so, edit the step by hand.', 'muted'));
786
856
  tbl.appendChild(row);
787
857
  }
788
858
  g.appendChild(tbl);
@@ -894,6 +964,265 @@ figcaption code{display:block;margin:2px 0 6px}
894
964
  if (!s.references.length) list.appendChild(el('li', 'No secret is referenced in .ia-qa/config.json.', 'muted'));
895
965
  })();
896
966
 
967
+ // ── Tabs. The tour is the product; the AI tab is optional and says so.
968
+ const setTab = (ai) => {
969
+ show('tabAi', ai); show('tabMain', !ai);
970
+ q('tabBtnAi').classList.toggle('on', ai); q('tabBtnMain').classList.toggle('on', !ai);
971
+ q('tabBtnAi').setAttribute('aria-selected', String(ai)); q('tabBtnMain').setAttribute('aria-selected', String(!ai));
972
+ try { localStorage.setItem('palTab', ai ? 'ai' : 'main'); } catch {}
973
+ if (ai) loadAi();
974
+ };
975
+ document.querySelectorAll('input[name=aiMode]').forEach((r) => {
976
+ r.onchange = async () => {
977
+ const out = await (await api('/api/ai/mode', { mode: r.value })).json();
978
+ if (!out.written) note('aiModeNotice', out.problems.join(' '), 'bad');
979
+ loadAi();
980
+ };
981
+ });
982
+ q('tabBtnMain').onclick = () => setTab(false);
983
+ q('tabBtnAi').onclick = () => setTab(true);
984
+
985
+ // ── AI suggestions. Reading this tab calls nothing; a preview runs the verb's own dry run
986
+ // (no key, no request); only "Send" reaches a model, with the preview's digest.
987
+ let ai = null;
988
+ const AI_ACTS = [
989
+ { id: 'suggest', icon: 'βš–οΈ', title: 'Which element did a broken test mean?', what: 'For each row the tour gave up on (gone, or several look alike), the model picks one of the elements on the page now. It is shown on the "Waiting on you" cards; the button stays yours.' },
990
+ { id: 'classify', icon: '🏷️', title: 'What is each page for, and how sensitive is it?', what: 'Labels every page that takes input (a login, a payment, a search…) against a closed list. Needs a scan of the app.' },
991
+ { id: 'plan', icon: '🎯', title: 'What does someone come to each page to do?', what: 'In business words, and what they can no longer do if it breaks β€” for the pages your tests do not visit. Sends less than the labels: no selectors, no API calls. Needs a scan.' },
992
+ ];
993
+ const shownDigest = {};
994
+
995
+ function fillProviderForm(s) {
996
+ const sel = q('aiProvider');
997
+ if (!sel.options.length) for (const p of s.providers) sel.appendChild(el('option', p.label)).value = p.id;
998
+ const urls = q('aiUrls'); if (!urls.options.length) for (const e of s.examples) { const o = document.createElement('option'); o.value = e.baseUrl; o.label = e.label; urls.appendChild(o); }
999
+ const cur = s.current;
1000
+ if (cur && !sel.dataset.touched) {
1001
+ sel.value = cur.provider; q('aiModel').value = cur.model; q('aiBaseUrl').value = cur.baseUrl || ''; q('aiKeyName').value = cur.keyName || '';
1002
+ }
1003
+ onProvider();
1004
+ }
1005
+ function providerInfo() { return ai && ai.settings.providers.find((p) => p.id === q('aiProvider').value); }
1006
+ function isLocalUrl(u) { try { const h = new URL(u).hostname.replace(/^\\[|\\]$/g, ''); return h === 'localhost' || h.endsWith('.localhost') || h === '::1' || /^127(\\.[0-9]+){3}$/.test(h); } catch { return false; } }
1007
+ function onProvider() {
1008
+ const p = providerInfo(); if (!p) return;
1009
+ show('aiUrlRow', p.needsBaseUrl);
1010
+ const local = p.needsBaseUrl && isLocalUrl(q('aiBaseUrl').value.trim());
1011
+ show('aiKeyRows', !local); show('aiLocalNote', local);
1012
+ if (!q('aiKeyName').value) q('aiKeyName').placeholder = p.keyEnv;
1013
+ const models = q('aiModels'); models.textContent = '';
1014
+ for (const m of p.models) { const o = document.createElement('option'); o.value = m.id; if (m.note) o.label = m.note; models.appendChild(o); }
1015
+ }
1016
+ q('aiProvider').onchange = () => { q('aiProvider').dataset.touched = '1'; onProvider(); };
1017
+ q('aiBaseUrl').oninput = onProvider;
1018
+ q('aiLocal').onclick = () => {
1019
+ q('aiProvider').value = 'openai-compatible'; q('aiProvider').dataset.touched = '1';
1020
+ q('aiBaseUrl').value = 'http://localhost:11434/v1'; if (!q('aiModel').value) q('aiModel').placeholder = 'e.g. llama3.1';
1021
+ onProvider(); q('aiModel').focus();
1022
+ };
1023
+
1024
+ q('aiSave').onclick = async () => {
1025
+ const p = providerInfo();
1026
+ const body = { provider: q('aiProvider').value, model: q('aiModel').value, baseUrl: q('aiBaseUrl').value, keyName: q('aiKeyName').value || (p ? p.keyEnv : '') };
1027
+ const value = q('aiKeyValue').value; q('aiKeyValue').value = '';
1028
+ const local = p && p.needsBaseUrl && isLocalUrl(body.baseUrl.trim());
1029
+ const saved = await (await api('/api/ai/settings', body)).json();
1030
+ if (!saved.written) { note('aiSaveNotice', saved.problems.join(String.fromCharCode(10)), 'bad'); return; }
1031
+ let keyLine = '';
1032
+ if (value && !local) {
1033
+ // The value goes to this machine's store under the variable's name β€” the same door as the Secrets card.
1034
+ const st = await (await api('/api/secrets/set', { name: body.keyName.trim(), value })).json();
1035
+ keyLine = st.stored ? ' The key is stored on this machine under ' + st.name + '.' : ' The key was NOT stored: ' + (st.reason || 'refused') + '.';
1036
+ }
1037
+ note('aiSaveNotice', 'βœ… Saved β€” ' + (saved.local ? '🏠 ' + saved.host + ', on this machine: nothing leaves it.' : 'questions will go to ' + saved.host + ' when you send them.') + keyLine, keyLine.includes('NOT') ? 'bad' : 'ok');
1038
+ q('aiProvider').dataset.touched = '';
1039
+ loadAi();
1040
+ };
1041
+
1042
+ function whereLine(pv) {
1043
+ return pv.local ? '🏠 To ' + pv.host + ' β€” a model on this machine: nothing leaves it.' : '🌐 To ' + pv.host + ' (' + pv.provider + ' Β· ' + pv.model + ') β€” this leaves your machine, on your key and your account.';
1044
+ }
1045
+
1046
+ function renderPreview(box, pv, act) {
1047
+ box.textContent = '';
1048
+ if (pv.count === 0) { box.appendChild(el('div', 'Nothing to send: ' + (act.id === 'suggest' ? 'the last tour left no row to choose on.' : 'no page to read in the capture.' ) + (pv.because ? ' ' + pv.because : ''), 'notice ok')); return; }
1049
+ if (!pv.host) { box.appendChild(el('div', pv.hostError || 'No model set up yet.', 'notice bad')); return; }
1050
+ box.appendChild(el('div', whereLine(pv), 'notice' + (pv.local ? ' ok' : '')));
1051
+ box.appendChild(el('div', pv.count + (act.id === 'suggest' ? ' question(s), one per row' : ' page(s)') + ' Β· ' + pv.bytes + ' bytes Β· about ' + pv.approxTokens + ' tokens (a rough order of magnitude, not a bill)' + (pv.notSent ? ' Β· ' + pv.notSent + ' not sent (nothing to ask about them)' : ''), 'muted'));
1052
+ if (pv.because) box.appendChild(el('div', pv.because, 'muted'));
1053
+ box.appendChild(el('div', 'Exactly what would be sent β€” open any of them:', 'q'));
1054
+ for (const a of pv.asks.slice(0, 60)) {
1055
+ const d = document.createElement('details');
1056
+ d.appendChild(el('summary', a.page + (a.label ? ' β€” ' + a.label : '')));
1057
+ d.appendChild(el('pre', a.prompt));
1058
+ box.appendChild(d);
1059
+ }
1060
+ if (pv.asks.length > 60) box.appendChild(el('div', '…and ' + (pv.asks.length - 60) + ' more, the same way.', 'muted'));
1061
+ const row = el('div', null, 'row');
1062
+ const send = el('button', pv.local ? 'β–Ά Run it on this machine' : 'πŸ“€ Send to ' + pv.host, 'primary');
1063
+ send.onclick = async () => {
1064
+ send.disabled = true;
1065
+ const r = await (await api('/api/ai/send', { action: act.id, digest: pv.digest })).json();
1066
+ if (!r.ok) { send.disabled = false; box.appendChild(el('div', r.reason || 'Not sent.', 'notice bad')); return; }
1067
+ box.textContent = ''; followAi();
1068
+ };
1069
+ row.appendChild(send);
1070
+ // Agent mode only: the same preview, the same send, and the confident repairs committed onto
1071
+ // a new branch β€” the person chose agent mode, and reviews the branch.
1072
+ if (act.id === 'suggest' && ai && ai.settings.mode === 'agent') {
1073
+ const br = el('button', '🌿 Send, and commit the confident ones (β‰₯ ' + Math.round((ai.settings.minConfidence || 0.9) * 100) + '/100) on a new branch');
1074
+ br.onclick = async () => {
1075
+ br.disabled = true; send.disabled = true;
1076
+ const r = await (await api('/api/ai/send', { action: act.id, digest: pv.digest, branch: true })).json();
1077
+ if (!r.ok) { br.disabled = false; send.disabled = false; box.appendChild(el('div', r.reason || 'Not sent.', 'notice bad')); return; }
1078
+ box.textContent = ''; followAi();
1079
+ };
1080
+ row.appendChild(br);
1081
+ }
1082
+ box.appendChild(row);
1083
+ }
1084
+
1085
+ function renderActions() {
1086
+ const list = q('aiActions');
1087
+ if (list.childElementCount) return;
1088
+ for (const act of AI_ACTS) {
1089
+ const wrap = el('div', null, 'aiAct');
1090
+ const head = el('div', null, 'row'); head.appendChild(el('strong', act.icon + ' ' + act.title)); wrap.appendChild(head);
1091
+ wrap.appendChild(el('div', act.what, 'muted'));
1092
+ const box = el('div');
1093
+ const btn = el('button', 'πŸ‘€ Show what would leave');
1094
+ btn.onclick = async () => {
1095
+ btn.disabled = true; box.textContent = '⏳ Preparing the preview β€” nothing is sent…';
1096
+ try {
1097
+ const r = await (await api('/api/ai/preview', { action: act.id })).json();
1098
+ if (!r.ok) { box.textContent = ''; box.appendChild(el('div', r.reason || 'No preview.', 'notice bad')); return; }
1099
+ shownDigest[act.id] = r.preview.digest; renderPreview(box, r.preview, act);
1100
+ } finally { btn.disabled = false; }
1101
+ };
1102
+ const row = el('div', null, 'row'); row.appendChild(btn); wrap.appendChild(row); wrap.appendChild(box);
1103
+ list.appendChild(wrap);
1104
+ }
1105
+ }
1106
+
1107
+ function followAi() {
1108
+ const out = q('aiJob');
1109
+ const tick = async () => {
1110
+ let j = null;
1111
+ try { j = (await (await api('/api/ai')).json()).job; } catch { setTimeout(tick, 2000); return; }
1112
+ if (!j) return;
1113
+ out.textContent = '';
1114
+ if (j.status === 'running') {
1115
+ out.className = 'decOut';
1116
+ const quiet = Date.now() - Date.parse(j.heardAt);
1117
+ out.appendChild(el('div', '⏳ Asking ' + (j.local ? 'the model on this machine' : j.host) + ' · ' + j.count + ' question(s) · ' + span(Date.now() - Date.parse(j.startedAt))));
1118
+ if (j.lastLine) out.appendChild(el('div', j.lastLine, 'line'));
1119
+ out.appendChild(el('div', quiet > 60000 ? '⚠️ Nothing heard for ' + span(quiet) + '.' : 'Last heard ' + span(quiet) + ' ago', 'muted'));
1120
+ setTimeout(tick, 1000); return;
1121
+ }
1122
+ const r = j.result || {};
1123
+ const failedAll = j.status === 'failed' || r.written === false || (j.exitCode === 2);
1124
+ out.className = 'decOut ' + (failedAll ? 'bad' : 'good');
1125
+ // A failed call is a fact about the request, never about the app.
1126
+ out.appendChild(el('div', failedAll ? '❌ The model call did not succeed β€” nothing is wrong with your app. ' + (j.error || firstFailure(r) || '') : 'βœ… The model answered. Its reading is below, labelled as such.'));
1127
+ if (r.branch) {
1128
+ out.appendChild(el('div', r.branch.ok
1129
+ ? '🌿 ' + r.branch.applied.length + ' repair(s) committed on ' + r.branch.branch + ' (' + r.branch.commit + '). ' + r.branch.note
1130
+ : '🌿 Nothing committed β€” ' + r.branch.refused, r.branch.ok ? 'line' : 'muted'));
1131
+ }
1132
+ loadAi(); loadDecisions();
1133
+ };
1134
+ tick();
1135
+ }
1136
+ function firstFailure(r) {
1137
+ const u = (r.unresolved || []).find((x) => x.failed); if (u) return u.failed;
1138
+ for (const p of Object.values(r.pages || {})) { if (p && p.failed && p.failed.reason) return p.failed.reason; if (p && p.status === 'failed') return p.reason; }
1139
+ return '';
1140
+ }
1141
+
1142
+ const stamp = (x) => 'A model reading β€” ' + x.model + ', ' + new Date(x.at).toLocaleString();
1143
+ function readingHead(box, title, x) {
1144
+ const h = el('div', null, 'row'); h.appendChild(el('strong', title)); h.appendChild(el('span', stamp(x), 'muted'));
1145
+ if (x.stale) h.appendChild(el('span', 'older capture', 'pill warn'));
1146
+ box.appendChild(h);
1147
+ }
1148
+ function renderReadings(res) {
1149
+ const box = q('aiReadings'); box.textContent = '';
1150
+ const any = res.suggest || res.classify || res.plan;
1151
+ show('aiReadCard', !!any);
1152
+ if (res.suggest) {
1153
+ const s = res.suggest; readingHead(box, 'βš–οΈ Broken tests', s);
1154
+ const ul = el('ul');
1155
+ for (const x of s.suggestions) {
1156
+ const li = el('li'); li.appendChild(el('span', x.status, 'pill ' + (x.status === 'lost' ? 'bad' : 'warn')));
1157
+ li.appendChild(el('span', x.role + ' "' + x.name + '" on ' + x.page + ' β†’ ' + x.suggested_name + ' (' + Math.round(x.confidence * 100) + '/100 by its own estimate)'));
1158
+ li.appendChild(el('div', '↳ ' + x.rationale, 'muted'));
1159
+ li.appendChild(el('div', x.status === 'ambiguous' ? 'Choose it β€” or another β€” on the "Waiting on you" card.' : 'Gone from the page: nothing is rewritten for a lost element. If the model is right, point the step at ' + x.suggested_selector + ' by hand.', 'muted'));
1160
+ ul.appendChild(li);
1161
+ }
1162
+ for (const u of s.unresolved) {
1163
+ const li = el('li'); li.appendChild(el('span', u.failed ? 'call failed' : 'no confident match', 'pill ' + (u.failed ? 'bad' : 'info')));
1164
+ li.appendChild(el('span', u.role + ' "' + u.name + '" on ' + u.page + (u.failed ? ' β€” ' + u.failed : ' β€” stays for you.')));
1165
+ ul.appendChild(li);
1166
+ }
1167
+ if (!s.suggestions.length && !s.unresolved.length) ul.appendChild(el('li', 'Nothing was asked.', 'muted'));
1168
+ box.appendChild(ul);
1169
+ }
1170
+ if (res.classify) {
1171
+ const c = res.classify; readingHead(box, '🏷️ What each page is for', c);
1172
+ const ul = el('ul');
1173
+ for (const p of c.pages) {
1174
+ const li = el('li'); li.appendChild(el('strong', p.page));
1175
+ if (p.failed) li.appendChild(el('span', 'call failed β€” ' + p.failed, 'pill bad'));
1176
+ for (const k of p.kept) { li.appendChild(el('span', k.intent + ' Β· ' + k.sensitivity, 'pill info')); li.appendChild(el('div', k.why, 'muted')); }
1177
+ if (p.refused) li.appendChild(el('span', p.refused + ' it would not label β€” a person decides', 'muted'));
1178
+ if (p.dropped) li.appendChild(el('span', p.dropped + ' dropped: their evidence did not check out', 'muted'));
1179
+ ul.appendChild(li);
1180
+ }
1181
+ box.appendChild(ul);
1182
+ }
1183
+ if (res.plan) {
1184
+ const p = res.plan; readingHead(box, '🎯 What someone comes to do', p);
1185
+ const ul = el('ul');
1186
+ for (const x of p.pages) {
1187
+ const li = el('li'); li.appendChild(el('strong', x.page));
1188
+ li.appendChild(el('span', x.status === 'unclear' ? 'unclear β€” needs a person' : x.status, 'pill ' + (x.status === 'read' ? 'ok' : x.status === 'unclear' ? 'warn' : 'bad')));
1189
+ if (x.purpose) li.appendChild(el('div', x.purpose));
1190
+ if (x.impact) li.appendChild(el('div', 'If it breaks: ' + x.impact, 'muted'));
1191
+ if (x.reason) li.appendChild(el('div', x.reason, 'muted'));
1192
+ ul.appendChild(li);
1193
+ }
1194
+ box.appendChild(ul);
1195
+ box.appendChild(el('div', 'It ranks nothing and gates nothing: the order is the coverage map\\'s.', 'muted'));
1196
+ }
1197
+ }
1198
+
1199
+ async function loadAi() {
1200
+ try { ai = await (await api('/api/ai')).json(); } catch { return; }
1201
+ const s = ai.settings;
1202
+ fillProviderForm(s);
1203
+ document.querySelectorAll('input[name=aiMode]').forEach((r) => { r.checked = r.value === s.mode; });
1204
+ const modeLine = s.error ? '⚠️ ' + s.error
1205
+ : s.mode === 'local' ? 'πŸ”’ Local: nothing is sent to any model from this project β€” here, from the CLIs or from an agent.'
1206
+ : s.mode === 'agent' ? 'πŸ€– Agent: repairs at or above ' + Math.round(s.minConfidence * 100) + '/100 may be committed onto a new branch. Everything else stays a suggestion.'
1207
+ : '';
1208
+ note('aiModeNotice', modeLine, s.error ? 'bad' : s.mode === 'local' ? 'ok' : '');
1209
+ const cur = q('aiCurrent');
1210
+ if (!s.setUp) note('aiCurrent', 'Set the project up first (Tour tab) β€” the model reads what the tour captured.', '');
1211
+ else if (!s.configured) note('aiCurrent', '', '');
1212
+ else {
1213
+ const who = s.current.provider + ' Β· ' + s.current.model + (s.current.keyName ? ' Β· key from ' + s.current.keyName : '');
1214
+ note('aiCurrent', (s.local ? '🏠 ' + s.host + ' β€” on this machine, nothing leaves it. ' : s.host ? '🌐 ' + s.host + ' β€” ' : '⚠️ ' + (s.hostError || '') + ' ') + who + (s.same ? '' : String.fromCharCode(10) + '⚠️ The healing and discovery configs name different models. Saving here writes the same one to both.'), s.same && s.host ? 'ok' : '');
1215
+ }
1216
+ show('aiAskCard', s.configured && s.setUp && s.mode !== 'local' && !s.error);
1217
+ // The actions carry the mode (agent adds a button): drawn again when it changes.
1218
+ if (renderActions.mode !== s.mode) { q('aiActions').textContent = ''; renderActions.mode = s.mode; }
1219
+ if (s.configured) renderActions();
1220
+ renderReadings(ai.results);
1221
+ if (ai.job && ai.job.status === 'running') followAi();
1222
+ }
1223
+
1224
+ try { if (localStorage.getItem('palTab') === 'ai' || location.hash === '#ai') setTab(true); } catch {}
1225
+
897
1226
  refresh();
898
1227
  loadDecisions();
899
1228
  setInterval(refresh, 2000);
@@ -1 +1 @@
1
- {"version":3,"file":"page.js","sourceRoot":"","sources":["../../src/ui/page.ts"],"names":[],"mappings":";;AAoBA,8CAm3BC;AAv4BD,iEAAkE;AAElE,4FAA4F;AAC5F,kFAAkF;AAClF,MAAM,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAiB,CAAC;AAEhE;;;;;;;;;;;;;GAaG;AACH,SAAgB,iBAAiB,CAAC,KAAa;IAC7C,OAAO;;EAEP,IAAA,qBAAW,GAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6DAqG8C,OAAO,MAAM,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAuJ/D,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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probeBrowser, installChromium } from '../browser';
5
5
  import { installPalShortcut } from '../shortcut';
6
+ import type { AiEntries } from '../ai';
6
7
  /**
7
8
  * `ia-qa-pal ui` β€” launch a tour, follow it live, see what it found, manage who it runs as.
8
9
  *
@@ -56,6 +57,8 @@ export interface PalUiOptions {
56
57
  discoverEntry?: string;
57
58
  /** Injected so tests never write to a real desktop. */
58
59
  shortcut?: (dir: string) => ReturnType<typeof installPalShortcut>;
60
+ /** The BYOK CLIs the AI tab runs. Default: the installed heal-ai and discover-ai. */
61
+ aiEntries?: AiEntries;
59
62
  }
60
63
  /**
61
64
  * The setup answers a request may carry. Every one is a string the person typed, checked for its
@@ -136,6 +139,25 @@ export declare function missingAuthSecrets(dir: string, config: {
136
139
  * The decisions this console can take in place: `ambiguous` rows a test uses, with candidates it
137
140
  * can show. The rest (lost, rebound, no picture) are counted and left to heal's repair console.
138
141
  */
142
+ /**
143
+ * A model's reading of one row, as a card may show it: never a button of its own.
144
+ *
145
+ * On an `ambiguous` card it marks one of the choices β€” only when the element it named IS one of
146
+ * `decide`'s choices (`inChoices`); otherwise it is shown as a remark, since the model's shortlist
147
+ * is wider than the diff's and `decide` accepts nothing outside the diff. On a `lost` row it is
148
+ * information only (spec D1, option a): `decide` has no candidates for a lost row, so the edit
149
+ * stays the person's, at the `file:line` already shown.
150
+ */
151
+ export interface RowSuggestion {
152
+ selector: string;
153
+ name: string;
154
+ confidence: number;
155
+ rationale: string;
156
+ model: string;
157
+ at: string;
158
+ stale: boolean;
159
+ inChoices: boolean;
160
+ }
139
161
  export declare function decisionsView(dir: string): {
140
162
  actionable: Array<{
141
163
  page: string;
@@ -147,6 +169,7 @@ export declare function decisionsView(dir: string): {
147
169
  }>;
148
170
  candidates: unknown[];
149
171
  watchable: boolean;
172
+ suggestion?: RowSuggestion;
150
173
  }>;
151
174
  /** Gone from the page: never a button β€” either nothing to do, or the person's edit. */
152
175
  lost: Array<{
@@ -156,6 +179,7 @@ export declare function decisionsView(dir: string): {
156
179
  file: string;
157
180
  line: number;
158
181
  }>;
182
+ suggestion?: RowSuggestion;
159
183
  }>;
160
184
  others: number;
161
185
  reason?: string;
package/dist/ui/server.js CHANGED
@@ -60,6 +60,8 @@ const setup_1 = require("../setup");
60
60
  const browser_1 = require("../browser");
61
61
  const discovery_1 = require("../discovery");
62
62
  const shortcut_1 = require("../shortcut");
63
+ const ai_1 = require("../ai");
64
+ const self_healing_2 = require("@ia-qa/self-healing");
63
65
  /**
64
66
  * The setup answers a request may carry. Every one is a string the person typed, checked for its
65
67
  * type and nothing is added: `planSetup` (behind `runSetup`) is what validates them and what
@@ -249,17 +251,31 @@ function missingAuthSecrets(dir, config, usesSession) {
249
251
  .filter((c) => needed.has(c.name) && c.resolves === false)
250
252
  .map((c) => ({ name: c.name, key: keyOf.get(c.name) ?? c.name }));
251
253
  }
252
- /**
253
- * The decisions this console can take in place: `ambiguous` rows a test uses, with candidates it
254
- * can show. The rest (lost, rebound, no picture) are counted and left to heal's repair console.
255
- */
256
254
  function decisionsView(dir) {
257
255
  const { decisions, reason } = inProject(dir, () => (0, self_healing_1.listDecisions)());
258
256
  const actionable = decisions.filter((d) => d.status === 'ambiguous' && d.sites.length > 0 && d.candidates.length > 0);
259
257
  const lost = decisions.filter((d) => d.status === 'lost' && !d.rebound);
258
+ const ai = (0, ai_1.aiResults)(dir).suggest;
259
+ const suggestionFor = (d) => {
260
+ const s = ai?.suggestions.find((x) => x.page === d.page && x.selector === d.selector);
261
+ if (!ai || !s)
262
+ return undefined;
263
+ const selector = String(s.suggested_selector);
264
+ return {
265
+ selector,
266
+ name: String(s.suggested_name ?? ''),
267
+ confidence: Number(s.confidence ?? 0),
268
+ rationale: String(s.rationale ?? ''),
269
+ model: ai.model,
270
+ at: ai.at,
271
+ stale: ai.stale,
272
+ inChoices: d.candidates.some((c) => c.selector === selector),
273
+ };
274
+ };
275
+ const withSuggestion = (row, s) => (s ? { ...row, suggestion: s } : row);
260
276
  return {
261
- actionable: actionable.map((d) => ({ page: d.page, selector: d.selector, label: d.label, sites: d.sites.slice(0, 3), candidates: d.candidates, watchable: d.watchable === true })),
262
- lost: lost.map((d) => ({ page: d.page, label: d.label, sites: d.sites.slice(0, 3) })),
277
+ actionable: actionable.map((d) => withSuggestion({ page: d.page, selector: d.selector, label: d.label, sites: d.sites.slice(0, 3), candidates: d.candidates, watchable: d.watchable === true }, suggestionFor(d))),
278
+ lost: lost.map((d) => withSuggestion({ page: d.page, label: d.label, sites: d.sites.slice(0, 3) }, suggestionFor(d))),
263
279
  others: decisions.length - actionable.length - lost.length,
264
280
  ...(reason ? { reason } : {}),
265
281
  };
@@ -392,6 +408,11 @@ async function startPalUi(opts) {
392
408
  // A coverage map already on disk is shown on arrival; computing it reads files, no browser.
393
409
  void refreshCoverage().catch(() => { });
394
410
  let previewed = null;
411
+ // The AI tab: the digest of the last preview SHOWN per action β€” a send must carry it, and one
412
+ // approval is one send. One model run at a time.
413
+ const aiApproved = new Map();
414
+ let aiJob = null;
415
+ const aiEntries = opts.aiEntries ?? {};
395
416
  return (0, self_healing_1.startSecureServer)({
396
417
  port: opts.port,
397
418
  keepAlive: opts.keepAlive,
@@ -768,6 +789,93 @@ async function startPalUi(opts) {
768
789
  (0, self_healing_1.sendJson)(res, 'url' in opened ? 200 : 500, opened);
769
790
  return true;
770
791
  }
792
+ // ── AI suggestions (BYOK). Reading settings and results calls nothing; a preview runs the
793
+ // verb's own --dry-run (no key, no request); only /api/ai/send reaches a model, and only
794
+ // with the digest of a preview this console showed, re-checked against a fresh one.
795
+ if (get && url.pathname === '/api/ai') {
796
+ (0, self_healing_1.sendJson)(res, 200, { settings: (0, ai_1.aiSettings)(dir), results: (0, ai_1.aiResults)(dir), job: aiJob });
797
+ return true;
798
+ }
799
+ if (post && url.pathname === '/api/ai/settings') {
800
+ const out = (0, ai_1.writeAiSettings)(dir, await jsonBody(req));
801
+ // A new destination makes every earlier approval about somewhere else.
802
+ if (out.written)
803
+ aiApproved.clear();
804
+ (0, self_healing_1.sendJson)(res, out.written ? 200 : 400, out);
805
+ return true;
806
+ }
807
+ if (post && url.pathname === '/api/ai/mode') {
808
+ const out = (0, ai_1.writeAiMode)(dir, (await jsonBody(req)).mode);
809
+ if (out.written)
810
+ aiApproved.clear();
811
+ (0, self_healing_1.sendJson)(res, out.written ? 200 : 400, out);
812
+ return true;
813
+ }
814
+ if (post && (url.pathname === '/api/ai/preview' || url.pathname === '/api/ai/send')) {
815
+ const body = await jsonBody(req);
816
+ const action = ai_1.AI_ACTIONS.find((a) => a === body.action);
817
+ if (!action) {
818
+ (0, self_healing_1.sendJson)(res, 400, { ok: false, reason: `The action is one of ${ai_1.AI_ACTIONS.join(', ')}.` });
819
+ return true;
820
+ }
821
+ const busy = aiJob?.status === 'running'
822
+ ? 'A model run is still going β€” wait for its answer.'
823
+ : (0, run_1.activeRun)(dir)
824
+ ? 'A tour is running β€” it rewrites what the model would read. Wait for it to finish.'
825
+ : scanJob?.status === 'running'
826
+ ? 'A scan is running β€” it rewrites what the model would read. Wait for it to finish.'
827
+ : null;
828
+ if (busy) {
829
+ (0, self_healing_1.sendJson)(res, 409, { ok: false, reason: busy });
830
+ return true;
831
+ }
832
+ const fresh = (0, ai_1.previewAi)(dir, action, aiEntries);
833
+ if (url.pathname === '/api/ai/preview') {
834
+ if (fresh.ok)
835
+ aiApproved.set(action, fresh.preview.digest);
836
+ (0, self_healing_1.sendJson)(res, fresh.ok ? 200 : 409, fresh);
837
+ return true;
838
+ }
839
+ // Local mode is a lock: refused here in the same words as every other door, before the CLI
840
+ // would refuse it too.
841
+ const locked = (0, ai_1.localModeRefusal)(dir);
842
+ if (locked) {
843
+ (0, self_healing_1.sendJson)(res, 409, { ok: false, reason: locked });
844
+ return true;
845
+ }
846
+ // A commit onto a new branch is the person's choice of `agent` mode, never a request flag alone.
847
+ const onBranch = body.branch === true;
848
+ if (onBranch && (action !== 'suggest' || (0, self_healing_2.projectMode)(dir).mode !== 'agent')) {
849
+ (0, self_healing_1.sendJson)(res, 409, { ok: false, reason: 'Committing onto a new branch needs agent mode, and applies to repair suggestions only.' });
850
+ return true;
851
+ }
852
+ const shown = aiApproved.get(action);
853
+ if (!shown || body.digest !== shown) {
854
+ (0, self_healing_1.sendJson)(res, 409, { ok: false, reason: 'Nothing is sent without its preview: show what leaves first, then send.' });
855
+ return true;
856
+ }
857
+ if (!fresh.ok) {
858
+ (0, self_healing_1.sendJson)(res, 409, fresh);
859
+ return true;
860
+ }
861
+ if (fresh.preview.digest !== shown) {
862
+ aiApproved.delete(action);
863
+ (0, self_healing_1.sendJson)(res, 409, { ok: false, reason: 'What would leave has changed since the preview (a new capture, or a new setting). Look at it again before sending.' });
864
+ return true;
865
+ }
866
+ if (!fresh.preview.host) {
867
+ (0, self_healing_1.sendJson)(res, 409, { ok: false, reason: fresh.preview.hostError ?? 'No model is set up yet β€” choose one above.' });
868
+ return true;
869
+ }
870
+ if (fresh.preview.count === 0) {
871
+ (0, self_healing_1.sendJson)(res, 409, { ok: false, reason: 'Nothing to send.' });
872
+ return true;
873
+ }
874
+ aiApproved.delete(action);
875
+ aiJob = (0, ai_1.startAiJob)(dir, fresh.preview, aiEntries, undefined, onBranch);
876
+ (0, self_healing_1.sendJson)(res, 202, { ok: true, started: true });
877
+ return true;
878
+ }
771
879
  if (get && url.pathname === '/api/secrets') {
772
880
  (0, self_healing_1.sendJson)(res, 200, consoleSecrets(dir));
773
881
  return true;