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
84/** Whether a new thread here may choose between Current checkout and New worktree. */
85export function offersWorkspaceModes(input: {
86 isScratchProject: boolean;
87 isGitRepo: boolean;
88 tracksGitRepositories: boolean;
89}): boolean {
90 // No project never has git, even while its status loads and isGitRepo still assumes it does.
91 return !input.isScratchProject && (input.isGitRepo || input.tracksGitRepositories);
92}
93
94export function shouldShowComposerContextStrip(input: {
95 isDraftHeroState: boolean;
96 persistInActiveThreads: boolean;
97 hasActiveProject: boolean;
98 isGitRepo: boolean;
99 showEnvironmentIndicator: boolean;
100}): boolean {
101 // A new thread always shows the strip, since it names the permissions the first send uses.
102 return (
103 input.hasActiveProject &&
104 (input.isDraftHeroState ||
105 (input.persistInActiveThreads && (input.isGitRepo || input.showEnvironmentIndicator)))
106 );
107}
108
109// Hysteresis prevents labels and icons from flapping at the width boundary.
110const CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX = 16;
111
112export function resolveContextStripLabelsCompact(input: {
113 compact: boolean;
114 neededWidth: number;
115 availableWidth: number;
116}): boolean {
117 return input.compact
118 ? input.neededWidth > input.availableWidth - CONTEXT_STRIP_COMPACT_EXPAND_HYSTERESIS_PX
119 : input.neededWidth > input.availableWidth;
120}
121
122export function resolveEnvModeLabel(mode: EnvMode, resolve: MessageResolver = m): string {
123 return mode === "worktree" ? resolve(msg("New worktree")) : resolve(msg("Current checkout"));
124}
125
126export const WORKTREE_SUBMODULES_LABELS: Record<WorktreeSubmodules, string> = {
127 recursive: msg("Recursive"),
128 "top-level": msg("Top level only"),
129 none: msg("Skip"),
130};
131
132export function resolveCurrentWorkspaceLabel(
133 activeWorktreePath: string | null,
134 resolve: MessageResolver = m,
135): string {
136 return activeWorktreePath
137 ? resolve(msg("Current worktree"))
138 : resolveEnvModeLabel("local", resolve);
139}
140
141export function resolveLockedWorkspaceLabel(
142 activeWorktreePath: string | null,
143 effectiveEnvMode: EnvMode,
144 resolve: MessageResolver = m,
145): string {
146 if (activeWorktreePath)
147 return activeWorktreePath.split(/[\\/]/).findLast(Boolean) ?? resolve(msg("Worktree"));
148 return effectiveEnvMode === "worktree"
149 ? resolveEnvModeLabel("worktree", resolve)
150 : resolve(msg("Local checkout"));
151}
152
153export interface PreviousWorktreeSeed {
154 branch: string | null;
155 worktreePath: string;
156}
157
158export function resolvePreviousWorktreeSeed(input: {
159 threads: ReadonlyArray<{
160 branch: string | null;
161 worktreePath: string | null;
162 updatedAt: string;
163 archivedAt?: string | null;
164 }>;
165 currentWorktreePath: string | null;
166}): PreviousWorktreeSeed | null {
167 let latest: { branch: string | null; worktreePath: string; updatedAt: number } | null = null;
168 for (const thread of input.threads) {
169 if (
170 !thread.worktreePath ||
171 thread.worktreePath === input.currentWorktreePath ||
172 (thread.archivedAt ?? null) !== null
173 ) {
174 continue;
175 }
176 const updatedAt = toSortableTimestamp(thread.updatedAt);
177 if (updatedAt === null) {
178 continue;
179 }
180 if (latest === null || updatedAt > latest.updatedAt) {
181 latest = {
182 branch: thread.branch,
183 worktreePath: thread.worktreePath,
184 updatedAt,
185 };
186 }
187 }
188 return latest === null ? null : { branch: latest.branch, worktreePath: latest.worktreePath };
189}
190
191export function resolvePreviousWorktreeLabel(
192 seed: PreviousWorktreeSeed,
193 resolve: MessageResolver = m,
194): string {
195 return seed.branch
196 ? resolve(msg("Previous worktree ({branch})", { branch: seed.branch }))
197 : resolve(msg("Previous worktree"));
198}
199
200export function resolveEffectiveEnvMode(input: {
201 activeWorktreePath: string | null;
202 hasServerThread: boolean;
203 draftThreadEnvMode: EnvMode | undefined;
204 preparingWorktree?: boolean;
205}): EnvMode {
206 const { activeWorktreePath, hasServerThread, draftThreadEnvMode, preparingWorktree } = input;
207 if (!hasServerThread) {
208 if (activeWorktreePath) {
209 return "local";
210 }
211 return draftThreadEnvMode === "worktree" ? "worktree" : "local";
212 }
213 return activeWorktreePath || preparingWorktree ? "worktree" : "local";
214}
215
216export function resolveDraftEnvModeAfterBranchChange(input: {
217 nextWorktreePath: string | null;
218 currentWorktreePath: string | null;
219 effectiveEnvMode: EnvMode;
220}): EnvMode {
221 const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
222 if (nextWorktreePath) {
223 return "worktree";
224 }
225 if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
226 return "worktree";
227 }
228 return "local";
229}
230
231export function resolveBranchToolbarValue(input: {
232 envMode: EnvMode;
233 activeWorktreePath: string | null;
234 activeThreadBranch: string | null;
235 currentGitBranch: string | null;
236}): string | null {
237 const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
238 if (envMode === "worktree" && !activeWorktreePath) {
239 return activeThreadBranch ?? currentGitBranch;
240 }
241 return currentGitBranch ?? activeThreadBranch;
242}
243
244export interface BranchHold {
245 readonly branch: string | null;
246 readonly environmentId: EnvironmentId;
247 /**
248 * Each checkout the thread can show before it catches up, with the branch its status reported
249 * before the switch. A move from a worktree to the project root lists both.
250 */
251 readonly checkouts: ReadonlyArray<{ readonly cwd: string; readonly replaces: string | null }>;
252}
253
254/**
255 * A finished checkout's branch stays on screen until status reports any change, because the status
256 * stream and the RPC reply are not ordered and showing status first would flip back to the old branch.
257 */
258export function isBranchHoldCurrent(
259 hold: BranchHold,
260 current: {
261 readonly canonicalBranch: string | null;
262 readonly environmentId: EnvironmentId;
263 readonly cwd: string | null;
264 },
265): boolean {
266 return (
267 hold.environmentId === current.environmentId &&
268 hold.checkouts.some(
269 (checkout) => checkout.cwd === current.cwd && checkout.replaces === current.canonicalBranch,
270 )
271 );
272}
273
274/**
275 * The base a New worktree thread gets without the user picking one. Only a listed ref qualifies:
276 * during a clone the status names an unborn HEAD that no ref backs.
277 */
278export function resolveDefaultWorktreeBaseBranch(
279 refs: ReadonlyArray<Pick<VcsRef, "name" | "isDefault" | "current">>,
280): string | null {
281 return (refs.find((ref) => ref.isDefault) ?? refs.find((ref) => ref.current))?.name ?? null;
282}
283
284export function resolveBranchTriggerLabel(
285 input: {
286 activeWorktreePath: string | null;
287 effectiveEnvMode: EnvMode;
288 resolvedActiveBranch: string | null;
289 resolvedActiveBranchIsRemote: boolean | null;
290 startFromOrigin: boolean;
291 },
292 resolve: MessageResolver = m,
293): string {
294 const {
295 activeWorktreePath,
296 effectiveEnvMode,
297 resolvedActiveBranch,
298 resolvedActiveBranchIsRemote,
299 startFromOrigin,
300 } = input;
301 if (!resolvedActiveBranch) {
302 return resolve(msg("Select ref"));
303 }
304 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
305 // Only the server can determine a local branch's configured remote.
306 return startFromOrigin && resolvedActiveBranchIsRemote === false
307 ? resolve(msg("From {branch} (remote)", { branch: resolvedActiveBranch }))
308 : resolve(msg("From {branch}", { branch: resolvedActiveBranch }));
309 }
310 return resolvedActiveBranch;
311}
312
313export function resolveBranchToolbarPrBranch(input: {
314 activeThreadBranch: string | null;
315 resolvedActiveBranch: string | null;
316}): string | null {
317 return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
318}
319
320export function resolveLocalCheckoutBranchMismatch(input: {
321 effectiveEnvMode: EnvMode;
322 activeWorktreePath: string | null;
323 activeThreadBranch: string | null;
324 currentGitBranch: string | null;
325}): { threadBranch: string; currentBranch: string } | null {
326 const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
327 if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
328 return null;
329 }
330 if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
331 return null;
332 }
333 return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
334}
335
336/**
337 * Keeps a picked ref's worktree claim only when a read in that worktree finds it checked out.
338 * `freshRead` is `null` when the read failed.
339 */
340export function resolveConfirmedSelectedRef(
341 listedRef: VcsRef,
342 freshRead: { readonly refs: ReadonlyArray<VcsRef> } | null,
343): VcsRef {
344 const checkedOut =
345 freshRead?.refs.some((ref) => ref.name === listedRef.name && !ref.isRemote && ref.current) ??
346 false;
347 return checkedOut ? listedRef : { ...listedRef, worktreePath: null };
348}
349
350export function resolveBranchSelectionTarget(input: {
351 activeProjectCwd: string;
352 activeProjectCheckoutRoot?: string | undefined;
353 activeWorktreePath: string | null;
354 refName: Pick<VcsRef, "isDefault" | "worktreePath">;
355}): {
356 checkoutCwd: string;
357 nextWorktreePath: string | null;
358 reuseExistingWorktree: boolean;
359 staysInActiveCheckout: boolean;
360} {
361 const { activeProjectCwd, activeWorktreePath, refName } = input;
362
363 if (refName.worktreePath) {
364 // Until the project's checkout root loads, a checkout containing the project counts as its own.
365 const isProjectCheckout =
366 input.activeProjectCheckoutRoot === undefined
367 ? workspaceRelativeFilePath(activeProjectCwd, refName.worktreePath) !== null
368 : workspaceRelativeFilePath(input.activeProjectCheckoutRoot, refName.worktreePath) === ".";
369 const nextWorktreePath = isProjectCheckout ? null : refName.worktreePath;
370 return {
371 checkoutCwd: refName.worktreePath,
372 nextWorktreePath,
373 reuseExistingWorktree: true,
374 // Listed refs can predate a checkout made outside the picker, so only Git can confirm this one.
375 staysInActiveCheckout: nextWorktreePath === activeWorktreePath,
376 };
377 }
378
379 const nextWorktreePath =
380 activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
381
382 return {
383 checkoutCwd: nextWorktreePath ?? activeProjectCwd,
384 nextWorktreePath,
385 reuseExistingWorktree: false,
386 staysInActiveCheckout: nextWorktreePath === activeWorktreePath,
387 };
388}
389
390export function isWorktreeChangeBlocked(input: {
391 runtime: ThreadStructureRuntime | null;
392 currentWorktreePath: string | null;
393 nextWorktreePath: string | null;
394}): boolean {
395 return (
396 input.nextWorktreePath !== input.currentWorktreePath &&
397 deriveCanInterruptRunningThread(true, input.runtime)
398 );
399}
400
401export function shouldIncludeBranchPickerItem(input: {
402 itemValue: string;
403 normalizedQuery: string;
404 createBranchItemValue: string | null;
405 checkoutPullRequestItemValue: string | null;
406}): boolean {
407 const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
408
409 if (normalizedQuery.length === 0) {
410 return true;
411 }
412
413 if (createBranchItemValue && itemValue === createBranchItemValue) {
414 return true;
415 }
416
417 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
418 return true;
419 }
420
421 const lowerItemValue = itemValue.toLowerCase();
422 if (lowerItemValue.includes(normalizedQuery)) {
423 return true;
424 }
425
426 const sanitizedQuery = sanitizeNewRefName(normalizedQuery);
427 return (
428 sanitizedQuery.length > 0 &&
429 sanitizedQuery !== normalizedQuery &&
430 lowerItemValue.includes(sanitizedQuery)
431 );
432}