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