@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 493 lines 18.7 KB
Raw
1 import {
2 WS_METHODS,
3 type EnvironmentId,
4 type IssueAssigneeCandidate,
5 type IssueCandidates,
6 type IssueComment,
7 type IssueCommentsPage,
8 type IssueDetail,
9 type IssueLabelCandidate,
10 type IssueListEntry,
11 type IssueListInput,
12 type IssueListResult,
13 type IssueRef,
14 type IssueScopeRef,
15 } from "@t3tools/contracts";
16 import type * as Cause from "effect/Cause";
17 import * as Effect from "effect/Effect";
18 import * as Exit from "effect/Exit";
19 import * as Option from "effect/Option";
20 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
21
22 import {
23 type AtomCommandResult,
24 createAtomCommandScheduler,
25 createEnvironmentRpcCommand,
26 createEnvironmentRpcQueryAtomFamily,
27 createEnvironmentRpcSubscriptionAtomFamily,
28 createEnvironmentQueryAtomFamily,
29 } from "./runtime.ts";
30 import type { EnvironmentRegistry } from "../connection/registry.ts";
31 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
32 import { request } from "../rpc/client.ts";
33
34 /** One row's identity across list pages and detail reads; hosts compare case-insensitively. */
35 export function issueEntryKey(
36 entry: Pick<IssueListEntry, "projectId" | "host" | "scope" | "key">,
37 ): string {
38 return `${entry.projectId}\u0000${entry.host.toLowerCase()}\u0000${entry.scope.toLowerCase()}\u0000${entry.key}`;
39 }
40
41 /**
42 * Lay a continuation page over the rows already held. A page only covers the scopes it was asked
43 * to continue, so rows from other scopes stay; a row the page repeats replaces the held one, so a
44 * title or state that moved between reads shows the newer words. Order stays newest-updated first,
45 * which is how every tracker hands them over.
46 */
47 export function mergeIssueListPage(
48 held: ReadonlyArray<IssueListEntry>,
49 page: ReadonlyArray<IssueListEntry>,
50 ): ReadonlyArray<IssueListEntry> {
51 if (held.length === 0) return page;
52 if (page.length === 0) return held;
53 const byKey = new Map<string, IssueListEntry>();
54 for (const entry of held) byKey.set(issueEntryKey(entry), entry);
55 for (const entry of page) byKey.set(issueEntryKey(entry), entry);
56 return [...byKey.values()].sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));
57 }
58
59 /** Older comments go in front: the detail carries the newest page and pages walk backwards. */
60 function prependIssueComments(
61 current: ReadonlyArray<IssueComment>,
62 older: ReadonlyArray<IssueComment>,
63 ): ReadonlyArray<IssueComment> {
64 if (older.length === 0) return current;
65 const seen = new Set(current.map((comment) => comment.id));
66 return [...older.filter((comment) => !seen.has(comment.id)), ...current];
67 }
68
69 export function createIssueCommentPager<E>(
70 detailAtom: Atom.Atom<
71 AsyncResult.AsyncResult<Pick<IssueDetail, "comments" | "commentsCursor">, E>
72 >,
73 ) {
74 const state = Atom.make<{
75 readonly older: (IssueCommentsPage & { readonly seed: string }) | null;
76 readonly loadingOlder: boolean;
77 readonly refreshing: boolean;
78 readonly refreshes: number;
79 }>({ older: null, loadingOlder: false, refreshing: false, refreshes: 0 });
80 const page = Atom.make((get) => {
81 const detailResult = get(detailAtom);
82 const detail = AsyncResult.getOrElse(detailResult, () => null);
83 const current = get(state);
84 const seed = detail?.commentsCursor ?? null;
85 const older = current.older?.seed === seed ? current.older : null;
86 const nextCursor = older ? older.nextCursor : seed;
87 return {
88 comments: detail?.comments ?? [],
89 seed,
90 older,
91 nextCursor,
92 loadingOlder: current.loadingOlder,
93 unavailable: detailResult.waiting || current.refreshing || current.loadingOlder,
94 };
95 });
96 const view = Atom.make((get) => {
97 const { comments, older, nextCursor, loadingOlder, unavailable } = get(page);
98 return {
99 comments: prependIssueComments(comments, older?.comments ?? []),
100 nextCursor,
101 loadingOlder,
102 canLoadOlder: nextCursor !== null && !unavailable,
103 };
104 });
105
106 return {
107 view,
108 /** `read` settles once the detail has been read again, whether or not that read failed. */
109 async refresh(registry: AtomRegistry.AtomRegistry, read: () => Promise<unknown>) {
110 const current = registry.get(state);
111 if (current.refreshing) return;
112 registry.set(state, { ...current, refreshing: true });
113 let succeeded = false;
114 try {
115 await read();
116 const result = registry.get(detailAtom);
117 succeeded = result._tag === "Success" && !result.waiting;
118 } finally {
119 const latest = registry.get(state);
120 // A successful read invalidates older pages even when the query reuses unchanged detail.
121 registry.set(
122 state,
123 succeeded
124 ? { ...latest, older: null, refreshing: false, refreshes: latest.refreshes + 1 }
125 : { ...latest, refreshing: false },
126 );
127 }
128 },
129 async loadOlder(
130 registry: AtomRegistry.AtomRegistry,
131 read: (cursor: string) => Promise<AtomCommandResult<IssueCommentsPage, unknown>>,
132 ) {
133 const { seed, older, nextCursor, unavailable } = registry.get(page);
134 if (seed === null || nextCursor === null || unavailable) return;
135 const current = registry.get(state);
136 registry.set(state, { ...current, loadingOlder: true });
137 try {
138 const result = await read(nextCursor);
139 const latest = registry.get(state);
140 if (latest.refreshes !== current.refreshes) return;
141 if (result._tag === "Failure") return result;
142 registry.set(state, {
143 ...latest,
144 older: {
145 seed,
146 comments: prependIssueComments(older?.comments ?? [], result.value.comments),
147 nextCursor: result.value.nextCursor,
148 },
149 });
150 } finally {
151 registry.set(state, { ...registry.get(state), loadingOlder: false });
152 }
153 },
154 };
155 }
156
157 type IssueListRefreshMode = "manual" | "background";
158
159 /**
160 * Every read goes to a tracker API over the environment, so results are reused for a short while
161 * and refreshed explicitly. Mutations run serially per environment: changes to one issue are
162 * order-sensitive. Each confirmed write refreshes the detail it touched; the list is refreshed by
163 * the page, which knows which listings it is showing.
164 */
165 export function createIssueEnvironmentAtoms<R, E>(
166 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
167 ) {
168 const commandScheduler = createAtomCommandScheduler();
169 const serialPerEnvironment = {
170 mode: "serial",
171 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
172 } as const;
173 const detail = createEnvironmentRpcQueryAtomFamily(runtime, {
174 label: "environment-data:issues:detail",
175 tag: WS_METHODS.issuesDetail,
176 staleTimeMs: 30_000,
177 });
178 const detailRef = ({ projectId, tracker, host, scope, key }: IssueRef): IssueRef => ({
179 projectId,
180 tracker,
181 ...(host === undefined ? {} : { host }),
182 scope,
183 key,
184 });
185 const refreshDetail = (
186 { environmentId, input }: { readonly environmentId: EnvironmentId; readonly input: IssueRef },
187 registry: AtomRegistry.AtomRegistry,
188 ) => Effect.sync(() => registry.refresh(detail({ environmentId, input: detailRef(input) })));
189 const linkedThreadSignals = createEnvironmentRpcSubscriptionAtomFamily(runtime, {
190 label: "environment-data:issues:linked-thread-refreshes",
191 tag: WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes,
192 });
193 const pendingListRefreshes = new WeakMap<
194 AtomRegistry.AtomRegistry,
195 WeakMap<Atom.Atom<unknown>, symbol>
196 >();
197 type ListRequest = ReturnType<typeof request<typeof WS_METHODS.issuesList>>;
198 const list = createEnvironmentQueryAtomFamily(runtime, {
199 label: "environment-data:issues:list",
200 staleTimeMs: 30_000,
201 execute: Effect.fnUntraced(function* (
202 input: IssueListInput,
203 ): Effect.fn.Return<
204 IssueListResult,
205 Effect.Error<ListRequest>,
206 Effect.Services<ListRequest> | AtomRegistry.AtomRegistry
207 > {
208 const registry = yield* AtomRegistry.AtomRegistry;
209 const {
210 target: { environmentId },
211 } = yield* EnvironmentSupervisor.EnvironmentSupervisor;
212 const pending = pendingListRefreshes.get(registry);
213 if (pending === undefined) return yield* request(WS_METHODS.issuesList, input);
214 const atom = list({ environmentId, input });
215 const intent = pending.get(atom);
216 if (intent === undefined) return yield* request(WS_METHODS.issuesList, input);
217 return yield* request(WS_METHODS.issuesList, { ...input, refresh: true }).pipe(
218 // Invalidation interrupts the read; its replacement still owes the explicit refresh.
219 Effect.onExit((exit) =>
220 Effect.sync(() => {
221 if (!Exit.hasInterrupts(exit) && pending.get(atom) === intent) pending.delete(atom);
222 }),
223 ),
224 );
225 }),
226 });
227 return {
228 /** The threads an issue is linked to, reread when the server signals a link changed. */
229 linkedThreads: createEnvironmentRpcQueryAtomFamily(runtime, {
230 label: "environment-data:issues:linked-threads",
231 tag: WS_METHODS.issuesLinkedThreads,
232 staleTimeMs: 0,
233 refreshTrigger: ({ environmentId }) => linkedThreadSignals({ environmentId, input: {} }),
234 }),
235 list,
236 refreshList(
237 registry: AtomRegistry.AtomRegistry,
238 target: IssueListTarget,
239 mode: IssueListRefreshMode,
240 ) {
241 const atom = list(target);
242 if (mode === "manual") {
243 let pending = pendingListRefreshes.get(registry);
244 if (pending === undefined) {
245 pending = new WeakMap();
246 pendingListRefreshes.set(registry, pending);
247 }
248 pending.set(atom, Symbol());
249 }
250 registry.refresh(atom);
251 },
252 /**
253 * A continuation of the listing, run as a command rather than read as a query: a page is
254 * asked for once and laid over the rows held, and a refresh of the first page forgets it.
255 */
256 listPage: createEnvironmentRpcCommand(runtime, {
257 label: "environment-data:issues:list-page",
258 tag: WS_METHODS.issuesList,
259 scheduler: commandScheduler,
260 concurrency: {
261 mode: "singleFlight",
262 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
263 },
264 }),
265 detail,
266 /** Older comments past the cursor the detail handed over; the panel prepends what arrives. */
267 comments: createEnvironmentRpcCommand(runtime, {
268 label: "environment-data:issues:comments",
269 tag: WS_METHODS.issuesComments,
270 scheduler: commandScheduler,
271 concurrency: {
272 mode: "singleFlight",
273 key: ({ environmentId, input }) =>
274 JSON.stringify([environmentId, input.projectId, input.scope, input.key, input.cursor]),
275 },
276 }),
277 /** Read when the composer opens: what a scope offers a new issue changes with a commit. */
278 templates: createEnvironmentRpcQueryAtomFamily(runtime, {
279 label: "environment-data:issues:templates",
280 tag: WS_METHODS.issuesTemplates,
281 staleTimeMs: 5 * 60_000,
282 }),
283 /** Read when a label or assignee picker opens, not with every issue. */
284 candidates: createEnvironmentRpcQueryAtomFamily(runtime, {
285 label: "environment-data:issues:candidates",
286 tag: WS_METHODS.issuesCandidates,
287 staleTimeMs: 60_000,
288 }),
289 create: createEnvironmentRpcCommand(runtime, {
290 label: "environment-data:issues:create",
291 tag: WS_METHODS.issuesCreate,
292 scheduler: commandScheduler,
293 concurrency: serialPerEnvironment,
294 }),
295 comment: createEnvironmentRpcCommand(runtime, {
296 label: "environment-data:issues:comment",
297 tag: WS_METHODS.issuesComment,
298 scheduler: commandScheduler,
299 concurrency: serialPerEnvironment,
300 onSuccess: refreshDetail,
301 }),
302 update: createEnvironmentRpcCommand(runtime, {
303 label: "environment-data:issues:update",
304 tag: WS_METHODS.issuesUpdate,
305 scheduler: commandScheduler,
306 concurrency: serialPerEnvironment,
307 onSuccess: refreshDetail,
308 }),
309 setState: createEnvironmentRpcCommand(runtime, {
310 label: "environment-data:issues:set-state",
311 tag: WS_METHODS.issuesSetState,
312 scheduler: commandScheduler,
313 concurrency: serialPerEnvironment,
314 onSuccess: refreshDetail,
315 }),
316 react: createEnvironmentRpcCommand(runtime, {
317 label: "environment-data:issues:react",
318 tag: WS_METHODS.issuesReact,
319 scheduler: commandScheduler,
320 concurrency: serialPerEnvironment,
321 onSuccess: refreshDetail,
322 }),
323 };
324 }
325
326 export interface IssueListTarget {
327 readonly environmentId: EnvironmentId;
328 readonly input: IssueListInput;
329 }
330
331 export interface MergedIssueList {
332 /** One answer per environment that has one, in target order. */
333 readonly answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>;
334 /** The first environment that failed outright; the others may still have answered. */
335 readonly error: string | null;
336 readonly isPending: boolean;
337 }
338
339 const NO_ISSUE_LISTS: MergedIssueList = { answers: [], error: null, isPending: false };
340
341 function refreshFailed<Target, A, E>(
342 registry: AtomRegistry.AtomRegistry,
343 targets: ReadonlyArray<Target>,
344 query: (target: Target) => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
345 ) {
346 for (const target of targets) {
347 const atom = query(target);
348 const result = registry.get(atom);
349 if (result._tag === "Failure" && !result.waiting) registry.refresh(atom);
350 }
351 }
352
353 /**
354 * One listing read across every environment at once: React cannot subscribe to a list of atoms
355 * whose length changes, so the fan-out lives in one derived atom keyed by the targets. An
356 * environment that fails contributes nothing rather than blanking the list. Retry reloads only
357 * the environments that failed, so a read still in flight elsewhere is not restarted.
358 */
359 export function createMergedIssueListAtoms<E>(
360 {
361 list,
362 refreshList,
363 }: {
364 readonly list: (
365 target: IssueListTarget,
366 ) => Atom.Atom<AsyncResult.AsyncResult<IssueListResult, E>>;
367 readonly refreshList: (
368 registry: AtomRegistry.AtomRegistry,
369 target: IssueListTarget,
370 mode: IssueListRefreshMode,
371 ) => void;
372 },
373 formatError: (cause: Cause.Cause<E>) => string,
374 ) {
375 const empty = Atom.make(NO_ISSUE_LISTS).pipe(Atom.withLabel("issues:merged-list:empty"));
376 const family = Atom.family((key: string) =>
377 Atom.make((get): MergedIssueList => {
378 const answers: Array<readonly [EnvironmentId, IssueListResult]> = [];
379 let error: string | null = null;
380 let isPending = false;
381 for (const target of JSON.parse(key) as ReadonlyArray<IssueListTarget>) {
382 const result = get(list(target));
383 isPending ||= result.waiting;
384 if (result._tag === "Failure" && error === null) error = formatError(result.cause);
385 const value = Option.getOrNull(AsyncResult.value(result));
386 if (value !== null) answers.push([target.environmentId, value]);
387 }
388 return { answers, error, isPending };
389 }).pipe(Atom.withLabel(`issues:merged-list:${key}`)),
390 );
391 const refresh = (
392 registry: AtomRegistry.AtomRegistry,
393 targets: ReadonlyArray<IssueListTarget>,
394 mode: IssueListRefreshMode,
395 ) => {
396 for (const target of targets) refreshList(registry, target, mode);
397 };
398 // The targets behind each listing atom, so a write made elsewhere can refresh the ones still
399 // shown. Weak, so a closed search goes with its atom once the registry drops it.
400 const targetsOf = new WeakMap<Atom.Atom<MergedIssueList>, ReadonlyArray<IssueListTarget>>();
401 return {
402 atom: (targets: ReadonlyArray<IssueListTarget>) => {
403 if (targets.length === 0) return empty;
404 const atom = family(JSON.stringify(targets));
405 targetsOf.set(atom, targets);
406 return atom;
407 },
408 refresh,
409 retry: (registry: AtomRegistry.AtomRegistry, targets: ReadonlyArray<IssueListTarget>) =>
410 refreshFailed(registry, targets, list),
411 /** Refreshes each listing of `environmentId` that something still reads. */
412 refreshEnvironment: (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) => {
413 for (const node of registry.getNodes().values()) {
414 const targets = targetsOf.get(node.atom);
415 if (targets === undefined) continue;
416 refresh(
417 registry,
418 targets.filter((target) => target.environmentId === environmentId),
419 "background",
420 );
421 }
422 },
423 };
424 }
425
426 export interface IssueCandidatesTarget {
427 readonly environmentId: EnvironmentId;
428 readonly input: IssueScopeRef;
429 }
430
431 /** What a list filter can offer: the labels and people of every scope asked, each named once. */
432 export interface MergedIssueCandidates {
433 readonly labels: ReadonlyArray<IssueLabelCandidate>;
434 readonly assignees: ReadonlyArray<IssueAssigneeCandidate>;
435 readonly error: string | null;
436 readonly isPending: boolean;
437 readonly truncated: boolean;
438 }
439
440 const NO_ISSUE_CANDIDATES: MergedIssueCandidates = {
441 labels: [],
442 assignees: [],
443 error: null,
444 isPending: false,
445 truncated: false,
446 };
447
448 /**
449 * Fans out like the merged listing: a scope that fails leaves the others' answers in place.
450 * Retry skips scopes that already answered or still have a request in flight.
451 */
452 export function createMergedIssueCandidatesAtoms<E>(
453 candidates: (
454 target: IssueCandidatesTarget,
455 ) => Atom.Atom<AsyncResult.AsyncResult<IssueCandidates, E>>,
456 formatError: (cause: Cause.Cause<E>) => string,
457 ) {
458 const empty = Atom.make(NO_ISSUE_CANDIDATES).pipe(Atom.withLabel("issues:candidates:empty"));
459 const family = Atom.family((key: string) =>
460 Atom.make((get): MergedIssueCandidates => {
461 const labels = new Map<string, IssueLabelCandidate>();
462 const assignees = new Map<string, IssueAssigneeCandidate>();
463 let error: string | null = null;
464 let isPending = false;
465 let truncated = false;
466 for (const target of JSON.parse(key) as ReadonlyArray<IssueCandidatesTarget>) {
467 const result = get(candidates(target));
468 isPending ||= result.waiting;
469 if (result._tag === "Failure" && error === null) error = formatError(result.cause);
470 const value = Option.getOrNull(AsyncResult.value(result));
471 if (value === null) continue;
472 truncated ||= value.truncated;
473 for (const label of value.labels)
474 if (!labels.has(label.name)) labels.set(label.name, label);
475 for (const actor of value.assignees)
476 if (!assignees.has(actor.login)) assignees.set(actor.login, actor);
477 }
478 return {
479 labels: [...labels.values()].sort((a, b) => a.name.localeCompare(b.name)),
480 assignees: [...assignees.values()].sort((a, b) => a.login.localeCompare(b.login)),
481 error,
482 isPending,
483 truncated,
484 };
485 }).pipe(Atom.withLabel(`issues:candidates:${key}`)),
486 );
487 return {
488 atom: (targets: ReadonlyArray<IssueCandidatesTarget>) =>
489 targets.length === 0 ? empty : family(JSON.stringify(targets)),
490 retry: (registry: AtomRegistry.AtomRegistry, targets: ReadonlyArray<IssueCandidatesTarget>) =>
491 refreshFailed(registry, targets, candidates),
492 };
493 }