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