opencode-azure-devops-pr-review 0.4.3 → 0.4.5

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/src/setup.mjs CHANGED
@@ -12,7 +12,7 @@ import { homedir } from 'node:os';
12
12
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
14
  import { createHash, randomUUID } from 'node:crypto';
15
- import { COMMANDS, MODES, SETTING_CHECKS, modelRef, modelSlots, patProblem, privateAgent, settingsText, validateSettings, withMissingSettings } from './config.mjs';
15
+ import { COMMANDS, MODES, REPOSITORY, SETTING_CHECKS, modelRef, modelSlots, patProblem, privateAgent, settingsText, validateSettings, withMissingSettings } from './config.mjs';
16
16
  import { parseUniqueJSON } from './output.mjs';
17
17
  import { appendReport } from './session.mjs';
18
18
  import { fetchTransportSupported, listOf, recordOf, requireMethods } from './host.mjs';
@@ -27,10 +27,14 @@ const SETUP_DESCRIPTION = 'Set up AZPR: organization, token, model; --help. In t
27
27
  const USAGE = '/pr-setup --organization ORG --model PROVIDER/MODEL [--pat-file "/absolute/path/to/pat"]';
28
28
  // How long setup waits for Azure DevOps when it checks a token: a person is waiting for the answer.
29
29
  const CHECK_TIMEOUT_MS = 20000;
30
- // How long a first setup waits for OpenCode to drop the commands that only said "setup required".
30
+ // How long a first setup waits for OpenCode to drop the commands that only said that AZPR is not ready.
31
31
  const RELEASE_WAIT_MS = 3000;
32
- // The commands of a process without usable settings: each only says what is missing.
33
- const PLACEHOLDER_DESCRIPTION = 'AZPR setup required; run /pr-setup';
32
+ // The commands of a process without usable settings: each only says that AZPR cannot run here yet. The words are
33
+ // true of every reason: no settings, settings that cannot be used, and settings that were saved elsewhere since
34
+ // (by a setup in another project directory, say) and wait for a restart. /pr-setup tells which it is.
35
+ const PLACEHOLDER_DESCRIPTION = 'AZPR is not ready here; run /pr-setup to see what it needs';
36
+ // Where every setting is described: the README is long, so its section is named, and linked for a terminal that opens links.
37
+ const SETTINGS_REFERENCE = `the README's section "All settings and defaults" (https://github.com/${REPOSITORY}#all-settings-and-defaults)`;
34
38
  const RESTART = 'restart the OpenCode service (in a terminal: opencode service restart; if you run opencode serve yourself, restart that process)';
35
39
  const MAX_SETTINGS_BYTES = 1024 * 1024;
36
40
  // A writer holds the setup lock for a few milliseconds. One this old was left behind by a process that
@@ -183,6 +187,9 @@ const PUBLISH_CONFIRMATION = { title: 'Post comments without a preview?', keep:
183
187
  * what a dialog starts with), takes an answer as a person gives it (`accept`: the value to save, or an
184
188
  * Error that says what is wrong without quoting the answer) and writes it (`set`). `flag` is its
185
189
  * /pr-setup option. The token has no option and is never part of `changes`: it travels alone.
190
+ * `hint` says what a row is for, where its name does not: the list shows it between the name and the value,
191
+ * which leaves room for a few words only. `prompt` and `variantPrompt` say more where there is room for it:
192
+ * in the search line of the dialog that lists the models, and of the one that lists a model's variants.
186
193
  */
