Open History to see the last commit
1import { EnvironmentId, ProjectId, SourceControlProviderKind } from "@t3tools/contracts";
2import { describe, expect, it } from "vite-plus/test";
3
4import type { EnvironmentProject } from "./models.ts";
5import { chooseLoadBalancedEnvironment } from "../load-balancing.ts";
6import {
7 buildProjectGroups,
8 deriveLogicalProjectKeyFromSettings,
9 derivePhysicalProjectKey,
10 resolveScratchProjectScopeKey,
11 sortProjectsByGroupOrder,
12 type ProjectGroupingSettings,
13} from "./projectGrouping.ts";
14
15const environmentId = EnvironmentId.make("environment");
16
17describe("load balancing shared project machines", () => {
18 const now = 100_000;
19 const resources = {
20 sampledAt: now,
21 cpuUtilization: 0.2,
22 cpuCount: 8,
23 availableMemoryBytes: 8_000,
24 totalMemoryBytes: 16_000,
25 };
26
27 it("compares three machines using free capacity and preference", () => {
28 const candidates = [
29 { environmentId: "busy", resources: { ...resources, cpuUtilization: 0.9 }, weight: 1 },
30 { environmentId: "idle", resources, weight: 1 },
31 { environmentId: "preferred", resources: { ...resources, cpuCount: 4 }, weight: 3 },
32 ];
33 expect(chooseLoadBalancedEnvironment(candidates, now)).toBe("preferred");
34 expect(chooseLoadBalancedEnvironment(candidates.slice(0, 2), now)).toBe("idle");
35 });
36
37 it("rejects stale, unknown, excluded and saturated machines", () => {
38 expect(
39 chooseLoadBalancedEnvironment(
40 [
41 {
42 environmentId: "stale",
43 resources: { ...resources, sampledAt: now - 15_001 },
44 weight: 1,
45 },
46 { environmentId: "unknown", resources: null, weight: 1 },
47 {
48 environmentId: "no-cpu-sample",
49 resources: { ...resources, cpuUtilization: null },
50 weight: 1,
51 },
52 { environmentId: "excluded", resources, weight: 0 },
53 {
54 environmentId: "cpu-full",
55 resources: { ...resources, cpuUtilization: 0.95 },
56 weight: 1,
57 },
58 {
59 environmentId: "memory-full",
60 resources: { ...resources, availableMemoryBytes: 100 },
61 weight: 1,
62 },
63 ],
64 now,
65 ),
66 ).toBeNull();
67 });
68
69 it("uses client receipt time when host clocks differ", () => {
70 const candidate = {
71 environmentId: "different-clock",
72 resources: { ...resources, sampledAt: now + 60_000 },
73 receivedAt: now,
74 weight: 1,
75 };
76 expect(chooseLoadBalancedEnvironment([candidate], now)).toBe("different-clock");
77 expect(chooseLoadBalancedEnvironment([candidate], now + 15_001)).toBeNull();
78 });
79});
80const repositoryIdentity = {
81 canonicalKey: "github.com/t3tools/t3code",
82 locator: {
83 source: "git-remote" as const,
84 remoteName: "upstream",
85 remoteUrl: "https://github.com/t3tools/t3code.git",
86 },
87 provider: SourceControlProviderKind.make("github"),
88 owner: "t3tools",
89 name: "t3code",
90 displayName: "T3 Code",
91};
92
93function makeProject(
94 id: string,
95 workspaceRoot: string,
96 overrides: Partial<EnvironmentProject> = {},
97): EnvironmentProject {
98 return {
99 environmentId,
100 id: ProjectId.make(id),
101 title: id,
102 workspaceRoot,
103 repositoryIdentity,
104 defaultModelSelection: null,
105 scripts: [],
106 createdAt: "2026-07-01T00:00:00.000Z",
107 updatedAt: "2026-07-01T00:00:00.000Z",
108 ...overrides,
109 };
110}
111
112function settings(
113 mode: ProjectGroupingSettings["sidebarProjectGroupingMode"],
114 overrides: ProjectGroupingSettings["sidebarProjectGroupingOverrides"] = {},
115): ProjectGroupingSettings {
116 return {
117 sidebarProjectGroupingMode: mode,
118 sidebarProjectGroupingOverrides: overrides,
119 };
120}
121
122describe("buildProjectGroups", () => {
123 it.each(["repository", "repository_path", "separate"] as const)(
124 "keeps scratch project ownership separate by default in %s mode",
125 (mode) => {
126 const projects = [
127 makeProject("scratch-local", "/local/scratch", {
128 isScratch: true,
129 repositoryIdentity: null,
130 }),
131 makeProject("scratch-remote", "/remote/scratch", {
132 environmentId: EnvironmentId.make("remote"),
133 isScratch: true,
134 repositoryIdentity: null,
135 }),
136 ];
137 const groups = buildProjectGroups({ projects, settings: settings(mode) });
138 expect(groups.map((group) => group.key)).toEqual(projects.map(derivePhysicalProjectKey));
139 expect(groups.map((group) => group.memberProjectRefs)).toEqual(
140 projects.map((project) => [
141 { environmentId: project.environmentId, projectId: project.id },
142 ]),
143 );
144 expect(
145 buildProjectGroups({ projects, settings: settings(mode), groupScratchProjects: true }),
146 ).toHaveLength(1);
147 },
148 );
149
150 it.each(["repository", "repository_path", "separate"] as const)(
151 "migrates a pre-config %s scratch selection and retains it after the original host is removed",
152 (mode) => {
153 const local = makeProject("scratch-local", "/local/repo/scratch", {
154 repositoryIdentity: { ...repositoryIdentity, rootPath: "/local/repo" },
155 });
156 const remote = makeProject("scratch-remote", "/remote/scratch", {
157 environmentId: EnvironmentId.make("remote"),
158 repositoryIdentity: null,
159 isScratch: true,
160 });
161 const groupingSettings = settings(mode);
162 const selectedBeforeConfig = deriveLogicalProjectKeyFromSettings(local, groupingSettings);
163 const loaded = [{ ...local, isScratch: true as const }, remote];
164 const migrated = resolveScratchProjectScopeKey(
165 selectedBeforeConfig,
166 loaded,
167 groupingSettings,
168 );
169 const scratchKey = buildProjectGroups({
170 projects: loaded,
171 settings: groupingSettings,
172 groupScratchProjects: true,
173 })[0]!.key;
174 expect(migrated).toBe(scratchKey);
175 expect(resolveScratchProjectScopeKey(migrated, [remote], groupingSettings)).toBe(scratchKey);
176 expect(
177 buildProjectGroups({
178 projects: [remote],
179 settings: groupingSettings,
180 groupScratchProjects: true,
181 })[0]?.memberProjectRefs,
182 ).toEqual([{ environmentId: remote.environmentId, projectId: remote.id }]);
183 },
184 );
185
186 it("retains a repository filter that still belongs to an ordinary project", () => {
187 const scratch = makeProject("scratch", "/scratch", { isScratch: true });
188 const ordinary = makeProject("ordinary", "/ordinary");
189 const key = deriveLogicalProjectKeyFromSettings(ordinary, settings("repository"));
190 expect(resolveScratchProjectScopeKey(key, [scratch, ordinary])).toBe(key);
191 });
192
193 it.each(["repository", "repository_path", "separate"] as const)(
194 "coalesces scratch homes in %s mode without merging ordinary same-title projects",
195 (mode) => {
196 const remoteEnvironmentId = EnvironmentId.make("remote");
197 const projects = [
198 makeProject("scratch-local", "/local/scratch", {
199 title: "No project",
200 isScratch: true,
201 repositoryIdentity: null,
202 }),
203 makeProject("scratch-remote", "/remote/scratch", {
204 title: "No project",
205 environmentId: remoteEnvironmentId,
206 isScratch: true,
207 }),
208 makeProject("scratch-duplicate", "/remote/scratch/", {
209 title: "No project",
210 environmentId: remoteEnvironmentId,
211 isScratch: true,
212 repositoryIdentity: null,
213 updatedAt: "2026-07-02T00:00:00.000Z",
214 }),
215 makeProject("ordinary", "/ordinary", { title: "No project" }),
216 makeProject("reserved-collision", "/other", {
217 title: "No project",
218 repositoryIdentity: { ...repositoryIdentity, canonicalKey: "\0no-project" },
219 }),
220 ];
221 const groups = buildProjectGroups({
222 projects,
223 groupScratchProjects: true,
224 settings: settings(mode, { [derivePhysicalProjectKey(projects[0]!)]: "separate" }),
225 preferredEnvironmentId: remoteEnvironmentId,
226 });
227 expect(groups).toHaveLength(3);
228 const scratch = groups.find((group) => group.representative.isScratch)!;
229 expect(scratch.label).toBe("No project");
230 expect(scratch.representative.id).toBe(projects[2]?.id);
231 expect(scratch.members).toHaveLength(2);
232 expect(scratch.memberProjectRefs).toEqual(
233 projects.slice(0, 3).map((project) => ({
234 environmentId: project.environmentId,
235 projectId: project.id,
236 })),
237 );
238 expect(resolveScratchProjectScopeKey(derivePhysicalProjectKey(projects[1]!), projects)).toBe(
239 scratch.key,
240 );
241 expect(resolveScratchProjectScopeKey(derivePhysicalProjectKey(projects[3]!), projects)).toBe(
242 derivePhysicalProjectKey(projects[3]!),
243 );
244 expect(groups.filter((group) => !group.representative.isScratch)).toHaveLength(2);
245 },
246 );
247
248 it("preserves every physical clone as a selectable member in repository modes", () => {
249 const projects = [
250 makeProject("t3code", "/work/t3code"),
251 makeProject("t3code-2", "/work/t3code-2"),
252 makeProject("t3code-3", "/work/t3code-3"),
253 ];
254
255 for (const mode of ["repository", "repository_path"] as const) {
256 const groups = buildProjectGroups({ projects, settings: settings(mode) });
257 expect(groups).toHaveLength(1);
258 expect(groups[0]?.members.map((member) => member.project.id)).toEqual([
259 "t3code",
260 "t3code-2",
261 "t3code-3",
262 ]);
263 expect(groups[0]?.memberProjectRefs).toHaveLength(3);
264 }
265 });
266
267 it("keeps a fork apart from its upstream checkout and labels it by its own remote", () => {
268 const fork = makeProject("fork", "/work/t3code-fork", {
269 repositoryIdentity: {
270 ...repositoryIdentity,
271 origin: {
272 canonicalKey: "github.com/julius/t3code-fork",
273 displayName: "julius/t3code-fork",
274 },
275 },
276 });
277 const forkWorktree = makeProject("fork-2", "/work/t3code-fork-2", {
278 repositoryIdentity: fork.repositoryIdentity,
279 });
280 const projects = [makeProject("t3code", "/work/t3code"), fork, forkWorktree];
281
282 const groups = buildProjectGroups({ projects, settings: settings("repository") });
283 expect(groups.map((group) => group.key)).toEqual([
284 "github.com/t3tools/t3code",
285 "github.com/julius/t3code-fork",
286 ]);
287 expect(groups[1]?.members.map((member) => member.project.id)).toEqual(["fork", "fork-2"]);
288 expect(groups[1]?.label).toBe("julius/t3code-fork");
289 });
290
291 it("applies a physical-project override without dropping its siblings", () => {
292 const first = makeProject("t3code", "/work/t3code");
293 const second = makeProject("t3code-2", "/work/t3code-2");
294 const third = makeProject("t3code-3", "/work/t3code-3");
295 const groups = buildProjectGroups({
296 projects: [first, second, third],
297 settings: settings("repository", {
298 [derivePhysicalProjectKey(second)]: "separate",
299 }),
300 });
301
302 expect(groups).toHaveLength(2);
303 expect(groups.flatMap((group) => group.members.map((member) => member.project.id))).toEqual([
304 "t3code",
305 "t3code-3",
306 "t3code-2",
307 ]);
308 });
309
310 it("dedupes stale registrations at one physical path using the freshest project", () => {
311 const stale = makeProject("stale", "/work/t3code", {
312 repositoryIdentity: null,
313 updatedAt: "2026-07-01T00:00:00.000Z",
314 });
315 const fresh = makeProject("fresh", "/work/t3code/", {
316 updatedAt: "2026-07-02T00:00:00.000Z",
317 });
318
319 const groups = buildProjectGroups({
320 projects: [stale, fresh],
321 settings: settings("repository"),
322 });
323 expect(groups).toHaveLength(1);
324 expect(groups[0]?.members).toHaveLength(1);
325 expect(groups[0]?.representative.id).toBe("fresh");
326 expect(groups[0]?.memberProjectRefs).toHaveLength(2);
327 });
328
329 it("uses the freshest winner's repository identity when stale duplicates disagree", () => {
330 const staleIdentity = {
331 ...repositoryIdentity,
332 canonicalKey: "github.com/t3tools/old-repository",
333 name: "old-repository",
334 displayName: "Old Repository",
335 };
336 const stale = makeProject("stale", "/work/t3code", {
337 repositoryIdentity: staleIdentity,
338 updatedAt: "2026-07-01T00:00:00.000Z",
339 });
340 const fresh = makeProject("fresh", "/work/t3code/", {
341 updatedAt: "2026-07-02T00:00:00.000Z",
342 });
343 const sibling = makeProject("sibling", "/work/t3code-2");
344
345 const groups = buildProjectGroups({
346 projects: [stale, fresh, sibling],
347 settings: settings("repository"),
348 });
349 expect(groups).toHaveLength(1);
350 expect(groups[0]?.members.map((member) => member.project.id)).toEqual(["fresh", "sibling"]);
351 });
352
353 it("uses the freshest identity-bearing duplicate when the winner lacks identity", () => {
354 const staleIdentity = {
355 ...repositoryIdentity,
356 canonicalKey: "github.com/t3tools/old-repository",
357 name: "old-repository",
358 displayName: "Old Repository",
359 };
360 const staleIdentified = makeProject("stale-identified", "/work/t3code", {
361 repositoryIdentity: staleIdentity,
362 updatedAt: "2026-07-01T00:00:00.000Z",
363 });
364 const freshIdentified = makeProject("fresh-identified", "/work/t3code/", {
365 updatedAt: "2026-07-02T00:00:00.000Z",
366 });
367 const winner = makeProject("winner", "/work/t3code", {
368 repositoryIdentity: null,
369 updatedAt: "2026-07-03T00:00:00.000Z",
370 });
371 const sibling = makeProject("sibling", "/work/t3code-2");
372
373 const groups = buildProjectGroups({
374 projects: [staleIdentified, freshIdentified, winner, sibling],
375 settings: settings("repository"),
376 });
377 expect(groups).toHaveLength(1);
378 expect(groups[0]?.members.map((member) => member.project.id)).toEqual(["winner", "sibling"]);
379 });
380});
381
382describe("sortProjectsByGroupOrder", () => {
383 const remote = EnvironmentId.make("remote");
384 const ref = (projectId: string, env = environmentId) => ({
385 environmentId: env,
386 projectId: ProjectId.make(projectId),
387 });
388 const project = (id: string, env: string = environmentId) => ({ id, environmentId: env });
389
390 it("tells the same project id on two environments apart", () => {
391 const sorted = sortProjectsByGroupOrder(
392 [project("shared"), project("shared", remote)],
393 [{ memberProjectRefs: [ref("shared", remote)] }, { memberProjectRefs: [ref("shared")] }],
394 );
395 expect(sorted.map((entry) => entry.environmentId)).toEqual([remote, environmentId]);
396 });
397});