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