diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index b2ad65cf05374..95cd4dc8343f8 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -79,6 +79,7 @@ import { AddProjectSourceRoute } from "./features/projects/AddProjectSourceRoute import { NewTaskBranchPickerRouteScreen, NewTaskEnvironmentPickerRouteScreen, + NewTaskRepositoriesPickerRouteScreen, } from "./features/threads/NewTaskContextPickerScreens"; import { ExistingThreadSettingsRouteScreen, @@ -572,6 +573,11 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: NewTaskBranchPickerRouteScreen, options: pageRoute({ title: "Branch" }), }), + NewTaskRepositories: createNativeStackScreen({ + linking: "new/draft/repositories", + screen: NewTaskRepositoriesPickerRouteScreen, + options: pageRoute({ title: "Repositories" }), + }), AddProject: createNativeStackScreen({ linking: "new/add-project", screen: AddProjectSourceRoute, diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx index 4fd54085c45f1..15724cf068744 100644 --- a/apps/mobile/src/components/ComposerToolbar.tsx +++ b/apps/mobile/src/components/ComposerToolbar.tsx @@ -29,6 +29,8 @@ export function ComposerInlineControl(props: { readonly accessibilityLabel?: string; readonly disabled?: boolean; readonly emphasized?: boolean; + /** The control asks for a decision; it stays usable. */ + readonly tone?: "warning"; readonly icon?: ComponentProps["name"]; readonly renderIcon?: (size: number) => ReactNode; readonly label: string; @@ -80,7 +82,11 @@ export function ComposerInlineControl(props: { name={props.icon} size={iconSize} tintColorClassName={ - props.emphasized || props.selected ? "accent-icon" : "accent-icon-muted" + props.tone === "warning" + ? "accent-warning-foreground" + : props.emphasized || props.selected + ? "accent-icon" + : "accent-icon-muted" } type="monochrome" /> @@ -93,7 +99,11 @@ export function ComposerInlineControl(props: { = new Set([ "AddProjectNew", "NewTaskEnvironment", "NewTaskBranch", + "NewTaskRepositories", "SettingsLegal", "SettingsAuth", "SettingsWaitlist", diff --git a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx index 88ec0c06e43b4..b0d73fd50799a 100644 --- a/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx +++ b/apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx @@ -331,6 +331,101 @@ export function NewTaskBranchPickerRouteScreen() { ); } +export function NewTaskRepositoriesPickerRouteScreen() { + const flow = useNewTaskFlow(); + const navigation = useNavigation(); + const insets = useSafeAreaInsets(); + const choices = flow.worktreeRepositoryChoices; + const selection = flow.worktreeRepositorySelection; + const selected = new Set(selection.selected); + const toggle = (repositoryPath: string) => { + if (choices === null) return; + void Haptics.selectionAsync(); + flow.setWorktreeRepositories( + choices.flatMap((choice) => + (choice.repositoryPath === repositoryPath) !== selected.has(choice.repositoryPath) + ? [choice.repositoryPath] + : [], + ), + ); + }; + const header = + choices === null || choices.length === 0 ? null : ( + + + {selection.needsChoice + ? "Choose the repositories this thread works on." + : "Each gets its own worktree on the thread's branch."} + + + diff --git a/apps/web/src/components/chat/ThreadDetailsPanel.tsx b/apps/web/src/components/chat/ThreadDetailsPanel.tsx index 95d622cef9840..444ae3bf25b34 100644 --- a/apps/web/src/components/chat/ThreadDetailsPanel.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPanel.tsx @@ -36,6 +36,8 @@ import { ThreadDetailsItemsMenuItems } from "./ThreadDetailsItemsMenu"; import { resolveThreadDetailsVisibility, THREAD_DETAILS_ITEMS } from "./threadDetailsItems"; import { useClientSettings } from "../../hooks/useSettings"; import { useProject, useServerConfigs } from "../../state/entities"; +import { filesystemEnvironment } from "../../state/filesystem"; +import { useEnvironmentQuery } from "../../state/query"; import { ThreadDetailsThreadPrRows } from "./ThreadDetailsPrRows"; import { cn } from "../../lib/utils"; import { SlidersHorizontalIcon } from "lucide-react"; @@ -104,6 +106,19 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { const activeThreadRef = { environmentId: props.environmentId, threadId: props.threadId }; const project = useProject(scopeProjectRef(props.environmentId, props.projectId)); const serverConfig = useServerConfigs().get(props.environmentId); + const tracksFolders = (project?.trackedFolders?.length ?? 0) > 0; + // A worktree thread reaches tracked repositories only through its own task folder. + const taskFolderQuery = useEnvironmentQuery( + props.isServerThread && props.worktreePath !== null && tracksFolders + ? filesystemEnvironment.taskFolder({ + environmentId: props.environmentId, + input: { worktreePath: props.worktreePath }, + }) + : null, + ); + const taskFolder = taskFolderQuery.data?.taskFolder ?? null; + // A task folder's plain project directory can sit inside someone else's repository. + const folderIsRepo = props.isGitRepo && taskFolder?.projectIsWorktree !== false; // A No project thread's folder sits inside the shared scratch root, so it must never get git. // Until the config and project load, a No project thread looks like any other folder. const offersGit = @@ -112,7 +127,7 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { project !== null && !isScratchProject(project, serverConfig.scratchWorkspaceRoot); const branchToolbarProps = { - showGitControls: props.isGitRepo, + showGitControls: folderIsRepo, environmentId: props.environmentId, threadId: props.threadId, projectId: props.projectId, @@ -170,21 +185,20 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { environment: density === "full" && visible.environment, openIn: density !== "essential" && visible.openIn && props.showOpenInPicker, scripts: visible.scripts && props.activeProjectScripts !== undefined, - branch: offersGit && props.isGitRepo && visible.branch, + branch: offersGit && folderIsRepo && visible.branch, // Without a branch selector, linked pull requests still need somewhere to show. - pullRequests: !(offersGit && props.isGitRepo) && visible.branch, + pullRequests: !(offersGit && folderIsRepo) && visible.branch, // A plain folder that tracks repositories is not asked to become one itself. git: offersGit && props.activeProjectName !== undefined && - (props.isGitRepo || (project?.trackedFolders?.length ?? 0) === 0) && - (visible.gitActions || (visible.changes && props.isGitRepo)), - // A thread in its own worktree reaches no tracked repository. + (folderIsRepo || !tracksFolders) && + (visible.gitActions || (visible.changes && folderIsRepo)), + // A thread in a single worktree of its own reaches no tracked repository. repositories: offersGit && density !== "essential" && - props.worktreePath === null && - (project?.trackedFolders?.length ?? 0) > 0 && + (props.worktreePath === null ? tracksFolders : taskFolder !== null) && visible.gitActions, }; return ( @@ -278,7 +292,9 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) { projectId={props.projectId} isServerThread={props.isServerThread} threadCwd={props.gitCwd} - explainsEmpty={!props.isGitRepo} + taskFolder={taskFolder} + onTaskFolderChange={taskFolderQuery.refresh} + explainsEmpty={!folderIsRepo} showActions={visible.gitActions} /> ) : null} diff --git a/apps/web/src/components/chat/ThreadRepositorySections.tsx b/apps/web/src/components/chat/ThreadRepositorySections.tsx index 7f16bf4170d87..5b5227aef571d 100644 --- a/apps/web/src/components/chat/ThreadRepositorySections.tsx +++ b/apps/web/src/components/chat/ThreadRepositorySections.tsx @@ -1,4 +1,5 @@ import { + addableTaskFolderRepositories, pinnableThreadRepositories, repositorySectionSummary, THREAD_REPOSITORY_SECTIONS_VISIBLE, @@ -8,7 +9,18 @@ import { type ThreadRepositorySections as RepositorySections, } from "@t3tools/client-runtime/state/thread-repositories"; import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; -import type { EnvironmentId, ProjectId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { + EnvironmentId, + ProjectId, + ScopedThreadRef, + TaskFolder, + ThreadId, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; import { ChevronDownIcon, ChevronRightIcon, @@ -22,11 +34,13 @@ import { cn } from "~/lib/utils"; import { useQuietThreadProjection } from "~/state/entities"; import { filesystemEnvironment, useFilesystemReadAccess } from "~/state/filesystem"; import { useEnvironmentQuery } from "~/state/query"; +import { useAtomCommand } from "~/state/use-atom-command"; import { vcsEnvironment } from "~/state/vcs"; import { useThreadRepositoryPins, useThreadRepositoryPinsStore } from "~/threadRepositoryPinsStore"; import { GitActionsControl } from "../GitActionsControl"; import { Menu, MenuItem, MenuItemLabel, MenuPopup, MenuTrigger } from "../ui/menu"; +import { stackedThreadToast, toastManager } from "../ui/toast"; import { ThreadDetailsControl } from "./ThreadDetailsControl"; import { THREAD_DETAILS_PANEL_CHEVRON_CLASS, @@ -41,6 +55,12 @@ interface ThreadRepositorySectionsProps { isServerThread: boolean; /** The thread's own folder, which has its own Git controls when it is a repository. */ threadCwd: string | null; + /** + * The thread's task folder. Its repositories are then the only ones listed, each bound to the + * thread's own worktree of it, and adding one creates that worktree. + */ + taskFolder: TaskFolder | null; + onTaskFolderChange: () => void; /** Says so when no repository is listed, instead of leaving the section blank. */ explainsEmpty: boolean; showActions: boolean; @@ -143,6 +163,7 @@ function OtherRepositoryItems(props: { environmentId: EnvironmentId; projectId: ProjectId; threadCwd: string | null; + taskFolder: TaskFolder | null; sections: RepositorySections; onPick: (repository: { repositoryPath: string; name: string }) => void; }) { @@ -159,11 +180,17 @@ function OtherRepositoryItems(props: { ); } - const repositories = pinnableThreadRepositories({ - folders: folders.data.folders, - sections: props.sections, - threadCwd: props.threadCwd, - }); + const repositories = + props.taskFolder === null + ? pinnableThreadRepositories({ + folders: folders.data.folders, + sections: props.sections, + threadCwd: props.threadCwd, + }) + : addableTaskFolderRepositories({ + folders: folders.data.folders, + taskFolder: props.taskFolder, + }); if (repositories.length === 0) { return ( @@ -180,8 +207,8 @@ function OtherRepositoryItems(props: { } /** - * Git state and actions for the tracked repositories a thread changed or the user added. Folded - * sections are not rendered, so they hold no subscription. + * Git state and actions for the tracked repositories a thread changed or the user added, or for + * the worktrees in its task folder. Folded sections are not rendered, so they hold no subscription. */ export function ThreadRepositorySections(props: ThreadRepositorySectionsProps) { const threadRef: ScopedThreadRef = { @@ -196,13 +223,47 @@ export function ThreadRepositorySections(props: ThreadRepositorySectionsProps) { const [showAll, setShowAll] = useState(false); const [expandedKey, setExpandedKey] = useState(null); const [isPickerOpen, setIsPickerOpen] = useState(false); + const canAddWorktree = useAtomValue( + filesystemEnvironment.addTaskFolderRepository.permissionAtom(props.environmentId), + ); + const addTaskFolderRepository = useAtomCommand(filesystemEnvironment.addTaskFolderRepository, { + label: "task folder add repository", + reportFailure: false, + }); + const [addingName, setAddingName] = useState(null); + const { taskFolder } = props; const sections = threadRepositorySections({ changed: structure === null ? [] : threadChangedRepositories(structure.projection), pinned, threadCwd: props.threadCwd, showAll, + taskFolder, }); + const addWorktree = async (repository: { repositoryPath: string; name: string }) => { + if (addingName !== null) return; + setAddingName(repository.name); + const result = await addTaskFolderRepository({ + environmentId: props.environmentId, + input: { threadId: props.threadId, repositoryPath: repository.repositoryPath }, + }); + setAddingName(null); + if (result._tag === "Failure") { + if (isAtomCommandInterrupted(result)) return; + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: `Could not add ${repository.name}`, + description: error instanceof Error ? error.message : String(error), + }), + ); + return; + } + props.onTaskFolderChange(); + setShowAll(true); + setExpandedKey(repository.repositoryPath); + }; const owner = props.isServerThread ? { threadId: props.threadId } : { projectId: props.projectId }; @@ -228,7 +289,9 @@ export function ThreadRepositorySections(props: ThreadRepositorySectionsProps) { <> {sections.visible.length === 0 && props.explainsEmpty ? (

