Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

gitStatusState.test.ts

326 lines10.0 KB

1import { EnvironmentId, type GitStatusResult } from "@t3tools/contracts";
2import { afterEach, describe, expect, it, vi } from "vitest";
3​
4import type { WsRpcClient } from "../rpc/wsRpcClient";
5import { resetAppAtomRegistryForTests } from "../rpc/atomRegistry";
6import {
7 getGitStatusSnapshot,
8 resetGitStatusStateForTests,
9 refreshGitStatus,
10 watchGitStatus,
11} from "./gitStatusState";
12​
13const serviceHarness = vi.hoisted(() => ({
14 connections: new Map<string, any>(),
15 listeners: new Set<() => void>(),
16}));
17​
18vi.mock("../environments/runtime/service", () => ({
19 readEnvironmentConnection: (environmentId: string) =>
20 serviceHarness.connections.get(environmentId) ?? null,
21 subscribeEnvironmentConnections: (listener: () => void) => {
22 serviceHarness.listeners.add(listener);
23 return () => {
24 serviceHarness.listeners.delete(listener);
25 };
26 },
27}));
28​
29function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
30 listeners.add(listener);
31 return () => {
32 listeners.delete(listener);
33 };
35​
36const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
37const ENVIRONMENT_ID = EnvironmentId.makeUnsafe("environment-local");
38const OTHER_ENVIRONMENT_ID = EnvironmentId.makeUnsafe("environment-remote");
39const TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/repo" } as const;
40const FRESH_TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/fresh" } as const;
41​
42const BASE_STATUS: GitStatusResult = {
43 isRepo: true,
44 hasOriginRemote: true,
45 isDefaultBranch: false,
46 branch: "feature/push-status",
47 hasWorkingTreeChanges: false,
48 workingTree: { files: [], insertions: 0, deletions: 0 },
49 hasUpstream: true,
50 aheadCount: 0,
51 behindCount: 0,
52 pr: null,
53};
54​
55const gitClient = {
56 refreshStatus: vi.fn(async (input: { cwd: string }) => ({
57 ...BASE_STATUS,
58 branch: `${input.cwd}-refreshed`,
59 })),
60 onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
61 registerListener(gitStatusListeners, listener),
62 ),
63};
64​
65function emitGitStatus(event: GitStatusResult) {
66 for (const listener of gitStatusListeners) {
67 listener(event);
68 }
70​
71function createRegisteredGitStatusClient(environmentId: EnvironmentId) {
72 const listeners = new Set<(event: GitStatusResult) => void>();
73 const client = {
74 dispose: vi.fn(async () => undefined),
75 reconnect: vi.fn(async () => undefined),
76 terminal: {
77 open: vi.fn(async () => undefined),
78 write: vi.fn(async () => undefined),
79 resize: vi.fn(async () => undefined),
80 clear: vi.fn(async () => undefined),
81 restart: vi.fn(async () => undefined),
82 close: vi.fn(async () => undefined),
83 onEvent: vi.fn(() => () => undefined),
84 },
85 projects: {
86 searchEntries: vi.fn(async () => []),
87 writeFile: vi.fn(async () => undefined),
88 },
89 shell: {
90 openInEditor: vi.fn(async () => undefined),
91 },
92 git: {
93 pull: vi.fn(async () => undefined),
94 refreshStatus: vi.fn(async (input: { cwd: string }) => ({
95 ...BASE_STATUS,
96 branch: `${input.cwd}-refreshed`,
97 })),
98 onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
99 registerListener(listeners, listener),
100 ),
101 runStackedAction: vi.fn(async () => ({}) as any),
102 listBranches: vi.fn(async () => []),
103 createWorktree: vi.fn(async () => undefined),
104 removeWorktree: vi.fn(async () => undefined),
105 createBranch: vi.fn(async () => undefined),
106 checkout: vi.fn(async () => undefined),
107 init: vi.fn(async () => undefined),
108 resolvePullRequest: vi.fn(async () => undefined),
109 preparePullRequestThread: vi.fn(async () => undefined),
110 },
111 server: {
112 getConfig: vi.fn(async () => ({
113 environment: {
114 environmentId,
115 },
116 })),
117 refreshProviders: vi.fn(async () => undefined),
118 upsertKeybinding: vi.fn(async () => undefined),
119 getSettings: vi.fn(async () => undefined),
120 updateSettings: vi.fn(async () => undefined),
121 subscribeConfig: vi.fn(() => () => undefined),
122 subscribeLifecycle: vi.fn(() => () => undefined),
123 subscribeAuthAccess: vi.fn(() => () => undefined),
124 },
125 orchestration: {
126 getSnapshot: vi.fn(async () => ({ snapshotSequence: 1, projects: [], threads: [] }) as any),
127 dispatchCommand: vi.fn(async () => undefined),
128 getTurnDiff: vi.fn(async () => undefined),
129 getFullThreadDiff: vi.fn(async () => undefined),
130 replayEvents: vi.fn(async () => []),
131 onDomainEvent: vi.fn(() => () => undefined),
132 },
133 } as unknown as WsRpcClient;
134​
135 serviceHarness.connections.set(environmentId, {
136 kind: "saved" as const,
137 knownEnvironment: {
138 id: environmentId,
139 label: `Environment ${environmentId}`,
140 source: "manual" as const,
141 environmentId,
142 target: {
143 httpBaseUrl: "http://example.test",
144 wsBaseUrl: "ws://example.test",
145 },
146 },
147 client,
148 environmentId,
149 ensureBootstrapped: async () => undefined,
150 reconnect: async () => undefined,
151 dispose: async () => undefined,
152 });
153 for (const listener of serviceHarness.listeners) {
154 listener();
155 }
156​
157 return {
158 client,
159 emit: (event: GitStatusResult) => {
160 for (const listener of listeners) {
161 listener(event);
162 }
163 },
164 };
166​
167afterEach(async () => {
168 gitStatusListeners.clear();
169 serviceHarness.connections.clear();
170 serviceHarness.listeners.clear();
171 gitClient.onStatus.mockClear();
172 gitClient.refreshStatus.mockClear();
173 resetGitStatusStateForTests();
174 resetAppAtomRegistryForTests();
175});
176​
177describe("gitStatusState", () => {
178 it("starts fresh cwd state in a pending state", () => {
179 expect(getGitStatusSnapshot(FRESH_TARGET)).toEqual({
180 data: null,
181 error: null,
182 cause: null,
183 isPending: true,
184 });
185 });
186​
187 it("shares one live subscription per cwd and updates the per-cwd atom snapshot", () => {
188 const releaseA = watchGitStatus(TARGET, gitClient);
189 const releaseB = watchGitStatus(TARGET, gitClient);
190​
191 expect(gitClient.onStatus).toHaveBeenCalledOnce();
192 expect(getGitStatusSnapshot(TARGET)).toEqual({
193 data: null,
194 error: null,
195 cause: null,
196 isPending: true,
197 });
198​
199 emitGitStatus(BASE_STATUS);
200​
201 expect(getGitStatusSnapshot(TARGET)).toEqual({
202 data: BASE_STATUS,
203 error: null,
204 cause: null,
205 isPending: false,
206 });
207​
208 releaseA();
209 expect(gitStatusListeners.size).toBe(1);
210​
211 releaseB();
212 expect(gitStatusListeners.size).toBe(0);
213 });
214​
215 it("refreshes git status through the unary RPC without restarting the stream", async () => {
216 const release = watchGitStatus(TARGET, gitClient);
217​
218 emitGitStatus(BASE_STATUS);
219 const refreshed = await refreshGitStatus(TARGET, gitClient);
220​
221 expect(gitClient.onStatus).toHaveBeenCalledOnce();
222 expect(gitClient.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
223 expect(refreshed).toEqual({ ...BASE_STATUS, branch: "/repo-refreshed" });
224 expect(getGitStatusSnapshot(TARGET)).toEqual({
225 data: BASE_STATUS,
226 error: null,
227 cause: null,
228 isPending: false,
229 });
230​
231 release();
232 });
233​
234 it("keeps git status subscriptions isolated by environment when cwds match", () => {
235 const localListeners = new Set<(event: GitStatusResult) => void>();
236 const remoteListeners = new Set<(event: GitStatusResult) => void>();
237 const localClient = {
238 refreshStatus: vi.fn(),
239 onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
240 registerListener(localListeners, listener),
241 ),
242 };
243 const remoteClient = {
244 refreshStatus: vi.fn(),
245 onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
246 registerListener(remoteListeners, listener),
247 ),
248 };
249 const remoteTarget = { environmentId: OTHER_ENVIRONMENT_ID, cwd: "/repo" } as const;
250​
251 const releaseLocal = watchGitStatus(TARGET, localClient);
252 const releaseRemote = watchGitStatus(remoteTarget, remoteClient);
253​
254 for (const listener of localListeners) {
255 listener(BASE_STATUS);
256 }
257 for (const listener of remoteListeners) {
258 listener({ ...BASE_STATUS, branch: "remote-branch" });
259 }
260​
261 expect(getGitStatusSnapshot(TARGET).data?.branch).toBe("feature/push-status");
262 expect(getGitStatusSnapshot(remoteTarget).data?.branch).toBe("remote-branch");
263​
264 releaseLocal();
265 releaseRemote();
266 });
267​
268 it("waits for a delayed environment client registration instead of throwing", () => {
269 const release = watchGitStatus(TARGET);
270​
271 expect(getGitStatusSnapshot(TARGET)).toEqual({
272 data: null,
273 error: null,
274 cause: null,
275 isPending: true,
276 });
277​
278 const registered = createRegisteredGitStatusClient(ENVIRONMENT_ID);
279 registered.emit(BASE_STATUS);
280​
281 expect(getGitStatusSnapshot(TARGET)).toEqual({
282 data: BASE_STATUS,
283 error: null,
284 cause: null,
285 isPending: false,
286 });
287​
288 release();
289 });
290​
291 it("resubscribes after the environment client is removed and re-registered", async () => {
292 const firstClient = createRegisteredGitStatusClient(ENVIRONMENT_ID);
293 const release = watchGitStatus(TARGET);
294​
295 firstClient.emit(BASE_STATUS);
296 expect(getGitStatusSnapshot(TARGET).data?.branch).toBe("feature/push-status");
297​
298 serviceHarness.connections.delete(ENVIRONMENT_ID);
299 for (const listener of serviceHarness.listeners) {
300 listener();
301 }
302​
303 expect(getGitStatusSnapshot(TARGET)).toEqual({
304 data: BASE_STATUS,
305 error: null,
306 cause: null,
307 isPending: true,
308 });
309​
310 const secondClient = createRegisteredGitStatusClient(ENVIRONMENT_ID);
311 secondClient.emit({ ...BASE_STATUS, branch: "reconnected-branch" });
312​
313 expect(getGitStatusSnapshot(TARGET)).toEqual({
314 data: { ...BASE_STATUS, branch: "reconnected-branch" },
315 error: null,
316 cause: null,
317 isPending: false,
318 });
319​
320 release();
321 });
322​
323 it("returns the cached snapshot when refresh is requested before the client is registered", async () => {
324 await expect(refreshGitStatus(TARGET)).resolves.toBeNull();
325 });
326});