Open History to see the last commit
1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3import {
4 repositoryRewindCheckpoint,
5 TASK_FOLDER_DEFAULT_REPOSITORIES_MAX,
6 type TaskFolder,
7} from "@t3tools/contracts";
8import type {
9 CheckpointScopeId,
10 OrchestrationV2Checkpoint,
11 OrchestrationV2CheckpointFileTotals,
12 OrchestrationV2CheckpointScope,
13 OrchestrationV2ThreadProjection,
14 RunId,
15 ThreadTurnRepositoryDiff,
16 VcsStatusResult,
17 WorkspaceFolder,
18} from "@t3tools/contracts";
19import { fileBasename, isAbsolutePath } from "@t3tools/shared/path";
20
21type ChangedFiles = OrchestrationV2Checkpoint["files"];
22
23/** One tracked Git repository a thread reaches. */
24export interface ThreadRepositoryScope {
25 readonly scopeId: CheckpointScopeId;
26 /** Display name. */
27 readonly name: string;
28 /** Stable identity; matches `ThreadTurnDiff.repositories[].repositoryPath`. */
29 readonly repositoryPath: string;
30 /** The repository folder on the environment's disk; file paths resolve against it. */
31 readonly cwd: string;
32 /**
33 * The repository folder from the thread's folder, `/`-separated; starts with `../` outside it.
34 * Absent when the two folders share no root.
35 */
36 readonly relativePath?: string;
37}
38
39/** What one turn changed in one repository. `files` paths are relative to the repository. */
40export interface TurnRepositoryChanges extends ThreadRepositoryScope {
41 /** May be a prefix of the changed files when `filesTotal` is set. */
42 readonly files: ChangedFiles;
43 readonly filesTotal?: OrchestrationV2CheckpointFileTotals;
44 /** The turn changed this repository, but nothing was recorded before it to compare with. */
45 readonly baselineMissing: boolean;
46}
47
48interface ChangedFileList {
49 readonly files: ChangedFiles;
50 readonly filesTotal?: OrchestrationV2CheckpointFileTotals | undefined;
51}
52
53/** A turn's own files plus its repositories; `ThreadCheckpointSummary` has this shape. */
54export interface TurnChangesSource extends ChangedFileList {
55 readonly repositories?: ReadonlyArray<TurnRepositoryChanges> | undefined;
56}
57
58export interface TurnChanges {
59 /** Files changed in the thread's own folder, relative to it. */
60 readonly rootFiles: ChangedFiles;
61 readonly repositories: ReadonlyArray<TurnRepositoryChanges>;
62 /** Across the thread's folder and every repository. */
63 readonly totals: OrchestrationV2CheckpointFileTotals;
64}
65
66/** One patch of a turn diff. Its file paths are relative to `relativePath`. */
67export interface TurnDiffSection {
68 readonly key: string;
69 readonly name: string;
70 /** Null for the thread's own folder. */
71 readonly repositoryPath: string | null;
72 /** Empty for the thread's own folder. */
73 readonly relativePath: string;
74 readonly diff: string;
75}
76
77const ROOT_SECTION_KEY = ".";
78const NO_REPOSITORY_CHANGES: ReadonlyArray<TurnRepositoryChanges> = Object.freeze([]);
79const NO_TURN_REPOSITORY_CHANGES: ReadonlyMap<
80 RunId,
81 ReadonlyArray<TurnRepositoryChanges>
82> = new Map();
83
84export function isRepositoryCheckpointScope(
85 scope: Pick<OrchestrationV2CheckpointScope, "repositoryPath">,
86): boolean {
87 return typeof scope.repositoryPath === "string";
88}
89
90/** Scopes whose checkpoints belong to a repository, never to the thread's own timeline. */
91export function repositoryCheckpointScopeIds(
92 scopes: ReadonlyArray<Pick<OrchestrationV2CheckpointScope, "id" | "repositoryPath">>,
93): ReadonlySet<CheckpointScopeId> {
94 return new Set(scopes.flatMap((scope) => (isRepositoryCheckpointScope(scope) ? [scope.id] : [])));
95}
96
97/**
98 * What a rewind to `checkpoint`, the thread's own rewind target, can restore on disk: every file,
99 * only the repositories of a task folder whose project folder has no snapshot, or nothing.
100 * The server refuses a file rewind this does not offer.
101 */
102export function rewindFileRestore(input: {
103 readonly projection: Pick<OrchestrationV2ThreadProjection, "checkpoints" | "checkpointScopes">;
104 readonly checkpoint: Pick<OrchestrationV2Checkpoint, "status" | "appRunOrdinal"> | undefined;
105 readonly taskFolder: Pick<TaskFolder, "projectIsWorktree"> | null | undefined;
106}): "files" | "repositories" | null {
107 const { checkpoint, projection } = input;
108 if (checkpoint === undefined) return null;
109 if (checkpoint.status === "ready") return "files";
110 if (checkpoint.status !== "missing" || input.taskFolder?.projectIsWorktree !== false) return null;
111 const targetOrdinal = checkpoint.appRunOrdinal ?? 0;
112 return projection.checkpointScopes.some(
113 (scope) =>
114 isRepositoryCheckpointScope(scope) &&
115 repositoryRewindCheckpoint(
116 projection.checkpoints.filter((candidate) => candidate.scopeId === scope.id),
117 targetOrdinal,
118 ) !== null,
119 )
120 ? "repositories"
121 : null;
122}
123
124function pathSegments(path: string): { root: string; segments: string[] } | undefined {
125 // A backslash is a separator on Windows but an ordinary filename character on POSIX.
126 if (path.startsWith("/")) return { root: "/", segments: path.split("/").filter(Boolean) };
127 const segments = path.replaceAll("\\", "/").split("/").filter(Boolean);
128 if (path.startsWith("\\")) return { root: "\\", segments };
129 const drive = segments[0];
130 if (drive === undefined || !/^[a-zA-Z]:$/.test(drive)) return undefined;
131 return { root: drive.toLowerCase(), segments: segments.slice(1) };
132}
133
134function relativeFolderPath(from: string, to: string): string | undefined {
135 const source = pathSegments(from);
136 const target = pathSegments(to);
137 if (source === undefined || target === undefined || source.root !== target.root) {
138 return undefined;
139 }
140 const same = (left: string, right: string) =>
141 source.root === "/" ? left === right : left.toLowerCase() === right.toLowerCase();
142 let shared = 0;
143 while (
144 shared < source.segments.length &&
145 shared < target.segments.length &&
146 same(source.segments[shared]!, target.segments[shared]!)
147 ) {
148 shared += 1;
149 }
150 return [...source.segments.slice(shared).map(() => ".."), ...target.segments.slice(shared)].join(
151 "/",
152 );
153}
154
155/** Whether a `/`-separated path from `folder` stays inside it; `folder` decides POSIX or Windows. */
156export function isRelativePathInsideFolder(relativePath: string, folder?: string): boolean {
157 return (
158 relativePath !== ".." &&
159 !relativePath.startsWith("../") &&
160 !(folder?.startsWith("/") ? relativePath.startsWith("/") : isAbsolutePath(relativePath))
161 );
162}
163
164function repositoryScope(
165 scope: OrchestrationV2CheckpointScope,
166 repositoryPath: string,
167 threadCwd: string | undefined,
168): ThreadRepositoryScope {
169 const relativePath =
170 threadCwd === undefined ? undefined : relativeFolderPath(threadCwd, scope.cwd);
171 return {
172 scopeId: scope.id,
173 name: scope.label ?? fileBasename(scope.cwd),
174 repositoryPath,
175 cwd: scope.cwd,
176 ...(relativePath === undefined ? {} : { relativePath }),
177 };
178}
179
180function byNameThenPath(left: ThreadRepositoryScope, right: ThreadRepositoryScope): number {
181 return (
182 left.name.localeCompare(right.name) || left.repositoryPath.localeCompare(right.repositoryPath)
183 );
184}
185
186/** The repositories a thread reaches, by name and then path. */
187export function threadRepositoryScopes(
188 projection: Pick<OrchestrationV2ThreadProjection, "checkpointScopes">,
189): ReadonlyArray<ThreadRepositoryScope> {
190 const scopes = projection.checkpointScopes;
191 return scopes
192 .flatMap((scope) =>
193 scope.repositoryPath === undefined
194 ? []
195 : [
196 repositoryScope(
197 scope,
198 scope.repositoryPath,
199 scopes.find((candidate) => candidate.id === scope.parentScopeId)?.cwd,
200 ),
201 ],
202 )
203 .sort(byNameThenPath);
204}
205
206// Rows compare a turn's repositories by identity, so an unchanged turn keeps the same objects
207// while later turns append checkpoints.
208const changesByCheckpoint = new WeakMap<
209 OrchestrationV2Checkpoint,
210 {
211 readonly scope: OrchestrationV2CheckpointScope;
212 readonly threadCwd: string | undefined;
213 readonly changes: TurnRepositoryChanges;
214 }
215>();
216const turnChangesByFirst = new WeakMap<
217 TurnRepositoryChanges,
218 ReadonlyArray<TurnRepositoryChanges>
219>();
220
221/**
222 * Per run, the repositories it changed, by name and then path. A run that changed none has no
223 * entry. Unchanged runs keep their array across calls.
224 */
225export function deriveTurnRepositoryChanges(
226 projection: Pick<OrchestrationV2ThreadProjection, "checkpoints" | "checkpointScopes">,
227): ReadonlyMap<RunId, ReadonlyArray<TurnRepositoryChanges>> {
228 const scopes = projection.checkpointScopes;
229 if (!scopes.some(isRepositoryCheckpointScope)) return NO_TURN_REPOSITORY_CHANGES;
230 const scopeById = new Map(scopes.map((scope) => [scope.id, scope]));
231 const withoutBaseline = new Set<string>();
232 for (const checkpoint of projection.checkpoints) {
233 if (checkpoint.status === "missing") {
234 withoutBaseline.add(`${checkpoint.scopeId}\u0000${checkpoint.ordinalWithinScope + 1}`);
235 }
236 }
237 const byRun = new Map<RunId, TurnRepositoryChanges[]>();
238 for (const checkpoint of projection.checkpoints) {
239 if (checkpoint.runId === null || checkpoint.status !== "ready") continue;
240 const scope = scopeById.get(checkpoint.scopeId);
241 if (scope?.repositoryPath === undefined) continue;
242 const baselineMissing =
243 checkpoint.files.length === 0 &&
244 withoutBaseline.has(`${checkpoint.scopeId}\u0000${checkpoint.ordinalWithinScope}`);
245 if (checkpoint.files.length === 0 && !baselineMissing) continue;
246 const threadCwd =
247 scope.parentScopeId === null ? undefined : scopeById.get(scope.parentScopeId)?.cwd;
248 const cached = changesByCheckpoint.get(checkpoint);
249 let changes = cached?.changes;
250 if (
251 cached === undefined ||
252 changes === undefined ||
253 cached.scope !== scope ||
254 cached.threadCwd !== threadCwd ||
255 changes.baselineMissing !== baselineMissing
256 ) {
257 changes = {
258 ...repositoryScope(scope, scope.repositoryPath, threadCwd),
259 files: checkpoint.files,
260 ...(checkpoint.filesTotal === undefined ? {} : { filesTotal: checkpoint.filesTotal }),
261 baselineMissing,
262 };
263 changesByCheckpoint.set(checkpoint, { scope, threadCwd, changes });
264 }
265 const forRun = byRun.get(checkpoint.runId);
266 if (forRun === undefined) byRun.set(checkpoint.runId, [changes]);
267 else forRun.push(changes);
268 }
269 const stable = new Map<RunId, ReadonlyArray<TurnRepositoryChanges>>();
270 for (const [runId, repositories] of byRun) {
271 repositories.sort(byNameThenPath);
272 const first = repositories[0]!;
273 const previous = turnChangesByFirst.get(first);
274 if (
275 previous !== undefined &&
276 previous.length === repositories.length &&
277 previous.every((entry, index) => entry === repositories[index])
278 ) {
279 stable.set(runId, previous);
280 } else {
281 turnChangesByFirst.set(first, repositories);
282 stable.set(runId, repositories);
283 }
284 }
285 return stable;
286}
287
288/** Totals for a file list that may be a prefix of what changed. */
289function changedFileTotals(list: ChangedFileList): OrchestrationV2CheckpointFileTotals {
290 if (list.filesTotal !== undefined) return list.filesTotal;
291 let additions = 0;
292 let deletions = 0;
293 for (const file of list.files) {
294 additions += file.additions;
295 deletions += file.deletions;
296 }
297 return { count: list.files.length, additions, deletions };
298}
299
300/** A turn's changed files: the thread folder's own, then each repository's, with totals. */
301export function turnChanges(turn: TurnChangesSource): TurnChanges {
302 const repositories = turn.repositories ?? NO_REPOSITORY_CHANGES;
303 const totals = { ...changedFileTotals(turn) };
304 for (const repository of repositories) {
305 const repositoryTotals = changedFileTotals(repository);
306 totals.count += repositoryTotals.count;
307 totals.additions += repositoryTotals.additions;
308 totals.deletions += repositoryTotals.deletions;
309 }
310 return { rootFiles: turn.files, repositories, totals };
311}
312
313/**
314 * Whether a turn has changes to show. The thread folder's own checkpoint need not be ready: a
315 * plain folder holding repositories never has one, and its turns still change those repositories.
316 */
317export function turnHasChanges(turn: TurnChangesSource): boolean {
318 return turn.files.length > 0 || (turn.repositories?.length ?? 0) > 0;
319}
320
321/** A repository file's path from the thread's folder, as the turn diff sections name it. */
322export function repositoryFilePath(relativePath: string, filePath: string): string {
323 return relativePath === "" || relativePath === "." ? filePath : `${relativePath}/${filePath}`;
324}
325
326/**
327 * The patches of a turn diff, the thread folder's own first. Empty patches are left out, so a
328 * diff without repositories gives its one patch or nothing.
329 */
330export function turnDiffSections(
331 diff: {
332 readonly diff: string;
333 readonly repositories?: ReadonlyArray<ThreadTurnRepositoryDiff> | undefined;
334 },
335 rootName: string,
336): ReadonlyArray<TurnDiffSection> {
337 const root: ReadonlyArray<TurnDiffSection> =
338 diff.diff.trim() === ""
339 ? []
340 : [
341 {
342 key: ROOT_SECTION_KEY,
343 name: rootName,
344 repositoryPath: null,
345 relativePath: "",
346 diff: diff.diff,
347 },
348 ];
349 return [
350 ...root,
351 ...(diff.repositories ?? []).flatMap((repository) =>
352 repository.diff.trim() === ""
353 ? []
354 : [
355 {
356 key: repository.repositoryPath,
357 name: repository.name,
358 repositoryPath: repository.repositoryPath,
359 relativePath: repository.relativePath,
360 diff: repository.diff,
361 },
362 ],
363 ),
364 ];
365}
366
367/**
368 * The repository section a thread-relative path belongs to, and the path inside that repository.
369 * Null for a file of the thread's own folder.
370 */
371export function repositorySectionForPath(
372 sections: ReadonlyArray<TurnDiffSection>,
373 filePath: string,
374): { readonly section: TurnDiffSection; readonly path: string } | null {
375 let match: { readonly section: TurnDiffSection; readonly path: string } | null = null;
376 for (const section of sections) {
377 if (section.repositoryPath === null || section.relativePath === "") continue;
378 const prefix = `${section.relativePath}/`;
379 if (!filePath.startsWith(prefix)) continue;
380 if (match === null || section.relativePath.length > match.section.relativePath.length) {
381 match = { section, path: filePath.slice(prefix.length) };
382 }
383 }
384 return match;
385}
386
387/** How many repository sections a thread shows before the rest fold behind "Show N more". */
388export const THREAD_REPOSITORY_SECTIONS_VISIBLE = 4;
389
390/** A tracked repository the user asked to see in a thread, besides those the thread changed. */
391export interface PinnedThreadRepository {
392 /** The tracked folder's path; matches `ThreadRepositoryScope.repositoryPath`. */
393 readonly repositoryPath: string;
394 readonly name: string;
395}
396
397/** One repository a thread shows Git state and actions for. */
398export interface ThreadRepositorySection {
399 /** Stable across renders and reorders; the repository's path. */
400 readonly key: string;
401 readonly name: string;
402 /** The folder Git commands run in. */
403 readonly cwd: string;
404 /**
405 * Pinned sections can be removed; changed ones stay for as long as the thread has them. A
406 * `worktree` section is the thread's own worktree of that repository.
407 */
408 readonly origin: "pinned" | "changed" | "worktree";
409}
410
411export interface ThreadRepositorySections {
412 readonly visible: ReadonlyArray<ThreadRepositorySection>;
413 /** Folded away until the user asks for them. Clients render and subscribe for none of these. */
414 readonly hidden: ReadonlyArray<ThreadRepositorySection>;
415}
416
417const NO_SECTIONS: ThreadRepositorySections = Object.freeze({
418 visible: Object.freeze([]),
419 hidden: Object.freeze([]),
420});
421
422/**
423 * The repositories a thread changed, most recently changed first. A repository no turn has a
424 * checkpoint for yet sorts last, by name.
425 */
426export function threadChangedRepositories(
427 projection: Pick<OrchestrationV2ThreadProjection, "checkpoints" | "checkpointScopes">,
428): ReadonlyArray<ThreadRepositoryScope> {
429 const scopes = threadRepositoryScopes(projection);
430 if (scopes.length < 2) return scopes;
431 const lastChange = new Map<CheckpointScopeId, number>();
432 // A repository scope's ordinal is the run's; a loaded snapshot is not in capture order.
433 for (const checkpoint of projection.checkpoints) {
434 if (checkpoint.runId === null) continue;
435 const latest = lastChange.get(checkpoint.scopeId) ?? -1;
436 if (checkpoint.ordinalWithinScope > latest) {
437 lastChange.set(checkpoint.scopeId, checkpoint.ordinalWithinScope);
438 }
439 }
440 // `scopes` is by name already, and the sort is stable.
441 return [...scopes].sort(
442 (left, right) => (lastChange.get(right.scopeId) ?? -1) - (lastChange.get(left.scopeId) ?? -1),
443 );
444}
445
446/** A repository whose uncommitted and branch changes a thread can show. */
447export type ThreadGitRepository = Pick<ThreadRepositoryScope, "repositoryPath" | "name" | "cwd">;
448
449/**
450 * Every repository a thread can read Git changes of: the ones it changed first, then the rest of
451 * its task folder's worktrees, or of the project's tracked repositories when it runs in place.
452 */
453export function threadGitRepositories(input: {
454 readonly changed: ReadonlyArray<ThreadGitRepository>;
455 readonly taskFolder: Pick<TaskFolder, "repositories"> | null;
456 /** The project's folders, for a thread in the project folder itself; null otherwise. */
457 readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">> | null;
458 readonly threadCwd: string | null;
459}): ReadonlyArray<ThreadGitRepository> {
460 const reached: ReadonlyArray<ThreadGitRepository> =
461 input.taskFolder !== null
462 ? input.taskFolder.repositories.map((repository) => ({
463 repositoryPath: repository.repositoryPath,
464 name: repository.name,
465 cwd: repository.worktreePath,
466 }))
467 : (input.folders ?? []).flatMap((folder) =>
468 folder.state === "git" && folder.path !== input.threadCwd
469 ? [{ repositoryPath: folder.path, name: folder.name, cwd: folder.path }]
470 : [],
471 );
472 if (reached.length === 0) return input.changed;
473 // A checkpoint scope keeps the folder it was captured in, which a moved thread has left.
474 const reachedByPath = new Map(
475 reached.map((repository) => [repository.repositoryPath, repository]),
476 );
477 const listed = new Set(input.changed.map((repository) => repository.repositoryPath));
478 return [
479 ...input.changed.map(
480 (repository) => reachedByPath.get(repository.repositoryPath) ?? repository,
481 ),
482 ...reached.filter((repository) => !listed.has(repository.repositoryPath)),
483 ];
484}
485
486/**
487 * A task folder's repositories, each bound to its worktree: changed ones first, then the rest.
488 * A changed repository inside one of those worktrees, such as a submodule, follows them.
489 */
490function taskFolderSections(
491 taskFolder: Pick<TaskFolder, "repositories" | "root">,
492 changed: ReadonlyArray<ThreadRepositoryScope>,
493): ThreadRepositorySection[] {
494 const byPath = new Map(
495 taskFolder.repositories.map((repository) => [repository.repositoryPath, repository]),
496 );
497 const ordered = new Set<string>();
498 for (const scope of changed) {
499 if (byPath.has(scope.repositoryPath)) ordered.add(scope.repositoryPath);
500 }
501 for (const repository of taskFolder.repositories) ordered.add(repository.repositoryPath);
502 const worktrees = [...ordered].map((repositoryPath) => {
503 const repository = byPath.get(repositoryPath)!;
504 return {
505 key: repositoryPath,
506 name: repository.name,
507 cwd: repository.worktreePath,
508 origin: "worktree" as const,
509 };
510 });
511 const inside = changed.flatMap((scope) => {
512 const relative = relativeFolderPath(taskFolder.root, scope.cwd);
513 return byPath.has(scope.repositoryPath) ||
514 relative === undefined ||
515 !isRelativePathInsideFolder(relative, taskFolder.root)
516 ? []
517 : [
518 {
519 key: scope.repositoryPath,
520 name: scope.name,
521 cwd: scope.cwd,
522 origin: "changed" as const,
523 },
524 ];
525 });
526 return [...worktrees, ...inside];
527}
528
529/**
530 * The repository sections of a thread: pinned ones in the order they were pinned, then the ones
531 * the thread changed. `threadCwd` is the thread's own folder, which has its own Git controls.
532 *
533 * A thread with a `taskFolder` lists that folder's repositories instead, changed or not, and
534 * never a pin or a changed repository outside it: those would be someone else's checkout.
535 */
536export function threadRepositorySections(input: {
537 readonly changed: ReadonlyArray<ThreadRepositoryScope>;
538 readonly pinned: ReadonlyArray<PinnedThreadRepository>;
539 readonly threadCwd: string | null;
540 readonly showAll: boolean;
541 readonly taskFolder?: Pick<TaskFolder, "repositories" | "root"> | null | undefined;
542 /**
543 * False for a thread that reaches no tracked repository: a project that tracks none, or a
544 * single worktree. It lists what it changed, such as a submodule, and no pin.
545 */
546 readonly reachesTracked?: boolean | undefined;
547}): ThreadRepositorySections {
548 const sections: ThreadRepositorySection[] = [];
549 if (input.taskFolder != null) {
550 sections.push(...taskFolderSections(input.taskFolder, input.changed));
551 } else {
552 const seen = new Set<string>(input.threadCwd === null ? [] : [input.threadCwd]);
553 const add = (section: ThreadRepositorySection) => {
554 if (seen.has(section.key)) return;
555 seen.add(section.key);
556 sections.push(section);
557 };
558 for (const pin of input.reachesTracked === false ? [] : input.pinned) {
559 add({ key: pin.repositoryPath, name: pin.name, cwd: pin.repositoryPath, origin: "pinned" });
560 }
561 for (const scope of input.changed) {
562 add({ key: scope.repositoryPath, name: scope.name, cwd: scope.cwd, origin: "changed" });
563 }
564 }
565 if (sections.length === 0) return NO_SECTIONS;
566 if (input.showAll || sections.length <= THREAD_REPOSITORY_SECTIONS_VISIBLE) {
567 return { visible: sections, hidden: NO_SECTIONS.hidden };
568 }
569 return {
570 visible: sections.slice(0, THREAD_REPOSITORY_SECTIONS_VISIBLE),
571 hidden: sections.slice(THREAD_REPOSITORY_SECTIONS_VISIBLE),
572 };
573}
574
575/** Adds a pin at the end; pinning a repository twice keeps its place. */
576export function pinThreadRepository(
577 pinned: ReadonlyArray<PinnedThreadRepository>,
578 repository: PinnedThreadRepository,
579): ReadonlyArray<PinnedThreadRepository> {
580 return pinned.some((entry) => entry.repositoryPath === repository.repositoryPath)
581 ? pinned
582 : [...pinned, repository];
583}
584
585export function unpinThreadRepository(
586 pinned: ReadonlyArray<PinnedThreadRepository>,
587 repositoryPath: string,
588): ReadonlyArray<PinnedThreadRepository> {
589 const next = pinned.filter((entry) => entry.repositoryPath !== repositoryPath);
590 return next.length === pinned.length ? pinned : next;
591}
592
593/** The tracked Git repositories a thread can still add: not its own folder, not shown yet. */
594export function pinnableThreadRepositories(input: {
595 readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">>;
596 readonly sections: ThreadRepositorySections;
597 readonly threadCwd: string | null;
598}): ReadonlyArray<PinnedThreadRepository> {
599 const shown = new Set(
600 [...input.sections.visible, ...input.sections.hidden].map((section) => section.key),
601 );
602 return input.folders.flatMap((folder) =>
603 folder.state !== "git" || folder.path === input.threadCwd || shown.has(folder.path)
604 ? []
605 : [{ repositoryPath: folder.path, name: folder.name }],
606 );
607}
608
609/** The tracked Git repositories a task folder has no worktree for yet. */
610export function addableTaskFolderRepositories(input: {
611 readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">>;
612 readonly taskFolder: Pick<TaskFolder, "projectRoot" | "repositories">;
613}): ReadonlyArray<PinnedThreadRepository> {
614 const present = new Set(
615 input.taskFolder.repositories.map((repository) => repository.repositoryPath),
616 );
617 return input.folders.flatMap((folder) =>
618 folder.state !== "git" ||
619 folder.path === input.taskFolder.projectRoot ||
620 present.has(folder.path)
621 ? []
622 : [{ repositoryPath: folder.path, name: folder.name }],
623 );
624}
625
626/** A tracked Git repository a new worktree thread can get a worktree of. */
627export interface WorktreeRepositoryChoice {
628 /** The tracked folder's path; what `workspaceStrategy.repositories[].path` takes. */
629 readonly repositoryPath: string;
630 readonly name: string;
631 /** The folder from the project folder, `/`-separated, when it sits inside it. */
632 readonly relativePath?: string;
633}
634
635/** A project's tracked Git folders, in the project's order. */
636export function worktreeRepositoryChoices(input: {
637 readonly folders: ReadonlyArray<Pick<WorkspaceFolder, "path" | "name" | "state">>;
638 readonly projectRoot: string;
639}): ReadonlyArray<WorktreeRepositoryChoice> {
640 return input.folders.flatMap((folder) => {
641 if (folder.state !== "git") return [];
642 const relativePath = relativeFolderPath(input.projectRoot, folder.path);
643 return [
644 {
645 repositoryPath: folder.path,
646 name: folder.name,
647 ...(relativePath === undefined ||
648 relativePath === "" ||
649 !isRelativePathInsideFolder(relativePath, input.projectRoot)
650 ? {}
651 : { relativePath }),
652 },
653 ];
654 });
655}
656
657export interface WorktreeRepositorySelection {
658 /** Chosen tracked paths, in the choices' order. */
659 readonly selected: ReadonlyArray<string>;
660 /** Short text for the control that opens the checklist. */
661 readonly label: string;
662 /** Nothing is selected only because the project tracks too many to take them all by default. */
663 readonly needsChoice: boolean;
664 /**
665 * What the launch sends as `workspaceStrategy.repositories`. Undefined until the user chooses,
666 * so the server applies its own default.
667 */
668 readonly strategyRepositories: ReadonlyArray<{ readonly path: string }> | undefined;
669}
670
671/**
672 * Which repositories a new worktree thread takes. Without a choice it mirrors the server: all of
673 * them up to `TASK_FOLDER_DEFAULT_REPOSITORIES_MAX`, none above. Chosen paths the project no
674 * longer tracks are dropped once its folders are known.
675 */
676export function resolveWorktreeRepositorySelection(
677 input: {
678 /** Null while the project's tracked folders are still loading. */
679 readonly choices: ReadonlyArray<WorktreeRepositoryChoice> | null;
680 readonly chosen: ReadonlyArray<string> | undefined;
681 },
682 resolve: MFunctionType = mFallback,
683): WorktreeRepositorySelection {
684 const { choices, chosen } = input;
685 if (choices === null) {
686 const selected = chosen ?? [];
687 return {
688 selected,
689 label: resolve(msg("Repositories")),
690 needsChoice: false,
691 strategyRepositories: chosen?.map((path) => ({ path })),
692 };
693 }
694 const takesAllByDefault = choices.length <= TASK_FOLDER_DEFAULT_REPOSITORIES_MAX;
695 const wanted = chosen === undefined ? null : new Set(chosen);
696 const selected = choices.flatMap((choice) =>
697 (wanted === null ? takesAllByDefault : wanted.has(choice.repositoryPath))
698 ? [choice.repositoryPath]
699 : [],
700 );
701 const needsChoice = chosen === undefined && !takesAllByDefault;
702 return {
703 selected,
704 label: needsChoice
705 ? resolve(msg("Choose repositories"))
706 : selected.length === 0
707 ? resolve(msg("No repositories"))
708 : selected.length !== 1 && selected.length === choices.length
709 ? resolve(msg("All repositories"))
710 : resolve(
711 msg("{count, plural, one {{count} repository} other {{count} repositories}}", {
712 count: selected.length,
713 }),
714 ),
715 needsChoice,
716 strategyRepositories: chosen === undefined ? undefined : selected.map((path) => ({ path })),
717 };
718}
719
720/** What a collapsed repository section shows; null until the first status arrives. */
721export interface RepositorySectionSummary {
722 /** Null on a detached HEAD. */
723 readonly branch: string | null;
724 readonly isRepository: boolean;
725 readonly changedFiles: number;
726 readonly insertions: number;
727 readonly deletions: number;
728 /** The branch's pull request, from the last remote read anyone made of this folder. */
729 readonly pullRequest: NonNullable<VcsStatusResult["pr"]> | null;
730}
731
732export function repositorySectionSummary(
733 status: VcsStatusResult | null | undefined,
734): RepositorySectionSummary | null {
735 if (status == null) return null;
736 return {
737 branch: status.refName,
738 isRepository: status.isRepo,
739 changedFiles: status.workingTree.files.length,
740 insertions: status.workingTree.insertions,
741 deletions: status.workingTree.deletions,
742 pullRequest: status.pr,
743 };
744}