Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 type EnvironmentId,
4 type GitManagerServiceError,
5 type GitStatusResult,
6} from "@workbench/contracts";
7import { Cause } from "effect";
8import { Atom } from "effect/unstable/reactivity";
9import { useEffect } from "react";
10
11import { appAtomRegistry } from "../rpc/atomRegistry";
12import {
13 readEnvironmentConnection,
14 subscribeEnvironmentConnections,
15} from "../environments/runtime";
16import type { WsRpcClient } from "~/rpc/wsRpcClient";
17
18interface GitStatusState {
19 readonly data: GitStatusResult | null;
20 readonly error: GitManagerServiceError | null;
21 readonly cause: Cause.Cause<GitManagerServiceError> | null;
22 readonly isPending: boolean;
23}
24
25type GitStatusClient = Pick<WsRpcClient["git"], "onStatus" | "refreshStatus">;
26interface ResolvedGitStatusClient {
27 readonly clientIdentity: string;
28 readonly client: GitStatusClient;
29}
30
31interface WatchedGitStatus {
32 refCount: number;
33 unsubscribe: () => void;
34}
35
36interface GitStatusTarget {
37 readonly environmentId: EnvironmentId | null;
38 readonly cwd: string | null;
39}
40
41const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
42 data: null,
43 error: null,
44 cause: null,
45 isPending: false,
46});
47const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
48 ...EMPTY_GIT_STATUS_STATE,
49 isPending: true,
50});
51const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
52 Atom.keepAlive,
53 Atom.withLabel("git-status:null"),
54);
55
56const NOOP: () => void = () => undefined;
57const watchedGitStatuses = new Map<string, WatchedGitStatus>();
58const knownGitStatusKeys = new Set<string>();
59const gitStatusRefreshInFlight = new Map<string, Promise<GitStatusResult>>();
60const gitStatusLastRefreshAtByKey = new Map<string, number>();
61
62const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
63
64const gitStatusStateAtom = Atom.family((key: string) => {
65 knownGitStatusKeys.add(key);
66 return Atom.make(INITIAL_GIT_STATUS_STATE).pipe(
67 Atom.keepAlive,
68 Atom.withLabel(`git-status:${key}`),
69 );
70});
71
72function getGitStatusTargetKey(target: GitStatusTarget): string | null {
73 if (target.environmentId === null || target.cwd === null) {
74 return null;
75 }
76
77 return `${target.environmentId}:${target.cwd}`;
78}
79
80function readResolvedGitStatusClient(target: GitStatusTarget): ResolvedGitStatusClient | null {
81 if (target.environmentId === null) {
82 return null;
83 }
84 const connection = readEnvironmentConnection(target.environmentId);
85 return connection
86 ? { clientIdentity: connection.environmentId, client: connection.client.git }
87 : null;
88}
89
90export function getGitStatusSnapshot(target: GitStatusTarget): GitStatusState {
91 const targetKey = getGitStatusTargetKey(target);
92 if (targetKey === null) {
93 return EMPTY_GIT_STATUS_STATE;
94 }
95
96 return appAtomRegistry.get(gitStatusStateAtom(targetKey));
97}
98
99export function watchGitStatus(target: GitStatusTarget, client?: GitStatusClient): () => void {
100 const targetKey = getGitStatusTargetKey(target);
101 if (targetKey === null) {
102 return NOOP;
103 }
104
105 const watched = watchedGitStatuses.get(targetKey);
106 if (watched) {
107 watched.refCount += 1;
108 return () => unwatchGitStatus(targetKey);
109 }
110
111 watchedGitStatuses.set(targetKey, {
112 refCount: 1,
113 unsubscribe: subscribeToGitStatusTarget(targetKey, target, client),
114 });
115
116 return () => unwatchGitStatus(targetKey);
117}
118
119export function refreshGitStatus(
120 target: GitStatusTarget,
121 client?: GitStatusClient,
122): Promise<GitStatusResult | null> {
123 const targetKey = getGitStatusTargetKey(target);
124 if (targetKey === null || target.cwd === null) {
125 return Promise.resolve(null);
126 }
127
128 const resolvedClient = client ?? readResolvedGitStatusClient(target)?.client;
129 if (!resolvedClient) {
130 return Promise.resolve(getGitStatusSnapshot(target).data);
131 }
132
133 const currentInFlight = gitStatusRefreshInFlight.get(targetKey);
134 if (currentInFlight) {
135 return currentInFlight;
136 }
137
138 const lastRequestedAt = gitStatusLastRefreshAtByKey.get(targetKey) ?? 0;
139 if (Date.now() - lastRequestedAt < GIT_STATUS_REFRESH_DEBOUNCE_MS) {
140 return Promise.resolve(getGitStatusSnapshot(target).data);
141 }
142
143 gitStatusLastRefreshAtByKey.set(targetKey, Date.now());
144 const refreshPromise = resolvedClient.refreshStatus({ cwd: target.cwd }).finally(() => {
145 gitStatusRefreshInFlight.delete(targetKey);
146 });
147 gitStatusRefreshInFlight.set(targetKey, refreshPromise);
148 return refreshPromise;
149}
150
151export function resetGitStatusStateForTests(): void {
152 for (const watched of watchedGitStatuses.values()) {
153 watched.unsubscribe();
154 }
155 watchedGitStatuses.clear();
156 gitStatusRefreshInFlight.clear();
157 gitStatusLastRefreshAtByKey.clear();
158
159 for (const key of knownGitStatusKeys) {
160 appAtomRegistry.set(gitStatusStateAtom(key), INITIAL_GIT_STATUS_STATE);
161 }
162 knownGitStatusKeys.clear();
163}
164
165export function useGitStatus(target: GitStatusTarget): GitStatusState {
166 const targetKey = getGitStatusTargetKey(target);
167 useEffect(
168 () => watchGitStatus({ environmentId: target.environmentId, cwd: target.cwd }),
169 [target.environmentId, target.cwd],
170 );
171
172 const state = useAtomValue(
173 targetKey !== null ? gitStatusStateAtom(targetKey) : EMPTY_GIT_STATUS_ATOM,
174 );
175 return targetKey === null ? EMPTY_GIT_STATUS_STATE : state;
176}
177
178function unwatchGitStatus(targetKey: string): void {
179 const watched = watchedGitStatuses.get(targetKey);
180 if (!watched) {
181 return;
182 }
183
184 watched.refCount -= 1;
185 if (watched.refCount > 0) {
186 return;
187 }
188
189 watched.unsubscribe();
190 watchedGitStatuses.delete(targetKey);
191}
192
193function subscribeToGitStatusTarget(
194 targetKey: string,
195 target: GitStatusTarget,
196 providedClient?: GitStatusClient,
197): () => void {
198 if (target.cwd === null) {
199 return NOOP;
200 }
201
202 const cwd = target.cwd;
203 let currentClientIdentity: string | null = null;
204 let currentUnsubscribe = NOOP;
205
206 const syncClientSubscription = () => {
207 const resolved = providedClient
208 ? {
209 clientIdentity: `provided:${targetKey}`,
210 client: providedClient,
211 }
212 : readResolvedGitStatusClient(target);
213
214 if (!resolved) {
215 if (currentClientIdentity !== null) {
216 currentUnsubscribe();
217 currentUnsubscribe = NOOP;
218 currentClientIdentity = null;
219 }
220 markGitStatusPending(targetKey);
221 return;
222 }
223
224 if (currentClientIdentity === resolved.clientIdentity) {
225 return;
226 }
227
228 currentUnsubscribe();
229 currentClientIdentity = resolved.clientIdentity;
230 currentUnsubscribe = subscribeToGitStatus(targetKey, cwd, resolved.client);
231 };
232
233 const unsubscribeRegistry = providedClient
234 ? NOOP
235 : subscribeEnvironmentConnections(syncClientSubscription);
236 syncClientSubscription();
237
238 return () => {
239 unsubscribeRegistry();
240 currentUnsubscribe();
241 };
242}
243
244function subscribeToGitStatus(targetKey: string, cwd: string, client: GitStatusClient): () => void {
245 markGitStatusPending(targetKey);
246 return client.onStatus(
247 { cwd },
248 (status: GitStatusResult) => {
249 appAtomRegistry.set(gitStatusStateAtom(targetKey), {
250 data: status,
251 error: null,
252 cause: null,
253 isPending: false,
254 });
255 },
256 {
257 onResubscribe: () => {
258 markGitStatusPending(targetKey);
259 },
260 },
261 );
262}
263
264function markGitStatusPending(targetKey: string): void {
265 const atom = gitStatusStateAtom(targetKey);
266 const current = appAtomRegistry.get(atom);
267 const next =
268 current.data === null
269 ? INITIAL_GIT_STATUS_STATE
270 : {
271 ...current,
272 error: null,
273 cause: null,
274 isPending: true,
275 };
276
277 if (
278 current.data === next.data &&
279 current.error === next.error &&
280 current.cause === next.cause &&
281 current.isPending === next.isPending
282 ) {
283 return;
284 }
285
286 appAtomRegistry.set(atom, next);
287}