opencode-azure-devops-pr-review 0.4.0 → 0.4.2

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.
@@ -0,0 +1,566 @@
1
+ /**
2
+ * What AZPR's terminal panel shows, worked out from what AZPR itself sent: the
3
+ * notices in a conversation, the report queued to a review session, and the
4
+ * sessions' `metadata.azpr`. Nothing here imports OpenTUI or the host: the view
5
+ * (tui-view.jsx, compiled to tui.js) hands it plain data, and so do the tests.
6
+ *
7
+ * The panel never sends a prompt, never reads AZPR's settings file and never
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.
12
+ */
13
+
14
+ /** The panel's name in the host's `session.panel` slot; names are shared between plugins. */
15
+ export const PANEL = 'azpr.panel';
16
+
17
+ const SESSION = 'ses_[A-Za-z0-9]+';
18
+ // `[AZPR <run>] STATUS…` for a run's notices; `[AZPR] …` for a command that answered at once.
19
+ const HEAD = /^\[AZPR(?: ([a-f0-9]{8}))?\] ?(?:([A-Z_]+)\b)?/;
20
+ const STAGE = new RegExp(`^- (azpr-[a-z-]+)(?: \\[([^\\]]+)\\])?: ([A-Z_]+); session=(${SESSION})`, 'gm');
21
+ // The block of a notice that encloses a document: its name (report or comment) and its text.
22
+ const DATA = /<azpr_(report|comment)_data>\n([\s\S]*?)\n<\/azpr_\1_data>/;
23
+ const REPORT_SESSION = new RegExp(`Report delivery: report queued to session=(${SESSION})\\.`);
24
+ // A comment run names the review it acts on: in its STARTED notice and in the head of its receipt.
25
+ const ACTS_ON = / It acts on review ([a-f0-9]{8}) /;
26
+ const SOURCE_REVIEW = /; source review=([a-f0-9]{8})/;
27
+ const RUN_STARTED = /^\[AZPR [a-f0-9]{8}\] STARTED \/pr-(?:review|quick|deep|comment)\b/;
28
+ // A run's receipt: its status, then `;`, a line break or the end. Text follows STARTED and PROGRESS, and a run
29
+ // also says things that are neither (`[AZPR <run>] Automatic preview skipped: …`).
30
+ const RECEIPT = /^\[AZPR [a-f0-9]{8}\] [A-Z_]+(?:;|\n|$)/;
31
+ const REPORT_HEAD = '# AZPR ';
32
+ // `/pr-comment [review] --show` answers at once with a review's saved preview, and names the review.
33
+ const SAVED_PREVIEW = /^\[AZPR\] Saved preview of review ([a-f0-9]{8})\b/;
34
+ // The summary table of a report or preview, whose cells the runtime writes with numeric character references.
35
+ const SUMMARY_TABLE = /^\| Severity \| Summary \| [^|\n]+ \|$/;
36
+ const MARKER = /^<!-- azpr-comment:[a-f0-9]{32} -->$/;
37
+ // The opening line of a fenced code block: backticks with no further backtick on the line, or tildes.
38
+ const FENCE = /^ {0,3}(?:(`{3,})(?!.*`)|(~{3,}))/;
39
+
40
+ /**
41
+ * What the runtime itself wrote in a notice: everything before the report or preview it encloses.
42
+ * The stage lines and the report session are facts only there; the enclosed text is a model's, and a
43
+ * line in it that looks like one of them is just text.
44
+ */
45
+ const ledgerOf = text => text.split(/^<azpr_(?:report|comment)_data>$/m)[0];
46
+
47
+ /**
48
+ * A block's text as it was before the runtime enclosed it. The runtime writes the block's own closing tag
49
+ * as `&lt;/azpr_NAME_data&gt;` and gives text that already had that form one more level of `&amp;` (see
50
+ * `enclose` in attribution.mjs): one level is taken off here, and nothing else is changed. A finding that
51
+ * quotes the tag is then shown as publication posts it.
52
+ */
53
+ export function disclose(name, text) {
54
+ const tag = `/azpr_${name}_data`;
55
+ return text.replace(new RegExp(`&((?:amp;)*)lt;${tag}&((?:amp;)*)gt;`, 'g'), (found, left, right) =>
56
+ (left === '' && right === '' ? `<${tag}>` : left && right ? `&${left.slice(4)}lt;${tag}&${right.slice(4)}gt;` : found));
57
+ }
58
+
59
+ /**
60
+ * The block of a notice that encloses a report or preview, or undefined: also for an empty block, which the
61
+ * receipt of a comment run carries when the run failed or was stopped before it had a preview.
62
+ */
63
+ const blockIn = text => {
64
+ const found = DATA.exec(text);
65
+ return found?.[2].trim() ? found : undefined;
66
+ };
67
+ const encloses = text => blockIn(text) !== undefined;
68
+ /** The report or preview a notice encloses, as it was written, or undefined. */
69
+ const enclosedIn = text => {
70
+ const found = blockIn(text);
71
+ return found && disclose(found[1], found[2]);
72
+ };
73
+
74
+ /** The text of a delivered message, or of a notice that still waits in a session's inbox. */
75
+ export const textOf = entry =>
76
+ typeof entry?.text === 'string' ? entry.text : typeof entry?.payload?.text === 'string' ? entry.payload.text : typeof entry?.description === 'string' ? entry.description : '';
77
+
78
+ /**
79
+ * A session's synthetic entries, oldest first: delivered messages and what its
80
+ * inbox still holds. AZPR queues its notices without waking the session, so
81
+ * most of them are in the inbox; the host shows both as messages for the
82
+ * session on screen, and only the inbox for others once it was read.
83
+ */
84
+ export function syntheticOf(messages, pending) {
85
+ const entries = new Map();
86
+ for (const entry of [...(messages ?? []), ...(pending ?? [])]) {
87
+ if (entry?.type === 'synthetic' && typeof entry.id === 'string') entries.set(entry.id, textOf(entry));
88
+ }
89
+ // 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 }));
91
+ }
92
+
93
+ /** AZPR's notices among a session's synthetic entries. */
94
+ export function noticesOf(entries) {
95
+ return entries.flatMap(({ id, text }) => {
96
+ const head = HEAD.exec(text);
97
+ if (!head) return [];
98
+ const [, run, status = ''] = head;
99
+ // NOTE: something a run says besides its start, its progress and its receipt; it changes nothing shown.
100
+ 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 }];
102
+ });
103
+ }
104
+
105
+ /** The report AZPR queued to a review session, or '' when these entries hold none. */
106
+ export const reportIn = entries => entries.map(entry => entry.text).findLast(text => text.startsWith(REPORT_HEAD)) ?? '';
107
+
108
+ /**
109
+ * A notice that opens the panel by itself in the session on screen: a review or
110
+ * comment run that starts, and a document that arrives: a report, a preview,
111
+ * the table of /pr-check. Progress notices and answers without a document do
112
+ * not, and no notice does with the setting terminalPanel: manual, which the
113
+ * runtime writes into the metadata of every notice it sends (`azpr.panel`).
114
+ */
115
+ export const opensPanel = (text, metadata) =>
116
+ typeof text === 'string' && metadata?.azpr?.panel !== 'manual' &&
117
+ (RUN_STARTED.test(text) || (HEAD.test(text) && (encloses(text) || REPORT_SESSION.test(ledgerOf(text)))));
118
+
119
+ /**
120
+ * The same Markdown, made readable in a terminal. AZPR writes the cells of its
121
+ * summary table with numeric character references so that Azure DevOps shows
122
+ * their characters literally, and marks its comments with HTML comments that
123
+ * Azure DevOps hides. The terminal renderer decodes neither: in that table,
124
+ * show each such character, escaped so that Markdown reads none of them as
125
+ * markup (a file named `__init__.py` keeps its underscores, a backtick stays
126
+ * a backtick, as on the PR), and leave the marker lines out.
127
+ *
128
+ * Only those two things change, and only where the runtime wrote them: a marker
129
+ * that stands alone between blank lines, and a table that begins after a blank
130
+ * line with the summary's header and its delimiter row. A reference or a marker
131
+ * that a finding quotes, in a code block, in a code span that runs over several
132
+ * lines or anywhere else, is its text: the preview shown must be the preview
133
+ * that publication posts.
134
+ */
135
+ export function readable(markdown) {
136
+ const lines = String(markdown ?? '').split('\n'), shown = [];
137
+ const blank = index => index < 0 || index >= lines.length || lines[index].trim() === '';
138
+ let fence = null, table = false;
139
+ for (const [index, line] of lines.entries()) {
140
+ if (fence) {
141
+ // A fence ends with at least as many of its own characters and nothing else.
142
+ if (new RegExp(`^ {0,3}${fence[0]}{${fence.length},}\\s*$`).test(line)) fence = null;
143
+ shown.push(line);
144
+ continue;
145
+ }
146
+ const opened = FENCE.exec(line);
147
+ if (opened) { fence = opened[1] ?? opened[2]; table = false; shown.push(line); continue; }
148
+ // The runtime puts each marker in a paragraph of its own. A line of a longer paragraph may be inside a code
149
+ // span, which can run over several lines but never over a blank one.
150
+ if (MARKER.test(line) && blank(index - 1) && blank(index + 1)) continue;
151
+ if (SUMMARY_TABLE.test(line) && blank(index - 1) && /^\|(?: --- \|)+$/.test(lines[index + 1] ?? '')) { table = true; shown.push(line); continue; }
152
+ table &&= line.startsWith('|');
153
+ // The characters the runtime writes as references (see `cell` in renderReviewSummary), each one literal.
154
+ shown.push(!table ? line : line.replace(/&#(\d{2,3});/g, (reference, code) => {
155
+ const character = String.fromCharCode(Number(code));
156
+ return /[&<>|`*_[\]\\]/.test(character) ? `\\${character}` : reference;
157
+ }));
158
+ }
159
+ return shown.join('\n');
160
+ }
161
+
162
+ /** Whether a failed request says that the session is not there, as opposed to a request that did not get through. */
163
+ export const notFound = error => /NotFound|\b404\b/.test(String(error?.name ?? '') + String(error?._tag ?? '') + String(error));
164
+
165
+ /**
166
+ * What looking a session up established, from the lookup's outcome (as
167
+ * `Promise.allSettled` gives it) and whether the host has the session now:
168
+ * 'exists'; 'missing', only when the server said so, by a not-found answer or
169
+ * a lookup that succeeded and found nothing; otherwise 'retry', since a request
170
+ * that failed says nothing about the session, and the host not having a session
171
+ * loaded is the usual case. The lookup reads the session itself, never what the
172
+ * session holds: whose it is must be known before anything of it is read.
173
+ */
174
+ export function lookupOutcome(looked, present) {
175
+ if (looked.status === 'rejected') return notFound(looked.reason) ? 'missing' : 'retry';
176
+ return present ? 'exists' : 'missing';
177
+ }
178
+
179
+ /**
180
+ * What the panel reads of sessions other than the one on screen, and when. It is kept apart from the
181
+ * view so that the order of its requests and their races are tested with delayed answers.
182
+ *
183
+ * The host is asked through the functions given:
184
+ * inbox(sessionID) → what waits in that session's inbox (an array, or `{ data }`)
185
+ * context(sessionID) → that session's messages since the last compaction; optional
186
+ * lookup(sessionID) → load the session itself into the host (nothing it holds)
187
+ * present(sessionID) → whether the host has the session now
188
+ * list(cursor) → a page of the server's sessions, `{ data, cursor }`; optional
189
+ * changed() → called whenever what the reader holds has changed
190
+ * pause(ms) → a wait between attempts
191
+ *
192
+ * The rules it keeps:
193
+ * - A session is looked up before anything it holds is read; the model decides from the session's own
194
+ * metadata whose it is, and only then names its inbox (see buildPanel).
195
+ * - A session counts as gone only when the server said so (lookupOutcome, notFound), and then it stays
196
+ * gone until the server reconnects: a lookup that was under way and answers later, from what the host
197
+ * still holds, does not bring it back.
198
+ * - From the moment a session's notices are asked for, every notice the host reports for it is kept,
199
+ * whatever becomes of the requests: while they are under way, after they failed, and afterwards.
200
+ * - An inbox is read before the messages: a notice that is delivered between the two reads was still in
201
+ * the inbox for the first. What the inbox answered is kept also when the messages cannot be read.
202
+ * - A request that failed is made again a few times; then it is left until the server reconnects. One
203
+ * lookup of a session is under way or waiting for its next attempt at a time, however often it is asked for.
204
+ * - What was asked before a reconnection is out of date when it answers: it is dropped and nothing is
205
+ * marked as read by it, since notices were missed while the TUI was away.
206
+ * - The entries of the `kept` sessions read last are held; one that was let go is read again when needed.
207
+ * A session with a read under way is held beside them and is not let go before that read has ended.
208
+ */
209
+ export function createReader({ inbox, context, lookup, present, list, changed = () => {}, pause = ms => new Promise(done => setTimeout(done, ms)), kept = 24 }) {
210
+ let connection = 0, disposed = false;
211
+ let known = {}, read = {};
212
+ const fetched = new Map(); // session → entries read from the server or reported since; the session read last comes last
213
+ const failed = new Map(); // session → lookups that failed without an answer about the session
214
+ const looking = new Map(); // session → its lookup under way, or the wait for its next attempt
215
+ const reading = new Set(); // `<session>:<token>` reads under way
216
+ const discovered = new Set(); // conversations whose sessions were asked for from the server
217
+ const listOf = result => (Array.isArray(result) ? result : Array.isArray(result?.data) ? result.data : []);
218
+ const gone = sessionID => known[sessionID] === 'missing';
219
+ /** Let go of what was read of a session, and of the marks that it was read. */
220
+ const forget = sessionID => {
221
+ fetched.delete(sessionID);
222
+ read = Object.fromEntries(Object.entries(read).filter(([key]) => !key.startsWith(`${sessionID}:`)));
223
+ };
224
+ const mark = (sessionID, value) => {
225
+ // Gone stays gone: nothing that answers later says otherwise.
226
+ if (known[sessionID] === value || gone(sessionID)) return;
227
+ known = { ...known, [sessionID]: value };
228
+ if (value === 'missing') forget(sessionID);
229
+ changed();
230
+ };
231
+ const beingRead = sessionID => { for (const key of reading) if (key.startsWith(`${sessionID}:`)) return true; return false; };
232
+ /**
233
+ * Hold what was read of the `kept` sessions read last, and beside them every session that has a read under
234
+ * way. One of those is not let go: what a read's requests answer one after the other belongs together, and
235
+ * so does what the host reports meanwhile; let go in between, the session would be held again with the later
236
+ * answer alone, and its read would end as if it had read everything. Nor does it take the place of one that
237
+ * was read: while many reads wait for their answers, what the panel shows stays held. (A read whose requests
238
+ * never answer keeps its session held until the server reconnects, like its place among the reads under way.)
239
+ */
240
+ const letGo = () => {
241
+ const idle = [...fetched.keys()].filter(id => !beingRead(id));
242
+ for (const id of idle.slice(0, Math.max(0, idle.length - kept))) forget(id);
243
+ };
244
+ const keep = (sessionID, entries) => {
245
+ fetched.delete(sessionID);
246
+ fetched.set(sessionID, entries);
247
+ letGo();
248
+ changed();
249
+ };
250
+
251
+ /**
252
+ * Read a session's notices into what is held of it: its inbox and, with `delivered`, its messages.
253
+ * Throws when a request failed; what the other one answered is held all the same.
254
+ */
255
+ async function fetchEntries(sessionID, delivered) {
256
+ const asked = connection;
257
+ const stale = () => asked !== connection || disposed || gone(sessionID);
258
+ if (stale()) return;
259
+ const pending = await inbox(sessionID);
260
+ if (stale()) return;
261
+ // With what is held of this session already: what was read before, and what the host reported meanwhile.
262
+ keep(sessionID, mergeEntries(fetched.get(sessionID) ?? [], listOf(pending)));
263
+ if (!delivered || !context) return;
264
+ const told = await context(sessionID);
265
+ if (stale()) return;
266
+ keep(sessionID, mergeEntries(listOf(told).filter(entry => entry?.type === 'synthetic'), fetched.get(sessionID) ?? []));
267
+ }
268
+
269
+ /** Look a session up: one lookup, or the wait for its next attempt, at a time. */
270
+ function lookupSession(sessionID) {
271
+ if (disposed || gone(sessionID) || failed.get(sessionID) >= 4) return Promise.resolve();
272
+ const running = looking.get(sessionID);
273
+ if (running) return running;
274
+ const asked = connection;
275
+ const started = (async () => {
276
+ const [looked] = await Promise.allSettled([Promise.resolve().then(() => lookup(sessionID))]);
277
+ if (asked !== connection || disposed) return;
278
+ const outcome = lookupOutcome(looked, Boolean(present(sessionID)));
279
+ if (outcome !== 'retry') {
280
+ failed.delete(sessionID);
281
+ looking.delete(sessionID);
282
+ return mark(sessionID, outcome);
283
+ }
284
+ const count = (failed.get(sessionID) ?? 0) + 1;
285
+ failed.set(sessionID, count);
286
+ if (count >= 4) return void looking.delete(sessionID);
287
+ // Again, further apart. Until then this lookup stands for the session: asking for it again, as the panel
288
+ // does whenever anything changes, neither shortens the wait nor uses up an attempt.
289
+ await pause(500 * 2 ** count);
290
+ if (asked !== connection || disposed) return;
291
+ looking.delete(sessionID);
292
+ return lookupSession(sessionID);
293
+ })();
294
+ looking.set(sessionID, started);
295
+ return started;
296
+ }
297
+
298
+ /**
299
+ * Read the inbox of a session the model named: the one that holds a report (`report`: a report that is
300
+ * not there after a moment is not coming; it is among the messages when someone prompted that session
301
+ * since), or a conversation's, for its notices, pending and delivered.
302
+ */
303
+ function readInbox(sessionID, token, report) {
304
+ const key = `${sessionID}:${token}`;
305
+ if (disposed || gone(sessionID) || read[key] || reading.has(key)) return Promise.resolve();
306
+ reading.add(key);
307
+ // Held from now on, also while it is empty: every notice the host reports for this session is kept.
308
+ if (!fetched.has(sessionID)) keep(sessionID, []);
309
+ const asked = connection;
310
+ const attempt = async (left, delivered) => {
311
+ try {
312
+ await fetchEntries(sessionID, delivered);
313
+ if (asked !== connection) return;
314
+ if (!report || reportIn(syntheticOf(fetched.get(sessionID) ?? [], []))) return;
315
+ } catch (error) {
316
+ if (asked !== connection) return;
317
+ if (notFound(error)) return mark(sessionID, 'missing');
318
+ }
319
+ // A session that was deleted meanwhile has nothing more to read.
320
+ if (left <= 1 || disposed || gone(sessionID)) return;
321
+ await pause(400);
322
+ if (asked !== connection) return;
323
+ return attempt(left - 1, true);
324
+ };
325
+ return attempt(4, !report).finally(() => {
326
+ // A read from before a reconnection says nothing about now: the reconnection started everything anew.
327
+ if (asked !== connection) return;
328
+ reading.delete(key);
329
+ // Marked as read while its session is held (one that is gone has nothing more to read), and the session
330
+ // read last from now on. When more reads have ended than sessions are kept, the one read longest ago is
331
+ // let go, with its marks, and read again when the panel needs it.
332
+ const held = fetched.get(sessionID);
333
+ if (held && !gone(sessionID)) {
334
+ fetched.delete(sessionID);
335
+ fetched.set(sessionID, held);
336
+ read = { ...read, [key]: true };
337
+ }
338
+ letGo();
339
+ changed();
340
+ });
341
+ }
342
+
343
+ /**
344
+ * Ask the server for the sessions of a conversation, once per conversation and connection: after a restart of
345
+ * the TUI the host has not loaded a run's sessions. Each one that says itself that it is the conversation's is
346
+ * looked up. At most five pages are read.
347
+ */
348
+ function discover(conversation) {
349
+ if (disposed || !list || discovered.has(conversation)) return Promise.resolve();
350
+ discovered.add(conversation);
351
+ const asked = connection;
352
+ const page = async (cursor, left) => {
353
+ const result = await list(cursor);
354
+ if (asked !== connection || disposed) return;
355
+ for (const session of listOf(result)) if (conversationOf(session) === conversation && typeof session.id === 'string') void lookupSession(session.id);
356
+ if (result?.cursor && result.cursor !== cursor && left > 1) return page(result.cursor, left - 1);
357
+ };
358
+ // A list that could not be read is asked for again the next time the panel is shown.
359
+ return page(undefined, 5).catch(() => { if (asked === connection) discovered.delete(conversation); });
360
+ }
361
+
362
+ return {
363
+ /** What is held of a session: read from the server or reported since; [] for one that was not read or was let go. */
364
+ entries: sessionID => fetched.get(sessionID) ?? [],
365
+ /** Sessions looked up: 'exists' or 'missing'. */
366
+ known: () => known,
367
+ /** Reads that ended, as `<session>:<token>`. */
368
+ read: () => read,
369
+ lookup: lookupSession,
370
+ readInbox,
371
+ discover,
372
+
373
+ /** A notice the host reported for a session: kept when that session's notices were asked for. */
374
+ arrived(sessionID, item) {
375
+ if (disposed || item?.type !== 'synthetic' || typeof item.id !== 'string') return;
376
+ const held = fetched.get(sessionID);
377
+ if (held && !held.some(entry => entry.id === item.id)) keep(sessionID, [...held, item]);
378
+ },
379
+
380
+ /** The server said that a session was deleted. */
381
+ deleted(sessionID) {
382
+ if (typeof sessionID === 'string') mark(sessionID, 'missing');
383
+ },
384
+
385
+ /** The server is connected again: what was missed meanwhile is read anew, and nothing asked before counts. */
386
+ reconnected() {
387
+ connection++;
388
+ failed.clear();
389
+ looking.clear();
390
+ reading.clear();
391
+ discovered.clear();
392
+ fetched.clear();
393
+ known = {};
394
+ read = {};
395
+ changed();
396
+ },
397
+
398
+ /** The TUI unloads the plugin: nothing is asked of the host after this. */
399
+ dispose() {
400
+ disposed = true;
401
+ },
402
+ };
403
+ }
404
+
405
+ const TITLE = /^\[AZPR ([a-f0-9]{8})\] /;
406
+ const short = title => String(title).replace(TITLE, '');
407
+
408
+ /**
409
+ * The conversation one of AZPR's own sessions belongs to, by what the session itself says: AZPR's
410
+ * metadata, or, for a session AZPR 0.4.0 or earlier created (a child of the conversation that carries
411
+ * AZPR's title and no such metadata), its parent. Undefined for any other session, a conversation included.
412
+ */
413
+ export function conversationOf(session) {
414
+ const azpr = session?.metadata?.azpr;
415
+ if (azpr) return typeof azpr.conversation === 'string' ? azpr.conversation : undefined;
416
+ return typeof session?.parentID === 'string' && TITLE.test(session.title ?? '') ? session.parentID : undefined;
417
+ }
418
+
419
+ /**
420
+ * Whether a session the host has is this conversation's and, where `run` is given, that run's, by what
421
+ * the session itself says: never by a text that names it. A session of 0.4.0 or earlier has no metadata:
422
+ * it is a child of its conversation, and its title, which AZPR gave it, names its run.
423
+ */
424
+ const belongs = (session, conversation, run) => {
425
+ const azpr = session.metadata?.azpr;
426
+ if (azpr) return azpr.conversation === conversation && (run === undefined || azpr.run === run);
427
+ return session.parentID === conversation && (run === undefined || TITLE.exec(session.title ?? '')?.[1] === run);
428
+ };
429
+
430
+ /** Entries of several lists as one, each ID once (a later list's entry wins), for what was read and what arrived meanwhile. */
431
+ export const mergeEntries = (...lists) => [...new Map(lists.flat().filter(entry => typeof entry?.id === 'string').map(entry => [entry.id, entry])).values()];
432
+
433
+ /**
434
+ * What the panel shows for the session on screen.
435
+ *
436
+ * `source` reads the host's data as the TUI has it loaded:
437
+ * session(id) → { id, title, metadata, … } | undefined, sessions() → those the TUI knows,
438
+ * status(id) → 'running' | 'idle', messages(id) and pending(id) → entries of that session.
439
+ * `known` says which sessions were looked up and are gone ('missing'); `read`
440
+ * names the inboxes read so far, as `<session>:<notice that named it>`;
441
+ * `titles` keeps the names of sessions seen while they existed.
442
+ *
443
+ * The result lists in `needs` the sessions to look up before more can be shown,
444
+ * in `inbox` the report session whose inbox holds the document, and in
445
+ * `notices` the conversation whose notices are to be read when the session on
446
+ * screen is one of AZPR's own. Only a session that proved to be this
447
+ * conversation's is named in `inbox`.
448
+ */
449
+ export function buildPanel(source, sessionID, { known = {}, read = {}, titles = new Map() } = {}) {
450
+ const needs = new Set();
451
+ const entriesOf = id => syntheticOf(source.messages(id), source.pending(id));
452
+ const self = source.session(sessionID);
453
+ // In one of AZPR's own sessions the notices are in the conversation that started the run, and with them those
454
+ // of commands typed in this session, which the runtime answers here (IDs sort by creation time across sessions).
455
+ const conversation = conversationOf(self) ?? sessionID;
456
+ if (conversation !== sessionID && !source.session(conversation) && known[conversation] !== 'missing') needs.add(conversation);
457
+ // The host holds the notices of the session on screen and of open tabs only: those of the conversation are
458
+ // read from the server, once, whether or not the host knows the conversation itself.
459
+ const notes = conversation !== sessionID && known[conversation] !== 'missing' && !read[`${conversation}:notices`] ? { sessionID: conversation, token: 'notices' } : undefined;
460
+ const entries = conversation === sessionID ? entriesOf(conversation)
461
+ : mergeEntries(entriesOf(conversation), entriesOf(sessionID)).sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
462
+ const notices = noticesOf(entries);
463
+ // What the panel is about is what happened last: a run that started, progressed or ended, or a saved preview
464
+ // shown again, which names its review. What a run says besides (a review's note that no preview follows can
465
+ // 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)));
467
+ const answered = subject?.kind === 'ANSWER' ? SAVED_PREVIEW.exec(subject.text)[1] : undefined;
468
+ // A saved preview shown again is about its review: that review's status, sessions and report session.
469
+ const run = answered ?? subject?.run;
470
+ const ofRun = notices.filter(notice => notice.run === run && notice.kind !== 'NOTE');
471
+ const receipt = ofRun.findLast(notice => notice.kind === 'RECEIPT');
472
+ const progress = ofRun.findLast(notice => notice.kind === 'PROGRESS');
473
+ const status = receipt ? receipt.status : run && !answered ? 'RUNNING' : '';
474
+ // A comment run belongs with the review it acts on: that review's sessions and report stay in view.
475
+ // 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;
477
+ const review = reviewRun === run ? receipt : notices.findLast(notice => notice.kind === 'RECEIPT' && notice.run === reviewRun);
478
+ const reportSession = REPORT_SESSION.exec(ledgerOf(review?.text ?? ''))?.[1];
479
+
480
+ // The document: the saved preview shown again, or the newest report or preview of the run and of the review it
481
+ // acts on, enclosed in a receipt or queued to the review's report session. A receipt that encloses nothing (a
482
+ // comment run that failed before it had a preview) leaves the document as it was: the review's report.
483
+ let document;
484
+ if (answered) document = { head: subject.text.split('\n')[0], markdown: enclosedIn(subject.text), token: subject.id };
485
+ else for (const notice of notices) {
486
+ if (notice.kind !== 'RECEIPT' || (notice.run !== run && notice.run !== reviewRun)) continue;
487
+ const head = notice.text.split('\n')[0];
488
+ const enclosed = enclosedIn(notice.text);
489
+ const queued = REPORT_SESSION.exec(ledgerOf(notice.text))?.[1];
490
+ if (enclosed !== undefined) document = { head, markdown: enclosed, token: notice.id };
491
+ else if (queued) document = { head, session: queued, run: notice.run, token: notice.id };
492
+ }
493
+ // A queued report is read from the session a receipt names, once that session says itself that it is this
494
+ // conversation's and holds the report of that receipt's run: until the host has it, it is looked up, and a
495
+ // session of someone else's, or of another review, is never read. A session the server said is gone is gone,
496
+ // whatever the host still holds of it.
497
+ const gone = id => known[id] === 'missing';
498
+ const holder = document?.session && !gone(document.session) ? source.session(document.session) : undefined;
499
+ const awaited = Boolean(document?.session) && !holder && !gone(document.session);
500
+ if (awaited) needs.add(document.session);
501
+ const held = holder !== undefined && belongs(holder, conversation, document.run);
502
+ const found = document?.markdown ?? (held ? reportIn(entriesOf(document.session)) : '');
503
+ // In a session that holds a report, that report is shown while the notices name no document, and only when it
504
+ // is the report of the review shown, or nothing is known yet of any run (the notices may not be read yet). A
505
+ // status never stands above another review's report.
506
+ const own = !document && conversation !== sessionID && self && (run === undefined || belongs(self, conversation, reviewRun)) ? reportIn(entriesOf(sessionID)) : '';
507
+ const markdown = readable(found || own);
508
+ // A queued report waits in its session's inbox, which the host loads only for the session on screen.
509
+ const inbox = !found && held ? { sessionID: document.session, token: document.token } : undefined;
510
+ const loading = !markdown && (awaited || (inbox !== undefined && !read[`${inbox.sessionID}:${inbox.token}`]));
511
+
512
+ // Candidates: what the host lists for these runs, what their receipts name, and the report session.
513
+ const stages = new Map();
514
+ for (const notice of new Set([review, receipt])) {
515
+ if (notice) for (const [, role, label, state, id] of ledgerOf(notice.text).matchAll(STAGE)) stages.set(id, { role, label, state });
516
+ }
517
+ const runs = new Set([run, reviewRun]);
518
+ const candidates = new Set(stages.keys());
519
+ if (reportSession) candidates.add(reportSession);
520
+ for (const session of source.sessions()) {
521
+ const azpr = session?.metadata?.azpr;
522
+ if (azpr?.conversation === conversation && azpr.run !== undefined && runs.has(azpr.run)) candidates.add(session.id);
523
+ }
524
+ const rows = [];
525
+ let deleted = 0;
526
+ for (const id of candidates) {
527
+ // The server's word that a session is gone outweighs what the host still holds of it.
528
+ const info = gone(id) ? undefined : source.session(id);
529
+ if (!info) {
530
+ // A finished run names every stage in its receipt; what was deleted since is counted, not listed.
531
+ if (gone(id)) deleted += stages.has(id) ? 1 : 0;
532
+ else needs.add(id);
533
+ continue;
534
+ }
535
+ // A session says itself whose it is: one of another conversation or run is not listed, whatever named it.
536
+ const azpr = info.metadata?.azpr;
537
+ if (!belongs(info, conversation) || (azpr && !runs.has(azpr.run))) continue;
538
+ if (info.title) titles.set(id, short(info.title));
539
+ const stage = stages.get(id);
540
+ rows.push({
541
+ id,
542
+ 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',
544
+ report: id === reportSession && belongs(info, conversation, reviewRun),
545
+ current: azpr?.run === run,
546
+ });
547
+ }
548
+ // The report first, then the run under way or last ended, then by name ("shard 2/12" before "shard 10/12").
549
+ rows.sort((a, b) => Number(b.report) - Number(a.report) || Number(b.current) - Number(a.current) || a.label.localeCompare(b.label, 'en', { numeric: true }));
550
+ return {
551
+ conversation,
552
+ run,
553
+ status,
554
+ progress: status === 'RUNNING' ? progress?.text.replace(/^\[AZPR [a-f0-9]{8}\] PROGRESS — /, '') : undefined,
555
+ rows,
556
+ deleted,
557
+ markdown,
558
+ // A report read from its session says its run and status in its own first line; an enclosed document is named by
559
+ // the notice that encloses it.
560
+ documentHead: own || document?.session ? '' : document?.head ?? '',
561
+ inbox,
562
+ notices: notes,
563
+ loading,
564
+ needs: [...needs],
565
+ };
566
+ }