Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BranchToolbar.logic.ts

433 lines14.4 KB

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."));
30​
31export interface EnvironmentOption {
32 environmentId: EnvironmentId;
33 projectId: ProjectId | null;
34 label: string;
35 isPrimary: boolean;
36 machine: EnvironmentMachineKind;
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;
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;
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;
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);
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 );
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;
121​
122export function resolveEnvModeLabel(mode: EnvMode, resolve: MessageResolver = m): string {
123 return mode === "worktree" ? resolve(msg("New worktree")) : resolve(msg("Current checkout"));
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);
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"));
152​
153export interface PreviousWorktreeSeed {
154 branch: string | null;
155 worktreePath: string;
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 };
190​
191export function resolvePreviousWorktreeLabel(
192 seed: PreviousWorktreeSeed,
193 resolve: MessageResolver = m,
194): string {
195 return seed.branch
196 ? resolve(msg`Previous worktree (${{ branch: seed.branch }})`)
197 : resolve(msg("Previous worktree"));
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";
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";
230​
231export function resolveBranchToolbarValue(input: {
232 envMode: EnvMode;
233 activeWorktreePath: string | null;
234 activeThreadBranch: string | null;
235 /** `null` when the checkout has a detached HEAD, `undefined` until its status is known. */
236 currentGitBranch: string | null | undefined;
237}): string | null {
238 const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
239 if (envMode === "worktree" && !activeWorktreePath) {
240 return activeThreadBranch ?? currentGitBranch ?? null;
241 }
242 return currentGitBranch === undefined ? activeThreadBranch : currentGitBranch;
244​
245export interface BranchHold {
246 readonly branch: string | null;
247 readonly environmentId: EnvironmentId;
248 /**
249 * Each checkout the thread can show before it catches up, with the branch its status reported
250 * before the switch. A move from a worktree to the project root lists both.
251 */
252 readonly checkouts: ReadonlyArray<{ readonly cwd: string; readonly replaces: string | null }>;
254​
255/**
256 * A finished checkout's branch stays on screen until status reports any change, because the status
257 * stream and the RPC reply are not ordered and showing status first would flip back to the old branch.
258 */
259export function isBranchHoldCurrent(
260 hold: BranchHold,
261 current: {
262 readonly canonicalBranch: string | null;
263 readonly environmentId: EnvironmentId;
264 readonly cwd: string | null;
265 },
266): boolean {
267 return (
268 hold.environmentId === current.environmentId &&
269 hold.checkouts.some(
270 (checkout) => checkout.cwd === current.cwd && checkout.replaces === current.canonicalBranch,
271 )
272 );
274​
275/**
276 * The base a New worktree thread gets without the user picking one. Only a listed ref qualifies:
277 * during a clone the status names an unborn HEAD that no ref backs.
278 */
279export function resolveDefaultWorktreeBaseBranch(
280 refs: ReadonlyArray<Pick<VcsRef, "name" | "isDefault" | "current">>,
281): string | null {
282 return (refs.find((ref) => ref.isDefault) ?? refs.find((ref) => ref.current))?.name ?? null;
284​
285export function resolveBranchTriggerLabel(
286 input: {
287 activeWorktreePath: string | null;
288 effectiveEnvMode: EnvMode;
289 resolvedActiveBranch: string | null;
290 resolvedActiveBranchIsRemote: boolean | null;
291 startFromOrigin: boolean;
292 },
293 resolve: MessageResolver = m,
294): string {
295 const {
296 activeWorktreePath,
297 effectiveEnvMode,
298 resolvedActiveBranch,
299 resolvedActiveBranchIsRemote,
300 startFromOrigin,
301 } = input;
302 if (!resolvedActiveBranch) {
303 return resolve(msg("Select ref"));
304 }
305 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
306 // Only the server can determine a local branch's configured remote.
307 return startFromOrigin && resolvedActiveBranchIsRemote === false
308 ? resolve(msg`From ${{ branch: resolvedActiveBranch }} (remote)`)
309 : resolve(msg`From ${{ branch: resolvedActiveBranch }}`);
310 }
311 return resolvedActiveBranch;
313​
314export function resolveBranchToolbarPrBranch(input: {
315 activeThreadBranch: string | null;
316 resolvedActiveBranch: string | null;
317}): string | null {
318 return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null;
320​
321export function resolveLocalCheckoutBranchMismatch(input: {
322 effectiveEnvMode: EnvMode;
323 activeWorktreePath: string | null;
324 activeThreadBranch: string | null;
325 currentGitBranch: string | null;
326}): { threadBranch: string; currentBranch: string } | null {
327 const { effectiveEnvMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
328 if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
329 return null;
330 }
331 if (!activeThreadBranch || !currentGitBranch || activeThreadBranch === currentGitBranch) {
332 return null;
333 }
334 return { threadBranch: activeThreadBranch, currentBranch: currentGitBranch };
336​
337/**
338 * Keeps a picked ref's worktree claim only when a read in that worktree finds it checked out.
339 * `freshRead` is `null` when the read failed.
340 */
341export function resolveConfirmedSelectedRef(
342 listedRef: VcsRef,
343 freshRead: { readonly refs: ReadonlyArray<VcsRef> } | null,
344): VcsRef {
345 const checkedOut =
346 freshRead?.refs.some((ref) => ref.name === listedRef.name && !ref.isRemote && ref.current) ??
347 false;
348 return checkedOut ? listedRef : { ...listedRef, worktreePath: null };
350​
351export function resolveBranchSelectionTarget(input: {
352 activeProjectCwd: string;
353 activeProjectCheckoutRoot?: string | undefined;
354 activeWorktreePath: string | null;
355 refName: Pick<VcsRef, "isDefault" | "worktreePath">;
356}): {
357 checkoutCwd: string;
358 nextWorktreePath: string | null;
359 reuseExistingWorktree: boolean;
360 staysInActiveCheckout: boolean;
361} {
362 const { activeProjectCwd, activeWorktreePath, refName } = input;
363​
364 if (refName.worktreePath) {
365 // Until the project's checkout root loads, a checkout containing the project counts as its own.
366 const isProjectCheckout =
367 input.activeProjectCheckoutRoot === undefined
368 ? workspaceRelativeFilePath(activeProjectCwd, refName.worktreePath) !== null
369 : workspaceRelativeFilePath(input.activeProjectCheckoutRoot, refName.worktreePath) === ".";
370 const nextWorktreePath = isProjectCheckout ? null : refName.worktreePath;
371 return {
372 checkoutCwd: refName.worktreePath,
373 nextWorktreePath,
374 reuseExistingWorktree: true,
375 // Listed refs can predate a checkout made outside the picker, so only Git can confirm this one.
376 staysInActiveCheckout: nextWorktreePath === activeWorktreePath,
377 };
378 }
379​
380 const nextWorktreePath =
381 activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
382​
383 return {
384 checkoutCwd: nextWorktreePath ?? activeProjectCwd,
385 nextWorktreePath,
386 reuseExistingWorktree: false,
387 staysInActiveCheckout: nextWorktreePath === activeWorktreePath,
388 };
390​
391export function isWorktreeChangeBlocked(input: {
392 runtime: ThreadStructureRuntime | null;
393 currentWorktreePath: string | null;
394 nextWorktreePath: string | null;
395}): boolean {
396 return (
397 input.nextWorktreePath !== input.currentWorktreePath &&
398 deriveCanInterruptRunningThread(true, input.runtime)
399 );
401​
402export function shouldIncludeBranchPickerItem(input: {
403 itemValue: string;
404 normalizedQuery: string;
405 createBranchItemValue: string | null;
406 checkoutPullRequestItemValue: string | null;
407}): boolean {
408 const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
409​
410 if (normalizedQuery.length === 0) {
411 return true;
412 }
413​
414 if (createBranchItemValue && itemValue === createBranchItemValue) {
415 return true;
416 }
417​
418 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
419 return true;
420 }
421​
422 const lowerItemValue = itemValue.toLowerCase();
423 if (lowerItemValue.includes(normalizedQuery)) {
424 return true;
425 }
426​
427 const sanitizedQuery = sanitizeNewRefName(normalizedQuery);
428 return (
429 sanitizedQuery.length > 0 &&
430 sanitizedQuery !== normalizedQuery &&
431 lowerItemValue.includes(sanitizedQuery)
432 );