Open History to see the last commit
1import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3import { toSortableTimestamp } from "../lib/threadSort";
4export {
5 dedupeRemoteBranchesWithLocalMatches,
6 deriveLocalBranchNameFromRemoteRef,
7} from "@t3tools/shared/git";
8
9export interface EnvironmentOption {
10 environmentId: EnvironmentId;
11 projectId: ProjectId;
12 label: string;
13 isPrimary: boolean;
14}
15
16export const EnvMode = Schema.Literals(["local", "worktree"]);
17export type EnvMode = typeof EnvMode.Type;
18
19const GENERIC_LOCAL_ENVIRONMENT_LABELS = new Set(["local", "local environment"]);
20
21function normalizeDisplayLabel(value: string | null | undefined): string | null {
22 const trimmed = value?.trim();
23 return trimmed && trimmed.length > 0 ? trimmed : null;
24}
25
26export function resolveEnvironmentOptionLabel(input: {
27 isPrimary: boolean;
28 environmentId: EnvironmentId;
29 runtimeLabel?: string | null;
30 savedLabel?: string | null;
31}): string {
32 const runtimeLabel = normalizeDisplayLabel(input.runtimeLabel);
33 const savedLabel = normalizeDisplayLabel(input.savedLabel);
34
35 if (input.isPrimary) {
36 const preferredLocalLabel = [runtimeLabel, savedLabel].find((label) => {
37 if (!label) return false;
38 return !GENERIC_LOCAL_ENVIRONMENT_LABELS.has(label.toLowerCase());
39 });
40 return preferredLocalLabel ?? "This device";
41 }
42
43 return runtimeLabel ?? savedLabel ?? input.environmentId;
44}
45
46// A remote (non-primary) environment is always surfaced, even when it is the
47// only environment available: with a single connected machine there is nothing
48// to pick, but the user still needs to see where the project runs.
49export function shouldShowEnvironmentIndicator(input: {
50 activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
51 canPickEnvironment: boolean;
52}): boolean {
53 if (input.canPickEnvironment) return true;
54 return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
55}
56
57export function shouldShowComposerContextStrip(input: {
58 hasActiveProject: boolean;
59 isGitRepo: boolean;
60 showEnvironmentIndicator: boolean;
61}): boolean {
62 return input.hasActiveProject && (input.isGitRepo || input.showEnvironmentIndicator);
63}
64
65export function resolveEnvModeLabel(mode: EnvMode): string {
66 return mode === "worktree" ? "New worktree" : "Current checkout";
67}
68
69export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null): string {
70 return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
71}
72
73export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): string {
74 return activeWorktreePath ? "Worktree" : "Local checkout";
75}
76
77export interface PreviousWorktreeSeed {
78 branch: string | null;
79 worktreePath: string;
80}
81
82// The most recently touched worktree in the project that the composer isn't
83// already pointing at. Backs the "Previous worktree" entry in the workspace
84// selector so a follow-up thread can hop back into the worktree you just
85// worked in without hunting for its branch. Archived threads don't compete —
86// the rest of the UI hides them, so their worktrees shouldn't resurface here.
87export function resolvePreviousWorktreeSeed(input: {
88 threads: ReadonlyArray<{
89 branch: string | null;
90 worktreePath: string | null;
91 updatedAt: string;
92 archivedAt?: string | null;
93 }>;
94 currentWorktreePath: string | null;
95}): PreviousWorktreeSeed | null {
96 let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
97 for (const thread of input.threads) {
98 if (
99 !thread.worktreePath ||
100 thread.worktreePath === input.currentWorktreePath ||
101 (thread.archivedAt ?? null) !== null
102 ) {
103 continue;
104 }
105 const updatedAt = toSortableTimestamp(thread.updatedAt);
106 if (updatedAt === null) {
107 continue;
108 }
109 if (latest === null || updatedAt > latest.updatedAt) {
110 latest = {
111 branch: thread.branch,
112 worktreePath: thread.worktreePath,
113 updatedAt,
114 };
115 }
116 }
117 return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
118}
119
120export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
121 return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
122}
123
124export function resolveEffectiveEnvMode(input: {
125 activeWorktreePath: string | null;
126 hasServerThread: boolean;
127 draftThreadEnvMode: EnvMode | undefined;
128}): EnvMode {
129 const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
130 if (!hasServerThread) {
131 if (activeWorktreePath) {
132 return "local";
133 }
134 return draftThreadEnvMode === "worktree" ? "worktree" : "local";
135 }
136 return activeWorktreePath ? "worktree" : "local";
137}
138
139export function resolveDraftEnvModeAfterBranchChange(input: {
140 nextWorktreePath: string | null;
141 currentWorktreePath: string | null;
142 effectiveEnvMode: EnvMode;
143}): EnvMode {
144 const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
145 if (nextWorktreePath) {
146 return "worktree";
147 }
148 if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
149 return "worktree";
150 }
151 return "local";
152}
153
154export function resolveBranchToolbarValue(input: {
155 envMode: EnvMode;
156 activeWorktreePath: string | null;
157 activeThreadBranch: string | null;
158 currentGitBranch: string | null;
159}): string | null {
160 const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
161 if (envMode === "worktree" && !activeWorktreePath) {
162 return activeThreadBranch ?? currentGitBranch;
163 }
164 return currentGitBranch ?? activeThreadBranch;
165}
166
167export function resolveBranchTriggerLabel(input: {
168 activeWorktreePath: string | null;
169 effectiveEnvMode: EnvMode;
170 resolvedActiveBranch: string | null;
171 resolvedActiveBranchIsRemote: boolean | null;
172 startFromOrigin: boolean;
173}): string {
174 const {
175 activeWorktreePath,
176 effectiveEnvMode,
177 resolvedActiveBranch,
178 resolvedActiveBranchIsRemote,
179 startFromOrigin,
180 } = input;
181 if (!resolvedActiveBranch) {
182 return "Select ref";
183 }
184 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
185 const baseRef =
186 startFromOrigin && resolvedActiveBranchIsRemote === false
187 ? `origin/${resolvedActiveBranch}`
188 : resolvedActiveBranch;
189 return `From ${baseRef}`;
190 }
191 return resolvedActiveBranch;
192}
193
194export function resolveBranchToolbarPrBranch(input: {
195 activeThreadBranch: string | null;
196 resolvedActiveBranch: string | null;
197}): string | null {
198 return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
199}
200
201export function resolveLocalCheckoutBranchMismatch(input: {
202 effectiveEnvMode: EnvMode;
203 activeWorktreePath: string | null;
204 activeThreadBranch: string | null;
205 currentGitBranch: string | null;
206}): { threadBranch: string; currentBranch: string } | null {
207 const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
208 if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
209 return null;
210 }
211 if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
212 return null;
213 }
214 return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
215}
216
217export function resolveBranchSelectionTarget(input: {
218 activeProjectCwd: string;
219 activeWorktreePath: string | null;
220 refName: Pick<VcsRef, "isDefault" | "worktreePath">;
221}): {
222 checkoutCwd: string;
223 nextWorktreePath: string | null;
224 reuseExistingWorktree: boolean;
225} {
226 const { activeProjectCwd, activeWorktreePath, refName } = input;
227
228 if (refName.worktreePath) {
229 return {
230 checkoutCwd: refName.worktreePath,
231 nextWorktreePath: refName.worktreePath === activeProjectCwd ? null : refName.worktreePath,
232 reuseExistingWorktree: true,
233 };
234 }
235
236 const nextWorktreePath =
237 activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
238
239 return {
240 checkoutCwd: nextWorktreePath ?? activeProjectCwd,
241 nextWorktreePath,
242 reuseExistingWorktree: false,
243 };
244}
245
246// Git rejects ASCII space and the ASCII control characters (tab, newline and
247// friends) in ref names, so the picker's "Create new ref" entry can only fail
248// for a typed name like "new branch". Replacing runs of those with a dash makes
249// the name usable without reimplementing check-ref-format: names invalid for
250// other reasons still surface the git error. Only the whitespace git actually
251// rejects is replaced — git accepts U+00A0 and friends, and rewriting those
252// would silently create a ref the user never asked for. Case and existing
253// dashes are left alone, since ref names are case sensitive and consecutive
254// dashes are valid.
255export function sanitizeNewRefName(rawName: string): string {
256 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
257}
258
259export function shouldIncludeBranchPickerItem(input: {
260 itemValue: string;
261 normalizedQuery: string;
262 createBranchItemValue: string | null;
263 checkoutPullRequestItemValue: string | null;
264}): boolean {
265 const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
266
267 if (normalizedQuery.length === 0) {
268 return true;
269 }
270
271 if (createBranchItemValue && itemValue === createBranchItemValue) {
272 return true;
273 }
274
275 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
276 return true;
277 }
278
279 const lowerItemValue = itemValue.toLowerCase();
280 if (lowerItemValue.includes(normalizedQuery)) {
281 return true;
282 }
283
284 // A query containing whitespace can only ever match a ref under its sanitized
285 // name, because that is the name such a ref would have been created with.
286 // Without this, typing "new branch" hides an existing "new-branch".
287 const sanitizedQuery = sanitizeNewRefName(normalizedQuery);
288 return (
289 sanitizedQuery.length > 0 &&
290 sanitizedQuery !== normalizedQuery &&
291 lowerItemValue.includes(sanitizedQuery)
292 );
293}