- Repositories appear here once this thread changes them. + {taskFolder === null + ? "Repositories appear here once this thread changes them." + : "This thread has no repository worktrees yet."}

) : null} {sections.visible.map(renderSection)} @@ -247,13 +310,18 @@ export function ThreadRepositorySections(props: ThreadRepositorySectionsProps) { ) : null} - {canReadFiles ? ( + {canReadFiles && (taskFolder === null || (props.isServerThread && canAddWorktree)) ? ( } + disabled={addingName !== null} > - Other repositories... + + {addingName === null + ? "Other repositories..." + : `Adding a worktree of ${addingName}...`} + {isPickerOpen ? ( @@ -261,8 +329,13 @@ export function ThreadRepositorySections(props: ThreadRepositorySectionsProps) { environmentId={props.environmentId} projectId={props.projectId} threadCwd={props.threadCwd} + taskFolder={taskFolder} sections={sections} onPick={(repository) => { + if (taskFolder !== null) { + void addWorktree(repository); + return; + } pin(threadRef, repository); // Pins beyond the visible few would land folded away, out of sight. if (pinned.length >= THREAD_REPOSITORY_SECTIONS_VISIBLE) setShowAll(true); diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 7257dee5ced9e..7863807a112ff 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -184,6 +184,8 @@ interface ComposerSendInput { readonly phase: SessionPhase; readonly runtimeMode: RuntimeMode; readonly sendEnvMode: DraftThreadEnvMode; + /** Tracked repositories a new worktree takes; undefined leaves the choice to the server. */ + readonly worktreeRepositories: ReadonlyArray<{ readonly path: string }> | undefined; readonly startFromOrigin: boolean; readonly localCheckoutBranchMismatch: { readonly threadBranch: string; @@ -284,6 +286,7 @@ export function useComposerSend(input: ComposerSendInput) { phase, runtimeMode, sendEnvMode, + worktreeRepositories, startFromOrigin, localCheckoutBranchMismatch, logicalProjectEnvironments, @@ -361,6 +364,7 @@ export function useComposerSend(input: ComposerSendInput) { promptRef, runtimeMode, startFromOrigin, + worktreeRepositories, resetLocalDispatch, setThreadError, }); @@ -802,6 +806,7 @@ export function useComposerSend(input: ComposerSendInput) { sendEnvMode, worktreePath: activeThread.worktreePath, activeThreadBranch, + projectIsGitRepo: isGitRepo, resumeCompactionTokens, keepFullHistory, phase, @@ -1271,6 +1276,7 @@ export function useComposerSend(input: ComposerSendInput) { projectCwd: activeProject.workspaceRoot, baseBranch: baseBranchForWorktree, ...(startFromOrigin ? { startFromOrigin: true } : {}), + ...(worktreeRepositories ? { repositories: worktreeRepositories } : {}), }, runSetupScript: true, } diff --git a/apps/web/src/components/chat/useMultipleModelSend.ts b/apps/web/src/components/chat/useMultipleModelSend.ts index ccea2378968f5..2fd7b94f489cc 100644 --- a/apps/web/src/components/chat/useMultipleModelSend.ts +++ b/apps/web/src/components/chat/useMultipleModelSend.ts @@ -52,6 +52,7 @@ interface MultipleModelSendInput { readonly promptRef: { current: string }; readonly runtimeMode: RuntimeMode; readonly startFromOrigin: boolean; + readonly worktreeRepositories: ReadonlyArray<{ readonly path: string }> | undefined; readonly resetLocalDispatch: ReturnType["resetLocalDispatch"]; readonly setThreadError: ReturnType; } @@ -72,6 +73,7 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { promptRef, runtimeMode, startFromOrigin, + worktreeRepositories, resetLocalDispatch, setThreadError, } = input; @@ -192,6 +194,7 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { baseBranch: branch, requireWorktree: true, ...(startFromOrigin ? { startFromOrigin: true } : {}), + ...(worktreeRepositories ? { repositories: worktreeRepositories } : {}), }, runSetupScript: true, }, diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 216f6635f7088..e6bb726355397 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -723,7 +723,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP JSON.stringify([thread.environmentId, gitCwd]), gitStatus.data, ); - const checkoutThread = withoutRemovedCheckout(thread, visibleGitStatus); + const checkoutThread = withoutRemovedCheckout(thread, visibleGitStatus, props.project); const pr = linkedPullRequestStatus?.pr ?? null; const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId); const currentLinkedPr = supportsMultiplePullRequests @@ -1696,7 +1696,7 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props JSON.stringify([thread.environmentId, gitCwd]), gitStatus.data, ); - const checkoutThread = withoutRemovedCheckout(thread, visibleGitStatus); + const checkoutThread = withoutRemovedCheckout(thread, visibleGitStatus, props.project); const branchMismatch = resolveLocalCheckoutBranchMismatch({ effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree", activeWorktreePath: thread.worktreePath, diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index c698f96e92e39..ef6cd67c8495b 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -2755,9 +2755,19 @@ describe("composerDraftStore checkout pull request", () => { store().setDraftThreadContext(draftId, { checkoutPullRequest: null }); expect(store().getDraftSession(draftId)?.checkoutPullRequest).toBeUndefined(); - store().setDraftThreadContext(draftId, { checkoutPullRequest: checkout }); + store().setDraftThreadContext(draftId, { + checkoutPullRequest: checkout, + worktreeRepositories: ["/work/api"], + }); + // An unrelated change keeps the repository choice; an empty choice is still a choice. + store().setDraftThreadContext(draftId, { envMode: "worktree" }); + expect(store().getDraftSession(draftId)?.worktreeRepositories).toEqual(["/work/api"]); + store().setDraftThreadContext(draftId, { worktreeRepositories: [] }); + expect(store().getDraftSession(draftId)?.worktreeRepositories).toEqual([]); + store().setDraftThreadContext(draftId, { projectRef: otherProjectRef }); expect(store().getDraftSession(draftId)?.checkoutPullRequest).toBeUndefined(); + expect(store().getDraftSession(draftId)?.worktreeRepositories).toBeUndefined(); }); it("persists the pull request and still restores drafts saved without one", async () => { @@ -2786,7 +2796,11 @@ describe("composerDraftStore checkout pull request", () => { state: { draftsByThreadKey: {}, draftThreadsByThreadKey: { - [draftId]: { ...persistedDraftThread(threadId), checkoutPullRequest: checkout }, + [draftId]: { + ...persistedDraftThread(threadId), + checkoutPullRequest: checkout, + worktreeRepositories: ["/work/api"], + }, [legacyDraftId]: persistedDraftThread(ThreadId.make("thread-legacy")), }, logicalProjectDraftThreadKeyByLogicalProjectKey: { @@ -2804,7 +2818,8 @@ describe("composerDraftStore checkout pull request", () => { expect(checkoutPullRequestUrlToLink(legacy)).toBeNull(); expect( partializeComposerDraftStoreState(store()).draftThreadsByThreadKey[draftId], - ).toMatchObject({ checkoutPullRequest: checkout }); + ).toMatchObject({ checkoutPullRequest: checkout, worktreeRepositories: ["/work/api"] }); + expect(legacy).not.toHaveProperty("worktreeRepositories"); } finally { await useComposerDraftStore.persist.clearStorage(); vi.useRealTimers(); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 68fdc2b2bca36..a94b6d9528a02 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -418,6 +418,7 @@ const PersistedDraftThreadState = Schema.Struct({ checkoutPullRequest: Schema.optionalKey( Schema.Struct({ url: Schema.String, branch: Schema.String }), ), + worktreeRepositories: Schema.optionalKey(Schema.Array(Schema.String)), promotedTo: Schema.optionalKey( Schema.NullOr( Schema.Struct({ @@ -516,6 +517,11 @@ export interface DraftSessionState { startFromOrigin: boolean; /** Linked to the thread when the draft is sent on this branch. */ checkoutPullRequest?: DraftCheckoutPullRequest; + /** + * Tracked repositories a new worktree thread gets a worktree for, by tracked path. Absent + * until the user chooses, which leaves the choice to the server's default. + */ + worktreeRepositories?: ReadonlyArray; promotedTo?: ScopedThreadRef | null; } @@ -622,6 +628,7 @@ interface ComposerDraftStoreState { environmentSelection?: "auto" | "manual"; loadBalancedEnvironmentId?: EnvironmentId | null; checkoutPullRequest?: DraftCheckoutPullRequest | null; + worktreeRepositories?: ReadonlyArray | null; }, ) => void; clearProjectDraftThreadId: (projectRef: ScopedProjectRef) => void; @@ -1679,10 +1686,22 @@ function createDraftThreadState( options?.envMode ?? (nextWorktreePath ? "worktree" : (existingThread?.envMode ?? "local")), startFromOrigin: nextStartFromOrigin, ...(checkoutPullRequest ? { checkoutPullRequest } : {}), + ...(!projectChanged && existingThread?.worktreeRepositories !== undefined + ? { worktreeRepositories: existingThread.worktreeRepositories } + : {}), promotedTo: null, }; } +function worktreeRepositoriesEqual( + left: ReadonlyArray | undefined, + right: ReadonlyArray | undefined, +): boolean { + if (left === right) return true; + if (left === undefined || right === undefined || left.length !== right.length) return false; + return left.every((path, index) => path === right[index]); +} + /** An explicit value wins; otherwise a checkout's pull request stays with its project. */ function resolveCheckoutPullRequest( existing: DraftThreadState | undefined, @@ -1731,6 +1750,7 @@ function draftThreadsEqual(left: DraftThreadState | undefined, right: DraftThrea left.envMode === right.envMode && left.startFromOrigin === right.startFromOrigin && checkoutPullRequestsEqual(left.checkoutPullRequest, right.checkoutPullRequest) && + worktreeRepositoriesEqual(left.worktreeRepositories, right.worktreeRepositories) && scopedThreadRefsEqual(left.promotedTo, right.promotedTo) ); } @@ -1904,6 +1924,13 @@ function normalizePersistedDraftThreads( ? { loadBalancedEnvironmentId: null } : {}), ...(checkoutPullRequest ? { checkoutPullRequest } : {}), + ...(Array.isArray(candidateDraftThread.worktreeRepositories) + ? { + worktreeRepositories: candidateDraftThread.worktreeRepositories.filter( + (path): path is string => typeof path === "string", + ), + } + : {}), promotedTo, }; } @@ -2382,7 +2409,11 @@ export function partializeComposerDraftStoreState( if (!keptSessionKeys.has(threadKey)) { continue; } - persistedDraftThreadsByThreadKey[threadKey] = draftThread; + const { worktreeRepositories, ...persistedDraftThread } = draftThread; + persistedDraftThreadsByThreadKey[threadKey] = { + ...persistedDraftThread, + ...(worktreeRepositories ? { worktreeRepositories: [...worktreeRepositories] } : {}), + }; } return { draftsByThreadKey: persistedDraftsByThreadKey, @@ -2679,6 +2710,9 @@ function toHydratedDraftThreadState( ...(persistedDraftThread.checkoutPullRequest ? { checkoutPullRequest: persistedDraftThread.checkoutPullRequest } : {}), + ...(persistedDraftThread.worktreeRepositories + ? { worktreeRepositories: persistedDraftThread.worktreeRepositories } + : {}), promotedTo: persistedDraftThread.promotedTo ? scopeThreadRef( persistedDraftThread.promotedTo.environmentId as EnvironmentId, @@ -2943,6 +2977,12 @@ const composerDraftStore = create()( options.checkoutPullRequest, projectChanged, ); + const worktreeRepositories = + options.worktreeRepositories === undefined + ? projectChanged + ? undefined + : existing.worktreeRepositories + : (options.worktreeRepositories ?? undefined); const nextDraftThread: DraftThreadState = { threadId: existing.threadId, environmentId: nextProjectRef.environmentId, @@ -2967,6 +3007,7 @@ const composerDraftStore = create()( options.envMode ?? (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")), startFromOrigin: nextStartFromOrigin, ...(checkoutPullRequest ? { checkoutPullRequest } : {}), + ...(worktreeRepositories ? { worktreeRepositories } : {}), promotedTo: existing.promotedTo ?? null, }; const isUnchanged = @@ -2986,6 +3027,10 @@ const composerDraftStore = create()( nextDraftThread.checkoutPullRequest, existing.checkoutPullRequest, ) && + worktreeRepositoriesEqual( + nextDraftThread.worktreeRepositories, + existing.worktreeRepositories, + ) && scopedThreadRefsEqual(nextDraftThread.promotedTo, existing.promotedTo); if (isUnchanged) { return state; diff --git a/apps/web/src/hooks/useWorktreeRepositoryChoices.ts b/apps/web/src/hooks/useWorktreeRepositoryChoices.ts new file mode 100644 index 0000000000000..634876f05e296 --- /dev/null +++ b/apps/web/src/hooks/useWorktreeRepositoryChoices.ts @@ -0,0 +1,51 @@ +import { + worktreeRepositoryChoices, + type WorktreeRepositoryChoice, +} from "@t3tools/client-runtime/state/thread-repositories"; +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; + +import { filesystemEnvironment } from "~/state/filesystem"; +import { useEnvironmentQuery } from "~/state/query"; + +interface WorktreeRepositoryChoices { + /** The project's tracked Git folders. Null while they load or when they cannot be read. */ + readonly choices: ReadonlyArray | null; + /** Whether a worktree thread has a repository to work in besides the project folder. */ + readonly tracksGitRepositories: boolean; +} + +const NO_TRACKED_FOLDERS: WorktreeRepositoryChoices = Object.freeze({ + choices: Object.freeze([]), + tracksGitRepositories: false, +}); + +/** + * The tracked Git folders a new worktree thread of this project can take. A project that tracks + * no folders asks the server nothing. + */ +export function useWorktreeRepositoryChoices( + project: Pick< + EnvironmentProject, + "environmentId" | "id" | "workspaceRoot" | "trackedFolders" + > | null, +): WorktreeRepositoryChoices { + const tracksFolders = (project?.trackedFolders?.length ?? 0) > 0; + const folders = useEnvironmentQuery( + project !== null && tracksFolders + ? filesystemEnvironment.listFolders({ + environmentId: project.environmentId, + input: { projectId: project.id }, + }) + : null, + ); + if (project === null || !tracksFolders) return NO_TRACKED_FOLDERS; + if (folders.data === null) { + // Until the folders arrive the tracked list stands in, as the checkout's Git state does. + return { choices: null, tracksGitRepositories: folders.error === null }; + } + const choices = worktreeRepositoryChoices({ + folders: folders.data.folders, + projectRoot: project.workspaceRoot, + }); + return { choices, tracksGitRepositories: choices.length > 0 }; +} diff --git a/docs/internals/overview.md b/docs/internals/overview.md index 64cb07b4b7a43..19029cd1d9f3f 100644 --- a/docs/internals/overview.md +++ b/docs/internals/overview.md @@ -90,13 +90,29 @@ capture workspace state without adding commits to the user's branch. A revert mu workspace state with the provider conversation. A provider that cannot roll back its conversation must reject that operation before changing the filesystem. -A thread that runs in its project folder also gets one `repository` checkpoint scope per tracked -Git folder it reaches, under its root scope. A project can track dozens of repositories while a +A thread also gets one `repository` checkpoint scope per tracked Git folder it reaches, under its +root scope. A project can track dozens of repositories while a turn touches a few, so these scopes are sparse: a turn costs one `git status` per repository, and only a repository the turn changed gets a snapshot ref, a `checkpoint.captured` record and, the first time, its `checkpoint-scope.created`. A missing record means the turn left the repository -alone, and a ref does not exist for every run ordinal. Rewind does not restore these folders: file -restore needs an isolated worktree, and a thread in its own worktree reaches no tracked folders. +alone, and a ref does not exist for every run ordinal. + +A file rewind restores the thread's folder and every repository a discarded run changed, or none +of them: each folder is snapshotted first and put back if a later restore fails. A repository +with no checkpoint at the target returns to the baseline taken before its first later change, +which `repositoryRewindCheckpoint` picks; one whose earlier state was never snapshotted is left as +it is. Run ordinals are never reused, so the snapshots of discarded runs are deleted rather than +overwritten. + +A worktree thread of a project that tracks Git folders works in a task folder: one directory under +the worktrees directory that holds the project folder and a worktree of each chosen repository at +the same relative places, all on the thread's branch. The record is keyed by that directory, not +by thread, because subagents, forks and reused worktrees share a path. Such a thread reaches only +those worktrees: a repository scope's `cwd` is the worktree and its `repositoryPath` the tracked +folder. A project folder that is not a repository root is never checked out; its entries are +linked, so they stay shared with the original. Its root checkpoints are `missing` by design, and +a file rewind there restores the repositories alone. `TaskFolders` owns every change to a task folder, +and removal keeps any checkout the single-worktree rules would keep. Thread settlement is server-owned. The [settlement service](../../apps/server/src/orchestration-v2/ThreadSettlementService.ts) evaluates PR diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index 7b2fa26b1db93..1a5cfa4c3151a 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -65,7 +65,14 @@ From a script, `t3 project add --track-repos` tracks every repository it Each turn's changes are listed per repository; see [Review turn changes](source-control.md#review-turn-changes). -A thread that runs in its own worktree works only in the project's own folder. +**New worktree** works for these projects too, including a plain folder that is not a repository +itself. The thread gets its own folder laid out like the project, and each repository you choose +gets its own worktree there, all on the thread's branch. Pick the repositories from the +repositories control next to the workspace picker before you send: every tracked repository is +included when the project tracks eight or fewer, and none until you choose when it tracks more. +To bring another repository into a running thread, open the thread details panel and pick it under +**Other repositories**. In a plain folder, the files outside your repositories are shared links to +the originals, not copies, so editing one changes it for every thread. ## Pin and archive projects diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 2e6c36d911ada..a9b882ad9ecff 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -178,6 +178,8 @@ interface StartThreadBootstrap { readonly baseBranch: string; readonly branch?: string; readonly startFromOrigin?: boolean; + /** Tracked repositories to give a worktree; absent leaves the choice to the server. */ + readonly repositories?: ReadonlyArray<{ readonly path: string }>; }; readonly runSetupScript?: boolean; } @@ -776,6 +778,9 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(prepareWorktree.startFromOrigin === undefined ? {} : { startFromOrigin: prepareWorktree.startFromOrigin }), + ...(prepareWorktree.repositories === undefined + ? {} + : { repositories: prepareWorktree.repositories }), } : bootstrap?.worktreePath ? { diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 718a9dda93c0e..8f617508f5474 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -155,6 +155,7 @@ describe("command permissions", () => { it.effect.each([ { method: WS_METHODS.serverRunStorageCleanup, scope: AuthSettingsWriteScope }, { method: WS_METHODS.serverReclaimDatabaseSpace, scope: AuthEnvironmentMaintainScope }, + { method: WS_METHODS.workspaceAddTaskFolderRepository, scope: AuthSourceControlWriteScope }, ])("requires the destination $scope grant for $method", ({ method, scope }) => Effect.gen(function* () { const registry = yield* setup; diff --git a/packages/client-runtime/src/state/filesystem.ts b/packages/client-runtime/src/state/filesystem.ts index 3370ca60dfdd5..f48234ba3f794 100644 --- a/packages/client-runtime/src/state/filesystem.ts +++ b/packages/client-runtime/src/state/filesystem.ts @@ -20,7 +20,7 @@ import { hasTrailingPathSeparator, isFilesystemBrowseQuery, } from "./projects.ts"; -import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; +import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; const BROWSE_IDLE_TTL_MS = 5_000; @@ -167,5 +167,15 @@ export function createFilesystemEnvironmentAtoms( tag: WS_METHODS.workspaceListFolders, staleTimeMs: 0, }), + /** The task folder a thread's `worktreePath` belongs to, with each repository's worktree. */ + taskFolder: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:workspace:task-folder", + tag: WS_METHODS.workspaceTaskFolder, + staleTimeMs: 0, + }), + addTaskFolderRepository: createEnvironmentRpcCommand(runtime, { + label: "environment-data:workspace:add-task-folder-repository", + tag: WS_METHODS.workspaceAddTaskFolderRepository, + }), }; } diff --git a/packages/client-runtime/src/state/threadRepositories.test.ts b/packages/client-runtime/src/state/threadRepositories.test.ts index 9fb8fa7590e93..46c89722cd792 100644 --- a/packages/client-runtime/src/state/threadRepositories.test.ts +++ b/packages/client-runtime/src/state/threadRepositories.test.ts @@ -13,12 +13,15 @@ import { describe, expect, it } from "vite-plus/test"; import { deriveThreadCheckpointSummaries } from "./threadCheckpoints.ts"; import { + addableTaskFolderRepositories, deriveTurnRepositoryChanges, pinnableThreadRepositories, pinThreadRepository, repositoryCheckpointScopeIds, repositoryFilePath, repositorySectionForPath, + resolveWorktreeRepositorySelection, + rewindFileRestore, THREAD_REPOSITORY_SECTIONS_VISIBLE, threadChangedRepositories, threadRepositoryScopes, @@ -27,6 +30,7 @@ import { turnChanges, turnDiffSections, turnHasChanges, + worktreeRepositoryChoices, } from "./threadRepositories.ts"; const now = DateTime.makeUnsafe("2026-11-10T00:00:00.000Z"); @@ -229,6 +233,192 @@ describe("threadRepositorySections", () => { }), ).toEqual([{ repositoryPath: "/work/wrapper/cli", name: "cli" }]); }); + + it("lists a task folder's worktrees, changed first, and never a shared checkout", () => { + const taskFolder = { + projectRoot: "/work/wrapper", + repositories: [ + { repositoryPath: "/work/wrapper/docs", worktreePath: "/wt/task/docs", name: "docs" }, + { repositoryPath: "/work/wrapper/web", worktreePath: "/wt/task/web", name: "web" }, + { + repositoryPath: "/work/wrapper/services/api", + worktreePath: "/wt/task/services/api", + name: "api", + }, + ], + }; + const sections = threadRepositorySections({ + // `/work/shared` is changed but has no worktree in the task folder. + changed, + pinned: [{ repositoryPath: "/work/wrapper/cli", name: "cli" }], + threadCwd: "/wt/task", + showAll: false, + taskFolder, + }); + expect(sections.visible.map((section) => [section.key, section.cwd, section.origin])).toEqual([ + ["/work/wrapper/web", "/wt/task/web", "worktree"], + ["/work/wrapper/services/api", "/wt/task/services/api", "worktree"], + ["/work/wrapper/docs", "/wt/task/docs", "worktree"], + ]); + expect( + threadRepositorySections({ + changed, + pinned: [], + threadCwd: "/wt/task", + showAll: false, + taskFolder: { repositories: [] }, + }).visible, + ).toEqual([]); + + expect( + addableTaskFolderRepositories({ + taskFolder, + folders: [ + { path: "/work/wrapper", name: "wrapper", state: "git" }, + { path: "/work/wrapper/docs", name: "docs", state: "git" }, + { path: "/work/wrapper/notes", name: "notes", state: "plain" }, + { path: "/work/shared", name: "shared", state: "git" }, + ], + }), + ).toEqual([{ repositoryPath: "/work/shared", name: "shared" }]); + }); +}); + +describe("rewindFileRestore", () => { + const projection = { checkpointScopes: scopes, checkpoints }; + const missingRoot = (appRunOrdinal: number | null) => + ({ status: "missing", appRunOrdinal }) as const; + const linkedProjectFolder = { projectIsWorktree: false }; + + it.each([ + { + why: "a ready snapshot restores every file", + checkpoint: { status: "ready", appRunOrdinal: 1 } as const, + taskFolder: null, + restores: "files", + }, + { + why: "a linked project folder restores a repository's own checkpoint", + checkpoint: missingRoot(1), + taskFolder: linkedProjectFolder, + restores: "repositories", + }, + { + why: "the thread start restores a repository's baseline", + checkpoint: missingRoot(null), + taskFolder: linkedProjectFolder, + restores: "repositories", + }, + { + why: "no repository changed after the target", + checkpoint: missingRoot(3), + taskFolder: linkedProjectFolder, + restores: null, + }, + { + why: "a worktree project folder needs its own snapshot", + checkpoint: missingRoot(1), + taskFolder: { projectIsWorktree: true }, + restores: null, + }, + { + why: "a thread outside a task folder has only its own snapshot", + checkpoint: missingRoot(1), + taskFolder: null, + restores: null, + }, + { + why: "a stale snapshot restores nothing", + checkpoint: { status: "stale", appRunOrdinal: 1 } as const, + taskFolder: linkedProjectFolder, + restores: null, + }, + { why: "no target", checkpoint: undefined, taskFolder: linkedProjectFolder, restores: null }, + ])("$why", ({ checkpoint: target, taskFolder, restores }) => { + expect(rewindFileRestore({ projection, checkpoint: target, taskFolder })).toBe(restores); + }); + + it("ignores the thread's own scope when looking for repository snapshots", () => { + expect( + rewindFileRestore({ + projection: { + checkpointScopes: [scope("scope-root", "/work/wrapper")], + checkpoints: [checkpoint("root-1", "scope-root", 1, { appRunOrdinal: 1 })], + }, + checkpoint: missingRoot(1), + taskFolder: linkedProjectFolder, + }), + ).toBe(null); + }); +}); + +describe("worktree repository selection", () => { + const folders = [ + { path: "/work/wrapper/web", name: "web", state: "git" }, + { path: "/work/wrapper/services/api", name: "api", state: "git" }, + { path: "/work/wrapper/notes", name: "notes", state: "plain" }, + { path: "/work/shared", name: "shared", state: "git" }, + ] as const; + const choices = worktreeRepositoryChoices({ folders, projectRoot: "/work/wrapper" }); + + it("offers tracked Git folders with their place inside the project folder", () => { + expect(choices).toEqual([ + { repositoryPath: "/work/wrapper/web", name: "web", relativePath: "web" }, + { repositoryPath: "/work/wrapper/services/api", name: "api", relativePath: "services/api" }, + { repositoryPath: "/work/shared", name: "shared" }, + ]); + }); + + it("takes every repository by default and sends nothing until the user chooses", () => { + expect(resolveWorktreeRepositorySelection({ choices, chosen: undefined })).toEqual({ + selected: ["/work/wrapper/web", "/work/wrapper/services/api", "/work/shared"], + label: "All repositories", + needsChoice: false, + strategyRepositories: undefined, + }); + }); + + it("sends the chosen repositories the project still tracks, and an empty choice as none", () => { + expect( + resolveWorktreeRepositorySelection({ + choices, + chosen: ["/work/shared", "/work/untracked", "/work/wrapper/web"], + }), + ).toMatchObject({ + label: "2 repositories", + strategyRepositories: [{ path: "/work/wrapper/web" }, { path: "/work/shared" }], + }); + expect(resolveWorktreeRepositorySelection({ choices, chosen: [] })).toMatchObject({ + label: "No repositories", + needsChoice: false, + strategyRepositories: [], + }); + }); + + it("takes none by default above the server's limit and asks for a choice", () => { + const many = Array.from({ length: 9 }, (_, index) => ({ + repositoryPath: `/work/wrapper/repo-${index}`, + name: `repo-${index}`, + })); + expect(resolveWorktreeRepositorySelection({ choices: many, chosen: undefined })).toEqual({ + selected: [], + label: "Choose repositories", + needsChoice: true, + strategyRepositories: undefined, + }); + expect( + resolveWorktreeRepositorySelection({ choices: many.slice(0, 8), chosen: undefined }).selected, + ).toHaveLength(8); + }); + + it("sends a stored choice as it is while the tracked folders are still loading", () => { + expect( + resolveWorktreeRepositorySelection({ choices: null, chosen: ["/work/shared"] }), + ).toMatchObject({ needsChoice: false, strategyRepositories: [{ path: "/work/shared" }] }); + expect( + resolveWorktreeRepositorySelection({ choices: null, chosen: undefined }).strategyRepositories, + ).toBeUndefined(); + }); }); describe("deriveTurnRepositoryChanges", () => { diff --git a/packages/client-runtime/src/state/threadRepositories.ts b/packages/client-runtime/src/state/threadRepositories.ts index a30212e6c6bcf..574c8edd60aaa 100644 --- a/packages/client-runtime/src/state/threadRepositories.ts +++ b/packages/client-runtime/src/state/threadRepositories.ts @@ -1,3 +1,8 @@ +import { + repositoryRewindCheckpoint, + TASK_FOLDER_DEFAULT_REPOSITORIES_MAX, + type TaskFolder, +} from "@t3tools/contracts"; import type { CheckpointScopeId, OrchestrationV2Checkpoint, @@ -86,6 +91,33 @@ export function repositoryCheckpointScopeIds( return new Set(scopes.flatMap((scope) => (isRepositoryCheckpointScope(scope) ? [scope.id] : []))); } +/** + * What a rewind to `checkpoint`, the thread's own rewind target, can restore on disk: every file, + * only the repositories of a task folder whose project folder has no snapshot, or nothing. + * The server refuses a file rewind this does not offer. + */ +export function rewindFileRestore(input: { + readonly projection: Pick; + readonly checkpoint: Pick | undefined; + readonly taskFolder: Pick | null | undefined; +}): "files" | "repositories" | null { + const { checkpoint, projection } = input; + if (checkpoint === undefined) return null; + if (checkpoint.status === "ready") return "files"; + if (checkpoint.status !== "missing" || input.taskFolder?.projectIsWorktree !== false) return null; + const targetOrdinal = checkpoint.appRunOrdinal ?? 0; + return projection.checkpointScopes.some( + (scope) => + isRepositoryCheckpointScope(scope) && + repositoryRewindCheckpoint( + projection.checkpoints.filter((candidate) => candidate.scopeId === scope.id), + targetOrdinal, + ) !== null, + ) + ? "repositories" + : null; +} + function pathSegments(path: string): { root: string; segments: string[] } | undefined { const normalized = path.replaceAll("\\", "/"); const segments = normalized.split("/").filter((segment) => segment.length > 0); @@ -356,8 +388,11 @@ export interface ThreadRepositorySection { readonly name: string; /** The folder Git commands run in. */ readonly cwd: string; - /** Pinned sections can be removed; changed ones stay for as long as the thread has them. */ - readonly origin: "pinned" | "changed"; + /** + * Pinned sections can be removed; changed ones stay for as long as the thread has them. A + * `worktree` section is the thread's own worktree of that repository. + */ + readonly origin: "pinned" | "changed" | "worktree"; } export interface ThreadRepositorySections { @@ -390,30 +425,62 @@ export function threadChangedRepositories( ); } +/** A task folder's repositories, each bound to its worktree: changed ones first, then the rest. */ +function taskFolderSections( + taskFolder: Pick, + changed: ReadonlyArray, +): ThreadRepositorySection[] { + const byPath = new Map( + taskFolder.repositories.map((repository) => [repository.repositoryPath, repository]), + ); + const ordered = new Set(); + for (const scope of changed) { + if (byPath.has(scope.repositoryPath)) ordered.add(scope.repositoryPath); + } + for (const repository of taskFolder.repositories) ordered.add(repository.repositoryPath); + return [...ordered].map((repositoryPath) => { + const repository = byPath.get(repositoryPath)!; + return { + key: repositoryPath, + name: repository.name, + cwd: repository.worktreePath, + origin: "worktree" as const, + }; + }); +} + /** * The repository sections of a thread: pinned ones in the order they were pinned, then the ones * the thread changed. `threadCwd` is the thread's own folder, which has its own Git controls. + * + * A thread with a `taskFolder` lists that folder's repositories instead, changed or not, and + * never a pin or a changed repository outside it: those would be someone else's checkout. */ export function threadRepositorySections(input: { readonly changed: ReadonlyArray; readonly pinned: ReadonlyArray; readonly threadCwd: string | null; readonly showAll: boolean; + readonly taskFolder?: Pick | null | undefined; }): ThreadRepositorySections { - if (input.changed.length === 0 && input.pinned.length === 0) return NO_SECTIONS; - const seen = new Set(input.threadCwd === null ? [] : [input.threadCwd]); const sections: ThreadRepositorySection[] = []; - const add = (section: ThreadRepositorySection) => { - if (seen.has(section.key)) return; - seen.add(section.key); - sections.push(section); - }; - for (const pin of input.pinned) { - add({ key: pin.repositoryPath, name: pin.name, cwd: pin.repositoryPath, origin: "pinned" }); - } - for (const scope of input.changed) { - add({ key: scope.repositoryPath, name: scope.name, cwd: scope.cwd, origin: "changed" }); + if (input.taskFolder != null) { + sections.push(...taskFolderSections(input.taskFolder, input.changed)); + } else { + const seen = new Set(input.threadCwd === null ? [] : [input.threadCwd]); + const add = (section: ThreadRepositorySection) => { + if (seen.has(section.key)) return; + seen.add(section.key); + sections.push(section); + }; + for (const pin of input.pinned) { + add({ key: pin.repositoryPath, name: pin.name, cwd: pin.repositoryPath, origin: "pinned" }); + } + for (const scope of input.changed) { + add({ key: scope.repositoryPath, name: scope.name, cwd: scope.cwd, origin: "changed" }); + } } + if (sections.length === 0) return NO_SECTIONS; if (input.showAll || sections.length <= THREAD_REPOSITORY_SECTIONS_VISIBLE) { return { visible: sections, hidden: NO_SECTIONS.hidden }; } @@ -457,6 +524,110 @@ export function pinnableThreadRepositories(input: { ); } +/** The tracked Git repositories a task folder has no worktree for yet. */ +export function addableTaskFolderRepositories(input: { + readonly folders: ReadonlyArray>; + readonly taskFolder: Pick; +}): ReadonlyArray { + const present = new Set( + input.taskFolder.repositories.map((repository) => repository.repositoryPath), + ); + return input.folders.flatMap((folder) => + folder.state !== "git" || + folder.path === input.taskFolder.projectRoot || + present.has(folder.path) + ? [] + : [{ repositoryPath: folder.path, name: folder.name }], + ); +} + +/** A tracked Git repository a new worktree thread can get a worktree of. */ +export interface WorktreeRepositoryChoice { + /** The tracked folder's path; what `workspaceStrategy.repositories[].path` takes. */ + readonly repositoryPath: string; + readonly name: string; + /** The folder from the project folder, `/`-separated, when it sits inside it. */ + readonly relativePath?: string; +} + +/** A project's tracked Git folders, in the project's order. */ +export function worktreeRepositoryChoices(input: { + readonly folders: ReadonlyArray>; + readonly projectRoot: string; +}): ReadonlyArray { + return input.folders.flatMap((folder) => { + if (folder.state !== "git") return []; + const relativePath = relativeFolderPath(input.projectRoot, folder.path); + return [ + { + repositoryPath: folder.path, + name: folder.name, + ...(relativePath === undefined || relativePath === "" || relativePath.startsWith("..") + ? {} + : { relativePath }), + }, + ]; + }); +} + +export interface WorktreeRepositorySelection { + /** Chosen tracked paths, in the choices' order. */ + readonly selected: ReadonlyArray; + /** Short text for the control that opens the checklist. */ + readonly label: string; + /** Nothing is selected only because the project tracks too many to take them all by default. */ + readonly needsChoice: boolean; + /** + * What the launch sends as `workspaceStrategy.repositories`. Undefined until the user chooses, + * so the server applies its own default. + */ + readonly strategyRepositories: ReadonlyArray<{ readonly path: string }> | undefined; +} + +/** + * Which repositories a new worktree thread takes. Without a choice it mirrors the server: all of + * them up to `TASK_FOLDER_DEFAULT_REPOSITORIES_MAX`, none above. Chosen paths the project no + * longer tracks are dropped once its folders are known. + */ +export function resolveWorktreeRepositorySelection(input: { + /** Null while the project's tracked folders are still loading. */ + readonly choices: ReadonlyArray | null; + readonly chosen: ReadonlyArray | undefined; +}): WorktreeRepositorySelection { + const { choices, chosen } = input; + if (choices === null) { + const selected = chosen ?? []; + return { + selected, + label: "Repositories", + needsChoice: false, + strategyRepositories: chosen?.map((path) => ({ path })), + }; + } + const takesAllByDefault = choices.length <= TASK_FOLDER_DEFAULT_REPOSITORIES_MAX; + const wanted = chosen === undefined ? null : new Set(chosen); + const selected = choices.flatMap((choice) => + (wanted === null ? takesAllByDefault : wanted.has(choice.repositoryPath)) + ? [choice.repositoryPath] + : [], + ); + const needsChoice = chosen === undefined && !takesAllByDefault; + return { + selected, + label: needsChoice + ? "Choose repositories" + : selected.length === 0 + ? "No repositories" + : selected.length === 1 + ? "1 repository" + : selected.length === choices.length + ? "All repositories" + : `${selected.length} repositories`, + needsChoice, + strategyRepositories: chosen === undefined ? undefined : selected.map((path) => ({ path })), + }; +} + /** What a collapsed repository section shows; null until the first status arrives. */ export interface RepositorySectionSummary { /** Null on a detached HEAD. */ diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 8681c1ea8abeb..09d98538bbe19 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -58,6 +58,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.gitPreparePullRequestThread]: AuthSourceControlWriteScope, [WS_METHODS.vcsCreateWorktree]: AuthSourceControlWriteScope, [WS_METHODS.vcsRemoveWorktree]: AuthSourceControlWriteScope, + [WS_METHODS.workspaceAddTaskFolderRepository]: AuthSourceControlWriteScope, [WS_METHODS.vcsCreateRef]: AuthSourceControlWriteScope, [WS_METHODS.vcsSwitchRef]: AuthSourceControlWriteScope, [WS_METHODS.vcsInit]: AuthSourceControlWriteScope, diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.ts index 3782307171e87..01ed2e3dc70be 100644 --- a/packages/contracts/src/orchestrationV2.test.ts +++ b/packages/contracts/src/orchestrationV2.test.ts @@ -2,9 +2,10 @@ import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; -import { NodeId, RunAttemptId, TrimmedNonEmptyString } from "./index.ts"; +import { NodeId, RunAttemptId, RunId, TrimmedNonEmptyString } from "./index.ts"; import { latestProviderTurnForAttempt, + repositoryRewindCheckpoint, OrchestrationV2ProviderCapabilities, OrchestrationV2ProviderThread, OrchestrationV2ProviderThreadJson, @@ -639,3 +640,31 @@ describe("latestProviderTurnForAttempt", () => { expect(latestProviderTurnForAttempt(turns, null)).toBeUndefined(); }); }); + +describe("repositoryRewindCheckpoint", () => { + const run = RunId.make("run"); + // Runs 2 and 6 changed the repository; a rewind to run 3 already discarded what run 5 recorded. + const checkpoints = [ + { ordinalWithinScope: 1, runId: null, status: "ready" }, + { ordinalWithinScope: 2, runId: run, status: "ready" }, + { ordinalWithinScope: 4, runId: null, status: "stale" }, + { ordinalWithinScope: 5, runId: run, status: "stale" }, + { ordinalWithinScope: 5, runId: null, status: "ready" }, + { ordinalWithinScope: 6, runId: run, status: "ready" }, + { ordinalWithinScope: 8, runId: null, status: "missing" }, + { ordinalWithinScope: 9, runId: run, status: "ready" }, + ] as const; + + it.each([ + { target: 0, restores: 1, why: "the baseline before the first change" }, + { target: 2, restores: 2, why: "the target run's own checkpoint" }, + { target: 3, restores: 5, why: "the baseline before the next change, past stale records" }, + { target: 6, restores: 6, why: "the target run's own checkpoint" }, + { target: 7, restores: null, why: "nothing: the state before run 9 was never snapshotted" }, + { target: 10, restores: null, why: "nothing: no later run changed the repository" }, + ])("a rewind to run $target restores $why", ({ target, restores }) => { + expect(repositoryRewindCheckpoint(checkpoints, target)?.ordinalWithinScope ?? null).toBe( + restores, + ); + }); +}); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 19f3485dcc533..11a998f9b759e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -79,6 +79,7 @@ import { } from "./providerPolicy.ts"; import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts"; import { OrchestrationProjectShell } from "./orchestrationProject.ts"; +import { PROJECT_TRACKED_FOLDERS_MAX } from "./project.ts"; import { TurnTokenUsage, ToolActivitySurface, @@ -714,6 +715,13 @@ export const OrchestrationV2ThreadLaunchWorkspaceStrategy = Schema.Union([ baseRef: TrimmedNonEmptyString, branch: Schema.optional(TrimmedNonEmptyString), startFromOrigin: Schema.optional(Schema.Boolean), + repositories: Schema.optional( + Schema.Array(Schema.Struct({ path: TrimmedNonEmptyString })) + .check(Schema.isMaxLength(PROJECT_TRACKED_FOLDERS_MAX)) + .annotate({ + description: "Tracked Git folders to give a worktree. Default: all, or none above 8.", + }), + ), }), ]); export type OrchestrationV2ThreadLaunchWorkspaceStrategy = @@ -1494,6 +1502,27 @@ export const OrchestrationV2Checkpoint = Schema.Struct({ }); export type OrchestrationV2Checkpoint = typeof OrchestrationV2Checkpoint.Type; +/** + * The checkpoint a file rewind to run `targetOrdinal` restores a tracked repository to, given that + * repository scope's checkpoints. Its records are sparse: the first snapshot at or after the + * target is the target's own, or the baseline taken before the first later run that changed the + * repository. Null when no later run changed it, or when that state was never snapshotted. + */ +export function repositoryRewindCheckpoint< + Checkpoint extends Pick, +>(checkpoints: ReadonlyArray, targetOrdinal: number): Checkpoint | null { + let first: Checkpoint | undefined; + for (const checkpoint of checkpoints) { + if (checkpoint.status !== "ready" || checkpoint.ordinalWithinScope < targetOrdinal) continue; + if (first === undefined || checkpoint.ordinalWithinScope < first.ordinalWithinScope) + first = checkpoint; + } + // A later run's own checkpoint holds that run's changes, not the state before them. + return first !== undefined && (first.ordinalWithinScope === targetOrdinal || first.runId === null) + ? first + : null; +} + export const OrchestrationV2CheckpointRollbackRequest = Schema.Struct({ scopeId: CheckpointScopeId, checkpointId: CheckpointId, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index c2d0d754864c8..62c18671e91c6 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -94,10 +94,15 @@ import { } from "./filesystem.ts"; import { WorkspaceFoldersError, + TaskFolder, + TaskFolderError, + WorkspaceAddTaskFolderRepositoryInput, WorkspaceListFoldersInput, WorkspaceListFoldersResult, WorkspaceScanFoldersInput, WorkspaceScanFoldersResult, + WorkspaceTaskFolderInput, + WorkspaceTaskFolderResult, } from "./workspaceFolders.ts"; import { AgentSessionImportInput, @@ -438,6 +443,8 @@ export const WS_METHODS = { filesystemBrowse: "filesystem.browse", workspaceListFolders: "workspace.listFolders", workspaceScanFolders: "workspace.scanFolders", + workspaceTaskFolder: "workspace.taskFolder", + workspaceAddTaskFolderRepository: "workspace.addTaskFolderRepository", filesystemGetMetadata: "filesystem.getMetadata", agentSessionsScan: "agentSessions.scan", agentSessionsImport: "agentSessions.import", @@ -1462,6 +1469,21 @@ const WsWorkspaceScanFoldersRpc = Rpc.make(WS_METHODS.workspaceScanFolders, { error: Schema.Union([WorkspaceFoldersError, EnvironmentAuthorizationError]), }); +const WsWorkspaceTaskFolderRpc = Rpc.make(WS_METHODS.workspaceTaskFolder, { + payload: WorkspaceTaskFolderInput, + success: WorkspaceTaskFolderResult, + error: Schema.Union([TaskFolderError, EnvironmentAuthorizationError]), +}); + +const WsWorkspaceAddTaskFolderRepositoryRpc = Rpc.make( + WS_METHODS.workspaceAddTaskFolderRepository, + { + payload: WorkspaceAddTaskFolderRepositoryInput, + success: TaskFolder, + error: Schema.Union([TaskFolderError, EnvironmentAuthorizationError]), + }, +); + const WsAgentSessionsScanRpc = Rpc.make(WS_METHODS.agentSessionsScan, { payload: AgentSessionScanInput, success: AgentSessionScanResult, @@ -2258,6 +2280,8 @@ export const WsRpcGroup = RpcGroup.make( WsFilesystemBrowseRpc, WsWorkspaceListFoldersRpc, WsWorkspaceScanFoldersRpc, + WsWorkspaceTaskFolderRpc, + WsWorkspaceAddTaskFolderRepositoryRpc, WsFilesystemGetMetadataRpc, WsAgentSessionsScanRpc, WsAgentSessionsImportRpc, diff --git a/packages/contracts/src/workspaceFolders.ts b/packages/contracts/src/workspaceFolders.ts index 2c990a4ecd408..64275f1004295 100644 --- a/packages/contracts/src/workspaceFolders.ts +++ b/packages/contracts/src/workspaceFolders.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; -import { ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; /** `git` folders are repositories with their own history; `plain` folders are only files. */ export const WorkspaceFolderState = Schema.Literals(["git", "plain", "missing"]); @@ -49,6 +49,67 @@ export const WorkspaceScanFoldersResult = Schema.Struct({ }); export type WorkspaceScanFoldersResult = typeof WorkspaceScanFoldersResult.Type; +/** A new worktree thread isolates every tracked repository by default only up to this many. */ +export const TASK_FOLDER_DEFAULT_REPOSITORIES_MAX = 8; + +/** A tracked repository's own worktree inside a thread's task folder. */ +export const TaskFolderRepository = Schema.Struct({ + /** The tracked folder's path, as the project stores it. */ + repositoryPath: TrimmedNonEmptyString, + worktreePath: TrimmedNonEmptyString, + name: TrimmedNonEmptyString, +}); +export type TaskFolderRepository = typeof TaskFolderRepository.Type; + +/** + * The folder a worktree thread of a multi-repository project works in: the project folder and + * each chosen repository at the same relative places, every repository on the thread's branch. + */ +export const TaskFolder = Schema.Struct({ + root: TrimmedNonEmptyString, + projectId: ProjectId, + /** The project folder this was laid out from. */ + projectRoot: TrimmedNonEmptyString, + /** The folder `root` stands in for: a path below it sits at the same place below `root`. */ + anchor: TrimmedNonEmptyString, + /** Where the project folder sits inside `root`: the thread's `worktreePath`. */ + projectPath: TrimmedNonEmptyString, + /** False when the project folder is not a repository: `projectPath` then links to its files. */ + projectIsWorktree: Schema.Boolean, + repositories: Schema.Array(TaskFolderRepository), +}); +export type TaskFolder = typeof TaskFolder.Type; + +export const WorkspaceTaskFolderInput = Schema.Struct({ + /** A thread's `worktreePath`, or any path inside its task folder. */ + worktreePath: TrimmedNonEmptyString, +}); +export type WorkspaceTaskFolderInput = typeof WorkspaceTaskFolderInput.Type; + +export const WorkspaceTaskFolderResult = Schema.Struct({ + /** Null for a thread whose worktree is a single checkout. */ + taskFolder: Schema.NullOr(TaskFolder), +}); +export type WorkspaceTaskFolderResult = typeof WorkspaceTaskFolderResult.Type; + +export const WorkspaceAddTaskFolderRepositoryInput = Schema.Struct({ + threadId: ThreadId, + /** One of the project's tracked Git folders. */ + repositoryPath: TrimmedNonEmptyString, +}); +export type WorkspaceAddTaskFolderRepositoryInput = + typeof WorkspaceAddTaskFolderRepositoryInput.Type; + +export class TaskFolderError extends Schema.TaggedError()("TaskFolderError", { + operation: Schema.Literals(["plan", "create", "add-repository", "remove", "read"]), + detail: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) { + override get message(): string { + return this.detail; + } +} + export class WorkspaceFoldersError extends Schema.TaggedError()( "WorkspaceFoldersError", { diff --git a/packages/shared/src/projectSettings.test.ts b/packages/shared/src/projectSettings.test.ts index a5edf854c3aec..93b3b87711a7b 100644 --- a/packages/shared/src/projectSettings.test.ts +++ b/packages/shared/src/projectSettings.test.ts @@ -30,6 +30,9 @@ describe("resolveSendEnvMode", () => { it.each(["local", "worktree"] as const)("preserves %s for git repositories", (mode) => { expect(resolveSendEnvMode({ requestedEnvMode: mode, isGitRepo: true })).toBe(mode); + expect( + resolveSendEnvMode({ requestedEnvMode: mode, isGitRepo: false, tracksGitRepositories: true }), + ).toBe(mode); }); }); diff --git a/packages/shared/src/projectSettings.ts b/packages/shared/src/projectSettings.ts index e6a9ac22418a0..f5c7941218f93 100644 --- a/packages/shared/src/projectSettings.ts +++ b/packages/shared/src/projectSettings.ts @@ -207,11 +207,13 @@ export function resolveNewThreadEnvMode(input: { return isNewProjectFolder ? "local" : configured; } +/** Worktree mode needs a repository: the project folder, or a folder the project tracks. */ export function resolveSendEnvMode(input: { readonly requestedEnvMode: ThreadEnvMode; readonly isGitRepo: boolean; + readonly tracksGitRepositories?: boolean; }): ThreadEnvMode { - return input.isGitRepo ? input.requestedEnvMode : "local"; + return input.isGitRepo || input.tracksGitRepositories === true ? input.requestedEnvMode : "local"; } export function clearProjectSettingsOverrides(