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}): boolean {
63 return input.hasActiveProject && (input.isGitRepo || input.showEnvironmentIndicator);
64}
65
66export function resolveEnvModeLabel(mode: EnvMode): string {
67 return mode === "worktree" ? "New worktree" : "Current checkout";
68}
69
70export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null): string {
71 return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
72}
73
74export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): string {
75 return activeWorktreePath ? "Worktree" : "Local checkout";
76}
77
78export interface PreviousWorktreeSeed {
79 branch: string | null;
80 worktreePath: string;
81}
82
83// The most recently touched worktree in the project that the composer isn't
84// already pointing at. Backs the "Previous worktree" entry in the workspace
85// selector so a follow-up thread can hop back into the worktree you just
86// worked in without hunting for its branch. Archived threads don't compete —
87// the rest of the UI hides them, so their worktrees shouldn't resurface here.
88export function resolvePreviousWorktreeSeed(input: {
89 threads: ReadonlyArray<{
90 branch: string | null;
91 worktreePath: string | null;
92 updatedAt: string;
93 archivedAt?: string | null;
94 }>;
95 currentWorktreePath: string | null;
96}): PreviousWorktreeSeed | null {
97 let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
98 for (const thread of input.threads) {
99 if (
100 !thread.worktreePath ||
101 thread.worktreePath === input.currentWorktreePath ||
102 (thread.archivedAt ?? null) !== null
103 ) {
104 continue;
105 }
106 const updatedAt = toSortableTimestamp(thread.updatedAt);
107 if (updatedAt === null) {
108 continue;
109 }
110 if (latest === null || updatedAt > latest.updatedAt) {
111 latest = {
112 branch: thread.branch,
113 worktreePath: thread.worktreePath,
114 updatedAt,
115 };
116 }
117 }
118 return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
119}
120
121export function resolvePreviousWorktreeLabel(seed: PreviousWorktreeSeed): string {
122 return seed.branch ? `Previous worktree (${seed.branch})` : "Previous worktree";
123}
124
125export function resolveEffectiveEnvMode(input: {
126 activeWorktreePath: string | null;
127 hasServerThread: boolean;
128 draftThreadEnvMode: EnvMode | undefined;
129}): EnvMode {
130 const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
131 if (!hasServerThread) {
132 if (activeWorktreePath) {
133 return "local";
134 }
135 return draftThreadEnvMode === "worktree" ? "worktree" : "local";
136 }
137 return activeWorktreePath ? "worktree" : "local";
138}
139
140export function resolveDraftEnvModeAfterBranchChange(input: {
141 nextWorktreePath: string | null;
142 currentWorktreePath: string | null;
143 effectiveEnvMode: EnvMode;
144}): EnvMode {
145 const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
146 if (nextWorktreePath) {
147 return "worktree";
148 }
149 if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
150 return "worktree";
151 }
152 return "local";
153}
154
155export function resolveBranchToolbarValue(input: {
156 envMode: EnvMode;
157 activeWorktreePath: string | null;
158 activeThreadBranch: string | null;
159 currentGitBranch: string | null;
160}): string | null {
161 const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
162 if (envMode === "worktree" && !activeWorktreePath) {
163 return activeThreadBranch ?? currentGitBranch;
164 }
165 return currentGitBranch ?? activeThreadBranch;
166}
167
168export function resolveBranchTriggerLabel(input: {
169 activeWorktreePath: string | null;
170 effectiveEnvMode: EnvMode;
171 resolvedActiveBranch: string | null;
172 resolvedActiveBranchIsRemote: boolean | null;
173 startFromOrigin: boolean;
174}): string {
175 const {
176 activeWorktreePath,
177 effectiveEnvMode,
178 resolvedActiveBranch,
179 resolvedActiveBranchIsRemote,
180 startFromOrigin,
181 } = input;
182 if (!resolvedActiveBranch) {
183 return "Select ref";
184 }
185 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
186 const baseRef =
187 startFromOrigin && resolvedActiveBranchIsRemote === false
188 ? `origin/${resolvedActiveBranch}`
189 : resolvedActiveBranch;
190 return `From ${baseRef}`;
191 }
192 return resolvedActiveBranch;
193}
194
195export function resolveBranchToolbarPrBranch(input: {
196 activeThreadBranch: string | null;
197 resolvedActiveBranch: string | null;
198}): string | null {
199 return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
200}
201
202export function resolveLocalCheckoutBranchMismatch(input: {
203 effectiveEnvMode: EnvMode;
204 activeWorktreePath: string | null;
205 activeThreadBranch: string | null;
206 currentGitBranch: string | null;
207}): { threadBranch: string; currentBranch: string } | null {
208 const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
209 if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
210 return null;
211 }
212 if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
213 return null;
214 }
215 return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
216}
217
218export function resolveBranchSelectionTarget(input: {
219 activeProjectCwd: string;
220 activeWorktreePath: string | null;
221 refName: Pick<VcsRef, "isDefault" | "worktreePath">;
222}): {
223 checkoutCwd: string;
224 nextWorktreePath: string | null;
225 reuseExistingWorktree: boolean;
226} {
227 const { activeProjectCwd, activeWorktreePath, refName } = input;
228
229 if (refName.worktreePath) {
230 return {
231 checkoutCwd: refName.worktreePath,
232 nextWorktreePath: refName.worktreePath === activeProjectCwd ? null : refName.worktreePath,
233 reuseExistingWorktree: true,
234 };
235 }
236
237 const nextWorktreePath =
238 activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
239
240 return {
241 checkoutCwd: nextWorktreePath ?? activeProjectCwd,
242 nextWorktreePath,
243 reuseExistingWorktree: false,
244 };
245}
246
247// Git rejects ASCII space and the ASCII control characters (tab, newline and
248// friends) in ref names, so the picker's "Create new ref" entry can only fail
249// for a typed name like "new branch". Replacing runs of those with a dash makes
250// the name usable without reimplementing check-ref-format: names invalid for
251// other reasons still surface the git error. Only the whitespace git actually
252// rejects is replaced — git accepts U+00A0 and friends, and rewriting those
253// would silently create a ref the user never asked for. Case and existing
254// dashes are left alone, since ref names are case sensitive and consecutive
255// dashes are valid.
256export function sanitizeNewRefName(rawName: string): string {
257 return rawName.trim().replace(/[ \t\n\r\f\v]+/g, "-");
258}
259
260export function shouldIncludeBranchPickerItem(input: {
261 itemValue: string;
262 normalizedQuery: string;
263 createBranchItemValue: string | null;
264 checkoutPullRequestItemValue: string | null;
265}): boolean {
266 const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
267
268 if (normalizedQuery.length === 0) {
269 return true;
270 }
271
272 if (createBranchItemValue && itemValue === createBranchItemValue) {
273 return true;
274 }
275
276 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
277 return true;
278 }
279
280 const lowerItemValue = itemValue.toLowerCase();
281 if (lowerItemValue.includes(normalizedQuery)) {
282 return true;
283 }
284
285 // A query containing whitespace can only ever match a ref under its sanitized
286 // name, because that is the name such a ref would have been created with.
287 // Without this, typing "new branch" hides an existing "new-branch".
288 const sanitizedQuery = sanitizeNewRefName(normalizedQuery);
289 return (
290 sanitizedQuery.length > 0 &&
291 sanitizedQuery !== normalizedQuery &&
292 lowerItemValue.includes(sanitizedQuery)
293 );
294}