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,438 @@
1
+ // AZPR's part in OpenCode's terminal UI: a panel beside the conversation.
2
+ //
3
+ // Its upper part lists the sessions of the run under way or last ended, each a row that opens
4
+ // that session when it is clicked; its lower part shows the newest report or comment preview as
5
+ // rendered Markdown. A run that starts, and a report or preview that arrives, opens the panel in
6
+ // the session on screen and leaves the keyboard with the prompt; with the setting
7
+ // terminalPanel: manual it opens only with /pr-panel, its one command.
8
+ //
9
+ // The panel only reads: AZPR's own notices in the conversation, the report queued to a review
10
+ // session, and the sessions' `metadata.azpr` (src/tui-model.mjs works out what to show). It sends
11
+ // no prompt, runs no command of the server part and reads no settings file: the server part writes
12
+ // that setting into the metadata of its notices.
13
+ //
14
+ // This is the source. OpenCode loads src/tui.js, which scripts/build-tui.mjs compiles from it:
15
+ // OpenCode 2.3.0 compiles no JSX of a package it installed, so the package carries the result.
16
+ import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js"
17
+ import { MouseButton, SyntaxStyle, TextAttributes } from "@opentui/core"
18
+ import { PANEL, buildPanel, conversationOf, createReader, opensPanel } from "./tui-model.mjs"
19
+
20
+ // Short enough for one line of a toast, which the host wraps at about fifty characters.
21
+ const READY = "AZPR: report or preview ready. /pr-panel shows it."
22
+
23
+ /** The first of these theme tokens that this OpenCode defines; their names have changed between releases. */
24
+ const token = (theme, ...paths) => {
25
+ for (const path of paths) {
26
+ const value = path.split(".").reduce((node, name) => node?.[name], theme)
27
+ if (value !== undefined) return value
28
+ }
29
+ }
30
+ const colors = (theme) => {
31
+ const base = token(theme, "text.base", "text.default")
32
+ return {
33
+ base,
34
+ muted: token(theme, "text.muted", "text.subdued") ?? base,
35
+ running: token(theme, "text.feedback.info.base") ?? base,
36
+ failed: token(theme, "text.feedback.error.base") ?? base,
37
+ done: token(theme, "text.feedback.success.base") ?? base,
38
+ link: token(theme, "markdown.link") ?? base,
39
+ text: token(theme, "markdown.text") ?? base,
40
+ surface: token(theme, "background.raised.base"),
41
+ hover: token(theme, "background.raised.high"),
42
+ }
43
+ }
44
+
45
+ /** Markdown colors from the theme's own tokens, for the renderer of this TUI. */
46
+ function markdownStyle(context) {
47
+ const theme = context.theme
48
+ const base = token(theme, "text.base", "text.default")
49
+ const of = (name) => token(theme, `markdown.${name}`) ?? base
50
+ const styles = {
51
+ default: { fg: of("text") },
52
+ "markup.heading": { fg: of("heading"), bold: true },
53
+ "markup.strong": { fg: of("strong"), bold: true },
54
+ "markup.bold": { fg: of("strong"), bold: true },
55
+ "markup.italic": { fg: of("emphasis"), italic: true },
56
+ "markup.strikethrough": { fg: token(theme, "text.muted", "text.subdued") ?? base, dim: true },
57
+ "markup.raw": { fg: of("code") },
58
+ "markup.raw.inline": { fg: of("code") },
59
+ "markup.raw.block": { fg: of("codeBlock") },
60
+ "markup.link": { fg: of("link"), underline: true },
61
+ "markup.link.label": { fg: of("linkText"), underline: true },
62
+ "markup.link.url": { fg: of("link"), underline: true },
63
+ "markup.list": { fg: of("listItem") },
64
+ "markup.quote": { fg: of("blockQuote"), italic: true },
65
+ }
66
+ for (const level of [1, 2, 3, 4, 5, 6]) styles[`markup.heading.${level}`] = { fg: of("heading"), bold: true }
67
+ return SyntaxStyle.fromStyles(styles, context.renderer.nativeScene)
68
+ }
69
+
70
+ function Row(props) {
71
+ const [hover, setHover] = createSignal(false)
72
+ const mark = () => (props.row.state === "running" ? props.colors.running : props.row.state === "failed" ? props.colors.failed : props.colors.done)
73
+ return (
74
+ <box
75
+ flexDirection="row"
76
+ gap={1}
77
+ backgroundColor={hover() ? props.colors.hover : undefined}
78
+ onMouseOver={() => setHover(true)}
79
+ onMouseOut={() => setHover(false)}
80
+ onMouseUp={(event) => {
81
+ if (event.button !== MouseButton.LEFT) return
82
+ event.stopPropagation()
83
+ props.open(props.row.id)
84
+ }}
85
+ >
86
+ <text fg={mark()} flexShrink={0} selectable={false}>
87
+ {props.row.state === "running" ? "●" : "○"}
88
+ </text>
89
+ <text fg={props.colors.base} flexShrink={0} selectable={false}>
90
+ {props.row.label}
91
+ {props.row.report ? " (report)" : ""}
92
+ </text>
93
+ <text fg={props.colors.muted} flexShrink={0} selectable={false}>
94
+ {props.row.state}
95
+ </text>
96
+ <Show when={props.wide}>
97
+ <text fg={props.colors.link} attributes={TextAttributes.UNDERLINE} wrapMode="none" selectable={false}>
98
+ {props.row.id}
99
+ </text>
100
+ </Show>
101
+ </box>
102
+ )
103
+ }
104
+
105
+ function Panel(props) {
106
+ const context = props.context
107
+ const state = props.state
108
+ const model = createMemo(() => buildPanel(state.source, props.panel.sessionID, { known: state.known(), read: state.read(), titles: state.titles }))
109
+ const palette = createMemo(() => colors(context.theme))
110
+ let scroll
111
+
112
+ // The style follows the theme; a style no longer drawn is destroyed once the renderer is idle.
113
+ const release = (style) =>
114
+ Promise.resolve(context.renderer.idle?.())
115
+ .catch(() => undefined)
116
+ .finally(() => style.destroy?.())
117
+ const syntax = createMemo((previous) => {
118
+ const next = markdownStyle(context)
119
+ if (previous) release(previous)
120
+ return next
121
+ })
122
+ onCleanup(() => release(syntax()))
123
+
124
+ const close = () => {
125
+ state.dismiss(props.panel.sessionID)
126
+ props.panel.close()
127
+ }
128
+ const open = (sessionID) => context.ui.router.navigate({ type: "session", sessionID })
129
+
130
+ // The host gives the keyboard to a panel that opens, and has no way to open one without it. AZPR is
131
+ // driven by commands, so the panel hands the keyboard back to the prompt: the next command can be typed
132
+ // while the report is on screen, and a click in the panel (or the host's "Focus right pane") gives it
133
+ // the keyboard. A terminal too narrow for two panes shows the panel alone, with no prompt to return to.
134
+ // A panel that opened by itself must never be left with the keyboard: where it cannot hand it back, it
135
+ // closes again, and says that something is ready when a notice opened it.
136
+ // The two steps below run a moment after the panel mounted. By then the host may show another plugin's panel in
137
+ // this place, or another session: each step acts only while this panel is the one open here, and none outlives it.
138
+ const timers = new Set()
139
+ const mine = () => {
140
+ const current = context.ui.panel.current()
141
+ return current?.name === PANEL && current.sessionID === props.panel.sessionID
142
+ }
143
+ const later = (step, delay) => {
144
+ const timer = setTimeout(() => {
145
+ timers.delete(timer)
146
+ if (mine()) step()
147
+ }, delay)
148
+ timers.add(timer)
149
+ }
150
+ onCleanup(() => {
151
+ for (const timer of timers) clearTimeout(timer)
152
+ timers.clear()
153
+ })
154
+ onMount(() => {
155
+ const unasked = state.takeUnasked()
156
+ const withdraw = () => {
157
+ state.dismiss(props.panel.sessionID)
158
+ props.panel.close()
159
+ if (unasked === "notice") context.ui.toast.show({ message: READY, variant: "info" })
160
+ }
161
+ if (props.panel.presentation === "fullscreen") return unasked ? withdraw() : undefined
162
+ later(() => {
163
+ context.keymap.dispatch("pane.focus.left")
164
+ if (unasked) later(() => props.panel.focused && withdraw(), 50)
165
+ }, 0)
166
+ })
167
+
168
+ // Sessions the host has not loaded here: a run's sessions after a TUI restart, the conversation of one of them.
169
+ createEffect(() => {
170
+ for (const sessionID of model().needs) void state.lookup(sessionID)
171
+ })
172
+ // The report of a review waits in its session's inbox; in one of AZPR's own sessions the notices are in the
173
+ // conversation's. The model names an inbox only once the session proved to be this conversation's.
174
+ createEffect(() => {
175
+ const inbox = model().inbox
176
+ if (inbox) state.readInbox(inbox.sessionID, inbox.token, true)
177
+ const notices = model().notices
178
+ if (notices) state.readInbox(notices.sessionID, notices.token, false)
179
+ })
180
+
181
+ // Active only while the panel has the keyboard; the IDs let a user bind other keys in the TUI's configuration.
182
+ const page = () => Math.max(4, (scroll?.viewport?.height ?? scroll?.height ?? 10) - 2)
183
+ context.keymap.layer(() => ({
184
+ commands: [
185
+ { id: "azpr.panel.close", title: "Close the AZPR panel", group: "AZPR", bind: "escape,q", run: close },
186
+ { id: "azpr.panel.up", title: "AZPR panel: scroll up", group: "AZPR", bind: "up,k", run: () => scroll?.scrollBy(-1) },
187
+ { id: "azpr.panel.down", title: "AZPR panel: scroll down", group: "AZPR", bind: "down,j", run: () => scroll?.scrollBy(1) },
188
+ { id: "azpr.panel.page.up", title: "AZPR panel: page up", group: "AZPR", bind: "pageup", run: () => scroll?.scrollBy(-page()) },
189
+ { id: "azpr.panel.page.down", title: "AZPR panel: page down", group: "AZPR", bind: "pagedown", run: () => scroll?.scrollBy(page()) },
190
+ { id: "azpr.panel.top", title: "AZPR panel: go to the top", group: "AZPR", bind: "home", run: () => scroll?.scrollTo(0) },
191
+ { id: "azpr.panel.bottom", title: "AZPR panel: go to the end", group: "AZPR", bind: "end", run: () => scroll?.scrollTo(scroll.scrollHeight) },
192
+ ],
193
+ }))
194
+
195
+ // Rows are keyed by session, so a row keeps its place and its hover while the list is worked out again.
196
+ const ids = createMemo(() => model().rows.map((row) => row.id), [], { equals: (a, b) => a.length === b.length && a.every((id, index) => id === b[index]) })
197
+ const row = (id) => model().rows.find((item) => item.id === id) ?? { id, label: "", state: "", report: false }
198
+
199
+ return (
200
+ <box flexDirection="column" flexGrow={1} minHeight={0} paddingLeft={2} paddingRight={2} paddingTop={1}>
201
+ <box flexDirection="row" flexShrink={0}>
202
+ <text fg={palette().base} flexShrink={0}>
203
+ <b>AZPR</b>
204
+ <Show when={model().run}>
205
+ <span> {model().run}</span>
206
+ </Show>
207
+ <Show when={model().status}>
208
+ <span style={{ fg: palette().muted }}> · {model().status}</span>
209
+ </Show>
210
+ </text>
211
+ <box flexGrow={1} />
212
+ <text
213
+ fg={palette().muted}
214
+ flexShrink={0}
215
+ selectable={false}
216
+ onMouseUp={(event) => {
217
+ if (event.button !== MouseButton.LEFT) return
218
+ event.stopPropagation()
219
+ close()
220
+ }}
221
+ >
222
+ close
223
+ </text>
224
+ </box>
225
+ <Show when={model().progress}>
226
+ <text fg={palette().muted} flexShrink={0}>
227
+ {model().progress}
228
+ </text>
229
+ </Show>
230
+ <scrollbox ref={(element) => (scroll = element)} flexGrow={1} minHeight={0} paddingTop={1} verticalScrollbarOptions={{ visible: false }} contentOptions={{ minHeight: 0 }}>
231
+ <Show when={ids().length > 0 || model().deleted > 0}>
232
+ <box flexDirection="column" flexShrink={0} paddingBottom={1}>
233
+ <Show when={ids().length > 0}>
234
+ <text fg={palette().muted} selectable={false}>
235
+ Sessions (click one to open it)
236
+ </text>
237
+ </Show>
238
+ <For each={ids()}>{(id) => <Row row={row(id)} colors={palette()} wide={props.panel.width >= 64} open={open} />}</For>
239
+ <Show when={model().deleted > 0}>
240
+ <text fg={palette().muted}>{model().deleted} session(s) were deleted when their run ended.</text>
241
+ </Show>
242
+ </box>
243
+ </Show>
244
+ <Show
245
+ when={model().markdown}
246
+ fallback={
247
+ <text fg={palette().muted}>
248
+ {model().loading
249
+ ? "Loading the report…"
250
+ : model().inbox
251
+ ? "The report is in its session: open it above."
252
+ : model().run
253
+ ? "No report or preview yet."
254
+ : "No AZPR run in this conversation yet."}
255
+ </text>
256
+ }
257
+ >
258
+ <Show when={model().documentHead}>
259
+ <text fg={palette().muted} flexShrink={0} paddingBottom={1}>
260
+ {model().documentHead}
261
+ </text>
262
+ </Show>
263
+ <markdown syntaxStyle={syntax()} content={model().markdown} conceal tableOptions={{ style: "grid", cellPaddingX: 1 }} fg={palette().text} bg={palette().surface} />
264
+ </Show>
265
+ </scrollbox>
266
+ </box>
267
+ )
268
+ }
269
+
270
+ export default {
271
+ id: "azpr.tui",
272
+ setup(context) {
273
+ // A host without these parts of the plugin API has no place for the panel: stay out of its way.
274
+ const needed = [context?.ui?.slot, context?.ui?.panel?.open, context?.ui?.router?.navigate, context?.keymap?.layer, context?.data?.listen, context?.data?.session?.pending?.list]
275
+ if (needed.some((part) => typeof part !== "function")) return
276
+ const data = context.data
277
+ // Set when the TUI unloads the plugin: nothing is asked of the host after that.
278
+ let disposed = false
279
+ // The host keeps the messages and the inbox of the session on screen and of open tabs, and drops those of
280
+ // other sessions again. What the panel needs of another session (the report waiting in a review session's
281
+ // inbox, the notices of the conversation when one of AZPR's own sessions is on screen) is read from the
282
+ // server by the reader in tui-model.mjs, which also knows which sessions are gone. `version` makes what it
283
+ // holds reactive.
284
+ const [version, setVersion] = createSignal(0)
285
+ const reader = createReader({
286
+ inbox: (sessionID) => context.client.session.inbox.list({ sessionID }),
287
+ context: typeof context.client?.session?.context === "function" ? (sessionID) => context.client.session.context({ sessionID }) : undefined,
288
+ lookup: (sessionID) => data.session.sync(sessionID),
289
+ present: (sessionID) => data.session.get(sessionID),
290
+ list: (cursor) => context.client.session.list(cursor ? { cursor } : {}),
291
+ changed: () => setVersion((count) => count + 1),
292
+ })
293
+ const source = {
294
+ session: (id) => data.session.get(id),
295
+ sessions: () => data.session.list(),
296
+ status: (id) => data.session.status(id),
297
+ messages: (id) => data.session.message.list(id),
298
+ pending: (id) => (version(), [...data.session.pending.list(id), ...reader.entries(id)]),
299
+ }
300
+ const known = () => (version(), reader.known())
301
+ const read = () => (version(), reader.read())
302
+
303
+ // Sessions whose panel this plugin opened and the user has not closed. The host closes a panel when the
304
+ // screen leaves its session; coming back to such a session opens it again.
305
+ const wanted = new Set()
306
+ // Why the panel is being opened without the user asking: "notice" or "return"; undefined when asked.
307
+ let unasked
308
+ // The session in which another plugin's panel is open; the host shows one panel at a time.
309
+ let occupied
310
+ const state = {
311
+ source,
312
+ known,
313
+ read,
314
+ titles: new Map(),
315
+ lookup: reader.lookup,
316
+ readInbox: reader.readInbox,
317
+ dismiss: (sessionID) => void wanted.delete(sessionID),
318
+ takeUnasked: () => {
319
+ const value = unasked
320
+ unasked = undefined
321
+ return value
322
+ },
323
+ }
324
+
325
+ context.ui.slot({
326
+ append: "session.panel",
327
+ render: (panel) => {
328
+ // Every contribution is told which panel is open: remember where it is someone else's.
329
+ createEffect(() => {
330
+ occupied = panel.name === PANEL ? undefined : panel.sessionID
331
+ })
332
+ onCleanup(() => {
333
+ occupied = undefined
334
+ })
335
+ return (
336
+ <Show when={panel.name === PANEL}>
337
+ <Panel context={context} panel={panel} state={state} />
338
+ </Show>
339
+ )
340
+ },
341
+ })
342
+
343
+ const shown = (sessionID) => {
344
+ const current = context.ui.panel.current()
345
+ return current?.name === PANEL && current.sessionID === sessionID
346
+ }
347
+ /**
348
+ * Show the panel in the session on screen. `byItself` says why when the user did not ask ("notice": one
349
+ * arrived; "return": the screen came back to a session that had the panel): then neither a dialog nor
350
+ * another plugin's panel is disturbed.
351
+ */
352
+ const show = (byItself) => {
353
+ if (disposed) return false
354
+ const route = context.ui.router.current()
355
+ if (route.type !== "session") return false
356
+ const sessionID = route.sessionID
357
+ // After a TUI restart the host has not loaded a run's sessions: the reader asks the server for them.
358
+ void reader.discover(conversationOf(data.session.get(sessionID)) ?? sessionID)
359
+ wanted.add(sessionID)
360
+ if (shown(sessionID)) return true
361
+ if (byItself && (occupied === sessionID || context.keymap.mode?.current?.() === "modal")) {
362
+ if (byItself === "notice") context.ui.toast.show({ message: READY, variant: "info" })
363
+ return false
364
+ }
365
+ unasked = byItself
366
+ return context.ui.panel.open(PANEL)
367
+ }
368
+
369
+ const stop = data.listen((event) => {
370
+ if (disposed) return
371
+ const details = event?.details
372
+ if (details?.type === "session.deleted") return reader.deleted(details.data?.sessionID)
373
+ if (details?.type === "server.connected") {
374
+ // What was published while the TUI was away was missed: look everything up again, and let nothing that
375
+ // was asked before the reconnection answer for now.
376
+ reader.reconnected()
377
+ return
378
+ }
379
+ if (details?.type !== "session.inbox.enqueued") return
380
+ const item = details.data?.item
381
+ // What was read of a session from the server is kept current: the host tells of each new notice.
382
+ reader.arrived(details.data?.sessionID, item)
383
+ // A run that starts, and a report or preview that arrives, opens the panel in the session on screen,
384
+ // unless the notice says that the settings leave the panel to /pr-panel.
385
+ if (item?.type !== "synthetic" || !opensPanel(item.payload?.text, item.payload?.metadata)) return
386
+ const route = context.ui.router.current()
387
+ if (route.type === "session" && route.sessionID === details.data.sessionID) show("notice")
388
+ })
389
+
390
+ context.ui.slot({
391
+ append: "app",
392
+ render: () => {
393
+ createEffect(() => {
394
+ const route = context.ui.router.current()
395
+ if (route.type !== "session" || !wanted.has(route.sessionID)) return
396
+ const sessionID = route.sessionID
397
+ // After the session's view has mounted.
398
+ setTimeout(() => {
399
+ const now = context.ui.router.current()
400
+ if (now.type === "session" && now.sessionID === sessionID && wanted.has(sessionID)) show("return")
401
+ }, 0)
402
+ })
403
+ return null
404
+ },
405
+ })
406
+
407
+ context.keymap.layer(() => ({
408
+ mode: "global",
409
+ commands: [
410
+ {
411
+ id: "azpr.panel",
412
+ title: "AZPR: show or hide the review panel",
413
+ description: "The sessions of the review in this conversation and its report or comment preview, rendered.",
414
+ group: "AZPR",
415
+ palette: true,
416
+ slash: { name: "pr-panel" },
417
+ run() {
418
+ const route = context.ui.router.current()
419
+ if (route.type !== "session") {
420
+ context.ui.toast.show({ message: "AZPR: open a conversation first.", variant: "info" })
421
+ return
422
+ }
423
+ if (shown(route.sessionID)) {
424
+ wanted.delete(route.sessionID)
425
+ context.ui.panel.close()
426
+ } else show()
427
+ },
428
+ },
429
+ ],
430
+ }))
431
+
432
+ return () => {
433
+ disposed = true
434
+ reader.dispose()
435
+ stop?.()
436
+ }
437
+ },
438
+ }