187
194
  const ROWS = Object.freeze([
188
195
  { id: 'organization', flag: '--organization', group: 'Azure DevOps', label: 'Organization', kind: 'text', title: 'Azure DevOps organization', placeholder: 'my-organization',
@@ -201,13 +208,15 @@ const ROWS = Object.freeze([
201
208
  description: () => 'Only where a company proxy inspects HTTPS: the absolute path of its root CA certificate, a PEM file. Leave it empty and press Enter to skip.',
202
209
  get: raw => text(azureOf(raw).caFile), show: value => value ? shortPath(value) : 'none', current: value => value,
203
210
  accept: async (_context, answer) => caFileOf(answer), set: (raw, value) => withAzure(raw, { caFile: value }) },
204
- { id: 'reviewModel', flag: '--review-model', group: 'Models', label: 'Review model', kind: 'model', title: 'Model for /pr-review',
211
+ { id: 'reviewModel', flag: '--review-model', group: 'Models', label: 'Review model', kind: 'model', title: 'Model for /pr-review', hint: 'for /pr-review',
205
212
  get: raw => modelsOf(raw, 'review'), show: values => together(values, 'not set', 'differs by role'), current: values => shared(values) ?? '',
206
213
  accept: (context, answer) => modelOf(context, answer, false), set: (raw, value) => withModels(raw, 'review', value) },
207
- { id: 'quickModel', flag: '--quick-model', group: 'Models', label: 'Quick model', kind: 'model', title: 'Model for /pr-quick', optional: { label: 'Off', description: '/pr-quick stays off' },
214
+ { id: 'quickModel', flag: '--quick-model', group: 'Models', label: 'Quick model', kind: 'model', title: 'Model for /pr-quick', hint: 'for /pr-quick', optional: { label: 'Off', description: '/pr-quick stays off' },
208
215
  get: raw => modelsOf(raw, 'quick'), show: values => values[0] || 'off', current: values => values[0],
209
216
  accept: (context, answer) => modelOf(context, answer, true), set: (raw, value) => withModels(raw, 'quick', value) },
210
- { id: 'deepModel', flag: '--deep-model', group: 'Models', label: 'Deep model', kind: 'model', title: 'Stronger model for /pr-deep', optional: { label: 'Off', description: '/pr-deep stays off' },
217
+ { id: 'deepModel', flag: '--deep-model', group: 'Models', label: 'Deep model', kind: 'model', title: 'Model for /pr-deep', hint: 'for /pr-deep',
218
+ // /pr-deep is the same review with stronger models: another model, or the same one reasoning longer.
219
+ prompt: 'Stronger than the review model, or a higher variant', variantPrompt: 'A higher variant reasons longer', optional: { label: 'Off', description: '/pr-deep stays off' },
211
220
  get: raw => modelsOf(raw, 'deep'), show: values => together(values, 'off', 'differs by role'), current: values => shared(values) ?? '',
212
221
  accept: (context, answer) => modelOf(context, answer, true), set: (raw, value) => withModels(raw, 'deep', value) },
213
222
  { id: 'language', flag: '--language', group: 'Reviews', label: 'Output language', kind: 'choice', title: 'Language of reports and comments',
@@ -561,7 +570,8 @@ async function guide(context, path, problem, environment) {
561
570
  `3. Run ${USAGE}\n\n` +
562
571
  '--organization also takes a PR or organization URL. Without --pat-file, setup uses the default PAT file, or with --replace the PAT file already set. ' +
563
572
  'The selected model fills the three review roles and the quick reviewer. Deep remains unchanged (off for a new profile). Existing settings require --replace for these three options; other settings are kept. No model request or Azure request is made.\n\n' +
564
- `One setting of existing settings is changed without --replace: ${options.join(', ')}.\n\n` +
573
+ `One setting of existing settings is changed without --replace: ${options.join(', ')}. A model takes a variant as PROVIDER/MODEL#VARIANT. ` +
574
+ `--deep-model sets the models of /pr-deep, which runs the same review: choose a stronger model than the review model, or the same model with a higher variant. Every setting is described in ${SETTINGS_REFERENCE}.\n\n` +
565
575
  `A first setup is loaded at once. After a later change, ${RESTART}. Then run /pr-check <PR URL>. Settings changes do not affect reviews already running.`;
566
576
  }
567
577
 
@@ -717,13 +727,14 @@ function createSetupService({ context, path, environment, options, loaded, saved
717
727
  : previous === null ? 'required'
718
728
  : (await drifted(use)) ? 'restart' : 'ready';
719
729
  return { version: 1, state, problem: use.blocked ? use.problem : '', editable: raw !== null, fileProblem,
720
- settingsFile: path, settingsFileShown: shortPath(shownPath(path)), organization: text(azureOf(view).organization),
730
+ settingsFile: path, settingsFileShown: shortPath(shownPath(path)), settingsReference: SETTINGS_REFERENCE, organization: text(azureOf(view).organization),
721
731
  rows: ROWS.map(row => row.kind === 'secret'
722
732
  ? { id: row.id, group: row.group, label: row.label, kind: row.kind, title: row.title, description: `${row.description(view, environment)}${token.note ? ` ${token.note}` : ''}`, value: token.shown, saved: token.saved,
723
733
  // Whether the settings name a token at all, usable or not: another organization then needs one of its own.
724
734
  bound: Boolean(text(azureOf(view).patFile) || text(azureOf(view).pat)) }
725
735
  : { id: row.id, group: row.group, label: row.label, kind: row.kind, title: row.title, value: row.show(row.get(view)), current: row.current(row.get(view)),
726
736
  ...(row.description ? { description: row.description(view, environment) } : {}), ...(row.placeholder ? { placeholder: row.placeholder } : {}),
737
+ ...(row.hint ? { hint: row.hint } : {}), ...(row.prompt ? { prompt: row.prompt } : {}), ...(row.variantPrompt ? { variantPrompt: row.variantPrompt } : {}),
727
738
  ...(row.optional ? { optional: row.optional } : {}), ...(row.choices ? { choices: row.choices } : {}), ...(row.other ? { other: row.other } : {}) }) };
728
739
  }
729
740
 
@@ -948,7 +959,7 @@ export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, t
948
959
  if (catalog.some(command => reserved.includes(command.name))) throw new Error('[AZPR] Reserved command name conflict; resolve it before loading AZPR.');
949
960
  let cleanup, placeholders, activating, rpc, closed = false;
950
961
  // What changes this plugin's review commands runs one after another: the load of a first setup, which
951
- // takes the commands that say "setup required" away and registers the runtime's, and putting those commands
962
+ // takes the commands that say that AZPR is not ready away and registers the runtime's, and putting those commands
952
963
  // back. Neither sees the other half done, and what one read of the host is not older than the other's work.
953
964
  let lane = Promise.resolve();
954
965
  const inLane = job => {
@@ -961,7 +972,7 @@ export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, t
961
972
  const turn = { busy: false };
962
973
  /**
963
974
  * The review command names that another plugin has by now: what is listed under one of them and is not a
964
- * command that only says "setup required". Asked right before those commands are registered, since a
975
+ * command that only says that AZPR is not ready. Asked right before those commands are registered, since a
965
976
  * plugin can take a name at any moment. Null where the host does not answer: nothing is known then, and
966
977
  * what was known earlier is not.
967
978
  */
@@ -1015,7 +1026,7 @@ export async function setupPlugin(context, sourceDirectory = SOURCE_DIRECTORY, t
1015
1026
  use.loadProblem = '';
1016
1027
  return false;
1017
1028
  }
1018
- // The runtime refuses command names that exist: the commands that only said "setup required" go first.
1029
+ // The runtime refuses command names that exist: the commands that only said that AZPR is not ready go first.
1019
1030
  await placeholders?.dispose();
1020
1031
  placeholders = undefined;
1021
1032
  // The host may list them a moment longer. What is listed under a review command's name and is not one
@@ -0,0 +1,239 @@
1
+ // What a person can do from AZPR's terminal panel. After a review or a comment preview: have the comments
2
+ // previewed, post the preview, leave findings out or change a level, reset those adjustments. While a run is
3
+ // under way: stop it. The panel lists these in one row at its foot; picking one asks what is needed in the
4
+ // host's own dialogs and then sends the same command a person would type, /pr-comment or /pr-stop, to the
5
+ // session on screen. Nothing else is ever sent from the terminal part, and nothing is decided here: the server
6
+ // part takes the command as it takes a typed one, with its own checks, its notices and its receipt.
7
+ //
8
+ // What is offered comes from the runtime, in the metadata of the notice that offers it (`previewActions` in
9
+ // comments.mjs for a review or a preview; the run's ID with its STARTED notice), and is checked before it gets
10
+ // here (`nextOf` and `stopOf` in tui-model.mjs): a command is made only of a review ID, finding IDs, level
11
+ // names and the word for the review's comments, or of a run ID, all of the checked forms, never of a text.
12
+ // Every /pr-comment command hands that word back (`--seen`): a notice shows what its own conversation was
13
+ // told, and the runtime refuses a command whose review was planned or adjusted since, from wherever. /pr-stop
14
+ // names its run, and a run that has ended is not stopped.
15
+ //
16
+ // Nothing here imports anything, so that the order of the dialogs is tested with scripted answers
17
+ // (tests/tui-actions.test.mjs); src/tui-view.jsx supplies the dialogs and the sending.
18
+
19
+ const LEVELS = ['high', 'medium', 'low'];
20
+ const APPLY = '\u0000apply', EXCLUDE = '\u0000exclude';
21
+ // The key that applies the adjustments from the list of findings, at the foot of that dialog. Letters go to the
22
+ // dialog's search line, so it is a chord; OpenCode binds nothing to this one.
23
+ const APPLY_KEY = 'ctrl+s';
24
+ // Said when a person's answer comes back for something the panel no longer offers.
25
+ const CHANGED = 'Nothing was sent: what the panel showed has changed since. Read it again, then pick.';
26
+
27
+ /**
28
+ * How the rows of a question answer to what is typed into its search line: by the beginning of their titles, in
29
+ * the order they are listed, and all of them while nothing is typed. The host's own search finds a letter
30
+ * anywhere in a title and lists the best match first. A step's key pressed once more than meant is typed into
31
+ * the question it opened, and `s` is in "Yes, stop it" and not in "No, let it run": "yes" would be the only
32
+ * row, and Enter would take it. By the beginning of a title, a stray letter leaves no row at all.
33
+ */
34
+ const byBeginning = (query, options) => {
35
+ const typed = String(query ?? '').trim().toLowerCase();
36
+ return typed ? options.filter(option => String(option.title).toLowerCase().startsWith(typed)) : [...options];
37
+ };
38
+
39
+ /** The level the review itself gave a finding. */
40
+ const own = finding => finding.original ?? finding.severity;
41
+ const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
42
+
43
+ /**
44
+ * What the panel lists for what a notice offers, in the order it is shown; nothing without an offer. `key`
45
+ * picks one while the panel has the keyboard. A label that ends in "…" asks before anything is sent; one that
46
+ * does not is sent at once. `primary` marks the step the others lead to.
47
+ */
48
+ export function actionRows(next) {
49
+ if (!next) return [];
50
+ // A run under way offers one thing. It is asked about first, and it is not the step anything leads to.
51
+ if (next.stop) return [{ id: 'stop', key: 's', label: 'Stop this run…' }];
52
+ const adjusted = next.findings.some(finding => finding.excluded || finding.original !== undefined);
53
+ return [
54
+ // A review without a preview yet: one is planned first, so that what is posted was read. A model runs,
55
+ // and nothing is posted.
56
+ ...(next.plan ? [{ id: 'plan', key: 'c', label: 'Preview comments', primary: true }] : []),
57
+ ...(next.publish ? [{ id: 'publish', key: 'p', label: `Post ${plural(next.posts, 'comment')}…`, primary: true }] : []),
58
+ ...(next.adjust && next.findings.length ? [{ id: 'adjust', key: 'a', label: 'Adjust findings…' }] : []),
59
+ // Both lists are cleared at once, which is more than the last step undone.
60
+ ...(next.adjust && adjusted ? [{ id: 'reset', key: 'u', label: 'Reset adjustments' }] : []),
61
+ ];
62
+ }
63
+
64
+ /** The adjustments a preview was planned with: the findings left out, and the levels that differ from the review's. */
65
+ export function savedAdjustments(next) {
66
+ return {
67
+ excluded: new Set(next.findings.filter(finding => finding.excluded).map(finding => finding.id)),
68
+ levels: new Map(next.findings.filter(finding => !finding.excluded && finding.original !== undefined).map(finding => [finding.id, finding.severity])),
69
+ };
70
+ }
71
+
72
+ const sameAdjustments = (a, b) => a.excluded.size === b.excluded.size && [...a.excluded].every(id => b.excluded.has(id)) &&
73
+ a.levels.size === b.levels.size && [...a.levels].every(([id, level]) => b.levels.get(id) === level);
74
+
75
+ /** What every command ends with: the word for the review's comments as they were offered. */
76
+ const seen = next => `--seen ${next.state}`;
77
+ /** The command that plans a preview of a review's comments; a model runs and nothing is posted. */
78
+ export const planCommand = next => ({ name: 'pr-comment', text: `${next.review} ${seen(next)}` });
79
+ /**
80
+ * The command that posts a preview. It names its review and the preview that was shown: what is on screen is
81
+ * what is posted, whatever is current by then and whatever was planned since.
82
+ */
83
+ export const publishCommand = next => ({ name: 'pr-comment', text: `${next.review} --publish ${seen(next)}` });
84
+ /** The command that clears a person's adjustments. */
85
+ export const resetCommand = next => ({ name: 'pr-comment', text: `${next.review} --reset ${seen(next)}` });
86
+ /** The command that stops the run under way. It names the run, so it stops no other one. */
87
+ export const stopCommand = next => ({ name: 'pr-stop', text: next.stop });
88
+
89
+ /**
90
+ * The command that saves `adjustments` for a preview's review, or undefined when they are the saved ones.
91
+ * Each list of /pr-comment replaces the saved one, so both are always given in full, in the order of the
92
+ * findings; a finding that is left out has no level.
93
+ */
94
+ export function adjustCommand(next, adjustments) {
95
+ // As they would be saved: only findings of this preview, no level for one that is left out, and no level that
96
+ // is the review's own.
97
+ const excluded = next.findings.filter(finding => adjustments.excluded.has(finding.id)).map(finding => finding.id);
98
+ const levels = next.findings.filter(finding => !adjustments.excluded.has(finding.id) && adjustments.levels.has(finding.id) && adjustments.levels.get(finding.id) !== own(finding))
99
+ .map(finding => [finding.id, adjustments.levels.get(finding.id)]);
100
+ if (sameAdjustments({ excluded: new Set(excluded), levels: new Map(levels) }, savedAdjustments(next))) return undefined;
101
+ if (!excluded.length && !levels.length) return resetCommand(next);
102
+ return { name: 'pr-comment', text: `${next.review} --exclude ${excluded.join(',') || 'none'} --severity ${levels.map(([id, level]) => `${id}=${level}`).join(',') || 'none'} ${seen(next)}` };
103
+ }
104
+
105
+ /** What changes, in a few words, for the row that applies it. */
106
+ function describeChanges(next, adjustments) {
107
+ const saved = savedAdjustments(next), parts = [];
108
+ for (const finding of next.findings) {
109
+ const out = adjustments.excluded.has(finding.id), was = saved.excluded.has(finding.id);
110
+ const level = out ? undefined : adjustments.levels.get(finding.id) ?? own(finding), before = was ? undefined : saved.levels.get(finding.id) ?? own(finding);
111
+ if (out && !was) parts.push(`${finding.id} left out`);
112
+ else if (!out && was) parts.push(`${finding.id} published${level === own(finding) ? '' : ` as ${level}`}`);
113
+ else if (!out && level !== before) parts.push(`${finding.id} as ${level}`);
114
+ }
115
+ return parts.length > 4 ? `${parts.slice(0, 4).join(', ')} and ${parts.length - 4} more` : parts.join(', ');
116
+ }
117
+
118
+ /**
119
+ * The panel's actions. `host.dialog` is the host's dialogs, `host.toast` its toasts and `host.send(sessionID,
120
+ * command)` sends one command, `{ name, text }`, to a session and resolves when the server took it.
121
+ * One action runs at a time; after `stop()` nothing is asked or sent, whatever answer arrives.
122
+ *
123
+ * An action is for what the panel offered when it was picked. `still()`, which the panel gives with each one,
124
+ * says whether that is still so: the same panel, open in the same session, showing the same notice's offer. A
125
+ * dialog can stay open for any time, and a preview can be planned again meanwhile: an answer that comes back
126
+ * for something else is said, and nothing is sent.
127
+ */
128
+ export function createActions(host) {
129
+ const { dialog, toast, send } = host;
130
+ let running = false, stopped = false;
131
+ const changed = () => { if (!stopped) toast({ title: 'AZPR', message: CHANGED, variant: 'warning', duration: 8000 }); };
132
+
133
+ /**
134
+ * Send one command. One that the server part refuses (another command is running, the review is no longer
135
+ * kept) or that does not get there is said with the reason given, as the host says it for a typed command:
136
+ * nothing else would tell. The reason is the server's own text, on one line and cut to what a toast holds.
137
+ */
138
+ async function dispatch(sessionID, command, still) {
139
+ if (stopped) return false;
140
+ if (!still()) { changed(); return false; }
141
+ try { await send(sessionID, command); return true; }
142
+ catch (error) {
143
+ const reason = String(error?.message ?? error ?? '').replace(/\s+/g, ' ').trim().slice(0, 300);
144
+ if (!stopped) toast({ title: 'AZPR', message: `/${command.name} was not started${reason ? `: ${reason}` : '.'}`, variant: 'error', duration: 10000 });
145
+ return false;
146
+ }
147
+ }
148
+
149
+ /** Posting is asked once more, with "no" first: a key pressed twice, or more often, posts nothing. */
150
+ async function publish(next, sessionID, still) {
151
+ const answer = await dialog.select({ title: 'Post these comments on the pull request?', search: byBeginning, options: [
152
+ { title: 'No, post nothing', value: 'keep', description: next.target || undefined },
153
+ { title: `Yes, post ${plural(next.posts, 'comment')}`, value: 'post', description: 'As the PAT owner; what is on the PR already is skipped' }] });
154
+ if (answer !== 'post' || stopped) return;
155
+ await dispatch(sessionID, publishCommand(next), still);
156
+ }
157
+
158
+ /** Stopping is asked once more, with "no" first: the run goes on unless a person says otherwise. */
159
+ async function stopRun(next, sessionID, still) {
160
+ const answer = await dialog.select({ title: 'Stop this run?', search: byBeginning, options: [
161
+ { title: 'No, let it run', value: 'keep', description: `AZPR ${next.stop}${next.command ? ` (/${next.command})` : ''}` },
162
+ { title: 'Yes, stop it', value: 'stop', description: 'Sent requests may still be billed' }] });
163
+ if (answer !== 'stop' || stopped) return;
164
+ await dispatch(sessionID, stopCommand(next), still);
165
+ }
166
+
167
+ /**
168
+ * The findings as a list: picking one says what happens to it. Once something differs from what is saved, it is
169
+ * applied at once from the foot of the dialog, which stays in view however long the list is (clicked there, or
170
+ * with its key), and from the list's last row, for a host that draws no such foot. Escape leaves everything as
171
+ * it was.
172
+ */
173
+ async function adjust(next, sessionID, still) {
174
+ const adjustments = savedAdjustments(next);
175
+ let last;
176
+ for (;;) {
177
+ if (stopped) return;
178
+ if (!still()) return changed();
179
+ const command = adjustCommand(next, adjustments);
180
+ // The foot's action does not close the dialog, so it is closed here; its answer is this promise's, since
181
+ // a dialog that is closed answers nothing. It acts once, and only while this list is the dialog that is
182
+ // open: `clear` closes whatever dialog is open at that moment.
183
+ let apply, listed = true;
184
+ const applied = new Promise(resolve => { apply = resolve; });
185
+ const foot = command && typeof dialog.clear === 'function'
186
+ ? [{ bind: APPLY_KEY, title: 'apply', side: 'right', selection: 'none', onTrigger: () => { if (!listed) return; listed = false; apply(APPLY); dialog.clear(); } }] : undefined;
187
+ const choice = await Promise.race([applied, dialog.select({ title: 'Adjust the findings before posting', placeholder: 'Search findings', current: last, options: [
188
+ ...next.findings.map(finding => {
189
+ const level = adjustments.levels.get(finding.id) ?? own(finding);
190
+ return { title: `${finding.id}${finding.summary ? ` — ${finding.summary}` : ''}`, value: finding.id, category: 'Findings',
191
+ footer: adjustments.excluded.has(finding.id) ? 'left out' : level === own(finding) ? level : `${level} (was ${own(finding)})` };
192
+ }),
193
+ ...(command ? [{ title: next.plan ? 'Apply, and plan the preview' : 'Apply, and plan the preview again', value: APPLY, description: describeChanges(next, adjustments), category: 'Then' }] : [])],
194
+ ...(foot ? { actions: foot } : {}) })]);
195
+ listed = false;
196
+ if (choice === undefined || stopped) return;
197
+ // The list was open for any time. What it was opened for may be gone by now: nothing more is asked then,
198
+ // and nothing is applied.
199
+ if (!still()) return changed();
200
+ if (choice === APPLY) { await dispatch(sessionID, command, still); return; }
201
+ const finding = next.findings.find(item => item.id === choice);
202
+ if (!finding) return;
203
+ last = choice;
204
+ const level = adjustments.levels.get(finding.id) ?? own(finding);
205
+ const picked = await dialog.select({ title: `${finding.id}: how is it published?`, current: adjustments.excluded.has(finding.id) ? EXCLUDE : level, options: [
206
+ ...LEVELS.map(name => ({ title: `As ${name}`, value: name, description: name === own(finding) ? 'The level the review gave it' : undefined })),
207
+ { title: 'Leave it out', value: EXCLUDE, description: 'Not posted, and named in no comment' }] });
208
+ if (picked === undefined) continue;
209
+ if (picked === EXCLUDE) { adjustments.excluded.add(finding.id); adjustments.levels.delete(finding.id); continue; }
210
+ if (!LEVELS.includes(picked)) continue;
211
+ adjustments.excluded.delete(finding.id);
212
+ if (picked === own(finding)) adjustments.levels.delete(finding.id); else adjustments.levels.set(finding.id, picked);
213
+ }
214
+ }
215
+
216
+ return {
217
+ /**
218
+ * Run one action (`plan`, `publish`, `adjust`, `reset` or `stop`) for what a notice offers, in the session
219
+ * on screen. `still` says whether the panel still offers it there; without one it is taken to.
220
+ */
221
+ async run(id, next, sessionID, still = () => true) {
222
+ if (running || stopped || !next || typeof sessionID !== 'string' || !actionRows(next).some(row => row.id === id)) return;
223
+ running = true;
224
+ try {
225
+ if (id === 'plan') await dispatch(sessionID, planCommand(next), still);
226
+ else if (id === 'publish') await publish(next, sessionID, still);
227
+ else if (id === 'adjust') await adjust(next, sessionID, still);
228
+ else if (id === 'reset') await dispatch(sessionID, resetCommand(next), still);
229
+ else if (id === 'stop') await stopRun(next, sessionID, still);
230
+ } catch {
231
+ // A dialog the host could not show: nothing was sent, and the commands can still be typed.
232
+ if (!stopped) toast({ title: 'AZPR', message: 'That could not be done here. Type the command in the conversation instead.', variant: 'error', duration: 8000 });
233
+ } finally { running = false; }
234
+ },
235
+ get running() { return running; },
236
+ /** The terminal part is being unloaded: an action that is open ends at its next step, and nothing is sent after it. */
237
+ stop() { stopped = true; },
238
+ };
239
+ }
package/src/tui-model.mjs CHANGED
@@ -6,9 +6,11 @@
6
6
  *
7
7
  * The panel never sends a prompt, never reads AZPR's settings file and never
8
8
  * decides anything about a review. It only reads texts whose form the runtime
9
- * owns (attribution.mjs, runtime.mjs) and the one setting meant for it, which
10
- * the runtime sends along with its notices; tests/tui-model.test.mjs holds
11
- * that form.
9
+ * owns (attribution.mjs, runtime.mjs) and what the runtime sends along with
10
+ * its notices: the one setting meant for it, and what a notice offers as a
11
+ * next step (`nextOf` for a review or a preview, `stopOf` for a run under
12
+ * way), which the rows of tui-actions.mjs turn into the command a person
13
+ * picks. tests/tui-model.test.mjs holds that form.
12
14
  */
13
15
 
14
16
  /** The panel's name in the host's `session.panel` slot; names are shared between plugins. */
@@ -25,9 +27,14 @@ const REPORT_SESSION = new RegExp(`Report delivery: report queued to session=(${
25
27
  const ACTS_ON = / It acts on review ([a-f0-9]{8}) /;
26
28
  const SOURCE_REVIEW = /; source review=([a-f0-9]{8})/;
27
29
  const RUN_STARTED = /^\[AZPR [a-f0-9]{8}\] STARTED \/pr-(?:review|quick|deep|comment)\b/;
30
+ // The command a STARTED notice names, of those that start a run (a check is one, though it opens no panel).
31
+ const STARTED_COMMAND = /^\[AZPR [a-f0-9]{8}\] STARTED \/(pr-(?:review|quick|deep|comment|check))\b/;
28
32
  // A run's receipt: its status, then `;`, a line break or the end. Text follows STARTED and PROGRESS, and a run
29
33
  // also says things that are neither (`[AZPR <run>] Automatic preview skipped: …`).
30
34
  const RECEIPT = /^\[AZPR [a-f0-9]{8}\] [A-Z_]+(?:;|\n|$)/;
35
+ // The receipt of a comment run whose preview another command replaced before it could be shown: the run has
36
+ // ended, but what it planned is not what happened last.
37
+ const REPLACED = 'REPLACED';
31
38
  const REPORT_HEAD = '# AZPR ';
32
39
  // `/pr-comment [review] --show` answers at once with a review's saved preview, and names the review.
33
40
  const SAVED_PREVIEW = /^\[AZPR\] Saved preview of review ([a-f0-9]{8})\b/;
@@ -74,6 +81,8 @@ const enclosedIn = text => {
74
81
  /** The text of a delivered message, or of a notice that still waits in a session's inbox. */
75
82
  export const textOf = entry =>
76
83
  typeof entry?.text === 'string' ? entry.text : typeof entry?.payload?.text === 'string' ? entry.payload.text : typeof entry?.description === 'string' ? entry.description : '';
84
+ /** What the runtime stored with a notice for clients that read it; a message has it itself, an inbox item in its payload. */
85
+ const metadataOf = entry => entry?.metadata ?? entry?.payload?.metadata;
77
86
 
78
87
  /**
79
88
  * A session's synthetic entries, oldest first: delivered messages and what its
@@ -84,21 +93,21 @@ export const textOf = entry =>
84
93
  export function syntheticOf(messages, pending) {
85
94
  const entries = new Map();
86
95
  for (const entry of [...(messages ?? []), ...(pending ?? [])]) {
87
- if (entry?.type === 'synthetic' && typeof entry.id === 'string') entries.set(entry.id, textOf(entry));
96
+ if (entry?.type === 'synthetic' && typeof entry.id === 'string') entries.set(entry.id, { text: textOf(entry), ...(metadataOf(entry) === undefined ? {} : { metadata: metadataOf(entry) }) });
88
97
  }
89
98
  // Message and inbox IDs sort by creation time.
90
- return [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([id, text]) => ({ id, text }));
99
+ return [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([id, entry]) => ({ id, ...entry }));
91
100
  }
92
101
 
93
102
  /** AZPR's notices among a session's synthetic entries. */
94
103
  export function noticesOf(entries) {
95
- return entries.flatMap(({ id, text }) => {
104
+ return entries.flatMap(({ id, text, metadata }) => {
96
105
  const head = HEAD.exec(text);
97
106
  if (!head) return [];
98
107
  const [, run, status = ''] = head;
99
108
  // NOTE: something a run says besides its start, its progress and its receipt; it changes nothing shown.
100
109
  const kind = !run ? 'ANSWER' : status === 'STARTED' ? 'STARTED' : status === 'PROGRESS' ? 'PROGRESS' : RECEIPT.test(text) ? 'RECEIPT' : 'NOTE';
101
- return [{ id, run, kind, status: kind === 'NOTE' ? '' : status, text }];
110
+ return [{ id, run, kind, status: kind === 'NOTE' ? '' : status, text, ...(metadata === undefined ? {} : { metadata }) }];
102
111
  });
103
112
  }
104
113
 
@@ -159,6 +168,45 @@ export function readable(markdown) {
159
168
  return shown.join('\n');
160
169
  }
161
170
 
171
+ const REVIEW_ID = /^[a-f0-9]{8}$/;
172
+ // The word for what the review's comments were when the step was offered; the commands hand it back (--seen).
173
+ const STATE = /^[a-f0-9]{12}$/;
174
+ const FINDING_ID = /^[A-Z]+-\d+$/;
175
+ const LEVELS = ['high', 'medium', 'low'];
176
+
177
+ /**
178
+ * What a preview's notice offers next, as the runtime stored it with the notice (`azpr.next`; see
179
+ * `previewActions` in comments.mjs), or undefined. Every value is checked here, since commands are made of
180
+ * them: the review, the word for its comments (`state`) and each finding by their form, each level by name. A
181
+ * summary is the review's own text and is only ever shown. Anything that is not as expected makes the whole of
182
+ * it nothing: a person then types the commands, as the receipt says them. That includes an offer without the
183
+ * word, which an earlier version left: its commands could not say what they were picked for.
184
+ */
185
+ export function nextOf(metadata, review) {
186
+ const next = metadata?.azpr?.next;
187
+ if (next === null || typeof next !== 'object' || !REVIEW_ID.test(next.review ?? '') || next.review !== review || !STATE.test(next.state ?? '') || !Array.isArray(next.findings)) return undefined;
188
+ const findings = [];
189
+ for (const finding of next.findings) {
190
+ if (finding === null || typeof finding !== 'object' || !FINDING_ID.test(finding.id ?? '') || !LEVELS.includes(finding.severity) ||
191
+ (finding.original !== undefined && !LEVELS.includes(finding.original)) || findings.some(other => other.id === finding.id)) return undefined;
192
+ findings.push({ id: finding.id, severity: finding.severity, ...(finding.original === undefined || finding.original === finding.severity ? {} : { original: finding.original }),
193
+ excluded: finding.excluded === true, summary: typeof finding.summary === 'string' ? finding.summary.replace(/\s+/g, ' ').trim().slice(0, 160) : '' });
194
+ }
195
+ return { review: next.review, state: next.state, target: typeof next.target === 'string' ? next.target.replace(/\s+/g, ' ').trim().slice(0, 200) : '',
196
+ plan: next.plan === true, publish: next.publish === true && next.plan !== true, adjust: next.adjust === true, posts: Number.isInteger(next.posts) && next.posts >= 0 ? next.posts : 0, findings };
197
+ }
198
+
199
+ /**
200
+ * The run a STARTED notice says can be stopped, as the runtime stored it with the notice (`azpr.next.stop`), or
201
+ * undefined. A command is made of it, so it is checked like the rest: by its form, and as the ID of the very run
202
+ * the notice starts. A notice of an earlier version says nothing of it, and its run is stopped by typing.
203
+ */
204
+ export function stopOf(metadata, run) {
205
+ const stop = metadata?.azpr?.next?.stop;
206
+ // A run's ID has the form of a review's: a review is named after the run that made it.
207
+ return typeof stop === 'string' && REVIEW_ID.test(stop) && stop === run ? stop : undefined;
208
+ }
209
+
162
210
  /** Whether a failed request says that the session is not there, as opposed to a request that did not get through. */
163
211
  export const notFound = error => /NotFound|\b404\b/.test(String(error?.name ?? '') + String(error?._tag ?? '') + String(error));
164
212
 
@@ -463,17 +511,24 @@ export function buildPanel(source, sessionID, { known = {}, read = {}, titles =
463
511
  // What the panel is about is what happened last: a run that started, progressed or ended, or a saved preview
464
512
  // shown again, which names its review. What a run says besides (a review's note that no preview follows can
465
513
  // arrive after the next run started) changes nothing, and neither does an answer without a document.
466
- const subject = notices.findLast(notice => (notice.run && notice.kind !== 'NOTE') || (notice.kind === 'ANSWER' && SAVED_PREVIEW.test(notice.text) && encloses(notice.text)));
514
+ // A run that ended REPLACED has a receipt, so that a panel which shows it running sees it end, but that
515
+ // receipt is not what happened last: the command that replaced its preview is, wherever it was answered.
516
+ const subject = notices.findLast(notice => (notice.run && notice.kind !== 'NOTE' && notice.status !== REPLACED) || (notice.kind === 'ANSWER' && SAVED_PREVIEW.test(notice.text) && encloses(notice.text)));
467
517
  const answered = subject?.kind === 'ANSWER' ? SAVED_PREVIEW.exec(subject.text)[1] : undefined;
518
+ // What can be done next is said by the notice that happened last: the receipt of a preview, the saved preview
519
+ // shown again, or the receipt of a review that no preview follows by itself. Once anything follows it (a run
520
+ // that starts, another receipt) it is offered no more.
521
+ const offering = subject?.kind === 'ANSWER' || (subject?.kind === 'RECEIPT' && ['PREVIEW', 'COMPLETE'].includes(subject.status)) ? subject : undefined;
468
522
  // A saved preview shown again is about its review: that review's status, sessions and report session.
469
523
  const run = answered ?? subject?.run;
470
524
  const ofRun = notices.filter(notice => notice.run === run && notice.kind !== 'NOTE');
471
525
  const receipt = ofRun.findLast(notice => notice.kind === 'RECEIPT');
472
526
  const progress = ofRun.findLast(notice => notice.kind === 'PROGRESS');
527
+ const started = ofRun.find(notice => notice.kind === 'STARTED');
473
528
  const status = receipt ? receipt.status : run && !answered ? 'RUNNING' : '';
474
529
  // A comment run belongs with the review it acts on: that review's sessions and report stay in view.
475
530
  // Any other run stands alone, so a review under way never shows the report of the review before it.
476
- const reviewRun = SOURCE_REVIEW.exec(receipt?.text.split('\n')[0] ?? '')?.[1] ?? ACTS_ON.exec(ofRun.find(notice => notice.kind === 'STARTED')?.text ?? '')?.[1] ?? run;
531
+ const reviewRun = SOURCE_REVIEW.exec(receipt?.text.split('\n')[0] ?? '')?.[1] ?? ACTS_ON.exec(started?.text ?? '')?.[1] ?? run;
477
532
  const review = reviewRun === run ? receipt : notices.findLast(notice => notice.kind === 'RECEIPT' && notice.run === reviewRun);
478
533
  const reportSession = REPORT_SESSION.exec(ledgerOf(review?.text ?? ''))?.[1];
479
534
 
@@ -521,6 +576,16 @@ export function buildPanel(source, sessionID, { known = {}, read = {}, titles =
521
576
  const azpr = session?.metadata?.azpr;
522
577
  if (azpr?.conversation === conversation && azpr.run !== undefined && runs.has(azpr.run)) candidates.add(session.id);
523
578
  }
579
+ // What a notice offers goes with the document it encloses: a review's receipt encloses a report and offers a
580
+ // preview of it, a preview's receipt and a saved preview shown again offer what is done with that preview.
581
+ // `offer` names the notice, so that a row that was picked is acted on only while that notice still offers.
582
+ const checked = offering ? nextOf(offering.metadata, answered ?? reviewRun) : undefined;
583
+ const offered = checked && checked.plan === (offering.kind === 'RECEIPT' && offering.status === 'COMPLETE') ? { ...checked, offer: offering.id } : undefined;
584
+ // A run under way can be stopped, as its STARTED notice says: from that notice until the run's receipt, whatever
585
+ // progress it reports in between. It names its command (the runtime's own word, one of a fixed few) for the
586
+ // question that is asked first, and its notice, like every offer.
587
+ const stoppable = status === 'RUNNING' && started ? stopOf(started.metadata, run) : undefined;
588
+ const halting = stoppable ? { stop: stoppable, command: STARTED_COMMAND.exec(started.text)?.[1] ?? '', offer: started.id } : undefined;
524
589
  const rows = [];
525
590
  let deleted = 0;
526
591
  for (const id of candidates) {
@@ -540,7 +605,10 @@ export function buildPanel(source, sessionID, { known = {}, read = {}, titles =
540
605
  rows.push({
541
606
  id,
542
607
  label: titles.get(id) ?? (stage ? `${stage.role}${stage.label ? ` ${stage.label}` : ''}` : azpr?.role ?? id),
543
- state: source.status(id) === 'running' ? 'running' : stage ? stage.state.toLowerCase() : 'idle',
608
+ // What a receipt says of a stage is its result. Until the run's receipt names it, a session whose model is
609
+ // not at work has finished what it was asked: the host calls that idle, which reads like a fault. (A session
610
+ // a receipt does not name stays "finished": one of a comment run, kept by debug.enabled.)
611
+ state: source.status(id) === 'running' ? 'running' : stage ? stage.state.toLowerCase() : 'finished',
544
612
  report: id === reportSession && belongs(info, conversation, reviewRun),
545
613
  current: azpr?.run === run,
546
614
  });
@@ -558,6 +626,9 @@ export function buildPanel(source, sessionID, { known = {}, read = {}, titles =
558
626
  // A report read from its session says its run and status in its own first line; an enclosed document is named by
559
627
  // the notice that encloses it.
560
628
  documentHead: own || document?.session ? '' : document?.head ?? '',
629
+ // What can be done next: the steps a review or a preview offers, for the review shown, or stopping the run
630
+ // under way. Absent once another notice has followed the one that offers, or the run has its receipt.
631
+ ...(offered ? { next: offered } : halting ? { next: halting } : {}),
561
632
  inbox,
562
633
  notices: notes,
563
634
  loading,
package/src/tui-setup.mjs CHANGED
@@ -128,13 +128,14 @@ export function createSetup(host) {
128
128
  return undefined;
129
129
  }
130
130
  const current = baseModel(row.current);
131
- const picked = await dialog.select({ title: row.title, placeholder: 'Search models', current: row.optional && !current ? '' : current || undefined,
131
+ // Where a row says what to look for (the deep model: a stronger one, or a higher variant), the search line says it.
132
+ const picked = await dialog.select({ title: row.title, placeholder: text(row.prompt) || 'Search models', current: row.optional && !current ? '' : current || undefined,
132
133
  options: [...(row.optional ? [{ title: row.optional.label, value: '', description: row.optional.description, category: 'Off' }] : []),
133
134
  ...list.map(model => ({ title: model.name, value: model.id, description: model.id, category: model.provider }))] });
134
135
  if (picked === undefined || picked === '') return picked;
135
136
  const variants = list.find(model => model.id === picked)?.variants ?? [];
136
137
  if (!variants.length) return picked;
137
- const variant = await dialog.select({ title: `Variant of ${picked}`, current: picked === current ? variantOf(row.current) : '',
138
+ const variant = await dialog.select({ title: `Variant of ${picked}`, ...(text(row.variantPrompt) ? { placeholder: row.variantPrompt } : {}), current: picked === current ? variantOf(row.current) : '',
138
139
  options: [{ title: 'Default', value: '', description: 'The model\'s own default' }, ...variants.map(name => ({ title: name, value: name }))] });
139
140
  return variant === undefined ? undefined : variant ? `${picked}#${variant}` : picked;
140
141
  }
@@ -248,7 +249,8 @@ export function createSetup(host) {
248
249
  // The list comes back on the row that was changed, which may be far from its top: the title says what is pending.
249
250
  const choice = await dialog.select({ title: status.state === 'restart' ? 'AZPR settings · restart needed' : 'AZPR settings', placeholder: 'Search settings', current: last, options: [
250
251
  ...(status.state === 'restart' ? [{ title: 'Restart needed', value: '@restart', footer: 'opencode service restart', category: 'Status' }] : []),
251
- ...rows.map(row => ({ title: row.label, value: row.id, footer: text(row.value), category: row.group })),
252
+ // A row whose name does not say what it is for carries a few words about it, between its name and its value.
253
+ ...rows.map(row => ({ title: row.label, value: row.id, ...(text(row.hint) ? { description: row.hint } : {}), footer: text(row.value), category: row.group })),
252
254
  { title: 'Settings file', value: '@file', footer: text(status.settingsFileShown) || text(status.settingsFile), category: 'More' }] });
253
255
  if (choice === undefined) return;
254
256
  last = choice;
@@ -257,7 +259,8 @@ export function createSetup(host) {
257
259
  continue;
258
260
  }
259
261
  if (choice === '@file') {
260
- await dialog.alert({ title: 'Settings file', message: `${text(status.settingsFile)}\n\nSettings that are not in this list are changed in this file; the README lists them all.` });
262
+ // The README is long: the server part names the section that describes every setting, with its address.
263
+ await dialog.alert({ title: 'Settings file', message: `${text(status.settingsFile)}\n\nSettings that are not in this list are changed in this file. Each one is described in ${text(status.settingsReference) || 'the README'}.` });
261
264
  continue;
262
265
  }
263
266
  const row = rows.find(item => item.id === choice);