@daoninc/opencode-pr-tracker 0.1.0 → 0.1.1

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/README.md CHANGED
@@ -2,16 +2,19 @@
2
2
 
3
3
  ## Install
4
4
 
5
- Initial npm release is pending. After publication, add to the existing `plugins`
5
+ Add the fixed `0.1.1` npm release to the existing `plugins`
6
6
  array in `~/.config/opencode/cli.json`:
7
7
 
8
8
  ```json
9
- { "plugins": ["@daoninc/opencode-pr-tracker@0.1.0"] }
9
+ { "plugins": ["@daoninc/opencode-pr-tracker@0.1.1"] }
10
10
  ```
11
11
 
12
12
  Requires OpenCode V2 and a local authenticated GitHub CLI (`gh auth login`). Remove
13
13
  the equivalent local entry when switching to npm. Do not enable this port alongside
14
- the upstream tracker: they share a runtime ID. This package is TUI-only.
14
+ the upstream tracker: their functionality overlaps, and published `0.1.0` still
15
+ shares its runtime ID. Version `0.1.1` uses `daoninc.pr-tracker` and ships
16
+ Solid-compiled JavaScript. Do not use the raw-TSX `0.1.0` build with OpenCode 2.3.1.
17
+ This package is TUI-only.
15
18
 
16
19
  ## Attribution and features
17
20
 
