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

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,678 @@
1
+ // AZPR's part in OpenCode's terminal UI: a panel beside the conversation, and the dialogs of /pr-setup.
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
+ // The dialogs of /pr-setup ask for AZPR's settings (src/tui-setup.mjs says what and in which order) and
15
+ // hand every answer to the server part over the plugin's RPC. They read and write no file and make no
16
+ // request to Azure DevOps; a token is typed into a field that shows nothing of it, and is kept nowhere.
17
+ //
18
+ // This is the source. OpenCode loads src/tui.js, which scripts/build-tui.mjs compiles from it:
19
+ // OpenCode 2.3.0 compiles no JSX of a package it installed, so the package carries the result.
20
+ import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js"
21
+ import { MouseButton, SyntaxStyle, TextAttributes } from "@opentui/core"
22
+ import { PANEL, buildPanel, conversationOf, createReader, opensPanel } from "./tui-model.mjs"
23
+ import { SETUP_RPC, createSetup, isSetupNotice } from "./tui-setup.mjs"
24
+
25
+ // Short enough for one line of a toast, which the host wraps at about fifty characters.
26
+ const READY = "AZPR: report or preview ready. /pr-panel shows it."
27
+
28
+ /** The first of these theme tokens that this OpenCode defines; their names have changed between releases. */
29
+ const token = (theme, ...paths) => {
30
+ for (const path of paths) {
31
+ const value = path.split(".").reduce((node, name) => node?.[name], theme)
32
+ if (value !== undefined) return value
33
+ }
34
+ }
35
+ const colors = (theme) => {
36
+ const base = token(theme, "text.base", "text.default")
37
+ return {
38
+ base,
39
+ muted: token(theme, "text.muted", "text.subdued") ?? base,
40
+ running: token(theme, "text.feedback.info.base") ?? base,
41
+ failed: token(theme, "text.feedback.error.base") ?? base,
42
+ done: token(theme, "text.feedback.success.base") ?? base,
43
+ link: token(theme, "markdown.link") ?? base,
44
+ text: token(theme, "markdown.text") ?? base,
45
+ surface: token(theme, "background.raised.base"),
46
+ hover: token(theme, "background.raised.high"),
47
+ }
48
+ }
49
+
50
+ /** Markdown colors from the theme's own tokens, for the renderer of this TUI. */
51
+ function markdownStyle(context) {
52
+ const theme = context.theme
53
+ const base = token(theme, "text.base", "text.default")
54
+ const of = (name) => token(theme, `markdown.${name}`) ?? base
55
+ const styles = {
56
+ default: { fg: of("text") },
57
+ "markup.heading": { fg: of("heading"), bold: true },
58
+ "markup.strong": { fg: of("strong"), bold: true },
59
+ "markup.bold": { fg: of("strong"), bold: true },
60
+ "markup.italic": { fg: of("emphasis"), italic: true },
61
+ "markup.strikethrough": { fg: token(theme, "text.muted", "text.subdued") ?? base, dim: true },
62
+ "markup.raw": { fg: of("code") },
63
+ "markup.raw.inline": { fg: of("code") },
64
+ "markup.raw.block": { fg: of("codeBlock") },
65
+ "markup.link": { fg: of("link"), underline: true },
66
+ "markup.link.label": { fg: of("linkText"), underline: true },
67
+ "markup.link.url": { fg: of("link"), underline: true },
68
+ "markup.list": { fg: of("listItem") },
69
+ "markup.quote": { fg: of("blockQuote"), italic: true },
70
+ }
71
+ for (const level of [1, 2, 3, 4, 5, 6]) styles[`markup.heading.${level}`] = { fg: of("heading"), bold: true }
72
+ return SyntaxStyle.fromStyles(styles, context.renderer.nativeScene)
73
+ }
74
+
75
+ function Row(props) {
76
+ const [hover, setHover] = createSignal(false)
77
+ const mark = () => (props.row.state === "running" ? props.colors.running : props.row.state === "failed" ? props.colors.failed : props.colors.done)
78
+ return (
79
+ <box
80
+ flexDirection="row"
81
+ gap={1}
82
+ backgroundColor={hover() ? props.colors.hover : undefined}
83
+ onMouseOver={() => setHover(true)}
84
+ onMouseOut={() => setHover(false)}
85
+ onMouseUp={(event) => {
86
+ if (event.button !== MouseButton.LEFT) return
87
+ event.stopPropagation()
88
+ props.open(props.row.id)
89
+ }}
90
+ >
91
+ <text fg={mark()} flexShrink={0} selectable={false}>
92
+ {props.row.state === "running" ? "●" : "○"}
93
+ </text>
94
+ <text fg={props.colors.base} flexShrink={0} selectable={false}>
95
+ {props.row.label}
96
+ {props.row.report ? " (report)" : ""}
97
+ </text>
98
+ <text fg={props.colors.muted} flexShrink={0} selectable={false}>
99
+ {props.row.state}
100
+ </text>
101
+ <Show when={props.wide}>
102
+ <text fg={props.colors.link} attributes={TextAttributes.UNDERLINE} wrapMode="none" selectable={false}>
103
+ {props.row.id}
104
+ </text>
105
+ </Show>
106
+ </box>
107
+ )
108
+ }
109
+
110
+ function Panel(props) {
111
+ const context = props.context
112
+ const state = props.state
113
+ const model = createMemo(() => buildPanel(state.source, props.panel.sessionID, { known: state.known(), read: state.read(), titles: state.titles }))
114
+ const palette = createMemo(() => colors(context.theme))
115
+ let scroll
116
+
117
+ // The style follows the theme; a style no longer drawn is destroyed once the renderer is idle.
118
+ const release = (style) =>
119
+ Promise.resolve(context.renderer.idle?.())
120
+ .catch(() => undefined)
121
+ .finally(() => style.destroy?.())
122
+ const syntax = createMemo((previous) => {
123
+ const next = markdownStyle(context)
124
+ if (previous) release(previous)
125
+ return next
126
+ })
127
+ onCleanup(() => release(syntax()))
128
+
129
+ const close = () => {
130
+ state.dismiss(props.panel.sessionID)
131
+ props.panel.close()
132
+ }
133
+ const open = (sessionID) => context.ui.router.navigate({ type: "session", sessionID })
134
+
135
+ // The host gives the keyboard to a panel that opens, and has no way to open one without it. AZPR is
136
+ // driven by commands, so the panel hands the keyboard back to the prompt: the next command can be typed
137
+ // while the report is on screen, and a click in the panel (or the host's "Focus right pane") gives it
138
+ // the keyboard. A terminal too narrow for two panes shows the panel alone, with no prompt to return to.
139
+ // A panel that opened by itself must never be left with the keyboard: where it cannot hand it back, it
140
+ // closes again, and says that something is ready when a notice opened it.
141
+ // The two steps below run a moment after the panel mounted. By then the host may show another plugin's panel in
142
+ // this place, or another session: each step acts only while this panel is the one open here, and none outlives it.
143
+ const timers = new Set()
144
+ const mine = () => {
145
+ const current = context.ui.panel.current()
146
+ return current?.name === PANEL && current.sessionID === props.panel.sessionID
147
+ }
148
+ const later = (step, delay) => {
149
+ const timer = setTimeout(() => {
150
+ timers.delete(timer)
151
+ if (mine()) step()
152
+ }, delay)
153
+ timers.add(timer)
154
+ }
155
+ onCleanup(() => {
156
+ for (const timer of timers) clearTimeout(timer)
157
+ timers.clear()
158
+ })
159
+ onMount(() => {
160
+ const unasked = state.takeUnasked()
161
+ const withdraw = () => {
162
+ state.dismiss(props.panel.sessionID)
163
+ props.panel.close()
164
+ if (unasked === "notice") context.ui.toast.show({ message: READY, variant: "info" })
165
+ }
166
+ if (props.panel.presentation === "fullscreen") return unasked ? withdraw() : undefined
167
+ later(() => {
168
+ context.keymap.dispatch("pane.focus.left")
169
+ if (unasked) later(() => props.panel.focused && withdraw(), 50)
170
+ }, 0)
171
+ })
172
+
173
+ // Sessions the host has not loaded here: a run's sessions after a TUI restart, the conversation of one of them.
174
+ createEffect(() => {
175
+ for (const sessionID of model().needs) void state.lookup(sessionID)
176
+ })
177
+ // The report of a review waits in its session's inbox; in one of AZPR's own sessions the notices are in the
178
+ // conversation's. The model names an inbox only once the session proved to be this conversation's.
179
+ createEffect(() => {
180
+ const inbox = model().inbox
181
+ if (inbox) state.readInbox(inbox.sessionID, inbox.token, true)
182
+ const notices = model().notices
183
+ if (notices) state.readInbox(notices.sessionID, notices.token, false)
184
+ })
185
+
186
+ // Active only while the panel has the keyboard; the IDs let a user bind other keys in the TUI's configuration.
187
+ const page = () => Math.max(4, (scroll?.viewport?.height ?? scroll?.height ?? 10) - 2)
188
+ context.keymap.layer(() => ({
189
+ commands: [
190
+ { id: "azpr.panel.close", title: "Close the AZPR panel", group: "AZPR", bind: "escape,q", run: close },
191
+ { id: "azpr.panel.up", title: "AZPR panel: scroll up", group: "AZPR", bind: "up,k", run: () => scroll?.scrollBy(-1) },
192
+ { id: "azpr.panel.down", title: "AZPR panel: scroll down", group: "AZPR", bind: "down,j", run: () => scroll?.scrollBy(1) },
193
+ { id: "azpr.panel.page.up", title: "AZPR panel: page up", group: "AZPR", bind: "pageup", run: () => scroll?.scrollBy(-page()) },
194
+ { id: "azpr.panel.page.down", title: "AZPR panel: page down", group: "AZPR", bind: "pagedown", run: () => scroll?.scrollBy(page()) },
195
+ { id: "azpr.panel.top", title: "AZPR panel: go to the top", group: "AZPR", bind: "home", run: () => scroll?.scrollTo(0) },
196
+ { id: "azpr.panel.bottom", title: "AZPR panel: go to the end", group: "AZPR", bind: "end", run: () => scroll?.scrollTo(scroll.scrollHeight) },
197
+ ],
198
+ }))
199
+
200
+ // Rows are keyed by session, so a row keeps its place and its hover while the list is worked out again.
201
+ const ids = createMemo(() => model().rows.map((row) => row.id), [], { equals: (a, b) => a.length === b.length && a.every((id, index) => id === b[index]) })
202
+ const row = (id) => model().rows.find((item) => item.id === id) ?? { id, label: "", state: "", report: false }
203
+
204
+ return (
205
+ <box flexDirection="column" flexGrow={1} minHeight={0} paddingLeft={2} paddingRight={2} paddingTop={1}>
206
+ <box flexDirection="row" flexShrink={0}>
207
+ <text fg={palette().base} flexShrink={0}>
208
+ <b>AZPR</b>
209
+ <Show when={model().run}>
210
+ <span> {model().run}</span>
211
+ </Show>
212
+ <Show when={model().status}>
213
+ <span style={{ fg: palette().muted }}> · {model().status}</span>
214
+ </Show>
215
+ </text>
216
+ <box flexGrow={1} />
217
+ <text
218
+ fg={palette().muted}
219
+ flexShrink={0}
220
+ selectable={false}
221
+ onMouseUp={(event) => {
222
+ if (event.button !== MouseButton.LEFT) return
223
+ event.stopPropagation()
224
+ close()
225
+ }}
226
+ >
227
+ close
228
+ </text>
229
+ </box>
230
+ <Show when={model().progress}>
231
+ <text fg={palette().muted} flexShrink={0}>
232
+ {model().progress}
233
+ </text>
234
+ </Show>
235
+ <scrollbox ref={(element) => (scroll = element)} flexGrow={1} minHeight={0} paddingTop={1} verticalScrollbarOptions={{ visible: false }} contentOptions={{ minHeight: 0 }}>
236
+ <Show when={ids().length > 0 || model().deleted > 0}>
237
+ <box flexDirection="column" flexShrink={0} paddingBottom={1}>
238
+ <Show when={ids().length > 0}>
239
+ <text fg={palette().muted} selectable={false}>
240
+ Sessions (click one to open it)
241
+ </text>
242
+ </Show>
243
+ <For each={ids()}>{(id) => <Row row={row(id)} colors={palette()} wide={props.panel.width >= 64} open={open} />}</For>
244
+ <Show when={model().deleted > 0}>
245
+ <text fg={palette().muted}>{model().deleted} session(s) were deleted when their run ended.</text>
246
+ </Show>
247
+ </box>
248
+ </Show>
249
+ <Show
250
+ when={model().markdown}
251
+ fallback={
252
+ <text fg={palette().muted}>
253
+ {model().loading
254
+ ? "Loading the report…"
255
+ : model().inbox
256
+ ? "The report is in its session: open it above."
257
+ : model().run
258
+ ? "No report or preview yet."
259
+ : "No AZPR run in this conversation yet."}
260
+ </text>
261
+ }
262
+ >
263
+ <Show when={model().documentHead}>
264
+ <text fg={palette().muted} flexShrink={0} paddingBottom={1}>
265
+ {model().documentHead}
266
+ </text>
267
+ </Show>
268
+ <markdown syntaxStyle={syntax()} content={model().markdown} conceal tableOptions={{ style: "grid", cellPaddingX: 1 }} fg={palette().text} bg={palette().surface} />
269
+ </Show>
270
+ </scrollbox>
271
+ </box>
272
+ )
273
+ }
274
+
275
+ /** The review panel: opens by itself or with /pr-panel, and only reads. Returns its cleanup, or nothing on a host without a place for it. */
276
+ function panelPart(context) {
277
+ // A host without these parts of the plugin API has no place for the panel: stay out of its way.
278
+ const needed = [context?.ui?.slot, context?.ui?.panel?.open, context?.ui?.router?.navigate, context?.keymap?.layer, context?.data?.listen, context?.data?.session?.pending?.list]
279
+ if (needed.some((part) => typeof part !== "function")) return undefined
280
+ const data = context.data
281
+ // Set when the TUI unloads the plugin: nothing is asked of the host after that.
282
+ let disposed = false
283
+ // The host keeps the messages and the inbox of the session on screen and of open tabs, and drops those of
284
+ // other sessions again. What the panel needs of another session (the report waiting in a review session's
285
+ // inbox, the notices of the conversation when one of AZPR's own sessions is on screen) is read from the
286
+ // server by the reader in tui-model.mjs, which also knows which sessions are gone. `version` makes what it
287
+ // holds reactive.
288
+ const [version, setVersion] = createSignal(0)
289
+ const reader = createReader({
290
+ inbox: (sessionID) => context.client.session.inbox.list({ sessionID }),
291
+ context: typeof context.client?.session?.context === "function" ? (sessionID) => context.client.session.context({ sessionID }) : undefined,
292
+ lookup: (sessionID) => data.session.sync(sessionID),
293
+ present: (sessionID) => data.session.get(sessionID),
294
+ list: (cursor) => context.client.session.list(cursor ? { cursor } : {}),
295
+ changed: () => setVersion((count) => count + 1),
296
+ })
297
+ const source = {
298
+ session: (id) => data.session.get(id),
299
+ sessions: () => data.session.list(),
300
+ status: (id) => data.session.status(id),
301
+ messages: (id) => data.session.message.list(id),
302
+ pending: (id) => (version(), [...data.session.pending.list(id), ...reader.entries(id)]),
303
+ }
304
+ const known = () => (version(), reader.known())
305
+ const read = () => (version(), reader.read())
306
+
307
+ // Sessions whose panel this plugin opened and the user has not closed. The host closes a panel when the
308
+ // screen leaves its session; coming back to such a session opens it again.
309
+ const wanted = new Set()
310
+ // Why the panel is being opened without the user asking: "notice" or "return"; undefined when asked.
311
+ let unasked
312
+ // The session in which another plugin's panel is open; the host shows one panel at a time.
313
+ let occupied
314
+ const state = {
315
+ source,
316
+ known,
317
+ read,
318
+ titles: new Map(),
319
+ lookup: reader.lookup,
320
+ readInbox: reader.readInbox,
321
+ dismiss: (sessionID) => void wanted.delete(sessionID),
322
+ takeUnasked: () => {
323
+ const value = unasked
324
+ unasked = undefined
325
+ return value
326
+ },
327
+ }
328
+
329
+ context.ui.slot({
330
+ append: "session.panel",
331
+ render: (panel) => {
332
+ // Every contribution is told which panel is open: remember where it is someone else's.
333
+ createEffect(() => {
334
+ occupied = panel.name === PANEL ? undefined : panel.sessionID
335
+ })
336
+ onCleanup(() => {
337
+ occupied = undefined
338
+ })
339
+ return (
340
+ <Show when={panel.name === PANEL}>
341
+ <Panel context={context} panel={panel} state={state} />
342
+ </Show>
343
+ )
344
+ },
345
+ })
346
+
347
+ const shown = (sessionID) => {
348
+ const current = context.ui.panel.current()
349
+ return current?.name === PANEL && current.sessionID === sessionID
350
+ }
351
+ /**
352
+ * Show the panel in the session on screen. `byItself` says why when the user did not ask ("notice": one
353
+ * arrived; "return": the screen came back to a session that had the panel): then neither a dialog nor
354
+ * another plugin's panel is disturbed.
355
+ */
356
+ const show = (byItself) => {
357
+ if (disposed) return false
358
+ const route = context.ui.router.current()
359
+ if (route.type !== "session") return false
360
+ const sessionID = route.sessionID
361
+ // After a TUI restart the host has not loaded a run's sessions: the reader asks the server for them.
362
+ void reader.discover(conversationOf(data.session.get(sessionID)) ?? sessionID)
363
+ wanted.add(sessionID)
364
+ if (shown(sessionID)) return true
365
+ if (byItself && (occupied === sessionID || context.keymap.mode?.current?.() === "modal")) {
366
+ if (byItself === "notice") context.ui.toast.show({ message: READY, variant: "info" })
367
+ return false
368
+ }
369
+ unasked = byItself
370
+ return context.ui.panel.open(PANEL)
371
+ }
372
+
373
+ const stop = data.listen((event) => {
374
+ if (disposed) return
375
+ const details = event?.details
376
+ if (details?.type === "session.deleted") return reader.deleted(details.data?.sessionID)
377
+ if (details?.type === "server.connected") {
378
+ // What was published while the TUI was away was missed: look everything up again, and let nothing that
379
+ // was asked before the reconnection answer for now.
380
+ reader.reconnected()
381
+ return
382
+ }
383
+ if (details?.type !== "session.inbox.enqueued") return
384
+ const item = details.data?.item
385
+ // What was read of a session from the server is kept current: the host tells of each new notice.
386
+ reader.arrived(details.data?.sessionID, item)
387
+ // A run that starts, and a report or preview that arrives, opens the panel in the session on screen,
388
+ // unless the notice says that the settings leave the panel to /pr-panel.
389
+ if (item?.type !== "synthetic" || !opensPanel(item.payload?.text, item.payload?.metadata)) return
390
+ const route = context.ui.router.current()
391
+ if (route.type === "session" && route.sessionID === details.data.sessionID) show("notice")
392
+ })
393
+
394
+ context.ui.slot({
395
+ append: "app",
396
+ render: () => {
397
+ createEffect(() => {
398
+ const route = context.ui.router.current()
399
+ if (route.type !== "session" || !wanted.has(route.sessionID)) return
400
+ const sessionID = route.sessionID
401
+ // After the session's view has mounted.
402
+ setTimeout(() => {
403
+ const now = context.ui.router.current()
404
+ if (now.type === "session" && now.sessionID === sessionID && wanted.has(sessionID)) show("return")
405
+ }, 0)
406
+ })
407
+ return null
408
+ },
409
+ })
410
+
411
+ context.keymap.layer(() => ({
412
+ mode: "global",
413
+ commands: [
414
+ {
415
+ id: "azpr.panel",
416
+ title: "AZPR: show or hide the review panel",
417
+ description: "The sessions of the review in this conversation and its report or comment preview, rendered.",
418
+ group: "AZPR",
419
+ palette: true,
420
+ slash: { name: "pr-panel" },
421
+ run() {
422
+ const route = context.ui.router.current()
423
+ if (route.type !== "session") {
424
+ context.ui.toast.show({ message: "AZPR: open a conversation first.", variant: "info" })
425
+ return
426
+ }
427
+ if (shown(route.sessionID)) {
428
+ wanted.delete(route.sessionID)
429
+ context.ui.panel.close()
430
+ } else show()
431
+ },
432
+ },
433
+ ],
434
+ }))
435
+
436
+ return () => {
437
+ disposed = true
438
+ reader.dispose()
439
+ stop?.()
440
+ }
441
+ }
442
+
443
+ /**
444
+ * A dialog that takes a secret and shows nothing of it. The host's own text prompt shows what is typed, and
445
+ * its text fields have no hidden mode, so keys and pastes are taken here: the value lives in this closure
446
+ * only and the screen holds bullets and a count, which neither a glance nor the terminal's own copy can read.
447
+ * Resolves with the value ('' only where `optional`), or with undefined when the dialog was closed.
448
+ */
449
+ function askSecret(context, options) {
450
+ return new Promise((resolve) => {
451
+ let settled = false
452
+ const done = (value) => {
453
+ if (settled) return
454
+ settled = true
455
+ resolve(value)
456
+ }
457
+ context.ui.dialog.show(
458
+ () => (
459
+ <Secret
460
+ context={context}
461
+ options={options}
462
+ done={(value) => {
463
+ done(value)
464
+ context.ui.dialog.clear()
465
+ }}
466
+ />
467
+ ),
468
+ () => done(undefined),
469
+ )
470
+ })
471
+ }
472
+
473
+ function Secret(props) {
474
+ let field
475
+ let value = ""
476
+ const [length, setLength] = createSignal(0)
477
+ const palette = createMemo(() => colors(props.context.theme))
478
+ // Far longer than any token: what is pasted beyond that is not kept.
479
+ const set = (next) => {
480
+ value = next.slice(0, 2048)
481
+ setLength(value.length)
482
+ }
483
+ const submit = () => {
484
+ if (value || props.options.optional) props.done(value)
485
+ }
486
+ const key = (event) => {
487
+ const name = event?.name
488
+ if (name === "return" || name === "enter" || name === "kpenter") {
489
+ event.preventDefault?.()
490
+ return submit()
491
+ }
492
+ if (name === "backspace" || name === "delete") {
493
+ event.preventDefault?.()
494
+ return set(value.slice(0, -1))
495
+ }
496
+ if (event?.ctrl && name === "u") {
497
+ event.preventDefault?.()
498
+ return set("")
499
+ }
500
+ const typed = event?.sequence
501
+ // One printable character; what a terminal sends for other keys is longer or starts with a control character.
502
+ if (!event?.ctrl && !event?.meta && typeof typed === "string" && [...typed].length === 1 && typed >= " " && typed !== "\x7f") {
503
+ event.preventDefault?.()
504
+ set(value + typed)
505
+ }
506
+ }
507
+ // A token is one word: line breaks and blanks around a pasted one are not part of it.
508
+ const paste = (event) => {
509
+ event?.preventDefault?.()
510
+ let pasted = ""
511
+ try {
512
+ pasted = new TextDecoder().decode(event?.bytes ?? new Uint8Array())
513
+ } catch {}
514
+ set(value + pasted.replace(/\s+/g, ""))
515
+ }
516
+ onMount(() => {
517
+ const timer = setTimeout(() => {
518
+ if (field && !field.isDestroyed) field.focus()
519
+ }, 1)
520
+ onCleanup(() => clearTimeout(timer))
521
+ })
522
+ onCleanup(() => {
523
+ value = ""
524
+ })
525
+ return (
526
+ <box flexDirection="column" paddingLeft={2} paddingRight={2} paddingTop={1} paddingBottom={1} gap={1}>
527
+ <text fg={palette().base}>
528
+ <b>{props.options.title}</b>
529
+ </text>
530
+ <Show when={props.options.problem}>
531
+ <text fg={palette().failed}>{props.options.problem}</text>
532
+ </Show>
533
+ <text fg={palette().muted}>{props.options.description}</text>
534
+ <box
535
+ ref={(node) => {
536
+ field = node
537
+ }}
538
+ focusable={true}
539
+ onKeyDown={key}
540
+ onPaste={paste}
541
+ onMouseDown={() => {
542
+ if (field && !field.isDestroyed) field.focus()
543
+ }}
544
+ backgroundColor={palette().hover ?? palette().surface}
545
+ height={1}
546
+ paddingLeft={1}
547
+ flexShrink={0}
548
+ >
549
+ <text fg={length() ? palette().base : palette().muted}>
550
+ {length() ? `${"•".repeat(Math.min(length(), 16))} (${length()} characters, hidden)` : "Paste the token here; it is not shown"}
551
+ </text>
552
+ </box>
553
+ <text fg={palette().muted}>enter save · ctrl+u clear · esc leave</text>
554
+ </box>
555
+ )
556
+ }
557
+
558
+ /**
559
+ * The dialogs of /pr-setup: they open when the server part answers /pr-setup without options in the session
560
+ * on screen, and from the command palette. Returns its cleanup, or nothing on a host without dialogs or RPC.
561
+ */
562
+ function setupPart(context) {
563
+ const needed = [context?.ui?.dialog?.select, context?.ui?.dialog?.prompt, context?.ui?.dialog?.confirm, context?.ui?.dialog?.alert, context?.ui?.dialog?.show, context?.ui?.toast?.show, context?.client?.rpc, context?.keymap?.layer, context?.data?.listen, context?.data?.location?.model?.list]
564
+ if (needed.some((part) => typeof part !== "function")) return undefined
565
+ let disposed = false
566
+ const rpc = context.client.rpc(SETUP_RPC)
567
+ // Each project directory has a server part of its own. Setup talks to the one of the session on screen, where
568
+ // the review commands that follow will run; without a session, to the one of the directory this TUI works in.
569
+ const onScreen = () => {
570
+ const route = context.ui.router?.current?.()
571
+ const session = route?.type === "session" ? context.data.session?.get?.(route.sessionID) : undefined
572
+ return session?.location ?? context.location ?? context.data.location.default?.()
573
+ }
574
+ // While a setup is open its place is fixed: another project's session may come on screen meanwhile, and what
575
+ // was checked for one project's server part must not be saved by another's.
576
+ let pinned
577
+ const place = () => (pinned ? pinned.at : onScreen())
578
+ const call = (method, input = {}) => {
579
+ const directory = place()?.directory
580
+ return rpc[method](input, directory ? { location: { directory } } : undefined)
581
+ }
582
+ // The models the host offers that can call tools, as the server part will accept them.
583
+ const models = async () => {
584
+ const at = place()
585
+ await Promise.all([context.data.location.model.sync?.(at), context.data.location.provider?.sync?.(at)]).catch(() => {})
586
+ const providers = new Map((context.data.location.provider?.list?.(at) ?? []).map((provider) => [provider.id, provider.name ?? provider.id]))
587
+ return (context.data.location.model.list(at) ?? [])
588
+ .filter((model) => model?.enabled !== false && model?.capabilities?.tools === true && typeof model.providerID === "string" && typeof model.id === "string")
589
+ .map((model) => ({
590
+ id: `${model.providerID}/${model.id}`,
591
+ name: typeof model.name === "string" && model.name ? model.name : model.id,
592
+ provider: providers.get(model.providerID) ?? model.providerID,
593
+ variants: (Array.isArray(model.variants) ? model.variants : []).map((variant) => variant?.id).filter((id) => typeof id === "string" && id),
594
+ }))
595
+ }
596
+ // The commands as the server has them now. OpenCode 2.3.0 does not tell its clients where commands changed
597
+ // when a plugin changes them after it was loaded, so after a first setup the list is read again here.
598
+ const commandsChanged = () => {
599
+ if (disposed) return
600
+ const at = place()
601
+ try {
602
+ context.data.location.command?.invalidate?.(at)
603
+ void Promise.resolve(context.data.location.command?.sync?.(at)).catch(() => {})
604
+ } catch {}
605
+ }
606
+ const setup = createSetup({
607
+ call,
608
+ dialog: context.ui.dialog,
609
+ secret: (options) => askSecret(context, options),
610
+ toast: (options) => {
611
+ if (!disposed) context.ui.toast.show(options)
612
+ },
613
+ models,
614
+ loaded: commandsChanged,
615
+ pin: () => {
616
+ const mine = (pinned = { at: onScreen() })
617
+ return () => {
618
+ if (pinned === mine) pinned = undefined
619
+ }
620
+ },
621
+ })
622
+ // Also when the settings were saved with options, or loaded by another command: the server part says so.
623
+ let unsubscribe
624
+ try {
625
+ unsubscribe = rpc.events?.on?.("loaded", commandsChanged)
626
+ } catch {}
627
+
628
+ const stop = context.data.listen((event) => {
629
+ if (disposed) return
630
+ const details = event?.details
631
+ if (details?.type !== "session.inbox.enqueued") return
632
+ const item = details.data?.item
633
+ if (item?.type !== "synthetic" || !isSetupNotice(item.payload?.metadata)) return
634
+ // Only where the person just typed /pr-setup: the session on screen.
635
+ const route = context.ui.router?.current?.()
636
+ if (route?.type === "session" && route.sessionID === details.data.sessionID) void setup.open()
637
+ })
638
+
639
+ context.keymap.layer(() => ({
640
+ mode: "global",
641
+ commands: [
642
+ {
643
+ id: "azpr.setup",
644
+ title: "AZPR: settings",
645
+ description: "Set AZPR up, or show and change its settings: organization, token, proxy, models and more.",
646
+ group: "AZPR",
647
+ palette: true,
648
+ run() {
649
+ void setup.open()
650
+ },
651
+ },
652
+ ],
653
+ }))
654
+
655
+ // Say once how to set AZPR up when it has no usable settings. The server part may still be loading when the
656
+ // TUI starts, so it is asked a second time a little later; neither timer outlives this part.
657
+ const timers = [1500, 6000].map((delay) => setTimeout(() => !disposed && void setup.hint(), delay))
658
+
659
+ return () => {
660
+ disposed = true
661
+ // A setup that is open ends at its next step: nothing is saved by a part that was unloaded.
662
+ setup.stop()
663
+ timers.forEach(clearTimeout)
664
+ stop?.()
665
+ try {
666
+ unsubscribe?.()
667
+ } catch {}
668
+ }
669
+ }
670
+
671
+ export default {
672
+ id: "azpr.tui",
673
+ setup(context) {
674
+ // Each part checks for itself what it needs of the host, and stays out of the way where that is missing.
675
+ const stops = [panelPart(context), setupPart(context)].filter((stop) => typeof stop === "function")
676
+ return () => stops.forEach((stop) => stop())
677
+ },
678
+ }