Open History to see the last commit
1import { ProjectId, ThreadId } from "@t3tools/contracts";
2import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
4import {
5 clearThreadUi,
6 hydratePersistedProjectState,
7 markThreadUnread,
8 PERSISTED_STATE_KEY,
9 type PersistedUiState,
10 persistState,
11 reorderProjects,
12 setProjectExpanded,
13 setThreadChangedFilesExpanded,
14 syncProjects,
15 syncThreads,
16 type UiState,
17} from "./uiStateStore";
18
19function makeUiState(overrides: Partial<UiState> = {}): UiState {
20 return {
21 projectExpandedById: {},
22 projectOrder: [],
23 threadLastVisitedAtById: {},
24 threadChangedFilesExpandedById: {},
25 ...overrides,
26 };
27}
28
29describe("uiStateStore pure functions", () => {
30 it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
31 const threadId = ThreadId.make("thread-1");
32 const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
33 const initialState = makeUiState({
34 threadLastVisitedAtById: {
35 [threadId]: "2026-02-25T12:35:00.000Z",
36 },
37 });
38
39 const next = markThreadUnread(initialState, threadId, latestTurnCompletedAt);
40
41 expect(next.threadLastVisitedAtById[threadId]).toBe("2026-02-25T12:29:59.999Z");
42 });
43
44 it("markThreadUnread does not change a thread without a completed turn", () => {
45 const threadId = ThreadId.make("thread-1");
46 const initialState = makeUiState({
47 threadLastVisitedAtById: {
48 [threadId]: "2026-02-25T12:35:00.000Z",
49 },
50 });
51
52 const next = markThreadUnread(initialState, threadId, null);
53
54 expect(next).toBe(initialState);
55 });
56
57 it("reorderProjects moves a project to a target index", () => {
58 const project1 = ProjectId.make("project-1");
59 const project2 = ProjectId.make("project-2");
60 const project3 = ProjectId.make("project-3");
61 const initialState = makeUiState({
62 projectOrder: [project1, project2, project3],
63 });
64
65 const next = reorderProjects(initialState, [project1], [project3]);
66
67 expect(next.projectOrder).toEqual([project2, project3, project1]);
68 });
69
70 it("reorderProjects is a no-op when dragged key is not in projectOrder", () => {
71 const project1 = ProjectId.make("project-1");
72 const project2 = ProjectId.make("project-2");
73 const initialState = makeUiState({
74 projectOrder: [project1, project2],
75 });
76
77 const next = reorderProjects(initialState, [ProjectId.make("missing")], [project2]);
78
79 expect(next).toBe(initialState);
80 });
81
82 it("reorderProjects moves all member keys of a multi-member group together", () => {
83 const keyALocal = "env-local:proj-a";
84 const keyARemote = "env-remote:proj-a";
85 const keyB = "env-local:proj-b";
86 const keyC = "env-local:proj-c";
87 const initialState = makeUiState({
88 projectOrder: [keyALocal, keyARemote, keyB, keyC],
89 });
90
91 const next = reorderProjects(initialState, [keyALocal, keyARemote], [keyC]);
92
93 expect(next.projectOrder).toEqual([keyB, keyC, keyALocal, keyARemote]);
94 });
95
96 it("reorderProjects handles member keys scattered across projectOrder", () => {
97 const keyALocal = "env-local:proj-a";
98 const keyB = "env-local:proj-b";
99 const keyARemote = "env-remote:proj-a";
100 const keyC = "env-local:proj-c";
101 const initialState = makeUiState({
102 projectOrder: [keyALocal, keyB, keyARemote, keyC],
103 });
104
105 const next = reorderProjects(initialState, [keyALocal, keyARemote], [keyC]);
106
107 expect(next.projectOrder).toEqual([keyB, keyC, keyALocal, keyARemote]);
108 });
109
110 it("reorderProjects places group after target when dragged from before a non-last target", () => {
111 const keyALocal = "env-local:proj-a";
112 const keyARemote = "env-remote:proj-a";
113 const keyB = "env-local:proj-b";
114 const keyC = "env-local:proj-c";
115 const keyD = "env-local:proj-d";
116 const initialState = makeUiState({
117 projectOrder: [keyALocal, keyARemote, keyB, keyC, keyD],
118 });
119
120 const next = reorderProjects(initialState, [keyALocal, keyARemote], [keyC]);
121
122 expect(next.projectOrder).toEqual([keyB, keyC, keyALocal, keyARemote, keyD]);
123 });
124
125 it("reorderProjects places group before target when dragged from after", () => {
126 const keyB = "env-local:proj-b";
127 const keyC = "env-local:proj-c";
128 const keyALocal = "env-local:proj-a";
129 const keyARemote = "env-remote:proj-a";
130 const initialState = makeUiState({
131 projectOrder: [keyB, keyC, keyALocal, keyARemote],
132 });
133
134 const next = reorderProjects(initialState, [keyALocal, keyARemote], [keyB]);
135
136 expect(next.projectOrder).toEqual([keyALocal, keyARemote, keyB, keyC]);
137 });
138
139 it("reorderProjects with multi-member target inserts after first target occurrence", () => {
140 const keyALocal = "env-local:proj-a";
141 const keyARemote = "env-remote:proj-a";
142 const keyBLocal = "env-local:proj-b";
143 const keyBRemote = "env-remote:proj-b";
144 const initialState = makeUiState({
145 projectOrder: [keyALocal, keyARemote, keyBLocal, keyBRemote],
146 });
147
148 const next = reorderProjects(initialState, [keyALocal, keyARemote], [keyBLocal, keyBRemote]);
149
150 // Target members may become non-contiguous; this is fine because the
151 // sidebar groups by logical key using first-occurrence positioning.
152 expect(next.projectOrder).toEqual([keyBLocal, keyALocal, keyARemote, keyBRemote]);
153 });
154
155 it("reorderProjects is a no-op when dragged group equals target group", () => {
156 const key1 = "env-local:proj-a";
157 const key2 = "env-remote:proj-a";
158 const initialState = makeUiState({
159 projectOrder: [key1, key2, "env-local:proj-b"],
160 });
161
162 const next = reorderProjects(initialState, [key1, key2], [key1, key2]);
163
164 expect(next).toBe(initialState);
165 });
166
167 it("reorderProjects is a no-op when dragged keys are not in projectOrder", () => {
168 const initialState = makeUiState({
169 projectOrder: ["env-local:proj-a", "env-local:proj-b"],
170 });
171
172 const next = reorderProjects(initialState, ["env-local:missing"], ["env-local:proj-b"]);
173
174 expect(next).toBe(initialState);
175 });
176
177 it("syncProjects preserves current project order during snapshot recovery", () => {
178 const project1 = ProjectId.make("project-1");
179 const project2 = ProjectId.make("project-2");
180 const project3 = ProjectId.make("project-3");
181 const initialState = makeUiState({
182 projectExpandedById: {
183 [project1]: true,
184 [project2]: false,
185 },
186 projectOrder: [project2, project1],
187 });
188
189 const next = syncProjects(initialState, [
190 { key: project1, logicalKey: project1, cwd: "/tmp/project-1" },
191 { key: project2, logicalKey: project2, cwd: "/tmp/project-2" },
192 { key: project3, logicalKey: project3, cwd: "/tmp/project-3" },
193 ]);
194
195 expect(next.projectOrder).toEqual([project2, project1, project3]);
196 expect(next.projectExpandedById[project2]).toBe(false);
197 });
198
199 it("syncProjects preserves manual order across project id churn at the same cwd", () => {
200 // Under the current design, physical key and logical key are both
201 // cwd-derived, so an internal project-id change doesn't alter the store
202 // keys. This test locks in that stability: re-syncing the same cwds keeps
203 // manual order and collapse state.
204 const keyProject1 = "env-local:/tmp/project-1";
205 const keyProject2 = "env-local:/tmp/project-2";
206 const initialState = syncProjects(
207 makeUiState({
208 projectExpandedById: {
209 [keyProject1]: true,
210 [keyProject2]: false,
211 },
212 projectOrder: [keyProject2, keyProject1],
213 }),
214 [
215 { key: keyProject1, logicalKey: keyProject1, cwd: "/tmp/project-1" },
216 { key: keyProject2, logicalKey: keyProject2, cwd: "/tmp/project-2" },
217 ],
218 );
219
220 const next = syncProjects(initialState, [
221 { key: keyProject1, logicalKey: keyProject1, cwd: "/tmp/project-1" },
222 { key: keyProject2, logicalKey: keyProject2, cwd: "/tmp/project-2" },
223 ]);
224
225 expect(next.projectOrder).toEqual([keyProject2, keyProject1]);
226 expect(next.projectExpandedById[keyProject2]).toBe(false);
227 });
228
229 it("syncProjects returns a new state when only project cwd changes", () => {
230 const project1 = ProjectId.make("project-1");
231 const initialState = syncProjects(
232 makeUiState({
233 projectExpandedById: {
234 [project1]: false,
235 },
236 projectOrder: [project1],
237 }),
238 [{ key: project1, logicalKey: project1, cwd: "/tmp/project-1" }],
239 );
240
241 const next = syncProjects(initialState, [
242 { key: project1, logicalKey: project1, cwd: "/tmp/project-1-renamed" },
243 ]);
244
245 expect(next).not.toBe(initialState);
246 expect(next.projectOrder).toEqual([project1]);
247 expect(next.projectExpandedById[project1]).toBe(false);
248 });
249
250 it("syncProjects keys projectExpandedById by the logical key, not the physical key", () => {
251 // In repository grouping mode, multiple physical projects (different
252 // environments or different repo-relative paths) collapse into one
253 // logical group. The group's expand state must be keyed by the logical
254 // key so clicks on the grouped row toggle the shared state, and so the
255 // state survives subsequent syncProjects calls (which rebuild the map
256 // from incoming inputs).
257 const physicalLocal = "env-local:/repo/project";
258 const physicalRemote = "env-remote:/repo/project";
259 const logicalKey = "repo-canonical-key";
260
261 const initial = syncProjects(makeUiState(), [
262 { key: physicalLocal, logicalKey, cwd: "/repo/project" },
263 { key: physicalRemote, logicalKey, cwd: "/repo/project" },
264 ]);
265
266 expect(initial.projectExpandedById).toEqual({ [logicalKey]: true });
267
268 const afterCollapse = { ...initial, projectExpandedById: { [logicalKey]: false } };
269 const next = syncProjects(afterCollapse, [
270 { key: physicalLocal, logicalKey, cwd: "/repo/project" },
271 { key: physicalRemote, logicalKey, cwd: "/repo/project" },
272 ]);
273
274 expect(next.projectExpandedById[logicalKey]).toBe(false);
275 });
276
277 it("syncProjects preserves expand state when a project's logical key changes", () => {
278 // Example: late-arriving repo metadata flips grouping identity from the
279 // physical key to a canonical repository key. The row did not actually
280 // change, so the user's collapse choice must carry over.
281 const physicalKey = "env-local:/repo/project";
282 const previousLogicalKey = physicalKey;
283 const nextLogicalKey = "repo-canonical-key";
284
285 const initial = syncProjects(makeUiState(), [
286 { key: physicalKey, logicalKey: previousLogicalKey, cwd: "/repo/project" },
287 ]);
288
289 expect(initial.projectExpandedById[previousLogicalKey]).toBe(true);
290
291 const afterCollapse = {
292 ...initial,
293 projectExpandedById: { [previousLogicalKey]: false },
294 };
295 const next = syncProjects(afterCollapse, [
296 { key: physicalKey, logicalKey: nextLogicalKey, cwd: "/repo/project" },
297 ]);
298
299 expect(next.projectExpandedById[nextLogicalKey]).toBe(false);
300 });
301
302 it("syncThreads prunes missing thread UI state", () => {
303 const thread1 = ThreadId.make("thread-1");
304 const thread2 = ThreadId.make("thread-2");
305 const initialState = makeUiState({
306 threadLastVisitedAtById: {
307 [thread1]: "2026-02-25T12:35:00.000Z",
308 [thread2]: "2026-02-25T12:36:00.000Z",
309 },
310 threadChangedFilesExpandedById: {
311 [thread1]: {
312 "turn-1": false,
313 },
314 [thread2]: {
315 "turn-2": false,
316 },
317 },
318 });
319
320 const next = syncThreads(initialState, [{ key: thread1 }]);
321
322 expect(next.threadLastVisitedAtById).toEqual({
323 [thread1]: "2026-02-25T12:35:00.000Z",
324 });
325 expect(next.threadChangedFilesExpandedById).toEqual({
326 [thread1]: {
327 "turn-1": false,
328 },
329 });
330 });
331
332 it("syncThreads seeds visit state for unseen snapshot threads", () => {
333 const thread1 = ThreadId.make("thread-1");
334 const initialState = makeUiState();
335
336 const next = syncThreads(initialState, [
337 {
338 key: thread1,
339 seedVisitedAt: "2026-02-25T12:35:00.000Z",
340 },
341 ]);
342
343 expect(next.threadLastVisitedAtById).toEqual({
344 [thread1]: "2026-02-25T12:35:00.000Z",
345 });
346 });
347
348 it("setProjectExpanded updates expansion without touching order", () => {
349 const project1 = ProjectId.make("project-1");
350 const initialState = makeUiState({
351 projectExpandedById: {
352 [project1]: true,
353 },
354 projectOrder: [project1],
355 });
356
357 const next = setProjectExpanded(initialState, project1, false);
358
359 expect(next.projectExpandedById[project1]).toBe(false);
360 expect(next.projectOrder).toEqual([project1]);
361 });
362
363 it("clearThreadUi removes visit state for deleted threads", () => {
364 const thread1 = ThreadId.make("thread-1");
365 const initialState = makeUiState({
366 threadLastVisitedAtById: {
367 [thread1]: "2026-02-25T12:35:00.000Z",
368 },
369 threadChangedFilesExpandedById: {
370 [thread1]: {
371 "turn-1": false,
372 },
373 },
374 });
375
376 const next = clearThreadUi(initialState, thread1);
377
378 expect(next.threadLastVisitedAtById).toEqual({});
379 expect(next.threadChangedFilesExpandedById).toEqual({});
380 });
381
382 it("setThreadChangedFilesExpanded stores collapsed turns per thread", () => {
383 const thread1 = ThreadId.make("thread-1");
384 const initialState = makeUiState();
385
386 const next = setThreadChangedFilesExpanded(initialState, thread1, "turn-1", false);
387
388 expect(next.threadChangedFilesExpandedById).toEqual({
389 [thread1]: {
390 "turn-1": false,
391 },
392 });
393 });
394
395 it("setThreadChangedFilesExpanded removes thread overrides when expanded again", () => {
396 const thread1 = ThreadId.make("thread-1");
397 const initialState = makeUiState({
398 threadChangedFilesExpandedById: {
399 [thread1]: {
400 "turn-1": false,
401 },
402 },
403 });
404
405 const next = setThreadChangedFilesExpanded(initialState, thread1, "turn-1", true);
406
407 expect(next.threadChangedFilesExpandedById).toEqual({});
408 });
409});
410
411describe("uiStateStore persistence round-trip", () => {
412 function createLocalStorageStub(): Storage {
413 const store = new Map<string, string>();
414 return {
415 clear: () => {
416 store.clear();
417 },
418 getItem: (key) => store.get(key) ?? null,
419 key: (index) => [...store.keys()][index] ?? null,
420 get length() {
421 return store.size;
422 },
423 removeItem: (key) => {
424 store.delete(key);
425 },
426 setItem: (key, value) => {
427 store.set(key, value);
428 },
429 };
430 }
431
432 let localStorageStub: Storage;
433
434 beforeEach(() => {
435 localStorageStub = createLocalStorageStub();
436 vi.stubGlobal("window", { localStorage: localStorageStub });
437 vi.stubGlobal("localStorage", localStorageStub);
438 // Reset module-level persistence state so tests don't bleed into each other.
439 hydratePersistedProjectState({ collapsedProjectCwds: [], expandedProjectCwds: [] });
440 });
441
442 afterEach(() => {
443 vi.unstubAllGlobals();
444 });
445
446 it("preserves all-collapsed project state across restart", () => {
447 // Regression: pre-fix, persistState only wrote `expandedProjectCwds`, so
448 // an empty array on rehydrate was indistinguishable from a fresh install
449 // and the syncProjects fallback re-expanded every row.
450 const projectA = { key: "kA", logicalKey: "kA", cwd: "/projA" };
451 const projectB = { key: "kB", logicalKey: "kB", cwd: "/projB" };
452
453 let state = syncProjects(makeUiState(), [projectA, projectB]);
454 state = setProjectExpanded(state, projectA.key, false);
455 state = setProjectExpanded(state, projectB.key, false);
456 persistState(state);
457
458 const persisted = JSON.parse(
459 localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}",
460 ) as PersistedUiState;
461 hydratePersistedProjectState(persisted);
462 const rehydrated = syncProjects(makeUiState(), [projectA, projectB]);
463
464 expect(rehydrated.projectExpandedById).toEqual({
465 [projectA.key]: false,
466 [projectB.key]: false,
467 });
468 });
469
470 it("respects mixed expand state on rehydrate and defaults new projects to expanded", () => {
471 const projectA = { key: "kA", logicalKey: "kA", cwd: "/projA" };
472 const projectB = { key: "kB", logicalKey: "kB", cwd: "/projB" };
473 const projectC = { key: "kC", logicalKey: "kC", cwd: "/projC" };
474
475 let state = syncProjects(makeUiState(), [projectA, projectB]);
476 state = setProjectExpanded(state, projectB.key, false);
477 persistState(state);
478
479 const persisted = JSON.parse(
480 localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}",
481 ) as PersistedUiState;
482 hydratePersistedProjectState(persisted);
483 const rehydrated = syncProjects(makeUiState(), [projectA, projectB, projectC]);
484
485 expect(rehydrated.projectExpandedById).toEqual({
486 [projectA.key]: true,
487 [projectB.key]: false,
488 [projectC.key]: true,
489 });
490 });
491
492 it("preserves legacy not-in-expanded-list = collapsed for one upgrade session", () => {
493 // Pre-fix shape only stored expandedProjectCwds. Absence of
494 // collapsedProjectCwds opts the session into the legacy fallback so
495 // upgrade users do not see previously collapsed rows pop open.
496 hydratePersistedProjectState({
497 expandedProjectCwds: ["/projA"],
498 });
499
500 const rehydrated = syncProjects(makeUiState(), [
501 { key: "kA", logicalKey: "kA", cwd: "/projA" },
502 { key: "kB", logicalKey: "kB", cwd: "/projB" },
503 ]);
504
505 expect(rehydrated.projectExpandedById).toEqual({
506 kA: true,
507 kB: false,
508 });
509 });
510
511 it("preserves manual project order across restart", () => {
512 const projectA = { key: "kOrderA", logicalKey: "kOrderA", cwd: "/order-projA" };
513 const projectB = { key: "kOrderB", logicalKey: "kOrderB", cwd: "/order-projB" };
514 const projectC = { key: "kOrderC", logicalKey: "kOrderC", cwd: "/order-projC" };
515
516 let state = syncProjects(makeUiState(), [projectA, projectB, projectC]);
517 state = reorderProjects(state, [projectC.key], [projectA.key]);
518 expect(state.projectOrder).toEqual([projectC.key, projectA.key, projectB.key]);
519 persistState(state);
520
521 const persisted = JSON.parse(
522 localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}",
523 ) as PersistedUiState;
524 expect(persisted.projectOrderCwds).toEqual([projectC.cwd, projectA.cwd, projectB.cwd]);
525
526 hydratePersistedProjectState(persisted);
527 // Fresh state (empty projectOrder) so syncProjects derives order from
528 // persistedProjectOrderCwds rather than the in-memory projectOrder branch.
529 const rehydrated = syncProjects(makeUiState(), [projectA, projectB, projectC]);
530
531 expect(rehydrated.projectOrder).toEqual([projectC.key, projectA.key, projectB.key]);
532 });
533
534 it("preserves expand state across restart when project's logical key changes", () => {
535 // After restart, in-memory previousExpandedById is empty, so the
536 // previousLogicalKey-to-state bridge in syncProjects cannot help. The
537 // persisted-cwd fallback is the only mechanism that can carry collapse
538 // state across a restart that also flips a project into a new logical
539 // group (e.g. late-arriving repo metadata). This locks in that path.
540 const physicalKey = "env-local:/lk-restart-proj";
541 const previousLogicalKey = physicalKey;
542 const cwd = "/lk-restart-proj";
543
544 let state = syncProjects(makeUiState(), [
545 { key: physicalKey, logicalKey: previousLogicalKey, cwd },
546 ]);
547 state = setProjectExpanded(state, previousLogicalKey, false);
548 persistState(state);
549
550 const persisted = JSON.parse(
551 localStorageStub.getItem(PERSISTED_STATE_KEY) ?? "{}",
552 ) as PersistedUiState;
553 hydratePersistedProjectState(persisted);
554
555 const nextLogicalKey = "lk-restart-canonical";
556 const rehydrated = syncProjects(makeUiState(), [
557 { key: physicalKey, logicalKey: nextLogicalKey, cwd },
558 ]);
559
560 expect(rehydrated.projectExpandedById[nextLogicalKey]).toBe(false);
561 });
562});