Open History to see the last commit
1import {
2 GitCommandError,
3 type EnvironmentId,
4 type EnvironmentMachineKind,
5 type VcsRef,
6 type ProjectId,
7 type WorktreeSubmodules,
8} from "@t3tools/contracts";
9import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
10import type { ThreadStructureRuntime } from "@t3tools/client-runtime/state/shell";
11import * as Schema from "effect/Schema";
12import { msg } from "gt-react";
13import { sanitizeNewRefName } from "@t3tools/shared/git";
14import { workspaceRelativeFilePath } from "@t3tools/shared/path";
15import { toSortableTimestamp } from "@t3tools/client-runtime/state/thread-sort";
16import { m, type MessageResolver } from "../i18n/messages";
17import { deriveCanInterruptRunningThread } from "../session-logic";
18export { deriveLocalBranchNameFromRemoteRef, sanitizeNewRefName } from "@t3tools/shared/git";
19
20const isGitCommandError = Schema.is(GitCommandError);
21
22// A toast clamps to a few lines, so Git failures show their sanitized detail
23// rather than the message's operation and cwd prefix.
24export function toBranchActionErrorMessage(error: unknown): string {
25 if (isGitCommandError(error)) {
26 return error.reason === undefined ? error.detail : `${error.detail} (${error.reason})`;
27 }
28 return thrownErrorMessage(error, m) ?? m(msg("An error occurred."));
29}
30
31export interface EnvironmentOption {
32 environmentId: EnvironmentId;
33 projectId: ProjectId | null;
34 label: string;
35 isPrimary: boolean;
36 machine: EnvironmentMachineKind;
37}
38
39/** "Add to another machine" stays muted until hovered: easy to find, quieter than the machines. */
40export const ADD_TO_MACHINE_LABEL_CLASS =
41 "flex min-w-0 items-center gap-1.5 opacity-55 in-data-highlighted:opacity-100 in-data-popup-open:opacity-100";
42
43export const EnvMode = Schema.Literals(["local", "worktree"]);
44export type EnvMode = typeof EnvMode.Type;
45
46const GENERIC_LOCAL_ENVIRONMENT_LABELS = new Set(["local", "local environment"]);
47
48function normalizeDisplayLabel(value: string | null | undefined): string | null {
49 const trimmed = value?.trim();
50 return trimmed && trimmed.length > 0 ? trimmed : null;
51}
52
53export function resolveEnvironmentOptionLabel(
54 input: {
55 isPrimary: boolean;
56 environmentId: EnvironmentId;
57 runtimeLabel?: string | null;
58 savedLabel?: string | null;
59 },
60 resolve: MessageResolver = m,
61): string {
62 const runtimeLabel = normalizeDisplayLabel(input.runtimeLabel);
63 const savedLabel = normalizeDisplayLabel(input.savedLabel);
64
65 if (input.isPrimary) {
66 const preferredLocalLabel = [runtimeLabel, savedLabel].find((label) => {
67 if (!label) return false;
68 return !GENERIC_LOCAL_ENVIRONMENT_LABELS.has(label.toLowerCase());
69 });
70 return preferredLocalLabel ?? resolve(msg("This device"));
71 }
72
73 return runtimeLabel ?? savedLabel ?? input.environmentId;
74}
75
76export function shouldShowEnvironmentIndicator(input: {
77 activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
78 canPickEnvironment: boolean;
79}): boolean {
80 if (input.canPickEnvironment) return true;
81 return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
82}
83
84export function shouldShowComposerContextStrip(input: {
85 isDraftHeroState: boolean;
86 persistInActiveThreads: boolean;
87 hasActiveProject: boolean;
88 isGitRepo: boolean;
89 showEnvironmentIndicator: boolean;
90}): boolean {
91 // A new thread always shows the strip, since it names the permissions the first send uses.
92 return (
93 input.hasActiveProject &&
94 (input.isDraftHeroState ||
95 (input.persistInActiveThreads && (input.isGitRepo || input.showEnvironmentIndicator)))
96 );
97}
98
99// Hysteresis prevents labels and icons from flapping at the width boundary.
100const CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX = 16;
101
102export function resolveContextStripLabelsCompact(input: {
103 compact: boolean;
104 neededWidth: number;
105 availableWidth: number;
106}): boolean {
107 return input.compact
108 ? input.neededWidth > input.availableWidth - CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX
109 : input.neededWidth > input.availableWidth;
110}
111
112export function resolveEnvModeLabel(mode: EnvMode, resolve: MessageResolver = m): string {
113 return mode === "worktree" ? resolve(msg("New worktree")) : resolve(msg("Current checkout"));
114}
115
116export const WORKTREE_SUBMODULES_LABELS: Record<WorktreeSubmodules, string> = {
117 recursive: msg("Recursive"),
118 "top-level": msg("Top level only"),
119 none: msg("Skip"),
120};
121
122export function resolveCurrentWorkspaceLabel(
123 activeWorktreePath: string | null,
124 resolve: MessageResolver = m,
125): string {
126 return activeWorktreePath
127 ? resolve(msg("Current worktree"))
128 : resolveEnvModeLabel("local", resolve);
129}
130
131export function resolveLockedWorkspaceLabel(
132 activeWorktreePath: string | null,
133 effectiveEnvMode: EnvMode,
134 resolve: MessageResolver = m,
135): string {
136 if (activeWorktreePath)
137 return activeWorktreePath.split(/[\\/]/).findLast(Boolean) ?? resolve(msg("Worktree"));
138 return effectiveEnvMode === "worktree"
139 ? resolveEnvModeLabel("worktree", resolve)
140 : resolve(msg("Local checkout"));
141}
142
143export interface PreviousWorktreeSeed {
144 branch: string | null;
145 worktreePath: string;
146}
147
148export function resolvePreviousWorktreeSeed(input: {
149 threads: ReadonlyArray<{
150 branch: string | null;
151 worktreePath: string | null;
152 updatedAt: string;
153 archivedAt?: string | null;
154 }>;
155 currentWorktreePath: string | null;
156}): PreviousWorktreeSeed | null {
157 let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
158 for (const thread of input.threads) {
159 if (
160 !thread.worktreePath ||
161 thread.worktreePath === input.currentWorktreePath ||
162 (thread.archivedAt ?? null) !== null
163 ) {
164 continue;
165 }
166 const updatedAt = toSortableTimestamp(thread.updatedAt);
167 if (updatedAt === null) {
168 continue;
169 }
170 if (latest === null || updatedAt > latest.updatedAt) {
171 latest = {
172 branch: thread.branch,
173 worktreePath: thread.worktreePath,
174 updatedAt,
175 };
176 }
177 }
178 return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
179}
180
181export function resolvePreviousWorktreeLabel(
182 seed: PreviousWorktreeSeed,
183 resolve: MessageResolver = m,
184): string {
185 return seed.branch
186 ? resolve(msg("Previous worktree ({branch})", { branch: seed.branch }))
187 : resolve(msg("Previous worktree"));
188}
189
190export function resolveEffectiveEnvMode(input: {
191 activeWorktreePath: string | null;
192 hasServerThread: boolean;
193 draftThreadEnvMode: EnvMode | undefined;
194 preparingWorktree?: boolean;
195}): EnvMode {
196 const { activeWorktreePath, hasServerThread, draftThreadEnvMode, preparingWorktree } = input;
197 if (!hasServerThread) {
198 if (activeWorktreePath) {
199 return "local";
200 }
201 return draftThreadEnvMode === "worktree" ? "worktree" : "local";
202 }
203 return activeWorktreePath || preparingWorktree ? "worktree" : "local";
204}
205
206export function resolveDraftEnvModeAfterBranchChange(input: {
207 nextWorktreePath: string | null;
208 currentWorktreePath: string | null;
209 effectiveEnvMode: EnvMode;
210}): EnvMode {
211 const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
212 if (nextWorktreePath) {
213 return "worktree";
214 }
215 if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
216 return "worktree";
217 }
218 return "local";
219}
220
221export function resolveBranchToolbarValue(input: {
222 envMode: EnvMode;
223 activeWorktreePath: string | null;
224 activeThreadBranch: string | null;
225 currentGitBranch: string | null;
226}): string | null {
227 const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
228 if (envMode === "worktree" && !activeWorktreePath) {
229 return activeThreadBranch ?? currentGitBranch;
230 }
231 return currentGitBranch ?? activeThreadBranch;
232}
233
234export interface BranchHold {
235 readonly branch: string | null;
236 readonly environmentId: EnvironmentId;
237 /**
238 * Each checkout the thread can show before it catches up, with the branch its status reported
239 * before the switch. A move from a worktree to the project root lists both.
240 */
241 readonly checkouts: ReadonlyArray<{ readonly cwd: string; readonly replaces: string | null }>;
242}
243
244/**
245 * A finished checkout's branch stays on screen until status reports any change, because the status
246 * stream and the RPC reply are not ordered and showing status first would flip back to the old branch.
247 */
248export function isBranchHoldCurrent(
249 hold: BranchHold,
250 current: {
251 readonly canonicalBranch: string | null;
252 readonly environmentId: EnvironmentId;
253 readonly cwd: string | null;
254 },
255): boolean {
256 return (
257 hold.environmentId === current.environmentId &&
258 hold.checkouts.some(
259 (checkout) => checkout.cwd === current.cwd && checkout.replaces === current.canonicalBranch,
260 )
261 );
262}
263
264/**
265 * The base a New worktree thread gets without the user picking one. Only a listed ref qualifies:
266 * during a clone the status names an unborn HEAD that no ref backs.
267 */
268export function resolveDefaultWorktreeBaseBranch(
269 refs: ReadonlyArray<Pick<VcsRef, "name" | "isDefault" | "current">>,
270): string | null {
271 return (refs.find((ref) => ref.isDefault) ?? refs.find((ref) => ref.current))?.name ?? null;
272}
273
274export function resolveBranchTriggerLabel(
275 input: {
276 activeWorktreePath: string | null;
277 effectiveEnvMode: EnvMode;
278 resolvedActiveBranch: string | null;
279 resolvedActiveBranchIsRemote: boolean | null;
280 startFromOrigin: boolean;
281 },
282 resolve: MessageResolver = m,
283): string {
284 const {
285 activeWorktreePath,
286 effectiveEnvMode,
287 resolvedActiveBranch,
288 resolvedActiveBranchIsRemote,
289 startFromOrigin,
290 } = input;
291 if (!resolvedActiveBranch) {
292 return resolve(msg("Select ref"));
293 }
294 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
295 // Only the server can determine a local branch's configured remote.
296 return startFromOrigin && resolvedActiveBranchIsRemote === false
297 ? resolve(msg("From {branch} (remote)", { branch: resolvedActiveBranch }))
298 : resolve(msg("From {branch}", { branch: resolvedActiveBranch }));
299 }
300 return resolvedActiveBranch;
301}
302
303export function resolveBranchToolbarPrBranch(input: {
304 activeThreadBranch: string | null;
305 resolvedActiveBranch: string | null;
306}): string | null {
307 return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
308}
309
310export function resolveLocalCheckoutBranchMismatch(input: {
311 effectiveEnvMode: EnvMode;
312 activeWorktreePath: string | null;
313 activeThreadBranch: string | null;
314 currentGitBranch: string | null;
315}): { threadBranch: string; currentBranch: string } | null {
316 const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
317 if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
318 return null;
319 }
320 if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
321 return null;
322 }
323 return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
324}
325
326/**
327 * Keeps a picked ref's worktree claim only when a read in that worktree finds it checked out.
328 * `freshRead` is `null` when the read failed.
329 */
330export function resolveConfirmedSelectedRef(
331 listedRef: VcsRef,
332 freshRead: { readonly refs: ReadonlyArray<VcsRef> } | null,
333): VcsRef {
334 const checkedOut =
335 freshRead?.refs.some((ref) => ref.name === listedRef.name && !ref.isRemote && ref.current) ??
336 false;
337 return checkedOut ? listedRef : { ...listedRef, worktreePath: null };
338}
339
340export function resolveBranchSelectionTarget(input: {
341 activeProjectCwd: string;
342 activeProjectCheckoutRoot?: string | undefined;
343 activeWorktreePath: string | null;
344 refName: Pick<VcsRef, "isDefault" | "worktreePath">;
345}): {
346 checkoutCwd: string;
347 nextWorktreePath: string | null;
348 reuseExistingWorktree: boolean;
349 staysInActiveCheckout: boolean;
350} {
351 const { activeProjectCwd, activeWorktreePath, refName } = input;
352
353 if (refName.worktreePath) {
354 // Until the project's checkout root loads, a checkout containing the project counts as its own.
355 const isProjectCheckout =
356 input.activeProjectCheckoutRoot === undefined
357 ? workspaceRelativeFilePath(activeProjectCwd, refName.worktreePath) !== null
358 : workspaceRelativeFilePath(input.activeProjectCheckoutRoot, refName.worktreePath) === ".";
359 const nextWorktreePath = isProjectCheckout ? null : refName.worktreePath;
360 return {
361 checkoutCwd: refName.worktreePath,
362 nextWorktreePath,
363 reuseExistingWorktree: true,
364 // Listed refs can predate a checkout made outside the picker, so only Git can confirm this one.
365 staysInActiveCheckout: nextWorktreePath === activeWorktreePath,
366 };
367 }
368
369 const nextWorktreePath =
370 activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
371
372 return {
373 checkoutCwd: nextWorktreePath ?? activeProjectCwd,
374 nextWorktreePath,
375 reuseExistingWorktree: false,
376 staysInActiveCheckout: nextWorktreePath === activeWorktreePath,
377 };
378}
379
380export function isWorktreeChangeBlocked(input: {
381 runtime: ThreadStructureRuntime | null;
382 currentWorktreePath: string | null;
383 nextWorktreePath: string | null;
384}): boolean {
385 return (
386 input.nextWorktreePath !== input.currentWorktreePath &&
387 deriveCanInterruptRunningThread(true, input.runtime)
388 );
389}
390
391export function shouldIncludeBranchPickerItem(input: {
392 itemValue: string;
393 normalizedQuery: string;
394 createBranchItemValue: string | null;
395 checkoutPullRequestItemValue: string | null;
396}): boolean {
397 const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
398
399 if (normalizedQuery.length === 0) {
400 return true;
401 }
402
403 if (createBranchItemValue && itemValue === createBranchItemValue) {
404 return true;
405 }
406
407 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
408 return true;
409 }
410
411 const lowerItemValue = itemValue.toLowerCase();
412 if (lowerItemValue.includes(normalizedQuery)) {
413 return true;
414 }
415
416 const sanitizedQuery = sanitizeNewRefName(normalizedQuery);
417 return (
418 sanitizedQuery.length > 0 &&
419 sanitizedQuery !== normalizedQuery &&
420 lowerItemValue.includes(sanitizedQuery)
421 );
422}