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 { sanitizeNewRefName } from "@t3tools/shared/git";
10import { toSortableTimestamp } from "../lib/threadSort";
11export {
12 dedupeRemoteBranchesWithLocalMatches,
13 deriveLocalBranchNameFromRemoteRef,
14 sanitizeNewRefName,
15} from "@t3tools/shared/git";
16
17export interface EnvironmentOption {
18 environmentId: EnvironmentId;
19 projectId: ProjectId;
20 label: string;
21 isPrimary: boolean;
22 machine: EnvironmentMachineKind;
23}
24
25export const EnvMode = Schema.Literals(["local", "worktree"]);
26export type EnvMode = typeof EnvMode.Type;
27
28const GENERIC_LOCAL_ENVIRONMENT_LABELS = new Set(["local", "local environment"]);
29
30function normalizeDisplayLabel(value: string | null | undefined): string | null {
31 const trimmed = value?.trim();
32 return trimmed && trimmed.length > 0 ? trimmed : null;
33}
34
35export function resolveEnvironmentOptionLabel(input: {
36 isPrimary: boolean;
37 environmentId: EnvironmentId;
38 runtimeLabel?: string | null;
39 savedLabel?: string | null;
40}): string {
41 const runtimeLabel = normalizeDisplayLabel(input.runtimeLabel);
42 const savedLabel = normalizeDisplayLabel(input.savedLabel);
43
44 if (input.isPrimary) {
45 const preferredLocalLabel = [runtimeLabel, savedLabel].find((label) => {
46 if (!label) return false;
47 return !GENERIC_LOCAL_ENVIRONMENT_LABELS.has(label.toLowerCase());
48 });
49 return preferredLocalLabel ?? "This device";
50 }
51
52 return runtimeLabel ?? savedLabel ?? input.environmentId;
53}
54
55// A remote (non-primary) environment is always surfaced, even when it is the
56// only environment available: with a single connected machine there is nothing
57// to pick, but the user still needs to see where the project runs.
58export function shouldShowEnvironmentIndicator(input: {
59 activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
60 canPickEnvironment: boolean;
61}): boolean {
62 if (input.canPickEnvironment) return true;
63 return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
64}
65
66export function shouldShowComposerContextStrip(input: {
67 hasActiveProject: boolean;
68 isGitRepo: boolean;
69 showEnvironmentIndicator: boolean;
70 /** A collapsed composer's controls currently fit in their measured strip host. */
71 hostsRestingComposerControls: boolean;
72}): boolean {
73 return (
74 input.hasActiveProject &&
75 (input.isGitRepo || input.showEnvironmentIndicator || input.hostsRestingComposerControls)
76 );
77}
78
79// Labels collapse to icons when the strip's content no longer fits. A small
80// hysteresis on the way back out keeps the boundary from flapping.
81const CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX = 16;
82
83export function resolveContextStripLabelsCompact(input: {
84 compact: boolean;
85 neededWidth: number;
86 availableWidth: number;
87}): boolean {
88 return input.compact
89 ? input.neededWidth > input.availableWidth - CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX
90 : input.neededWidth > input.availableWidth;
91}
92
93export function resolveEnvModeLabel(mode: EnvMode): string {
94 return mode === "worktree" ? "New worktree" : "Current checkout";
95}
96
97export const WORKTREE_SUBMODULES_LABELS: Record<WorktreeSubmodules, string> = {
98 recursive: "Recursive",
99 "top-level": "Top level only",
100 none: "Skip",
101};
102
103export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null): string {
104 return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
105}
106
107// A locked thread in worktree mode with no path is still creating its
108// worktree, so it reads as a new worktree rather than the project checkout.
109export function resolveLockedWorkspaceLabel(
110 activeWorktreePath: string | null,
111 effectiveEnvMode: EnvMode,
112): string {
113 if (activeWorktreePath) return "Worktree";
114 return effectiveEnvMode === "worktree" ? resolveEnvModeLabel("worktree") : "Local checkout";
115}
116
117export interface PreviousWorktreeSeed {
118 branch: string | null;
119 worktreePath: string;
120}
121
122// The most recently touched worktree in the project that the composer isn't
123// already pointing at. Backs the "Previous worktree" entry in the workspace
124// selector so a follow-up thread can hop back into the worktree you just
125// worked in without hunting for its branch. Archived threads don't compete —
126// the rest of the UI hides them, so their worktrees shouldn't resurface here.
127export function resolvePreviousWorktreeSeed(input: {
128 threads: ReadonlyArray<{
129 branch: string | null;
130 worktreePath: string | null;
131 updatedAt: string;
132 archivedAt?: string | null;
133 }>;
134 currentWorktreePath: string | null;
135}): PreviousWorktreeSeed | null {
136 let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
137 for (const thread of input.threads) {
138 if (
139 !thread.worktreePath ||
140 thread.worktreePath === input.currentWorktreePath ||
141 (thread.archivedAt ?? null) !== null
142 ) {
143 continue;
144 }
145 const updatedAt = toSortableTimestamp(thread.updatedAt);
146 if (updatedAt === null) {
147 continue;
148 }
149 if (latest === null || updatedAt > latest.updatedAt) {
150 latest = {
151 branch: thread.branch,
152 worktreePath: thread.worktreePath,
153 updatedAt,
154 };
155 }
156 }
157 return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
158}
159
160export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
161 return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
162}
163
164export function resolveEffectiveEnvMode(input: {
165 activeWorktreePath: string | null;
166 hasServerThread: boolean;
167 draftThreadEnvMode: EnvMode | undefined;
168 /**
169 * The server is still creating this thread's worktree. The thread exists
170 * from the start of that setup but gets its worktree path only at the end.
171 */
172 preparingWorktree?: boolean;
173}): EnvMode {
174 const { activeWorktreePath, hasServerThread, draftThreadEnvMode, preparingWorktree } = input;
175 if (!hasServerThread) {
176 if (activeWorktreePath) {
177 return "local";
178 }
179 return draftThreadEnvMode === "worktree" ? "worktree" : "local";
180 }
181 return activeWorktreePath || preparingWorktree ? "worktree" : "local";
182}
183
184export function resolveDraftEnvModeAfterBranchChange(input: {
185 nextWorktreePath: string | null;
186 currentWorktreePath: string | null;
187 effectiveEnvMode: EnvMode;
188}): EnvMode {
189 const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
190 if (nextWorktreePath) {
191 return "worktree";
192 }
193 if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
194 return "worktree";
195 }
196 return "local";
197}
198
199export function resolveBranchToolbarValue(input: {
200 envMode: EnvMode;
201 activeWorktreePath: string | null;
202 activeThreadBranch: string | null;
203 currentGitBranch: string | null;
204}): string | null {
205 const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
206 if (envMode === "worktree" && !activeWorktreePath) {
207 return activeThreadBranch ?? currentGitBranch;
208 }
209 return currentGitBranch ?? activeThreadBranch;
210}
211
212export function resolveBranchTriggerLabel(input: {
213 activeWorktreePath: string | null;
214 effectiveEnvMode: EnvMode;
215 resolvedActiveBranch: string | null;
216 resolvedActiveBranchIsRemote: boolean | null;
217 startFromOrigin: boolean;
218}): string {
219 const {
220 activeWorktreePath,
221 effectiveEnvMode,
222 resolvedActiveBranch,
223 resolvedActiveBranchIsRemote,
224 startFromOrigin,
225 } = input;
226 if (!resolvedActiveBranch) {
227 return "Select ref";
228 }
229 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
230 const baseRef =
231 startFromOrigin && resolvedActiveBranchIsRemote === false
232 ? `origin/${resolvedActiveBranch}`
233 : resolvedActiveBranch;
234 return `From ${baseRef}`;
235 }
236 return resolvedActiveBranch;
237}
238
239export function resolveBranchToolbarPrBranch(input: {
240 activeThreadBranch: string | null;
241 resolvedActiveBranch: string | null;
242}): string | null {
243 return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
244}
245
246export function resolveLocalCheckoutBranchMismatch(input: {
247 effectiveEnvMode: EnvMode;
248 activeWorktreePath: string | null;
249 activeThreadBranch: string | null;
250 currentGitBranch: string | null;
251}): { threadBranch: string; currentBranch: string } | null {
252 const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
253 if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
254 return null;
255 }
256 if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
257 return null;
258 }
259 return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
260}
261
262export function resolveBranchSelectionTarget(input: {
263 activeProjectCwd: string;
264 activeWorktreePath: string | null;
265 refName: Pick<VcsRef, "isDefault" | "worktreePath">;
266}): {
267 checkoutCwd: string;
268 nextWorktreePath: string | null;
269 reuseExistingWorktree: boolean;
270} {
271 const { activeProjectCwd, activeWorktreePath, refName } = input;
272
273 if (refName.worktreePath) {
274 return {
275 checkoutCwd: refName.worktreePath,
276 nextWorktreePath: refName.worktreePath === activeProjectCwd ? null : refName.worktreePath,
277 reuseExistingWorktree: true,
278 };
279 }
280
281 const nextWorktreePath =
282 activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
283
284 return {
285 checkoutCwd: nextWorktreePath ?? activeProjectCwd,
286 nextWorktreePath,
287 reuseExistingWorktree: false,
288 };
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}