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

main
ts 255 lines 9.06 KB
Raw
1 import {
2 type AtomCommandResult,
3 isAtomCommandInterrupted,
4 runAtomCommand,
5 } from "@t3tools/client-runtime/state/runtime";
6 import type {
7 EnvironmentId,
8 PullRequestFilesViewedResult,
9 PullRequestRef,
10 } from "@t3tools/contracts";
11
12 import { msg } from "gt-react";
13
14 import { m } from "~/i18n/messages";
15 import { appAtomRegistry } from "~/rpc/atomRegistry";
16 import {
17 pullRequestEnvironment,
18 subscribePullRequestFilesViewedAnswers,
19 } from "~/state/pullRequests";
20
21 import { toastManager } from "../ui/toast";
22 import {
23 revertFileViewedOverlay,
24 settleFileViewedOverlay,
25 toFileViewedBatch,
26 toFileViewedStates,
27 type FileViewedOverlay,
28 type FileViewedPress,
29 } from "./pullRequestFilesViewed.logic";
30
31 export interface FilesViewedTarget {
32 readonly environmentId: EnvironmentId;
33 readonly reference: PullRequestRef;
34 }
35
36 type FilesViewedBatch = ReadonlyArray<{
37 readonly path: string;
38 readonly viewed: boolean;
39 readonly revision?: string;
40 }>;
41
42 export interface FilesViewedStoreDeps {
43 readonly flushDelayMs: number;
44 /** Calls `onAnswer` only after completed server reads, excluding persisted values. */
45 readonly subscribeAnswers: (
46 target: FilesViewedTarget,
47 onAnswer: (answer: PullRequestFilesViewedResult | null) => void,
48 ) => () => void;
49 readonly send: (
50 target: FilesViewedTarget,
51 batch: FilesViewedBatch,
52 ) => Promise<AtomCommandResult<unknown, unknown>>;
53 readonly refresh: (target: FilesViewedTarget) => void;
54 readonly reportFailure: () => void;
55 }
56
57 export interface FilesViewedScopeHandle {
58 /** Holds the scope open while subscribed; the last reader to leave sends its last presses. */
59 readonly subscribe: (listener: () => void) => () => void;
60 readonly getSnapshot: () => FileViewedOverlay;
61 /** `revision` is the file's version in the diff the press was made on, when it names one. */
62 readonly setViewed: (path: string, viewed: boolean, revision?: string) => void;
63 }
64
65 const NO_OVERLAY: FileViewedOverlay = new Map();
66
67 interface FilesViewedScope {
68 readonly target: FilesViewedTarget;
69 readonly listeners: Set<() => void>;
70 readonly unsubscribeAnswers: () => void;
71 overlay: FileViewedOverlay;
72 queued: Map<string, FileViewedPress>;
73 readonly sentBy: Map<string, number>;
74 requests: number;
75 timer: ReturnType<typeof setTimeout> | null;
76 // Completed reads retire acknowledged presses even when equal data is structurally shared.
77 readonly answeredFrom: Set<string>;
78 }
79
80 /**
81 * Presses on one change request on one environment. The environment is part of the scope: two of
82 * them can hand out the same project id, and a press made against one must never be answered for
83 * by the other.
84 */
85 export function createFilesViewedStore(deps: FilesViewedStoreDeps) {
86 const scopes = new Map<string, FilesViewedScope>();
87 const handles = new Map<string, FilesViewedScopeHandle>();
88
89 const publish = (scope: FilesViewedScope, overlay: FileViewedOverlay) => {
90 if (overlay === scope.overlay) return;
91 scope.overlay = overlay;
92 for (const listener of scope.listeners) listener();
93 };
94
95 const isLive = (key: string, scope: FilesViewedScope) => scopes.get(key) === scope;
96
97 const settle = (scope: FilesViewedScope, answer: PullRequestFilesViewedResult | null) => {
98 if (answer === null) return;
99 const pending = new Set([...scope.queued.keys(), ...scope.sentBy.keys()]);
100 const answered = new Set<string>();
101 for (const path of scope.answeredFrom) {
102 if (pending.has(path)) continue;
103 answered.add(path);
104 scope.answeredFrom.delete(path);
105 }
106 publish(
107 scope,
108 settleFileViewedOverlay(scope.overlay, toFileViewedStates(answer), pending, answered),
109 );
110 };
111
112 const flush = (key: string, scope: FilesViewedScope) => {
113 scope.timer = null;
114 const batch = toFileViewedBatch(scope.queued);
115 if (batch.length === 0) return;
116 scope.queued = new Map();
117 const request = ++scope.requests;
118 for (const file of batch) scope.sentBy.set(file.path, request);
119 void deps.send(scope.target, batch).then((result) => {
120 const mine = batch
121 .map((file) => file.path)
122 .filter((path) => scope.sentBy.get(path) === request);
123 for (const path of mine) scope.sentBy.delete(path);
124 if (!isLive(key, scope)) {
125 // The overlay this press stood in is gone, but the cached answer still predates the
126 // write, and a reader coming back to this change request would be shown that.
127 if (result._tag === "Success" || !isAtomCommandInterrupted(result)) {
128 deps.refresh(scope.target);
129 }
130 return;
131 }
132 if (result._tag === "Failure") {
133 const owned = new Set(mine.filter((path) => !scope.queued.has(path)));
134 publish(scope, revertFileViewedOverlay(scope.overlay, batch, owned));
135 if (owned.size > 0 && !isAtomCommandInterrupted(result)) {
136 deps.reportFailure();
137 deps.refresh(scope.target);
138 }
139 return;
140 }
141 // Answered for from the next read on, whatever it says. A push landing between the write
142 // and that read comes back as `dismissed`, and the press must not stand over it.
143 for (const path of mine) scope.answeredFrom.add(path);
144 deps.refresh(scope.target);
145 });
146 };
147
148 const acquire = (
149 key: string,
150 target: FilesViewedTarget,
151 handle: FilesViewedScopeHandle,
152 listener: () => void,
153 ) => {
154 // Registered from `subscribe`, which runs at commit, so a render that never commits leaves
155 // nothing behind. Re-registering here also carries a handle across StrictMode's
156 // subscribe-release-subscribe, so later renders keep returning it.
157 if (!handles.has(key)) handles.set(key, handle);
158 let scope = scopes.get(key);
159 if (scope === undefined) {
160 const listeners = new Set<() => void>();
161 let created: FilesViewedScope | undefined;
162 const unsubscribeAnswers = deps.subscribeAnswers(target, (answer) => {
163 if (created !== undefined) settle(created, answer);
164 });
165 created = {
166 target,
167 listeners,
168 unsubscribeAnswers,
169 overlay: NO_OVERLAY,
170 queued: new Map(),
171 sentBy: new Map(),
172 requests: 0,
173 timer: null,
174 answeredFrom: new Set(),
175 };
176 scope = created;
177 scopes.set(key, scope);
178 }
179 const owned = scope;
180 owned.listeners.add(listener);
181 return () => {
182 if (!owned.listeners.delete(listener) || owned.listeners.size > 0) return;
183 // Leaving a change request, the environment it lives on, or the page itself records what
184 // was pressed and then drops the rest, sending those last presses to the scope being left.
185 if (owned.timer !== null) {
186 clearTimeout(owned.timer);
187 flush(key, owned);
188 }
189 scopes.delete(key);
190 handles.delete(key);
191 owned.unsubscribeAnswers();
192 };
193 };
194
195 return {
196 /**
197 * One stable handle per open scope, so readers keep their subscription across renders. Pure
198 * during render: an uncommitted handle is not cached, and any handle for a key behaves the same.
199 */
200 scope(target: FilesViewedTarget): FilesViewedScopeHandle {
201 const key = filesViewedScopeKey(target);
202 const cached = handles.get(key);
203 if (cached !== undefined) return cached;
204 const owned = { environmentId: target.environmentId, reference: { ...target.reference } };
205 const handle: FilesViewedScopeHandle = {
206 subscribe: (listener) => acquire(key, owned, handle, listener),
207 getSnapshot: () => scopes.get(key)?.overlay ?? NO_OVERLAY,
208 setViewed: (path, viewed, revision) => {
209 const scope = scopes.get(key);
210 if (scope === undefined) return;
211 scope.queued.set(path, { viewed, revision });
212 publish(scope, new Map(scope.overlay).set(path, viewed));
213 if (scope.timer !== null) clearTimeout(scope.timer);
214 scope.timer = setTimeout(() => flush(key, scope), deps.flushDelayMs);
215 },
216 };
217 return handle;
218 },
219 };
220 }
221
222 function filesViewedScopeKey({ environmentId, reference }: FilesViewedTarget): string {
223 return JSON.stringify([
224 environmentId,
225 reference.projectId,
226 reference.host ?? null,
227 reference.expectedAccountId ?? null,
228 reference.allowStale ?? null,
229 reference.repository,
230 reference.number,
231 ]);
232 }
233
234 const filesViewedAtom = ({ environmentId, reference }: FilesViewedTarget) =>
235 pullRequestEnvironment.filesViewed({ environmentId, input: reference });
236
237 const filesViewedStore = createFilesViewedStore({
238 flushDelayMs: 400,
239 subscribeAnswers: ({ environmentId, reference }, onAnswer) =>
240 subscribePullRequestFilesViewedAnswers({ environmentId, input: reference }, onAnswer),
241 send: ({ environmentId, reference }, files) =>
242 runAtomCommand(
243 appAtomRegistry,
244 pullRequestEnvironment.setFilesViewed,
245 { environmentId, input: { ...reference, files } },
246 { reportFailure: false },
247 ),
248 refresh: (target) => appAtomRegistry.refresh(filesViewedAtom(target)),
249 reportFailure: () =>
250 toastManager.add({ type: "error", title: m(msg("Could not update viewed files")) }),
251 });
252
253 export function filesViewedScope(target: FilesViewedTarget): FilesViewedScopeHandle {
254 return filesViewedStore.scope(target);
255 }