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 isDraftHeroState: boolean;
68 persistInActiveThreads: boolean;
69 hasActiveProject: boolean;
70 isGitRepo: boolean;
71 showEnvironmentIndicator: boolean;
72 /** A collapsed composer's controls currently fit in their measured strip host. */
73 hostsRestingComposerControls: boolean;
74}): boolean {
75 return (
76 input.hasActiveProject &&
77 (input.isDraftHeroState || input.persistInActiveThreads) &&
78 (input.isGitRepo || input.showEnvironmentIndicator || input.hostsRestingComposerControls)
79 );
80}
81
82// Labels collapse to icons when the strip's content no longer fits. A small
83// hysteresis on the way back out keeps the boundary from flapping.
84const CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX = 16;
85
86export function resolveContextStripLabelsCompact(input: {
87 compact: boolean;
88 neededWidth: number;
89 availableWidth: number;
90}): boolean {
91 return input.compact
92 ? input.neededWidth > input.availableWidth - CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX
93 : input.neededWidth > input.availableWidth;
94}
95
96export function resolveEnvModeLabel(mode: EnvMode): string {
97 return mode === "worktree" ? "New worktree" : "Current checkout";
98}
99
100export const WORKTREE_SUBMODULES_LABELS: Record<WorktreeSubmodules, string> = {
101 recursive: "Recursive",
102 "top-level": "Top level only",
103 none: "Skip",
104};
105
106export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null): string {
107 return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
108}
109
110// A locked thread in worktree mode with no path is still creating its
111// worktree, so it reads as a new worktree rather than the project checkout.
112export function resolveLockedWorkspaceLabel(
113 activeWorktreePath: string | null,
114 effectiveEnvMode: EnvMode,
115): string {
116 if (activeWorktreePath) return "Worktree";
117 return effectiveEnvMode === "worktree" ? resolveEnvModeLabel("worktree") : "Local checkout";
118}
119
120export function resolveWorkspaceDisplayName(path: string | null): string | null {
121 if (!path) return null;
122 const normalizedPath = path.replace(/[\\/]+$/, "");
123 if (normalizedPath.length === 0) return path;
124 return normalizedPath.split(/[\\/]/).at(-1) ?? normalizedPath;
125}
126
127export interface PreviousWorktreeSeed {
128 branch: string | null;
129 worktreePath: string;
130}
131
132// The most recently touched worktree in the project that the composer isn't
133// already pointing at. Backs the "Previous worktree" entry in the workspace
134// selector so a follow-up thread can hop back into the worktree you just
135// worked in without hunting for its branch. Archived threads don't compete —
136// the rest of the UI hides them, so their worktrees shouldn't resurface here.
137export function resolvePreviousWorktreeSeed(input: {
138 threads: ReadonlyArray<{
139 branch: string | null;
140 worktreePath: string | null;
141 updatedAt: string;
142 archivedAt?: string | null;
143 }>;
144 currentWorktreePath: string | null;
145}): PreviousWorktreeSeed | null {
146 let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
147 for (const thread of input.threads) {
148 if (
149 !thread.worktreePath ||
150 thread.worktreePath === input.currentWorktreePath ||
151 (thread.archivedAt ?? null) !== null
152 ) {
153 continue;
154 }
155 const updatedAt = toSortableTimestamp(thread.updatedAt);
156 if (updatedAt === null) {
157 continue;
158 }
159 if (latest === null || updatedAt > latest.updatedAt) {
160 latest = {
161 branch: thread.branch,
162 worktreePath: thread.worktreePath,
163 updatedAt,
164 };
165 }
166 }
167 return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
168}
169
170export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
171 return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
172}
173
174export function resolveEffectiveEnvMode(input: {
175 activeWorktreePath: string | null;
176 hasServerThread: boolean;
177 draftThreadEnvMode: EnvMode | undefined;
178 /**
179 * The server is still creating this thread's worktree. The thread exists
180 * from the start of that setup but gets its worktree path only at the end.
181 */
182 preparingWorktree?: boolean;
183}): EnvMode {
184 const { activeWorktreePath, hasServerThread, draftThreadEnvMode, preparingWorktree } = input;
185 if (!hasServerThread) {
186 if (activeWorktreePath) {
187 return "local";
188 }
189 return draftThreadEnvMode === "worktree" ? "worktree" : "local";
190 }
191 return activeWorktreePath || preparingWorktree ? "worktree" : "local";
192}
193
194export function resolveDraftEnvModeAfterBranchChange(input: {
195 nextWorktreePath: string | null;
196 currentWorktreePath: string | null;
197 effectiveEnvMode: EnvMode;
198}): EnvMode {
199 const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
200 if (nextWorktreePath) {
201 return "worktree";
202 }
203 if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
204 return "worktree";
205 }
206 return "local";
207}
208
209export function resolveBranchToolbarValue(input: {
210 envMode: EnvMode;
211 activeWorktreePath: string | null;
212 activeThreadBranch: string | null;
213 currentGitBranch: string | null;
214}): string | null {
215 const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
216 if (envMode === "worktree" && !activeWorktreePath) {
217 return activeThreadBranch ?? currentGitBranch;
218 }
219 return currentGitBranch ?? activeThreadBranch;
220}
221
222export function resolveBranchTriggerLabel(input: {
223 activeWorktreePath: string | null;
224 effectiveEnvMode: EnvMode;
225 resolvedActiveBranch: string | null;
226 resolvedActiveBranchIsRemote: boolean | null;
227 startFromOrigin: boolean;
228}): string {
229 const {
230 activeWorktreePath,
231 effectiveEnvMode,
232 resolvedActiveBranch,
233 resolvedActiveBranchIsRemote,
234 startFromOrigin,
235 } = input;
236 if (!resolvedActiveBranch) {
237 return "Select ref";
238 }
239 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
240 const baseRef =
241 startFromOrigin && resolvedActiveBranchIsRemote === false
242 ? `origin/${resolvedActiveBranch}`
243 : resolvedActiveBranch;
244 return `From ${baseRef}`;
245 }
246 return resolvedActiveBranch;
247}
248
249export function resolveBranchToolbarPrBranch(input: {
250 activeThreadBranch: string | null;
251 resolvedActiveBranch: string | null;
252}): string | null {
253 return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
254}
255
256export function resolveLocalCheckoutBranchMismatch(input: {
257 effectiveEnvMode: EnvMode;
258 activeWorktreePath: string | null;
259 activeThreadBranch: string | null;
260 currentGitBranch: string | null;
261}): { threadBranch: string; currentBranch: string } | null {
262 const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
263 if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
264 return null;
265 }
266 if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
267 return null;
268 }
269 return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
270}
271
272export function resolveBranchSelectionTarget(input: {
273 activeProjectCwd: string;
274 activeWorktreePath: string | null;
275 refName: Pick<VcsRef, "isDefault" | "worktreePath">;
276}): {
277 checkoutCwd: string;
278 nextWorktreePath: string | null;
279 reuseExistingWorktree: boolean;
280} {
281 const { activeProjectCwd, activeWorktreePath, refName } = input;
282
283 if (refName.worktreePath) {
284 return {
285 checkoutCwd: refName.worktreePath,
286 nextWorktreePath: refName.worktreePath === activeProjectCwd ? null : refName.worktreePath,
287 reuseExistingWorktree: true,
288 };
289 }
290
291 const nextWorktreePath =
292 activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
293
294 return {
295 checkoutCwd: nextWorktreePath ?? activeProjectCwd,
296 nextWorktreePath,
297 reuseExistingWorktree: false,
298 };
299}
300
301export function shouldIncludeBranchPickerItem(input: {
302 itemValue: string;
303 normalizedQuery: string;
304 createBranchItemValue: string | null;
305 checkoutPullRequestItemValue: string | null;
306}): boolean {
307 const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
308
309 if (normalizedQuery.length === 0) {
310 return true;
311 }
312
313 if (createBranchItemValue && itemValue === createBranchItemValue) {
314 return true;
315 }
316
317 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
318 return true;
319 }
320
321 const lowerItemValue = itemValue.toLowerCase();
322 if (lowerItemValue.includes(normalizedQuery)) {
323 return true;
324 }
325
326 // A query containing whitespace can only ever match a ref under its sanitized
327 // name, because that is the name such a ref would have been created with.
328 // Without this, typing "new branch" hides an existing "new-branch".
329 const sanitizedQuery = sanitizeNewRefName(normalizedQuery);
330 return (
331 sanitizedQuery.length > 0 &&
332 sanitizedQuery !== normalizedQuery &&
333 lowerItemValue.includes(sanitizedQuery)
334 );
335}