Open History to see the last commit
1import type { ThreadStructureVisibleTurnItem } from "@t3tools/client-runtime/state/shell";
2import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
3import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4import {
5 trimAsciiWhitespace,
6 type RunId,
7 type ScopedThreadRef,
8 type ThreadId,
9 type TurnItemId,
10} from "@t3tools/contracts";
11import { create } from "zustand";
12import { createJSONStorage, persist } from "zustand/middleware";
13
14import { withNewFilesFolded } from "./lib/diffCollapse";
15import { resolveStorage } from "./lib/storage";
16
17export interface ToolCallDiffTarget {
18 readonly threadId: ThreadId;
19 readonly itemId: TurnItemId;
20 readonly revision: string;
21}
22
23export type DiffPanelSelection =
24 | ({ kind: "tool-call" } & ToolCallDiffTarget)
25 | { kind: "branch"; baseRef: string | null }
26 | { kind: "unstaged" }
27 | { kind: "commit"; sha: string; baseRef: string | null }
28 | {
29 kind: "turn";
30 turnId: RunId;
31 /** From the thread's folder, so a tracked repository's file carries that repository's folder. */
32 filePath: string | null;
33 revealRequestId: number;
34 /** A turn diff section key to narrow to; absent shows every repository. */
35 repository?: string;
36 };
37
38const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null };
39
40interface DiffPanelStoreState {
41 byThreadKey: Record<string, DiffPanelSelection>;
42 branchBaseRefByThreadKey: Record<string, string | null>;
43 /** A tracked repository the Git scopes read instead of the thread's folder. */
44 gitRepositoryPathByThreadKey: Record<string, string>;
45 selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void;
46 selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void;
47 selectToolCall: (ref: ScopedThreadRef, target: ToolCallDiffTarget) => void;
48 selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void;
49 selectTurnRepository: (ref: ScopedThreadRef, turnId: RunId, repository: string | null) => void;
50 /** Records the checkout the commit came from; null is the thread's folder. */
51 selectCommit: (ref: ScopedThreadRef, sha: string, repositoryPath: string | null) => void;
52 selectGitRepository: (ref: ScopedThreadRef, repositoryPath: string | null) => void;
53 reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray<RunId>) => void;
54 removeThread: (ref: ScopedThreadRef) => void;
55}
56
57function normalizeBaseRef(baseRef: string | null): string | null {
58 const normalized = baseRef === null ? null : trimAsciiWhitespace(baseRef);
59 return normalized ? normalized : null;
60}
61
62function branchBaseRef(
63 state: Pick<DiffPanelStoreState, "byThreadKey" | "branchBaseRefByThreadKey">,
64 threadKey: string,
65): string | null {
66 const previous = state.byThreadKey[threadKey];
67 return previous?.kind === "branch" || previous?.kind === "commit"
68 ? previous.baseRef
69 : (state.branchBaseRefByThreadKey[threadKey] ?? null);
70}
71
72function withGitRepositoryPath(
73 byThreadKey: Record<string, string>,
74 threadKey: string,
75 repositoryPath: string | null,
76): Record<string, string> {
77 const { [threadKey]: _previous, ...rest } = byThreadKey;
78 return repositoryPath === null ? rest : { ...rest, [threadKey]: repositoryPath };
79}
80
81export const useDiffPanelStore = create<DiffPanelStoreState>()(
82 persist(
83 (set) => ({
84 byThreadKey: {},
85 branchBaseRefByThreadKey: {},
86 gitRepositoryPathByThreadKey: {},
87 selectGitScope: (ref, scope) =>
88 set((state) => {
89 const threadKey = scopedThreadKey(ref);
90 const previous = state.byThreadKey[threadKey];
91 const previousBaseRef = branchBaseRef(state, threadKey);
92 return {
93 byThreadKey: {
94 ...state.byThreadKey,
95 [threadKey]:
96 scope === "branch"
97 ? { kind: "branch", baseRef: previousBaseRef }
98 : { kind: "unstaged" },
99 },
100 branchBaseRefByThreadKey:
101 previous?.kind === "branch" || previous?.kind === "commit"
102 ? { ...state.branchBaseRefByThreadKey, [threadKey]: previous.baseRef }
103 : state.branchBaseRefByThreadKey,
104 };
105 }),
106 selectBranchBaseRef: (ref, baseRef) =>
107 set((state) => {
108 const threadKey = scopedThreadKey(ref);
109 const normalizedBaseRef = normalizeBaseRef(baseRef);
110 return {
111 byThreadKey: {
112 ...state.byThreadKey,
113 [threadKey]: { kind: "branch", baseRef: normalizedBaseRef },
114 },
115 branchBaseRefByThreadKey: {
116 ...state.branchBaseRefByThreadKey,
117 [threadKey]: normalizedBaseRef,
118 },
119 };
120 }),
121 selectToolCall: (ref, target) =>
122 set((state) => ({
123 byThreadKey: {
124 ...state.byThreadKey,
125 [scopedThreadKey(ref)]: { kind: "tool-call", ...target },
126 },
127 })),
128 selectTurn: (ref, turnId, filePath) =>
129 set((state) => {
130 const threadKey = scopedThreadKey(ref);
131 const previous = state.byThreadKey[threadKey];
132 // Git reports paths with their edge whitespace; only a blank one means no file.
133 const requestedPath = filePath !== undefined && filePath.trim() !== "" ? filePath : null;
134 return {
135 byThreadKey: {
136 ...state.byThreadKey,
137 [threadKey]: {
138 kind: "turn",
139 turnId,
140 filePath: requestedPath,
141 revealRequestId: previous?.kind === "turn" ? previous.revealRequestId + 1 : 1,
142 // A requested file may sit outside the repository the view was narrowed to.
143 ...(requestedPath === null &&
144 previous?.kind === "turn" &&
145 previous.repository !== undefined
146 ? { repository: previous.repository }
147 : {}),
148 },
149 },
150 };
151 }),
152 selectTurnRepository: (ref, turnId, repository) =>
153 set((state) => {
154 const threadKey = scopedThreadKey(ref);
155 const previous = state.byThreadKey[threadKey];
156 return {
157 byThreadKey: {
158 ...state.byThreadKey,
159 [threadKey]: {
160 kind: "turn",
161 turnId,
162 filePath: null,
163 revealRequestId: previous?.kind === "turn" ? previous.revealRequestId : 0,
164 ...(repository === null ? {} : { repository }),
165 },
166 },
167 };
168 }),
169 selectCommit: (ref, sha, repositoryPath) =>
170 set((state) => {
171 const threadKey = scopedThreadKey(ref);
172 const baseRef = branchBaseRef(state, threadKey);
173 return {
174 byThreadKey: {
175 ...state.byThreadKey,
176 [threadKey]: { kind: "commit", sha, baseRef },
177 },
178 branchBaseRefByThreadKey: { ...state.branchBaseRefByThreadKey, [threadKey]: baseRef },
179 gitRepositoryPathByThreadKey: withGitRepositoryPath(
180 state.gitRepositoryPathByThreadKey,
181 threadKey,
182 repositoryPath,
183 ),
184 };
185 }),
186 selectGitRepository: (ref, repositoryPath) =>
187 set((state) => ({
188 gitRepositoryPathByThreadKey: withGitRepositoryPath(
189 state.gitRepositoryPathByThreadKey,
190 scopedThreadKey(ref),
191 repositoryPath,
192 ),
193 })),
194 reconcileTurnSelection: (ref, availableTurnIds) =>
195 set((state) => {
196 const threadKey = scopedThreadKey(ref);
197 const previous = state.byThreadKey[threadKey];
198 const latestTurnId = availableTurnIds[0];
199 if (
200 previous?.kind !== "turn" ||
201 latestTurnId === undefined ||
202 availableTurnIds.includes(previous.turnId)
203 ) {
204 return state;
205 }
206 return {
207 byThreadKey: {
208 ...state.byThreadKey,
209 [threadKey]: { ...previous, turnId: latestTurnId },
210 },
211 };
212 }),
213 removeThread: (ref) =>
214 set((state) => {
215 const threadKey = scopedThreadKey(ref);
216 if (
217 !(threadKey in state.byThreadKey) &&
218 !(threadKey in state.branchBaseRefByThreadKey) &&
219 !(threadKey in state.gitRepositoryPathByThreadKey)
220 ) {
221 return state;
222 }
223 const { [threadKey]: _removed, ...byThreadKey } = state.byThreadKey;
224 const { [threadKey]: _removedBaseRef, ...branchBaseRefByThreadKey } =
225 state.branchBaseRefByThreadKey;
226 const { [threadKey]: _removedRepository, ...gitRepositoryPathByThreadKey } =
227 state.gitRepositoryPathByThreadKey;
228 return { byThreadKey, branchBaseRefByThreadKey, gitRepositoryPathByThreadKey };
229 }),
230 }),
231 {
232 name: "t3code:diff-panel-state:v1",
233 version: 2,
234 storage: createJSONStorage(() =>
235 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
236 ),
237 partialize: (state) => ({
238 byThreadKey: state.byThreadKey,
239 branchBaseRefByThreadKey: state.branchBaseRefByThreadKey,
240 gitRepositoryPathByThreadKey: state.gitRepositoryPathByThreadKey,
241 }),
242 },
243 ),
244);
245
246interface DiffPanelSessionStoreState {
247 collapsedFileKeysByScopeKey: Record<string, ReadonlySet<string>>;
248 // Every file present at a fold change; a file outside it starts folded as the default says.
249 knownFileKeysByScopeKey: Record<string, ReadonlySet<string>>;
250 updateCollapsedFileKeys: (
251 scopeKey: string,
252 fileKeys: ReadonlyArray<string>,
253 defaults: ReadonlySet<string>,
254 update: (current: ReadonlySet<string>) => ReadonlySet<string>,
255 ) => void;
256 // Null follows the diffIgnoreWhitespace setting until the panel toggle is used.
257 ignoreWhitespace: boolean | null;
258 setIgnoreWhitespace: (ignoreWhitespace: boolean) => void;
259}
260
261// Session-only so folds and the whitespace toggle survive right-panel switches without
262// changing reload defaults.
263export const useDiffPanelSessionStore = create<DiffPanelSessionStoreState>()((set) => ({
264 collapsedFileKeysByScopeKey: {},
265 knownFileKeysByScopeKey: {},
266 updateCollapsedFileKeys: (scopeKey, fileKeys, defaults, update) =>
267 set((state) => {
268 const current = withNewFilesFolded(
269 state.collapsedFileKeysByScopeKey[scopeKey],
270 state.knownFileKeysByScopeKey[scopeKey],
271 defaults,
272 );
273 const next = update(current);
274 if (next === current) return state;
275 const known = state.knownFileKeysByScopeKey[scopeKey] ?? [];
276 return {
277 collapsedFileKeysByScopeKey: { ...state.collapsedFileKeysByScopeKey, [scopeKey]: next },
278 knownFileKeysByScopeKey: {
279 ...state.knownFileKeysByScopeKey,
280 [scopeKey]: new Set([...known, ...fileKeys]),
281 },
282 };
283 }),
284 ignoreWhitespace: null,
285 setIgnoreWhitespace: (ignoreWhitespace) => set({ ignoreWhitespace }),
286}));
287
288export function selectThreadDiffPanelSelection(
289 byThreadKey: Record<string, DiffPanelSelection>,
290 ref: ScopedThreadRef | null | undefined,
291): DiffPanelSelection {
292 if (!ref) return DEFAULT_SELECTION;
293 return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_SELECTION;
294}
295
296export function selectThreadBranchBaseRef(
297 state: Pick<DiffPanelStoreState, "byThreadKey" | "branchBaseRefByThreadKey">,
298 ref: ScopedThreadRef | null | undefined,
299): string | null {
300 return ref ? branchBaseRef(state, scopedThreadKey(ref)) : null;
301}
302
303export function selectThreadGitRepositoryPath(
304 state: Pick<DiffPanelStoreState, "gitRepositoryPathByThreadKey">,
305 ref: ScopedThreadRef | null | undefined,
306): string | null {
307 return ref ? (state.gitRepositoryPathByThreadKey[scopedThreadKey(ref)] ?? null) : null;
308}
309
310export function resolveToolCallDiffTarget(
311 target: ToolCallDiffTarget,
312 items: ReadonlyArray<ThreadStructureVisibleTurnItem>,
313): ToolCallDiffTarget {
314 const row = items.find(
315 (row) => row.sourceThreadId === target.threadId && row.sourceItemId === target.itemId,
316 );
317 if (row?.item.type !== "file_change") return target;
318 const revision = turnItemDetailRevision(row.item);
319 return revision === target.revision ? target : { ...target, revision };
320}