@@ -0,0 +1,4 @@
1
+ export function prUrls(command, output) {
2
+ if (typeof command !== "string" || !/\bgh\s+pr\s+create\b/.test(command) || typeof output !== "string") return [];
3
+ return [...output.matchAll(/https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+/g)].map(match => match[0]);
4
+ }
package/dist/tui.js ADDED
@@ -0,0 +1,313 @@
1
+ import { createComponent as _$createComponent } from "@opentui/solid";
2
+ import { memo as _$memo } from "@opentui/solid";
3
+ import { effect as _$effect } from "@opentui/solid";
4
+ import { createTextNode as _$createTextNode } from "@opentui/solid";
5
+ import { insertNode as _$insertNode } from "@opentui/solid";
6
+ import { insert as _$insert } from "@opentui/solid";
7
+ import { setProp as _$setProp } from "@opentui/solid";
8
+ import { createElement as _$createElement } from "@opentui/solid";
9
+ import { Plugin } from "@opencode/plugin/tui";
10
+ import { createEffect, createSignal, untrack } from "solid-js";
11
+ import { prUrls } from "./reference.js";
12
+ const POLL_MS = 45_000;
13
+ const COLORS = {
14
+ OPEN: "#a6da95",
15
+ MERGED: "#c6a0f6",
16
+ CLOSED: "#ed8796"
17
+ };
18
+ async function run(cwd, ...command) {
19
+ const proc = Bun.spawn(command, {
20
+ cwd,
21
+ stdout: "pipe",
22
+ stderr: "ignore"
23
+ });
24
+ const stdout = await proc.stdout.text();
25
+ return {
26
+ code: await proc.exited,
27
+ stdout: stdout.trim()
28
+ };
29
+ }
30
+ async function fetchPr(directory, reference) {
31
+ try {
32
+ const result = await run(directory, "gh", "pr", "view", ...(reference ? [reference] : []), "--json", "number,url,state,title,isDraft,mergedAt,statusCheckRollup");
33
+ if (result.code !== 0) return undefined;
34
+ const parsed = JSON.parse(result.stdout);
35
+ if (typeof parsed !== "object" || parsed === null) return undefined;
36
+ const pr = parsed;
37
+ return typeof pr.number === "number" && typeof pr.url === "string" ? pr : undefined;
38
+ } catch {
39
+ return undefined;
40
+ }
41
+ }
42
+ async function fetchAuthoredPrs(directory) {
43
+ try {
44
+ const result = await run(directory, "gh", "pr", "list", "--author", "@me", "--state", "open", "--limit", "100", "--json", "number,url,state,title,isDraft,mergedAt,statusCheckRollup");
45
+ if (result.code !== 0) return undefined;
46
+ const parsed = JSON.parse(result.stdout);
47
+ if (!Array.isArray(parsed)) return undefined;
48
+ return parsed.filter(pr => typeof pr === "object" && pr !== null && typeof pr.number === "number" && typeof pr.url === "string");
49
+ } catch {
50
+ return undefined;
51
+ }
52
+ }
53
+ function inputCommand(input) {
54
+ return typeof input === "object" && input !== null && !Array.isArray(input) && "command" in input ? input.command : undefined;
55
+ }
56
+ function createdPrUrls(messages) {
57
+ const urls = new Set();
58
+ const adopt = (command, output) => prUrls(command, output).forEach(url => urls.add(url));
59
+ for (const message of messages) {
60
+ if (message.type === "shell") {
61
+ if (message.status === "exited" && message.exit === 0) adopt(message.command, message.output?.output);
62
+ continue;
63
+ }
64
+ if (message.type !== "assistant") continue;
65
+ for (const part of message.content) {
66
+ if (part.type !== "tool" || part.state.status !== "completed") continue;
67
+ adopt(inputCommand(part.state.input), part.state.content.filter(item => item.type === "text").map(item => item.text).join("\n"));
68
+ }
69
+ }
70
+ return [...urls];
71
+ }
72
+ function checkStatus(pr) {
73
+ const checks = (pr.statusCheckRollup ?? []).filter(check => check.conclusion !== "SKIPPED");
74
+ if (checks.some(check => check.status && check.status !== "COMPLETED")) return "pending";
75
+ if (checks.some(check => ["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE", "STALE"].includes(check.conclusion ?? ""))) return "failed";
76
+ return checks.length > 0 ? "passed" : "none";
77
+ }
78
+ function statusIcon(pr) {
79
+ if (pr.isDraft) return "◇";
80
+ if (pr.state === "MERGED") return "✓";
81
+ if (pr.state === "CLOSED") return "×";
82
+ const checks = checkStatus(pr);
83
+ if (checks === "pending") return "◌";
84
+ if (checks === "failed") return "×";
85
+ return "●";
86
+ }
87
+ function statusColor(pr) {
88
+ if (pr.isDraft) return "#8aadf4";
89
+ if (pr.state === "MERGED") return COLORS.MERGED;
90
+ const checks = checkStatus(pr);
91
+ if (pr.state === "CLOSED" || checks === "failed") return COLORS.CLOSED;
92
+ if (checks === "pending") return "#eed49f";
93
+ return COLORS.OPEN;
94
+ }
95
+ function changed(left, right) {
96
+ return JSON.stringify(left) !== JSON.stringify(right);
97
+ }
98
+ function PrRow(props) {
99
+ const [hovered, setHovered] = createSignal(false);
100
+ return (() => {
101
+ var _el$ = _$createElement("box"),
102
+ _el$2 = _$createElement("text"),
103
+ _el$3 = _$createElement("text"),
104
+ _el$4 = _$createElement("span"),
105
+ _el$5 = _$createTextNode(`#`),
106
+ _el$6 = _$createTextNode(` `);
107
+ _$insertNode(_el$, _el$2);
108
+ _$insertNode(_el$, _el$3);
109
+ _$setProp(_el$, "flexDirection", "row");
110
+ _$setProp(_el$, "gap", 1);
111
+ _$setProp(_el$, "onMouseOver", () => setHovered(true));
112
+ _$setProp(_el$, "onMouseOut", () => setHovered(false));
113
+ _$setProp(_el$, "onMouseUp", () => Bun.spawn(["open", props.pr.url]));
114
+ _$setProp(_el$2, "flexShrink", 0);
115
+ _$insert(_el$2, () => statusIcon(props.pr));
116
+ _$insertNode(_el$3, _el$4);
117
+ _$insertNode(_el$3, _el$6);
118
+ _$setProp(_el$3, "wrapMode", "word");
119
+ _$insertNode(_el$4, _el$5);
120
+ _$insert(_el$4, () => props.pr.number, null);
121
+ _$insert(_el$3, () => props.pr.title, null);
122
+ _$effect(_p$ => {
123
+ var _v$ = hovered() ? props.context.theme.background.action.primary.hovered : undefined,
124
+ _v$2 = statusColor(props.pr),
125
+ _v$3 = props.context.theme.text.base,
126
+ _v$4 = {
127
+ fg: hovered() ? props.context.theme.text.base : props.context.theme.text.muted
128
+ };
129
+ _v$ !== _p$.e && (_p$.e = _$setProp(_el$, "backgroundColor", _v$, _p$.e));
130
+ _v$2 !== _p$.t && (_p$.t = _$setProp(_el$2, "fg", _v$2, _p$.t));
131
+ _v$3 !== _p$.a && (_p$.a = _$setProp(_el$3, "fg", _v$3, _p$.a));
132
+ _v$4 !== _p$.o && (_p$.o = _$setProp(_el$4, "style", _v$4, _p$.o));
133
+ return _p$;
134
+ }, {
135
+ e: undefined,
136
+ t: undefined,
137
+ a: undefined,
138
+ o: undefined
139
+ });
140
+ return _el$;
141
+ })();
142
+ }
143
+ export default Plugin.define({
144
+ id: "daoninc.pr-tracker",
145
+ setup: async context => {
146
+ const location = context.location ?? context.data.location.default();
147
+ const sessionDirectory = sessionID => context.data.session.get(sessionID)?.location.directory ?? location.directory;
148
+ const [state, update] = context.storage.memory("pr-sidebar-v2", {
149
+ initial: {
150
+ roots: {},
151
+ prs: {},
152
+ directories: {}
153
+ }
154
+ });
155
+ const recovered = new Set();
156
+ const branchLookups = new Set();
157
+ const authoredLookups = new Set();
158
+ const [branchPr, setBranchPr] = createSignal();
159
+ const [authoredPrs, setAuthoredPrs] = createSignal();
160
+ let activeRoot = "";
161
+ let activeDirectory = "";
162
+ let disposed = false;
163
+ let inFlight = false;
164
+ const adopt = async (sessionID, urls, directory = sessionDirectory(sessionID)) => {
165
+ if (disposed || urls.length === 0) return;
166
+ const root = context.data.session.root(sessionID);
167
+ const previous = state.roots[root] ?? [];
168
+ const next = [...new Set([...previous, ...urls])];
169
+ if (next.length !== previous.length || urls.some(url => state.directories?.[url] !== directory)) update(draft => {
170
+ draft.roots[root] = next;
171
+ draft.directories ??= {};
172
+ for (const url of urls) draft.directories[url] = directory;
173
+ });
174
+ const missing = urls.filter(url => !state.prs[url]);
175
+ const prs = (await Promise.all(missing.map(url => fetchPr(directory, url)))).filter(pr => pr !== undefined);
176
+ if (disposed || prs.length === 0) return;
177
+ if (prs.some(pr => changed(state.prs[pr.url], pr))) update(draft => {
178
+ for (const pr of prs) draft.prs[pr.url] = pr;
179
+ });
180
+ };
181
+ const recover = sessionID => {
182
+ const root = context.data.session.root(sessionID);
183
+ if (recovered.has(root)) return;
184
+ recovered.add(root);
185
+ for (const member of new Set([root, ...context.data.session.family(root)])) void adopt(member, createdPrUrls(context.data.session.message.list(member)));
186
+ };
187
+ const refreshBranch = async () => {
188
+ const directory = activeDirectory;
189
+ if (disposed || !directory || branchLookups.has(directory)) return;
190
+ branchLookups.add(directory);
191
+ try {
192
+ const pr = await fetchPr(directory);
193
+ if (disposed || activeDirectory !== directory) return;
194
+ const previous = branchPr();
195
+ if (!pr) {
196
+ if (previous?.directory === directory) setBranchPr(undefined);
197
+ } else if (previous?.directory !== directory || changed(previous.pr, pr)) {
198
+ setBranchPr({
199
+ directory,
200
+ pr
201
+ });
202
+ }
203
+ } finally {
204
+ branchLookups.delete(directory);
205
+ }
206
+ };
207
+ const refreshAuthored = async () => {
208
+ const directory = activeDirectory;
209
+ if (disposed || !directory || authoredLookups.has(directory)) return;
210
+ authoredLookups.add(directory);
211
+ try {
212
+ const prs = await fetchAuthoredPrs(directory);
213
+ if (disposed || activeDirectory !== directory || !prs) return;
214
+ const previous = authoredPrs();
215
+ if (previous?.directory !== directory || JSON.stringify(previous.prs) !== JSON.stringify(prs)) setAuthoredPrs({
216
+ directory,
217
+ prs
218
+ });
219
+ } finally {
220
+ authoredLookups.delete(directory);
221
+ }
222
+ };
223
+ const refresh = async () => {
224
+ if (disposed || inFlight) return;
225
+ inFlight = true;
226
+ try {
227
+ const urls = state.roots[activeRoot] ?? [];
228
+ const prs = (await Promise.all(urls.map(url => fetchPr(state.directories?.[url] ?? sessionDirectory(activeRoot), url)))).filter(pr => pr !== undefined);
229
+ if (disposed || !prs.some(pr => changed(state.prs[pr.url], pr))) return;
230
+ update(draft => {
231
+ for (const pr of prs) draft.prs[pr.url] = pr;
232
+ });
233
+ } finally {
234
+ inFlight = false;
235
+ }
236
+ };
237
+ const timer = setInterval(() => {
238
+ void refreshBranch();
239
+ void refreshAuthored();
240
+ void refresh();
241
+ }, POLL_MS);
242
+ const unsubscribers = [context.data.on("session.shell.ended", event => {
243
+ if (event.data.shell.status !== "exited" || event.data.shell.exit !== 0) return;
244
+ void adopt(event.data.sessionID, prUrls(event.data.shell.command, event.data.output.output), event.location?.directory);
245
+ }), context.data.on("session.tool.success", event => {
246
+ const message = context.data.session.message.get(event.data.sessionID, event.data.assistantMessageID);
247
+ if (message?.type !== "assistant") return;
248
+ const part = message.content.find(item => item.type === "tool" && item.id === event.data.id);
249
+ if (part?.type !== "tool" || part.state.status !== "completed") return;
250
+ void adopt(event.data.sessionID, prUrls(inputCommand(part.state.input), event.data.content.filter(item => item.type === "text").map(item => item.text).join("\n")), event.location?.directory);
251
+ })];
252
+ context.ui.slot({
253
+ append: "sidebar.content",
254
+ render: props => {
255
+ const root = () => context.data.session.root(props.sessionID);
256
+ createEffect(() => {
257
+ const sessionID = props.sessionID;
258
+ const nextRoot = root();
259
+ const directory = sessionDirectory(sessionID);
260
+ const changedContext = activeRoot !== nextRoot || activeDirectory !== directory;
261
+ if (activeDirectory !== directory) {
262
+ setBranchPr(undefined);
263
+ setAuthoredPrs(undefined);
264
+ }
265
+ activeRoot = nextRoot;
266
+ activeDirectory = directory;
267
+ untrack(() => {
268
+ recover(sessionID);
269
+ if (changedContext) {
270
+ void refreshBranch();
271
+ void refreshAuthored();
272
+ void refresh();
273
+ }
274
+ });
275
+ });
276
+ const list = () => {
277
+ const urls = state.roots[root()] ?? [];
278
+ const prs = new Map();
279
+ const current = branchPr();
280
+ if (current?.directory === sessionDirectory(props.sessionID)) prs.set(current.pr.url, current.pr);
281
+ for (const url of urls) {
282
+ const pr = state.prs[url];
283
+ if (pr && !prs.has(url)) prs.set(url, pr);
284
+ }
285
+ const authored = authoredPrs();
286
+ if (authored?.directory === sessionDirectory(props.sessionID)) for (const pr of authored.prs) {
287
+ if (!prs.has(pr.url)) prs.set(pr.url, pr);
288
+ }
289
+ return [...prs.values()];
290
+ };
291
+ return _$memo(() => _$memo(() => list().length > 0)() ? (() => {
292
+ var _el$7 = _$createElement("box"),
293
+ _el$8 = _$createElement("text"),
294
+ _el$9 = _$createElement("b");
295
+ _$insertNode(_el$7, _el$8);
296
+ _$insertNode(_el$8, _el$9);
297
+ _$insertNode(_el$9, _$createTextNode(`Pull requests`));
298
+ _$insert(_el$7, () => list().map(pr => _$createComponent(PrRow, {
299
+ context: context,
300
+ pr: pr
301
+ })), null);
302
+ _$effect(_$p => _$setProp(_el$8, "fg", context.theme.text.base, _$p));
303
+ return _el$7;
304
+ })() : undefined);
305
+ }
306
+ });
307
+ return () => {
308
+ disposed = true;
309
+ for (const unsubscribe of unsubscribers) unsubscribe();
310
+ clearInterval(timer);
311
+ };
312
+ }
313
+ });
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@daoninc/opencode-pr-tracker",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "OpenCode V2 port of Kit Langton's PR tracker with branch and authored pull requests",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
- "exports": { "./tui": "./tui.tsx" },
8
- "files": ["tui.tsx", "reference.ts", "README.md", "LICENSE"],
9
- "scripts": { "test": "bun test", "prepublishOnly": "bun run ../../scripts/check-release.ts ." },
7
+ "exports": { "./tui": "./dist/tui.js" },
8
+ "files": ["dist", "README.md", "LICENSE"],
9
+ "scripts": { "test": "bun test", "prepack": "bun run ../../scripts/build.ts .", "prepublishOnly": "bun run ../../scripts/build.ts . && bun run ../../scripts/check-release.ts ." },
10
10
  "dependencies": { "@opencode/plugin": "^2.3.1" },
11
11
  "peerDependencies": { "@opentui/core": ">=0.8.4 <0.9", "@opentui/solid": ">=0.8.4 <0.9", "solid-js": "^1.9.0" },
12
12
  "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
package/reference.ts DELETED
@@ -1,5 +0,0 @@
1
- // Preserve the published plugin's session-scoped PR discovery.
2
- export function prUrls(command: unknown, output: unknown): string[] {
3
- if (typeof command !== "string" || !/\bgh\s+pr\s+create\b/.test(command) || typeof output !== "string") return []
4
- return [...output.matchAll(/https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+/g)].map((match) => match[0])
5
- }
package/tui.tsx DELETED
@@ -1,371 +0,0 @@
1
- /** @jsxImportSource @opentui/solid */
2
- // OpenCode V2 compatibility port of @kitlangton/opencode-pr-tracker 0.1.1.
3
-
4
- import { Plugin } from "@opencode/plugin/tui"
5
- import { createEffect, createSignal, untrack } from "solid-js"
6
- import { prUrls } from "./reference"
7
-
8
- const POLL_MS = 45_000
9
-
10
- const COLORS: Record<string, string> = {
11
- OPEN: "#a6da95",
12
- MERGED: "#c6a0f6",
13
- CLOSED: "#ed8796",
14
- }
15
-
16
- type Check = { status?: string; conclusion?: string }
17
- type Pr = {
18
- number: number
19
- url: string
20
- state: string
21
- title: string
22
- isDraft: boolean
23
- mergedAt?: string
24
- statusCheckRollup: Check[]
25
- }
26
-
27
- async function run(cwd: string, ...command: string[]) {
28
- const proc = Bun.spawn(command, { cwd, stdout: "pipe", stderr: "ignore" })
29
- const stdout = await proc.stdout.text()
30
- return { code: await proc.exited, stdout: stdout.trim() }
31
- }
32
-
33
- async function fetchPr(directory: string, reference?: string): Promise<Pr | undefined> {
34
- try {
35
- const result = await run(
36
- directory,
37
- "gh",
38
- "pr",
39
- "view",
40
- ...(reference ? [reference] : []),
41
- "--json",
42
- "number,url,state,title,isDraft,mergedAt,statusCheckRollup",
43
- )
44
- if (result.code !== 0) return undefined
45
- const parsed: unknown = JSON.parse(result.stdout)
46
- if (typeof parsed !== "object" || parsed === null) return undefined
47
- const pr = parsed as Pr
48
- return typeof pr.number === "number" && typeof pr.url === "string" ? pr : undefined
49
- } catch {
50
- // Missing gh, inaccessible directories, and malformed responses should not break the sidebar.
51
- return undefined
52
- }
53
- }
54
-
55
- async function fetchAuthoredPrs(directory: string): Promise<Pr[] | undefined> {
56
- try {
57
- const result = await run(
58
- directory,
59
- "gh",
60
- "pr",
61
- "list",
62
- "--author",
63
- "@me",
64
- "--state",
65
- "open",
66
- "--limit",
67
- "100",
68
- "--json",
69
- "number,url,state,title,isDraft,mergedAt,statusCheckRollup",
70
- )
71
- if (result.code !== 0) return undefined
72
- const parsed: unknown = JSON.parse(result.stdout)
73
- if (!Array.isArray(parsed)) return undefined
74
- return parsed.filter((pr): pr is Pr =>
75
- typeof pr === "object" && pr !== null && typeof pr.number === "number" && typeof pr.url === "string",
76
- )
77
- } catch {
78
- return undefined
79
- }
80
- }
81
-
82
- function inputCommand(input: unknown) {
83
- return typeof input === "object" && input !== null && !Array.isArray(input) && "command" in input
84
- ? input.command
85
- : undefined
86
- }
87
-
88
- function createdPrUrls(messages: ReturnType<Plugin.Context["data"]["session"]["message"]["list"]>) {
89
- const urls = new Set<string>()
90
- const adopt = (command: unknown, output: unknown) => prUrls(command, output).forEach((url) => urls.add(url))
91
-
92
- for (const message of messages) {
93
- if (message.type === "shell") {
94
- if (message.status === "exited" && message.exit === 0) adopt(message.command, message.output?.output)
95
- continue
96
- }
97
- if (message.type !== "assistant") continue
98
- for (const part of message.content) {
99
- if (part.type !== "tool" || part.state.status !== "completed") continue
100
- adopt(
101
- inputCommand(part.state.input),
102
- part.state.content
103
- .filter((item) => item.type === "text")
104
- .map((item) => item.text)
105
- .join("\n"),
106
- )
107
- }
108
- }
109
- return [...urls]
110
- }
111
-
112
- function checkStatus(pr: Pr) {
113
- const checks = (pr.statusCheckRollup ?? []).filter((check) => check.conclusion !== "SKIPPED")
114
- if (checks.some((check) => check.status && check.status !== "COMPLETED")) return "pending"
115
- if (
116
- checks.some((check) =>
117
- ["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE", "STALE"].includes(
118
- check.conclusion ?? "",
119
- ),
120
- )
121
- )
122
- return "failed"
123
- return checks.length > 0 ? "passed" : "none"
124
- }
125
-
126
- function statusIcon(pr: Pr) {
127
- if (pr.isDraft) return "◇"
128
- if (pr.state === "MERGED") return "✓"
129
- if (pr.state === "CLOSED") return "×"
130
- const checks = checkStatus(pr)
131
- if (checks === "pending") return "◌"
132
- if (checks === "failed") return "×"
133
- return "●"
134
- }
135
-
136
- function statusColor(pr: Pr) {
137
- if (pr.isDraft) return "#8aadf4"
138
- if (pr.state === "MERGED") return COLORS.MERGED
139
- const checks = checkStatus(pr)
140
- if (pr.state === "CLOSED" || checks === "failed") return COLORS.CLOSED
141
- if (checks === "pending") return "#eed49f"
142
- return COLORS.OPEN
143
- }
144
-
145
- function changed(left: Pr | undefined, right: Pr | undefined) {
146
- return JSON.stringify(left) !== JSON.stringify(right)
147
- }
148
-
149
- function PrRow(props: { context: Plugin.Context; pr: Pr }) {
150
- const [hovered, setHovered] = createSignal(false)
151
- return (
152
- <box
153
- flexDirection="row"
154
- gap={1}
155
- backgroundColor={hovered() ? props.context.theme.background.action.primary.hovered : undefined}
156
- onMouseOver={() => setHovered(true)}
157
- onMouseOut={() => setHovered(false)}
158
- onMouseUp={() => Bun.spawn(["open", props.pr.url])}
159
- >
160
- <text fg={statusColor(props.pr)} flexShrink={0}>
161
- {statusIcon(props.pr)}
162
- </text>
163
- <text fg={props.context.theme.text.base} wrapMode="word">
164
- <span style={{ fg: hovered() ? props.context.theme.text.base : props.context.theme.text.muted }}>
165
- #{props.pr.number}
166
- </span>{" "}
167
- {props.pr.title}
168
- </text>
169
- </box>
170
- )
171
- }
172
-
173
- export default Plugin.define({
174
- id: "kit.pr-tracker",
175
- setup: async (context) => {
176
- const location = context.location ?? context.data.location.default()
177
- const sessionDirectory = (sessionID: string) =>
178
- context.data.session.get(sessionID)?.location.directory ?? location.directory
179
- const [state, update] = context.storage.memory("pr-sidebar-v2", {
180
- initial: {
181
- roots: {} as Record<string, string[]>,
182
- prs: {} as Record<string, Pr>,
183
- directories: {} as Record<string, string>,
184
- },
185
- })
186
-
187
- const recovered = new Set<string>()
188
- const branchLookups = new Set<string>()
189
- const authoredLookups = new Set<string>()
190
- const [branchPr, setBranchPr] = createSignal<{ directory: string; pr: Pr }>()
191
- const [authoredPrs, setAuthoredPrs] = createSignal<{ directory: string; prs: Pr[] }>()
192
- let activeRoot = ""
193
- let activeDirectory = ""
194
- let disposed = false
195
- let inFlight = false
196
-
197
- const adopt = async (sessionID: string, urls: string[], directory = sessionDirectory(sessionID)) => {
198
- if (disposed || urls.length === 0) return
199
- const root = context.data.session.root(sessionID)
200
- const previous = state.roots[root] ?? []
201
- const next = [...new Set([...previous, ...urls])]
202
- if (next.length !== previous.length || urls.some((url) => state.directories?.[url] !== directory))
203
- update((draft) => {
204
- draft.roots[root] = next
205
- draft.directories ??= {}
206
- for (const url of urls) draft.directories[url] = directory
207
- })
208
- const missing = urls.filter((url) => !state.prs[url])
209
- const prs = (await Promise.all(missing.map((url) => fetchPr(directory, url)))).filter((pr) => pr !== undefined)
210
- if (disposed || prs.length === 0) return
211
- if (prs.some((pr) => changed(state.prs[pr.url], pr)))
212
- update((draft) => {
213
- for (const pr of prs) draft.prs[pr.url] = pr
214
- })
215
- }
216
-
217
- const recover = (sessionID: string) => {
218
- const root = context.data.session.root(sessionID)
219
- if (recovered.has(root)) return
220
- recovered.add(root)
221
- for (const member of new Set([root, ...context.data.session.family(root)]))
222
- void adopt(member, createdPrUrls(context.data.session.message.list(member)))
223
- }
224
-
225
- const refreshBranch = async () => {
226
- const directory = activeDirectory
227
- if (disposed || !directory || branchLookups.has(directory)) return
228
- branchLookups.add(directory)
229
- try {
230
- const pr = await fetchPr(directory)
231
- if (disposed || activeDirectory !== directory) return
232
- const previous = branchPr()
233
- if (!pr) {
234
- if (previous?.directory === directory) setBranchPr(undefined)
235
- } else if (previous?.directory !== directory || changed(previous.pr, pr)) {
236
- setBranchPr({ directory, pr })
237
- }
238
- } finally {
239
- branchLookups.delete(directory)
240
- }
241
- }
242
-
243
- const refreshAuthored = async () => {
244
- const directory = activeDirectory
245
- if (disposed || !directory || authoredLookups.has(directory)) return
246
- authoredLookups.add(directory)
247
- try {
248
- const prs = await fetchAuthoredPrs(directory)
249
- if (disposed || activeDirectory !== directory || !prs) return
250
- const previous = authoredPrs()
251
- if (previous?.directory !== directory || JSON.stringify(previous.prs) !== JSON.stringify(prs))
252
- setAuthoredPrs({ directory, prs })
253
- } finally {
254
- authoredLookups.delete(directory)
255
- }
256
- }
257
-
258
- const refresh = async () => {
259
- if (disposed || inFlight) return
260
- inFlight = true
261
- try {
262
- const urls = state.roots[activeRoot] ?? []
263
- const prs = (
264
- await Promise.all(
265
- urls.map((url) => fetchPr(state.directories?.[url] ?? sessionDirectory(activeRoot), url)),
266
- )
267
- ).filter((pr) => pr !== undefined)
268
- if (disposed || !prs.some((pr) => changed(state.prs[pr.url], pr))) return
269
- update((draft) => {
270
- for (const pr of prs) draft.prs[pr.url] = pr
271
- })
272
- } finally {
273
- inFlight = false
274
- }
275
- }
276
-
277
- const timer = setInterval(() => {
278
- void refreshBranch()
279
- void refreshAuthored()
280
- void refresh()
281
- }, POLL_MS)
282
- const unsubscribers = [
283
- context.data.on("session.shell.ended", (event) => {
284
- if (event.data.shell.status !== "exited" || event.data.shell.exit !== 0) return
285
- void adopt(
286
- event.data.sessionID,
287
- prUrls(event.data.shell.command, event.data.output.output),
288
- event.location?.directory,
289
- )
290
- }),
291
- context.data.on("session.tool.success", (event) => {
292
- const message = context.data.session.message.get(event.data.sessionID, event.data.assistantMessageID)
293
- if (message?.type !== "assistant") return
294
- const part = message.content.find((item) => item.type === "tool" && item.id === event.data.id)
295
- if (part?.type !== "tool" || part.state.status !== "completed") return
296
- void adopt(
297
- event.data.sessionID,
298
- prUrls(
299
- inputCommand(part.state.input),
300
- event.data.content
301
- .filter((item) => item.type === "text")
302
- .map((item) => item.text)
303
- .join("\n"),
304
- ),
305
- event.location?.directory,
306
- )
307
- }),
308
- ]
309
-
310
- context.ui.slot({
311
- append: "sidebar.content",
312
- render: (props) => {
313
- const root = () => context.data.session.root(props.sessionID)
314
- createEffect(() => {
315
- const sessionID = props.sessionID
316
- const nextRoot = root()
317
- const directory = sessionDirectory(sessionID)
318
- const changedContext = activeRoot !== nextRoot || activeDirectory !== directory
319
- if (activeDirectory !== directory) {
320
- setBranchPr(undefined)
321
- setAuthoredPrs(undefined)
322
- }
323
- activeRoot = nextRoot
324
- activeDirectory = directory
325
- untrack(() => {
326
- recover(sessionID)
327
- if (changedContext) {
328
- void refreshBranch()
329
- void refreshAuthored()
330
- void refresh()
331
- }
332
- })
333
- })
334
- const list = () => {
335
- const urls = state.roots[root()] ?? []
336
- const prs = new Map<string, Pr>()
337
- const current = branchPr()
338
- if (current?.directory === sessionDirectory(props.sessionID)) prs.set(current.pr.url, current.pr)
339
- for (const url of urls) {
340
- const pr = state.prs[url]
341
- if (pr && !prs.has(url)) prs.set(url, pr)
342
- }
343
- const authored = authoredPrs()
344
- if (authored?.directory === sessionDirectory(props.sessionID))
345
- for (const pr of authored.prs) {
346
- if (!prs.has(pr.url)) prs.set(pr.url, pr)
347
- }
348
- return [...prs.values()]
349
- }
350
- return (
351
- <>
352
- {list().length > 0 ? (
353
- <box>
354
- <text fg={context.theme.text.base}>
355
- <b>Pull requests</b>
356
- </text>
357
- {list().map((pr) => <PrRow context={context} pr={pr} />)}
358
- </box>
359
- ) : undefined}
360
- </>
361
- )
362
- },
363
- })
364
-
365
- return () => {
366
- disposed = true
367
- for (const unsubscribe of unsubscribers) unsubscribe()
368
- clearInterval(timer)
369
- }
370
- },
371
- })