diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 7a9a806f54f19..5789cf18c29cd 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -64,6 +64,7 @@ import { DevicePreviewRouteScreen } from "./features/devices/DevicePreviewRouteS import { BrowserPreviewRouteScreen } from "./features/browser/BrowserPreviewRouteScreen"; import { LocalPreviewRouteScreen } from "./features/browser/LocalPreviewRouteScreen"; import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet"; +import { GitRemoteSheet } from "./features/threads/git/GitRemoteSheet"; import { GitCommitSheet } from "./features/threads/git/GitCommitSheet"; import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet"; import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet"; @@ -808,6 +809,11 @@ const RootStackConfig = createWorkspaceStackNavigator({ linking: `${THREAD_LINKING_PREFIX}/git/branches`, options: sheetRoute({ detent: 0.55, androidFit: true }), }), + GitRemote: createNativeStackScreen({ + screen: GitRemoteSheet, + linking: `${THREAD_LINKING_PREFIX}/git/remote`, + options: sheetRoute({ detent: 0.55, androidFit: true }), + }), GitConfirm: createNativeStackScreen({ screen: GitConfirmSheet, linking: `${THREAD_LINKING_PREFIX}/git-confirm`, diff --git a/apps/mobile/src/features/layout/workspace-overlay-routes.ts b/apps/mobile/src/features/layout/workspace-overlay-routes.ts index 592e5ce4eb6ea..bf876369dfe9d 100644 --- a/apps/mobile/src/features/layout/workspace-overlay-routes.ts +++ b/apps/mobile/src/features/layout/workspace-overlay-routes.ts @@ -11,6 +11,7 @@ const LISTED_OVERLAY_ROUTES: ReadonlySet = new Set([ "GitBranches", "GitCommit", "GitConfirm", + "GitRemote", "GitOverview", "NewTaskProject", "NewTaskFiles", diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx index f84ea9d0ccc24..ff950176432a3 100644 --- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -341,6 +341,22 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) { ) } /> + {gitStatus.data?.remotes && gitStatus.data.refName ? ( + + presentRoute(() => + navigation.navigate("GitRemote", { + environmentId: String(environmentId), + threadId: String(threadId), + }), + ) + } + /> + ) : null} {linkedPrActions.canLink ? ( ; + +export function GitRemoteSheet(props: GitRemoteSheetProps) { + const { environmentId, threadId, action, commitMessage, featureBranch, filePaths } = + props.route.params; + const gt = useGT(); + const navigation = useNavigation(); + const insets = useSafeAreaInsets(); + const { height: windowHeight } = useWindowDimensions(); + const { selectedThread } = useThreadSelection(); + const { selectedThreadCwd } = useSelectedThreadWorktree(); + const gitActions = useSelectedThreadGitActions(); + const gitStatus = useEnvironmentQuery( + selectedThread !== null && selectedThreadCwd !== null + ? vcsEnvironment.status({ + environmentId: selectedThread.environmentId, + input: { cwd: selectedThreadCwd }, + }) + : null, + ); + const selecting = useRef(false); + const [isSelecting, setIsSelecting] = useState(false); + const remotes = gitStatus.data?.remotes ?? []; + const pushRemote = gitStatus.data?.pushRemote; + + const runSelection = async (remoteName: string) => { + if (action) { + navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); + await gitActions.onRunSelectedThreadGitAction({ + action, + pushRemote: remoteName, + ...(commitMessage ? { commitMessage } : {}), + ...(featureBranch === "true" ? { featureBranch: true } : {}), + ...(filePaths ? { filePaths: JSON.parse(filePaths) as string[] } : {}), + }); + return; + } + const result = await gitActions.onSetSelectedThreadPushRemote(remoteName); + if (result !== null && navigation.isFocused()) navigation.goBack(); + }; + const selectRemote = async (remoteName: string) => { + if (selecting.current) return; + selecting.current = true; + setIsSelecting(true); + await runSelection(remoteName).finally(() => { + selecting.current = false; + setIsSelecting(false); + }); + }; + + return ( + + + + + {remotes.map((remoteName) => ( + void selectRemote(remoteName)} + /> + ))} + + + + navigation.goBack()} + /> + + ); +} diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 30116da93d8aa..0a707b6f2a3cc 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1613,6 +1613,7 @@ "5521de0732509b7c": "Neueste Änderungen werden gepullt", "adb9c574404d1db8": "Bereits auf dem neuesten Stand", "84964b49287ced17": "Neuester Stand auf {branch} gepullt", + "ea8ce1c79f81b25d": "Push-Remote wird geändert", "439fbd498ad5aba1": "Anhänge sind nicht bereit", "f928da494821aeb0": "Warte, bis die Uploads abgeschlossen sind, oder wiederhole fehlgeschlagene Uploads.", "4c7966190fc234b4": "Zu viele Kontextelemente", @@ -5258,10 +5259,14 @@ "5c72439f2a8e12bf": "Änderungen, nicht committete Bearbeitungen und Diffs der Runden untersuchen", "466265a5e2628fb2": "Branch wechseln, Branch erstellen oder in einen Worktree wechseln", "6ed8a3818ccfda2d": "Branches und Worktrees anzeigen", + "18cf05cd2cd7dd0e": "Push-Remote", + "8ba218cd9a65f767": "Nicht ausgewählt", "b294ba924b8cd9c1": "{term, select, mr {Einen Merge Request per URL oder Nummer anhängen} cr {Eine Änderungsanfrage per URL oder Nummer anhängen} other {Einen Pull Request per URL oder Nummer anhängen}}", "518ca475a032d313": "Verknüpfte {terms}", "28dd3410a8843fed": "Worktree", "a46d99e72af41cd4": "Repository-Status aktualisieren", + "00c1e5d0b43e70be": "Dieses Repository hat mehrere Remotes und für diesen Branch wurde noch keines ausgewählt. Er wird das ausgewählte Remote verfolgen.", + "db3369af717edbfb": "An welches Remote pushen?", "cd49e17eaf69eee3": "Branch-Status wird geladen…", "95be4cac9ca707c4": "Kein Git-Repository", "d804d85750efb3b8": "{term, select, mr {MR #{number} offen} cr {Änderungsanfrage #{number} offen} other {PR #{number} offen}}", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index a7433f8a74360..6cbc224d1b829 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1613,6 +1613,7 @@ "5521de0732509b7c": "Pulling latest changes", "adb9c574404d1db8": "Already up to date", "84964b49287ced17": "Pulled latest on {branch}", + "ea8ce1c79f81b25d": "Changing push remote", "439fbd498ad5aba1": "Attachments are not ready", "f928da494821aeb0": "Wait for uploads to finish, or retry failed uploads.", "4c7966190fc234b4": "Too many context items", @@ -5259,10 +5260,14 @@ "5c72439f2a8e12bf": "Inspect changes, uncommitted edits, and turn diffs", "466265a5e2628fb2": "Switch branch, create branch, or move to a worktree", "6ed8a3818ccfda2d": "View branches and worktrees", + "18cf05cd2cd7dd0e": "Push remote", + "8ba218cd9a65f767": "Not chosen", "b294ba924b8cd9c1": "{term, select, mr {Attach a merge request by URL or number} cr {Attach a change request by URL or number} other {Attach a pull request by URL or number}}", "518ca475a032d313": "Linked {terms}", "28dd3410a8843fed": "Worktree", "a46d99e72af41cd4": "Refresh repository status", + "00c1e5d0b43e70be": "This repository has several remotes and the branch has none chosen yet. It will track the one you pick.", + "db3369af717edbfb": "Push to which remote?", "cd49e17eaf69eee3": "Loading branch status…", "95be4cac9ca707c4": "Not a git repository", "d804d85750efb3b8": "{term, select, mr {MR #{number} open} cr {change request #{number} open} other {PR #{number} open}}", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 5b7e4a1df6b1f..dc7bf30b1afef 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1613,6 +1613,7 @@ "5521de0732509b7c": "Haciendo pull de los últimos cambios", "adb9c574404d1db8": "Ya está actualizado", "84964b49287ced17": "Pull de los últimos cambios en {branch} completado", + "ea8ce1c79f81b25d": "Cambiando remoto de push", "439fbd498ad5aba1": "Los adjuntos no están listos", "f928da494821aeb0": "Espera a que terminen las subidas o reintenta las fallidas.", "4c7966190fc234b4": "Demasiados elementos de contexto", @@ -5252,10 +5253,14 @@ "5c72439f2a8e12bf": "Inspecciona los cambios, las ediciones sin commit y los diffs de turnos", "466265a5e2628fb2": "Cambia de rama, crea una rama o pasa a un worktree", "6ed8a3818ccfda2d": "Ver ramas y worktrees", + "18cf05cd2cd7dd0e": "Remoto de push", + "8ba218cd9a65f767": "Sin elegir", "b294ba924b8cd9c1": "{term, select, mr {Adjuntar una merge request por URL o número} cr {Adjuntar una solicitud de cambios por URL o número} other {Adjuntar una pull request por URL o número}}", "518ca475a032d313": "{terms} vinculadas", "28dd3410a8843fed": "Worktree", "a46d99e72af41cd4": "Actualizar el estado del repositorio", + "00c1e5d0b43e70be": "Este repositorio tiene varios remotos y la rama aún no tiene uno elegido. Seguirá al que elijas.", + "db3369af717edbfb": "¿A qué remoto enviar?", "cd49e17eaf69eee3": "Cargando el estado de la rama…", "95be4cac9ca707c4": "No es un repositorio git", "d804d85750efb3b8": "{term, select, mr {MR #{number} abierta} cr {solicitud de cambios #{number} abierta} other {PR #{number} abierta}}", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 791e9bdbb1bdd..a22fdc33e338c 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1613,6 +1613,7 @@ "5521de0732509b7c": "Récupération des dernières modifications", "adb9c574404d1db8": "Déjà à jour", "84964b49287ced17": "Dernières modifications récupérées sur {branch}", + "ea8ce1c79f81b25d": "Modification du dépôt distant de push", "439fbd498ad5aba1": "Les pièces jointes ne sont pas prêtes", "f928da494821aeb0": "Attendez la fin des envois, ou relancez les envois échoués.", "4c7966190fc234b4": "Trop d’éléments de contexte", @@ -5252,10 +5253,14 @@ "5c72439f2a8e12bf": "Inspecter les modifications, les changements non commités et les diffs des tours", "466265a5e2628fb2": "Changer de branche, créer une branche ou passer à un worktree", "6ed8a3818ccfda2d": "Voir les branches et worktrees", + "18cf05cd2cd7dd0e": "Dépôt distant de push", + "8ba218cd9a65f767": "Non choisi", "b294ba924b8cd9c1": "{term, select, mr {Joindre une merge request par URL ou numéro} cr {Joindre une demande de modification par URL ou numéro} other {Joindre une pull request par URL ou numéro}}", "518ca475a032d313": "{terms} associées", "28dd3410a8843fed": "Worktree", "a46d99e72af41cd4": "Actualiser le statut du dépôt", + "00c1e5d0b43e70be": "Ce dépôt a plusieurs dépôts distants et la branche n’en a pas encore choisi. Elle suivra celui que vous choisissez.", + "db3369af717edbfb": "Vers quel dépôt distant pousser ?", "cd49e17eaf69eee3": "Chargement du statut de la branche…", "95be4cac9ca707c4": "Pas un dépôt git", "d804d85750efb3b8": "{term, select, mr {MR #{number} ouverte} cr {demande de modification #{number} ouverte} other {PR #{number} ouverte}}", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 991bb7852b731..c3ff287d488ee 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1613,6 +1613,7 @@ "5521de0732509b7c": "最新の変更をプルしています", "adb9c574404d1db8": "すでに最新です", "84964b49287ced17": "{branch} で最新の変更をプルしました", + "ea8ce1c79f81b25d": "プッシュ先リモートを変更中", "439fbd498ad5aba1": "添付ファイルの準備ができていません", "f928da494821aeb0": "アップロードが完了するまで待つか、失敗したアップロードを再試行してください。", "4c7966190fc234b4": "コンテキストの項目が多すぎます", @@ -5234,10 +5235,14 @@ "5c72439f2a8e12bf": "変更、未コミットの編集、ターンの差分を確認", "466265a5e2628fb2": "ブランチの切り替え・作成、またはワークツリーへの移動", "6ed8a3818ccfda2d": "ブランチとワークツリーを表示", + "18cf05cd2cd7dd0e": "プッシュ先リモート", + "8ba218cd9a65f767": "未選択", "b294ba924b8cd9c1": "{term, select, mr {URL または番号でマージリクエストを添付} cr {URL または番号で変更リクエストを添付} other {URL または番号でプルリクエストを添付}}", "518ca475a032d313": "リンクされた {terms}", "28dd3410a8843fed": "ワークツリー", "a46d99e72af41cd4": "リポジトリのステータスを更新", + "00c1e5d0b43e70be": "このリポジトリには複数のリモートがあり、ブランチのリモートは未選択です。選択したリモートを追跡します。", + "db3369af717edbfb": "どのリモートにプッシュしますか?", "cd49e17eaf69eee3": "ブランチのステータスを読み込んでいます…", "95be4cac9ca707c4": "Git リポジトリではありません", "d804d85750efb3b8": "{term, select, mr {MR #{number} オープン} cr {変更リクエスト #{number} オープン} other {PR #{number} オープン}}", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 6b91487ccbbc5..ad8191ca24d39 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1613,6 +1613,7 @@ "5521de0732509b7c": "최신 변경 사항 가져오는 중", "adb9c574404d1db8": "이미 최신 상태", "84964b49287ced17": "{branch}에서 최신 변경 사항을 가져왔습니다", + "ea8ce1c79f81b25d": "푸시 원격 저장소 변경 중", "439fbd498ad5aba1": "첨부 파일이 준비되지 않았습니다", "f928da494821aeb0": "업로드가 끝날 때까지 기다리거나 실패한 업로드를 다시 시도하세요.", "4c7966190fc234b4": "컨텍스트 항목이 너무 많습니다", @@ -5238,10 +5239,14 @@ "5c72439f2a8e12bf": "변경 사항, 커밋되지 않은 편집, 턴 변경 사항 검사", "466265a5e2628fb2": "브랜치 전환, 브랜치 만들기 또는 워크트리로 이동", "6ed8a3818ccfda2d": "브랜치 및 워크트리 보기", + "18cf05cd2cd7dd0e": "푸시 원격 저장소", + "8ba218cd9a65f767": "선택 안 함", "b294ba924b8cd9c1": "{term, select, mr {URL이나 번호로 병합 요청 첨부} cr {URL이나 번호로 변경 요청 첨부} other {URL이나 번호로 풀 리퀘스트 첨부}}", "518ca475a032d313": "연결된 {terms}", "28dd3410a8843fed": "워크트리", "a46d99e72af41cd4": "저장소 상태 새로 고침", + "00c1e5d0b43e70be": "이 저장소에는 여러 원격 저장소가 있으며 브랜치에 아직 선택된 원격 저장소가 없습니다. 선택한 원격 저장소를 추적합니다.", + "db3369af717edbfb": "어느 원격 저장소에 푸시할까요?", "cd49e17eaf69eee3": "브랜치 상태 불러오는 중…", "95be4cac9ca707c4": "Git 저장소가 아님", "d804d85750efb3b8": "{term, select, mr {MR #{number} 열림} cr {변경 요청 #{number} 열림} other {PR #{number} 열림}}", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 251993b1b9210..b4e66f7d707b3 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1613,6 +1613,7 @@ "5521de0732509b7c": "Fazendo pull das alterações mais recentes", "adb9c574404d1db8": "Já está atualizado", "84964b49287ced17": "Pull mais recente feito em {branch}", + "ea8ce1c79f81b25d": "Alterando remoto de push", "439fbd498ad5aba1": "Os anexos não estão prontos", "f928da494821aeb0": "Aguarde os envios terminarem ou tente novamente os que falharam.", "4c7966190fc234b4": "Itens de contexto demais", @@ -5252,10 +5253,14 @@ "5c72439f2a8e12bf": "Inspecione alterações, edições sem commit e diffs dos turnos", "466265a5e2628fb2": "Troque de branch, crie um branch ou mude para um worktree", "6ed8a3818ccfda2d": "Ver branches e worktrees", + "18cf05cd2cd7dd0e": "Remoto de push", + "8ba218cd9a65f767": "Não escolhido", "b294ba924b8cd9c1": "{term, select, mr {Anexar um merge request por URL ou número} cr {Anexar uma solicitação de alteração por URL ou número} other {Anexar um pull request por URL ou número}}", "518ca475a032d313": "{terms} vinculados", "28dd3410a8843fed": "Worktree", "a46d99e72af41cd4": "Atualizar status do repositório", + "00c1e5d0b43e70be": "Este repositório tem vários remotos e a branch ainda não tem um escolhido. Ela rastreará o que você escolher.", + "db3369af717edbfb": "Para qual remoto enviar?", "cd49e17eaf69eee3": "Carregando status do branch…", "95be4cac9ca707c4": "Não é um repositório git", "d804d85750efb3b8": "{term, select, mr {MR #{number} aberto} cr {solicitação de alteração #{number} aberta} other {PR #{number} aberto}}", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index eb53bc6a85093..fad9b208fb910 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1613,6 +1613,7 @@ "5521de0732509b7c": "Получение последних изменений", "adb9c574404d1db8": "Уже актуально", "84964b49287ced17": "Получены последние изменения в {branch}", + "ea8ce1c79f81b25d": "Изменение репозитория для отправки", "439fbd498ad5aba1": "Вложения не готовы", "f928da494821aeb0": "Дождитесь окончания загрузки или повторите неудавшиеся загрузки.", "4c7966190fc234b4": "Слишком много элементов контекста", @@ -5332,10 +5333,14 @@ "5c72439f2a8e12bf": "Изменения, незакоммиченные правки и диффы ходов", "466265a5e2628fb2": "Переключить ветку, создать ветку или перейти в рабочее дерево", "6ed8a3818ccfda2d": "Показать ветки и рабочие деревья", + "18cf05cd2cd7dd0e": "Репозиторий для отправки", + "8ba218cd9a65f767": "Не выбран", "b294ba924b8cd9c1": "{term, select, mr {Прикрепить мерж-реквест по URL или номеру} cr {Прикрепить запрос на изменение по URL или номеру} other {Прикрепить пул-реквест по URL или номеру}}", "518ca475a032d313": "Привязанные {terms}", "28dd3410a8843fed": "Рабочее дерево", "a46d99e72af41cd4": "Обновить статус репозитория", + "00c1e5d0b43e70be": "У этого репозитория несколько удалённых репозиториев, и для ветки ещё не выбран ни один. Она будет отслеживать выбранный вами.", + "db3369af717edbfb": "В какой репозиторий отправить?", "cd49e17eaf69eee3": "Загрузка статуса ветки…", "95be4cac9ca707c4": "Не git-репозиторий", "d804d85750efb3b8": "{term, select, mr {MR #{number} открыт} cr {Запрос на изменение #{number} открыт} other {PR #{number} открыт}}", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 0b335f057cdce..d4dbfec042a41 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1613,6 +1613,7 @@ "5521de0732509b7c": "Pullar senaste ändringarna", "adb9c574404d1db8": "Redan uppdaterad", "84964b49287ced17": "Pullade senaste på {branch}", + "ea8ce1c79f81b25d": "Ändrar fjärrarkiv för push", "439fbd498ad5aba1": "Bilagorna är inte klara", "f928da494821aeb0": "Vänta tills uppladdningarna är klara, eller försök igen med misslyckade uppladdningar.", "4c7966190fc234b4": "För många kontextobjekt", @@ -5258,10 +5259,14 @@ "5c72439f2a8e12bf": "Granska ändringar, ej committade redigeringar och omgångsdiffar", "466265a5e2628fb2": "Byt gren, skapa gren eller flytta till en worktree", "6ed8a3818ccfda2d": "Visa grenar och worktrees", + "18cf05cd2cd7dd0e": "Fjärrarkiv för push", + "8ba218cd9a65f767": "Inte valt", "b294ba924b8cd9c1": "{term, select, mr {Bifoga en merge request via URL eller nummer} cr {Bifoga en ändringsbegäran via URL eller nummer} other {Bifoga en pull request via URL eller nummer}}", "518ca475a032d313": "Länkade {terms}", "28dd3410a8843fed": "Worktree", "a46d99e72af41cd4": "Uppdatera repots status", + "00c1e5d0b43e70be": "Det här arkivet har flera fjärrarkiv och grenen har inget valt ännu. Den kommer att spåra det du väljer.", + "db3369af717edbfb": "Till vilket fjärrarkiv vill du pusha?", "cd49e17eaf69eee3": "Läser in grenstatus…", "95be4cac9ca707c4": "Inte ett Git-repo", "d804d85750efb3b8": "{term, select, mr {MR #{number} öppen} cr {ändringsbegäran #{number} öppen} other {PR #{number} öppen}}", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 9002438aed15e..314d901508066 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1614,6 +1614,7 @@ "5521de0732509b7c": "正在拉取最新更改", "adb9c574404d1db8": "已是最新", "84964b49287ced17": "已拉取 {branch} 的最新更改", + "ea8ce1c79f81b25d": "正在更改推送远程仓库", "439fbd498ad5aba1": "附件尚未就绪", "f928da494821aeb0": "请等待上传完成,或重试失败的上传。", "4c7966190fc234b4": "上下文项过多", @@ -5243,10 +5244,14 @@ "5c72439f2a8e12bf": "检查更改、未提交的编辑和轮次差异", "466265a5e2628fb2": "切换分支、创建分支或移到工作树", "6ed8a3818ccfda2d": "查看分支和工作树", + "18cf05cd2cd7dd0e": "推送远程仓库", + "8ba218cd9a65f767": "未选择", "b294ba924b8cd9c1": "{term, select, mr {通过 URL 或编号附加 MR} cr {通过 URL 或编号附加 change request} other {通过 URL 或编号附加 PR}}", "518ca475a032d313": "关联的 {terms}", "28dd3410a8843fed": "工作树", "a46d99e72af41cd4": "刷新仓库状态", + "00c1e5d0b43e70be": "此仓库有多个远程仓库,当前分支尚未选择。它将跟踪你选择的远程仓库。", + "db3369af717edbfb": "推送到哪个远程仓库?", "cd49e17eaf69eee3": "正在加载分支状态…", "95be4cac9ca707c4": "不是 Git 仓库", "d804d85750efb3b8": "{term, select, mr {MR #{number} 开放} cr {change request #{number} 开放} other {PR #{number} 开放}}", diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.test.ts b/apps/mobile/src/state/use-selected-thread-git-actions.test.ts index 548ae2d3ce6b0..0d4f781ea29af 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.test.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.test.ts @@ -53,7 +53,10 @@ vi.mock("./queries", () => ({ useBranches: () => ({ data: { refs: state.cachedRefs }, refresh: () => {} }), })); vi.mock("./use-atom-command", () => ({ useAtomCommand: (command: unknown) => command })); -vi.mock("./atom-registry", () => ({ appAtomRegistry: {} })); +vi.mock("./atom-registry", () => ({ + appAtomRegistry: { get: () => AsyncResult.initial() }, +})); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ navigate: () => {} }) })); vi.mock("./use-remote-environment-registry", () => ({ environmentConnectedAtom: () => null, setPendingConnectionError: () => {}, @@ -84,6 +87,7 @@ vi.mock("./threads", () => ({ vi.mock("./vcs", () => ({ vcsEnvironment: { readRefs: state.readRefs, + status: () => null, refreshStatus: async () => { state.statusRefreshes += 1; return AsyncResult.success({ refName: state.branch }); diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.ts b/apps/mobile/src/state/use-selected-thread-git-actions.ts index 42336835cc440..c9d0a45a66616 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.ts @@ -1,3 +1,4 @@ +import { useNavigation } from "@react-navigation/native"; import { useAtomMount } from "@effect/atom-react"; import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; @@ -6,6 +7,7 @@ import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; import { createVcsStatusRevalidationAtomFamily, type GitActionRequestInput, + pushRemoteChoicesFor, type VcsActionOperation, type VcsRef, } from "@t3tools/client-runtime/state/vcs"; @@ -56,12 +58,14 @@ const selectedThreadStatusRevalidation = createVcsStatusRevalidationAtomFamily({ }); export function useSelectedThreadGitActions() { + const navigation = useNavigation(); const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false, }); const readRefs = useAtomCommand(vcsEnvironment.readRefs, { reportFailure: false }); const refreshStatus = useAtomCommand(vcsEnvironment.refreshStatus, { reportFailure: false }); const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false }); + const setPushRemote = useAtomCommand(vcsEnvironment.setPushRemote, { reportFailure: false }); const createRef = useAtomCommand(vcsEnvironment.createRef, { reportFailure: false }); const createWorktree = useAtomCommand(vcsEnvironment.createWorktree, { reportFailure: false }); const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false }); @@ -367,9 +371,54 @@ export function useSelectedThreadGitActions() { ); }; + const selectedThreadGitStatus = () => + selectedThread && selectedThreadCwd + ? AsyncResult.getOrElse( + appAtomRegistry.get( + vcsEnvironment.status({ + environmentId: selectedThread.environmentId, + input: { cwd: selectedThreadCwd }, + }), + ), + () => null, + ) + : null; + + const onSetSelectedThreadPushRemote = async (remoteName: string) => { + const refName = selectedThreadGitStatus()?.refName; + if (!refName) return null; + return runSelectedThreadGitMutation( + "switch_ref", + m(msg("Changing push remote")), + async ({ thread, cwd }) => { + const result = await setPushRemote({ + environmentId: thread.environmentId, + input: { cwd, refName, remoteName }, + }); + if (AsyncResult.isSuccess(result)) { + await refreshSelectedThreadGitStatus({ quiet: true, cwd }); + } + return result; + }, + ); + }; + const onRunSelectedThreadGitAction = async ( input: GitActionRequestInput, ): Promise => { + // Every entry point lands here, after any default-branch confirmation. + const pushRemoteChoices = pushRemoteChoicesFor(input, selectedThreadGitStatus()); + if (pushRemoteChoices && selectedThread) { + navigation.navigate("GitRemote", { + environmentId: String(selectedThread.environmentId), + threadId: String(selectedThread.id), + action: input.action, + ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), + ...(input.featureBranch ? { featureBranch: "true" } : {}), + ...(input.filePaths?.length ? { filePaths: JSON.stringify(input.filePaths) } : {}), + }); + return null; + } const actionId = uuidv4(); return await runSelectedThreadGitMutation( "run_change_request", @@ -381,6 +430,7 @@ export function useSelectedThreadGitActions() { ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), ...(input.featureBranch ? { featureBranch: input.featureBranch } : {}), ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}), + ...(input.pushRemote ? { pushRemote: input.pushRemote } : {}), threadId: thread.id, }); if (AsyncResult.isFailure(result)) { @@ -423,6 +473,7 @@ export function useSelectedThreadGitActions() { onCreateSelectedThreadBranch, onCreateSelectedThreadWorktree, onPullSelectedThreadBranch, + onSetSelectedThreadPushRemote, onRunSelectedThreadGitAction, }; } diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 73da4ec2a6bac..2afca5b9f52e7 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -58,9 +58,11 @@ import * as VcsProjectConfig from "../vcs/VcsProjectConfig.ts"; import * as GitWorkflowService from "./GitWorkflowService.ts"; import type { SourceControlProvider, + SourceControlProviderContext, SourceControlRefSelector, } from "@t3tools/source-control-core/server/SourceControlProvider"; import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import * as ServerConfig from "../config.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; @@ -608,6 +610,7 @@ function runStackedAction( commitMessage?: string; featureBranch?: boolean; filePaths?: readonly string[]; + pushRemote?: string; }, options?: Parameters[1], ) { @@ -631,6 +634,10 @@ function makeManager(input?: { providerScenario?: FakeProviderScenario; pullRequests?: Partial; sourceControlProvider?: SourceControlProvider["Service"]; + /** Served when a caller resolves the provider for a specific remote. */ + remoteSourceControlProvider?: SourceControlProvider["Service"]; + /** The checkout-wide context the default provider was resolved from. */ + sourceControlContext?: SourceControlProviderContext; textGeneration?: Partial; serverSettings?: Parameters[0]; setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]; @@ -728,7 +735,11 @@ function makeManager(input?: { SourceControlProviderRegistry.SourceControlProviderRegistry.of({ resolveLink: (input) => provider.resolveLink?.(input), get: () => Effect.succeed(provider), - resolveHandle: () => Effect.succeed({ provider, context: null }), + resolveHandle: (request) => + Effect.succeed({ + provider: (request.context && input?.remoteSourceControlProvider) || provider, + context: request.context ?? input?.sourceControlContext ?? null, + }), resolve: () => Effect.succeed(provider), discover: Effect.succeed([]), }), @@ -1027,6 +1038,159 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect.each([ + { label: "the branch's push remote", key: "branch.feature/status-push-remote-host.pushRemote" }, + { label: "the repository's default push remote", key: "remote.pushDefault" }, + ])("status detects the host from $label before the first push", ({ key }) => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-push-remote-host"]); + yield* runGit(repoDir, ["remote", "add", "hub", "https://github.com/acme/repo.git"]); + yield* runGit(repoDir, ["remote", "add", "lab", "https://gitlab.com/acme/repo.git"]); + yield* runGit(repoDir, ["config", key, "lab"]); + + const { manager } = yield* makeManager(); + + const status = yield* manager.status({ cwd: repoDir }); + + expect(status.sourceControlProvider?.kind).toBe("gitlab"); + }), + ); + + it.effect("status finds the PR on the host of the remote the branch is pushed to", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-mixed-hosts"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "hub", "https://github.com/acme/repo.git"]); + yield* runGit(repoDir, ["remote", "add", "lab", "https://gitlab.com/acme/repo.git"]); + yield* runGit(repoDir, ["config", "remote.lab.pushurl", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "lab", "feature/status-mixed-hosts"]); + + const gitlab = createFakeSourceControlProvider({ + kind: "gitlab", + prListSequence: [ + [ + { + number: 21, + title: "Mixed hosts", + url: "https://gitlab.com/acme/repo/-/merge_requests/21", + baseRefName: "main", + headRefName: "feature/status-mixed-hosts", + isCrossRepository: true, + headRepositoryNameWithOwner: "acme/repo", + headRepositoryOwnerLogin: "acme", + }, + ], + ], + }); + const { manager } = yield* makeManager({ remoteSourceControlProvider: gitlab.service }); + + const status = yield* manager.status({ cwd: repoDir }); + + expect(status.pr?.url).toBe("https://gitlab.com/acme/repo/-/merge_requests/21"); + }), + ); + + it.effect( + "create_pr reads the base from the branch host when the primary has a different base", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const labDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "origin", "HEAD:main"]); + yield* runGit(repoDir, ["remote", "add", "lab", "https://gitlab.com/acme/repo.git"]); + yield* runGit(repoDir, ["config", "remote.lab.pushurl", labDir]); + yield* runGit(repoDir, ["update-ref", "refs/remotes/lab/develop", "HEAD"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/lab-base"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "lab.txt"), "lab\n"); + yield* runGit(repoDir, ["add", "lab.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Lab base"]); + yield* runGit(repoDir, ["push", "-u", "lab", "feature/lab-base"]); + + const gitlab = createFakeSourceControlProvider({ + kind: "gitlab", + defaultBranch: "develop", + prListSequence: [ + [], + [ + { + number: 8, + title: "Lab base", + url: "https://gitlab.com/acme/repo/-/merge_requests/8", + baseRefName: "develop", + headRefName: "feature/lab-base", + }, + ], + ], + }); + yield* runGit(repoDir, ["update-ref", "refs/remotes/origin/develop", "HEAD"]); + let commitSummary = ""; + const { manager } = yield* makeManager({ + remoteSourceControlProvider: gitlab.service, + textGeneration: { + generatePrContent: (input) => { + commitSummary = input.commitSummary; + return Effect.succeed({ title: "Lab base", body: "Lab changes" }); + }, + }, + }); + + const result = yield* runStackedAction(manager, { cwd: repoDir, action: "create_pr" }); + + expect(result.pr.status).toBe("created"); + expect(commitSummary).toContain("Lab base"); + expect(created(gitlab.calls).map((call) => call.baseRefName)).toEqual(["develop"]); + }), + ); + + it.effect("status finds the PR on the branch remote's host when both hosts are GitHub", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/status-mixed-github-hosts"]); + const remoteDir = yield* createBareRemote(); + const originUrl = "https://github.com/acme/repo.git"; + const originProvider = sourceControlDefinitions.recognizeRemote(originUrl); + if (!originProvider) throw new Error("github.com is not recognized"); + yield* runGit(repoDir, ["remote", "add", "origin", originUrl]); + yield* runGit(repoDir, ["remote", "add", "ghe", "https://acme.ghe.com/acme/repo.git"]); + yield* runGit(repoDir, ["config", "remote.ghe.pushurl", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "ghe", "feature/status-mixed-github-hosts"]); + + const enterprise = createFakeSourceControlProvider({ + prListSequence: [ + [ + { + number: 5, + title: "Enterprise host", + url: "https://acme.ghe.com/acme/repo/pull/5", + baseRefName: "main", + headRefName: "feature/status-mixed-github-hosts", + }, + ], + ], + }); + const { manager } = yield* makeManager({ + remoteSourceControlProvider: enterprise.service, + sourceControlContext: { + provider: originProvider, + remoteName: "origin", + remoteUrl: originUrl, + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + + expect(status.pr?.url).toBe("https://acme.ghe.com/acme/repo/pull/5"); + }), + ); + it.effect("status returns an explicit non-repo result for deleted directories", () => Effect.gen(function* () { const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-"); @@ -3857,6 +4021,49 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("commit_push_pr pushes to the chosen remote when none is named origin", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const forkDir = yield* createBareRemote(); + const upstreamDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "fork", forkDir]); + yield* runGit(repoDir, ["remote", "add", "upstream", upstreamDir]); + yield* runGit(repoDir, ["push", "upstream", "HEAD:main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/chosen-remote"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "chosen.txt"), "chosen\n"); + + const { manager } = yield* makeManager({ + providerScenario: { + prListSequence: [ + [], + [ + { + number: 61, + title: "Chosen remote", + url: "https://github.com/pingdotgg/codething-mvp/pull/61", + baseRefName: "main", + headRefName: "feature/chosen-remote", + }, + ], + ], + }, + }); + + const result = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit_push_pr", + pushRemote: "fork", + }); + + expect(result.push.status).toBe("pushed"); + expect(result.pr.status).toBe("created"); + expect( + (yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(), + ).toBe("fork/feature/chosen-remote"); + }), + ); + it.effect.each([ { localBranch: "develop" }, // Pushes to origin's develop under a name that differs from the base. diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 77acae07dee63..a08a2e6f488a3 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -738,6 +738,9 @@ function toPullRequestHeadRemoteInfo(pr: { }; } +const sameBaseUrlHost = (left: string, right: string) => + URL.canParse(left) && URL.canParse(right) && new URL(left).host === new URL(right).host; + export const make = Effect.gen(function* () { const gitCore = yield* GitVcsDriver.GitVcsDriver; const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry; @@ -759,6 +762,32 @@ export const make = Effect.gen(function* () { allowNonZeroExit: true, }) .pipe(Effect.map((result) => result.stdout.split("\n", 1)[0]?.trim() || null)); + // The checkout's provider follows origin, but a branch's change requests live on the host + // of the remote it was pushed to, which can differ when a repository mixes hosts. + const branchSourceControlProvider = Effect.fn("GitManager.branchSourceControlProvider")( + function* (cwd: string, remoteName: string | null) { + const fallback = yield* sourceControlProviders.resolveHandle({ cwd }); + const remoteUrl = remoteName + ? yield* readRemoteUrl(cwd, remoteName).pipe(Effect.orElseSucceed(() => null)) + : null; + const provider = remoteUrl ? sourceControlDefinitions.recognizeRemote(remoteUrl) : null; + if ( + !remoteName || + !remoteUrl || + !provider || + (provider.kind === fallback.provider.kind && + fallback.context !== null && + sameBaseUrlHost(provider.baseUrl, fallback.context.provider.baseUrl)) + ) { + return fallback.provider; + } + const handle = yield* sourceControlProviders.resolveHandle({ + cwd, + context: { provider, remoteName, remoteUrl }, + }); + return handle.provider; + }, + ); const changeRequestTermsFor = Effect.fn("GitManager.changeRequestTermsFor")(function* ( cwd: string, ) { @@ -838,8 +867,11 @@ export const make = Effect.gen(function* () { const pushCurrentBranch = Effect.fn("GitManager.pushCurrentBranch")(function* ( cwd: string, branch: string | null, + remoteName?: string, ) { - const result = yield* gitCore.pushCurrentBranch(cwd, branch); + const result = yield* gitCore.pushCurrentBranch(cwd, branch, { + remoteName: remoteName ?? null, + }); if (result.status === "pushed" && result.branch) { yield* shareBranchBase(cwd, result.branch); } @@ -1240,13 +1272,16 @@ export const make = Effect.gen(function* () { Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), ); const hostingProvider = details.isRepo - ? yield* resolveHostingProvider(cwd, details.branch) + ? yield* resolveHostingProvider(cwd, details.branch, details.pushRemote ?? null) : null; return { isRepo: details.isRepo, ...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}), hasPrimaryRemote: details.hasOriginRemote, + ...(details.remotes ? { remotes: details.remotes } : {}), + ...(details.pushRemote ? { pushRemote: details.pushRemote } : {}), + ...(details.pushRemoteChoices ? { pushRemoteChoices: details.pushRemoteChoices } : {}), isDefaultRef: details.isDefaultBranch, refName: details.branch, hasWorkingTreeChanges: details.hasWorkingTreeChanges, @@ -1607,11 +1642,13 @@ export const make = Effect.gen(function* () { const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* ( cwd: string, branch: string | null, + pushRemote: string | null, ) { const preferredRemoteName = - branch === null + pushRemote ?? + (branch === null ? "origin" - : ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? "origin"); + : ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? "origin")); const remoteUrl = (yield* readRemoteUrlNullable(cwd, preferredRemoteName)) ?? (yield* readRemoteUrlNullable(cwd, "origin")); @@ -2001,10 +2038,11 @@ export const make = Effect.gen(function* () { | "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin" | "isCrossRepository" + | "remoteName" >, ownerHeadSelector?: string, ) { - const provider = yield* sourceControlProvider(cwd); + const provider = yield* branchSourceControlProvider(cwd, headContext.remoteName); const probe = headBranchProbe(provider, headContext.headSelectors, "open", ownerHeadSelector); for (const headSelector of probe.headSelectors) { const pullRequests = yield* provider.listChangeRequests({ @@ -2037,7 +2075,7 @@ export const make = Effect.gen(function* () { ) { const parsedByNumber = new Map(); - const provider = yield* sourceControlProvider(cwd); + const provider = yield* branchSourceControlProvider(cwd, headContext.remoteName); const probe = headBranchProbe( provider, headContext.headSelectors, @@ -2220,7 +2258,10 @@ export const make = Effect.gen(function* () { } } - const defaultFromProvider = yield* sourceControlProvider(cwd).pipe( + const defaultFromProvider = yield* branchSourceControlProvider( + cwd, + headContext.remoteName, + ).pipe( Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })), Effect.orElseSucceed(() => null), ); @@ -2239,26 +2280,43 @@ export const make = Effect.gen(function* () { return { baseBranch: "main", baseRef: "main" }; }); + // Same-host forks target the primary repository; other hosts use their own base. const resolveBaseRangeRef = Effect.fn("resolveBaseRangeRef")(function* ( cwd: string, baseBranch: string, + branchRemoteName: string | null, ) { if (baseBranch.startsWith("refs/")) return baseBranch; - const remoteName = yield* gitCore + const primaryRemoteName = yield* gitCore .resolvePrimaryRemoteName(cwd) .pipe(Effect.orElseSucceed(() => null)); - if (!remoteName) return baseBranch; - - return yield* gitCore - .resolveRemoteTrackingCommit({ - cwd, - refName: baseBranch, - fallbackRemoteName: remoteName, - }) - .pipe( - Effect.map((resolved) => resolved.commitSha), - Effect.orElseSucceed(() => baseBranch), - ); + const primary = yield* sourceControlProviders.resolveHandle({ cwd }); + const branchUrl = branchRemoteName + ? yield* readRemoteUrl(cwd, branchRemoteName).pipe(Effect.orElseSucceed(() => null)) + : null; + const branchProvider = branchUrl ? sourceControlDefinitions.recognizeRemote(branchUrl) : null; + const preferBranchRemote = + branchProvider !== null && + (branchProvider.kind !== primary.provider.kind || + primary.context === null || + !sameBaseUrlHost(branchProvider.baseUrl, primary.context.provider.baseUrl)); + const remoteNames = [ + ...new Set( + preferBranchRemote + ? [branchRemoteName, primaryRemoteName] + : [primaryRemoteName, branchRemoteName], + ), + ].filter((remoteName) => remoteName !== null); + for (const remoteName of remoteNames) { + const commitSha = yield* gitCore + .resolveRemoteTrackingCommit({ cwd, refName: baseBranch, fallbackRemoteName: remoteName }) + .pipe( + Effect.map((resolved) => resolved.commitSha), + Effect.orElseSucceed(() => null), + ); + if (commitSha) return commitSha; + } + return baseBranch; }); const resolveCommitAndBranchSuggestion = Effect.fn("resolveCommitAndBranchSuggestion")( @@ -2435,8 +2493,9 @@ export const make = Effect.gen(function* () { cwd: string, status: { branch: string; upstreamRef: string | null; hasUpstream: boolean }, changeRequestLabel: string, + pushRemote: string | undefined, ) { - const target = yield* gitCore.resolvePushTarget(cwd, status); + const target = yield* gitCore.resolvePushTarget(cwd, { ...status, remoteName: pushRemote }); if (!target) return; const headContext = yield* resolveBranchHeadContext(cwd, { branch: status.branch, @@ -2470,10 +2529,9 @@ export const make = Effect.gen(function* () { readonly baseBranch: string; readonly baseRef: string; readonly headBranch: string; + readonly headRemoteName: string | null; }) => Effect.Effect<{ readonly title: string; readonly body: string }, E>, ) { - const provider = yield* sourceControlProvider(cwd); - const terms = sourceControlDefinitions.get(provider.kind).changeRequest; const details = yield* gitCore.statusDetails(cwd); const branch = details.branch ?? fallbackBranch; if (!branch) { @@ -2497,6 +2555,8 @@ export const make = Effect.gen(function* () { cwd, pushRemoteRef ? { branch, ...pushRemoteRef } : { branch, upstreamRef: details.upstreamRef }, ); + const provider = yield* branchSourceControlProvider(cwd, headContext.remoteName); + const terms = sourceControlDefinitions.get(provider.kind).changeRequest; const existing = yield* findOpenPr(cwd, headContext); if (existing) { @@ -2511,7 +2571,8 @@ export const make = Effect.gen(function* () { } // A PR opened from the remote branch would leave out commits not pushed yet. - if (details.aheadCount > 0) { + // With a push remote, ahead counts against the upstream, which the push does not move. + if (!pushRemoteRef && details.aheadCount > 0) { return yield* new GitManagerError({ operation: "runPrStep", cwd, @@ -2522,6 +2583,7 @@ export const make = Effect.gen(function* () { const baseBranch = requestedBase ?? resolved.baseBranch; const generated = yield* content({ provider, + headRemoteName: headContext.remoteName, baseBranch, baseRef: requestedBase ?? resolved.baseRef, headBranch: headContext.headBranch, @@ -2608,7 +2670,7 @@ export const make = Effect.gen(function* () { emit, pushRemoteRef, undefined, - ({ provider, baseBranch, baseRef, headBranch }) => + ({ provider, baseBranch, baseRef, headBranch, headRemoteName }) => Effect.gen(function* () { const terms = sourceControlDefinitions.get(provider.kind).changeRequest; yield* emit({ @@ -2616,7 +2678,7 @@ export const make = Effect.gen(function* () { phase: "pr", label: `Generating ${terms.shortLabel} content...`, }); - const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseRef); + const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseRef, headRemoteName); const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef); const policy = yield* resolveStylePolicy(cwd, settings); const changeRequestTemplate = @@ -3729,6 +3791,7 @@ export const make = Effect.gen(function* () { input.cwd, { ...initialStatus, branch: initialStatus.branch }, changeRequestTerms.shortLabelWithArticle, + input.pushRemote, ); } @@ -3759,7 +3822,7 @@ export const make = Effect.gen(function* () { }) .pipe( Effect.tap(() => Ref.set(currentPhase, Option.some("push"))), - Effect.flatMap(() => pushCurrentBranch(input.cwd, currentBranch)), + Effect.flatMap(() => pushCurrentBranch(input.cwd, currentBranch, input.pushRemote)), ) : { status: "skipped_not_requested" as const }; diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 287207840ad6a..998da812b178d 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -6,6 +6,7 @@ import * as FileSystem from "effect/FileSystem"; import { GitManagerError, GitCommandError, + type VcsSetPushRemoteInput, type VcsSwitchRefInput, type VcsSwitchRefResult, type VcsCreateRefInput, @@ -142,6 +143,7 @@ export class GitWorkflowService extends Context.Service< readonly switchRef: ( input: VcsSwitchRefInput, ) => Effect.Effect; + readonly setPushRemote: (input: VcsSetPushRemoteInput) => Effect.Effect; readonly renameBranch: (input: { readonly exactName?: boolean; readonly cwd: string; @@ -542,6 +544,11 @@ export const make = Effect.gen(function* () { ), ); }), + setPushRemote: Effect.fn("GitWorkflowService.setPushRemote")(function (input) { + return ensureGitCommand("GitWorkflowService.setPushRemote", input.cwd).pipe( + Effect.andThen(git.setPushRemote(input)), + ); + }), renameBranch: Effect.fn("GitWorkflowService.renameBranch")(function (input) { return ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe( Effect.andThen(git.renameBranch(input)), diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index a2b698657afcb..87cd6fdd3d3d6 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -210,6 +210,7 @@ const RPC_AGGREGATES = { [WS_METHODS.vcsRemoveWorktree]: "vcs", [WS_METHODS.vcsCreateRef]: "vcs", [WS_METHODS.vcsSwitchRef]: "vcs", + [WS_METHODS.vcsSetPushRemote]: "vcs", [WS_METHODS.vcsInit]: "vcs", [WS_METHODS.reviewGetBranchCommits]: "review", [WS_METHODS.reviewGetDiffPreview]: "review", diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 22e19fc03ab99..95c06c4cd2229 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -17,6 +17,7 @@ import { VcsCheckpointStorageError, VcsProcessExitError, VcsUnsupportedOperationError, + type VcsSetPushRemoteInput, type VcsSwitchRefInput, type VcsSwitchRefResult, type VcsCreateRefInput, @@ -80,6 +81,9 @@ export interface GitStatusDetails { isRepo: boolean; sourceControlProvider?: VcsStatusResult["sourceControlProvider"]; hasOriginRemote: boolean; + remotes?: VcsStatusResult["remotes"]; + pushRemote?: VcsStatusResult["pushRemote"]; + pushRemoteChoices?: VcsStatusResult["pushRemoteChoices"]; isDefaultBranch: boolean; branch: string | null; upstreamRef: string | null; @@ -360,7 +364,11 @@ export class GitVcsDriver extends Context.Service< /** Where `pushCurrentBranch` would push the checked-out branch; null with no remote or when Git picks. */ readonly resolvePushTarget: ( cwd: string, - current: { readonly branch: string; readonly hasUpstream: boolean }, + current: { + readonly branch: string; + readonly hasUpstream: boolean; + readonly remoteName?: string | undefined; + }, ) => Effect.Effect; readonly readRangeContext: ( cwd: string, @@ -471,6 +479,7 @@ export class GitVcsDriver extends Context.Service< readonly switchRef: ( input: VcsSwitchRefInput, ) => Effect.Effect; + readonly setPushRemote: (input: VcsSetPushRemoteInput) => Effect.Effect; readonly initRepo: (input: VcsInitInput) => Effect.Effect; /** Drops cached refs after something outside this driver changed them, such as a clone into `cwd`. */ readonly invalidateRefs: (cwd: string) => Effect.Effect; diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 8e07c0ff98c07..0e0b8af3d3e5f 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -413,6 +413,25 @@ const commitInitialRepo = (cwd: string, initArgs: ReadonlyArray = []) => yield* git(cwd, ["commit", "-m", "initial commit"]); }); +/** Remotes `fork` and `upstream` (holding the initial branch), no origin, on `feature/remote`. */ +const makeForkWorkflowRepo = Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const cwd = yield* makeTmpDir(); + const forkRemote = yield* makeTmpDir("git-remote-"); + const upstreamRemote = yield* makeTmpDir("git-remote-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(forkRemote, ["init", "--bare"]); + yield* git(upstreamRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "fork", forkRemote]); + yield* git(cwd, ["remote", "add", "upstream", upstreamRemote]); + yield* git(cwd, ["push", "upstream", initialBranch]); + yield* git(cwd, ["checkout", "-b", "feature/remote"]); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add feature", ""); + return { cwd, initialBranch }; +}); + // Most tests start from the same one-commit repository; they copy it instead of spawning git. let repoTemplate: string | undefined; afterAll(() => { @@ -9707,11 +9726,120 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect.each(["branch.topic.pushRemote", "remote.pushDefault"] as const)( + it.effect("asks which remote to push to when several remotes have no origin", () => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const { cwd } = yield* makeForkWorkflowRepo; + // A push remote that was since removed is no choice at all. + yield* git(cwd, ["config", "branch.feature/remote.pushRemote", "removed"]); + + const status = yield* driver.statusDetailsLocal(cwd); + assert.deepEqual(status.pushRemoteChoices, ["fork", "upstream"]); + assert.isUndefined(status.pushRemote); + const refused = yield* driver.pushCurrentBranch(cwd, null).pipe(Effect.flip); + assert.include(refused.message, "Choose which remote"); + + // A push re-reads the cached remotes, so the configured default shows up after it. + yield* git(cwd, ["config", "remote.pushDefault", "fork"]); + yield* driver.pushCurrentBranch(cwd, null, { remoteName: "upstream" }); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), + "upstream/feature/remote", + ); + assert.isUndefined((yield* driver.statusDetailsLocal(cwd)).pushRemoteChoices); + }), + ); + + it.effect("asks for a push remote while the upstream is only the branch's base", () => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const { cwd, initialBranch } = yield* makeForkWorkflowRepo; + yield* git(cwd, ["branch", "--set-upstream-to", `upstream/${initialBranch}`]); + + const status = yield* driver.statusDetailsLocal(cwd); + assert.isTrue(status.hasUpstream); + assert.isUndefined(status.pushRemote); + const refused = yield* driver.pushCurrentBranch(cwd, null).pipe(Effect.flip); + assert.include(refused.message, "Choose which remote"); + const unknown = yield* driver + .pushCurrentBranch(cwd, null, { remoteName: cwd }) + .pipe(Effect.flip); + assert.include(unknown.message, "does not exist"); + + yield* driver.pushCurrentBranch(cwd, null, { remoteName: "fork" }); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), + "fork/feature/remote", + ); + assert.equal( + yield* git(cwd, ["config", "branch.feature/remote.t3-merge-base-ref"]), + `refs/remotes/upstream/${initialBranch}`, + ); + }), + ); + + it.effect("selecting a push remote keeps the branch's tracking", () => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const { cwd } = yield* makeForkWorkflowRepo; + const refName = "feature/remote"; + + const unset = yield* driver.statusDetailsLocal(cwd); + assert.deepEqual(unset.remotes, ["fork", "upstream"]); + assert.isUndefined(unset.pushRemote); + + yield* driver.setPushRemote({ cwd, refName, remoteName: "fork" }); + assert.equal((yield* driver.statusDetailsLocal(cwd)).pushRemote, "fork"); + yield* driver.pushCurrentBranch(cwd, null); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), + `fork/${refName}`, + ); + + // A fork workflow pulls from `upstream` and pushes to `fork`; picking a remote keeps that. + yield* git(cwd, ["push", "upstream", refName]); + yield* git(cwd, ["branch", `--set-upstream-to=upstream/${refName}`]); + yield* driver.setPushRemote({ cwd, refName, remoteName: "fork" }); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), + `upstream/${refName}`, + ); + yield* writeTextFile(cwd, "fork.txt", "fork\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add fork update", ""); + assert.deepInclude(yield* driver.pushCurrentBranch(cwd, null), { + status: "pushed", + upstreamBranch: `fork/${refName}`, + pushRemote: "fork", + setUpstream: false, + }); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), + `upstream/${refName}`, + ); + + const unknown = yield* driver + .setPushRemote({ cwd, refName, remoteName: "missing" }) + .pipe(Effect.flip); + assert.include(unknown.message, "missing"); + const unknownBranch = yield* driver + .setPushRemote({ cwd, refName: "feature/renamed", remoteName: "fork" }) + .pipe(Effect.flip); + assert.include(unknownBranch.message, "does not exist"); + assert.equal( + yield* git(cwd, ["config", "--get-regexp", "^branch\\.feature/renamed\\."]).pipe( + Effect.orElseSucceed(() => ""), + ), + "", + ); + }), + ); + + it.effect.each(["branch.topic.pushRemote", "remote.pushDefault", "worktree"] as const)( "pushes a branch tracking its upstream head to the %s remote", (configKey) => Effect.gen(function* () { - const cwd = yield* makeTmpDir(); + let cwd = yield* makeTmpDir(); const upstreamRemote = yield* makeTmpDir("git-upstream-remote-"); const forkRemote = yield* makeTmpDir("git-fork-remote-"); yield* initRepoWithCommit(cwd); @@ -9724,7 +9852,17 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(cwd, ["push", "upstream", "topic"]); yield* git(cwd, ["push", "fork", "topic"]); yield* git(cwd, ["branch", "--set-upstream-to=upstream/topic"]); - yield* git(cwd, ["config", configKey, "fork"]); + if (configKey === "worktree") { + yield* git(cwd, ["config", "extensions.worktreeConfig", "true"]); + yield* git(cwd, ["config", "remote.pushDefault", "upstream"]); + const worktreeCwd = yield* makeTmpDir(); + yield* git(cwd, ["worktree", "add", "--force", worktreeCwd, "topic"]); + cwd = worktreeCwd; + yield* git(cwd, ["config", "--worktree", "remote.pushDefault", "fork"]); + } else { + yield* git(cwd, ["config", configKey, "fork"]); + } + assert.equal((yield* driver.statusDetailsLocal(cwd)).pushRemote, "fork"); const upstreamTopicSha = yield* git(cwd, ["rev-parse", "HEAD"]); yield* writeTextFile(cwd, "fork.txt", "fork\n"); yield* git(cwd, ["add", "-A"]); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 7fb1e77373796..67c39c692ccef 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -136,7 +136,7 @@ const LIST_REFS_SNAPSHOT_CACHE_TTL = Duration.minutes(2); const LIST_REFS_REFRESH_COALESCE_TTL = Duration.seconds(5); const LIST_REFS_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30); const STATUS_DEFAULT_BRANCH_CACHE_TTL = Duration.minutes(5); -const STATUS_ORIGIN_EXISTS_CACHE_TTL = Duration.minutes(5); +const STATUS_REMOTES_CACHE_TTL = Duration.minutes(5); const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({ GCM_INTERACTIVE: "never", GIT_ASKPASS: "", @@ -458,6 +458,8 @@ function parseUpstreamRefByFirstSeparator( }; } +// Differently named upstreams are bases, not publish targets: pushing HEAD there would write +// features to shared branches. function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null { for (const line of stdout.split("\n")) { const trimmedLine = line.trim(); @@ -1692,23 +1694,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }), }, ); - const primaryRemoteExistsCache = yield* Cache.makeWith( + const readStatusRemotes = (cwd: string, gitArgs: ReadonlyArray = []) => + executeGit("GitVcsDriver.statusDetails.remotes", cwd, [...gitArgs, "remote"], { + allowNonZeroExit: true, + }).pipe( + Effect.map((remotes) => { + const names = remotes.exitCode === 0 ? parseRemoteNamesInGitOrder(remotes.stdout) : []; + return { hasRemote: names.length > 0, ...(names.length > 1 ? { names } : {}) }; + }), + ); + const NO_STATUS_REMOTES: { hasRemote: boolean; names?: ReadonlyArray } = { + hasRemote: false, + }; + const remotesCache = yield* Cache.makeWith( (gitCommonDir: string) => Effect.gen(function* () { const path = yield* Path.Path; const fetchCwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; - return yield* executeGit( - "GitVcsDriver.statusDetails.primaryRemoteExists", - fetchCwd, - ["--git-dir", gitCommonDir, "remote"], - { allowNonZeroExit: true }, - ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim().length > 0)); + return yield* readStatusRemotes(fetchCwd, ["--git-dir", gitCommonDir]); }), { capacity: 2_048, timeToLive: Exit.match({ - onSuccess: () => STATUS_ORIGIN_EXISTS_CACHE_TTL, + onSuccess: () => STATUS_REMOTES_CACHE_TTL, onFailure: () => Duration.zero, }), }, @@ -1723,7 +1732,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : gitCommonDir; const cacheKey = commonDir ?? normalizeRepositoryPathsCacheKey(cwd); yield* Cache.invalidate(defaultBranchCache, cacheKey); - yield* Cache.invalidate(primaryRemoteExistsCache, cacheKey); + yield* Cache.invalidate(remotesCache, cacheKey); }, ); @@ -1967,13 +1976,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd: string, refName: string, ) { + // A configured remote that was since removed or renamed is ignored, as status ignores it. + const remoteNames: ReadonlyArray = yield* listRemoteNames(cwd).pipe( + Effect.orElseSucceed(() => []), + ); const branchPushRemote = yield* runGitStdout( "GitVcsDriver.resolvePushRemoteName.branchPushRemote", cwd, ["config", "--get", `branch.${refName}.pushRemote`], true, ).pipe(Effect.map((stdout) => stdout.trim())); - if (branchPushRemote.length > 0) { + if (remoteNames.includes(branchPushRemote)) { return branchPushRemote; } @@ -1983,7 +1996,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["config", "--get", "remote.pushDefault"], true, ).pipe(Effect.map((stdout) => stdout.trim())); - return pushDefaultRemote.length > 0 ? pushDefaultRemote : null; + return remoteNames.includes(pushDefaultRemote) ? pushDefaultRemote : null; }); const resolvePushRemoteName = Effect.fn("resolvePushRemoteName")(function* ( @@ -2000,9 +2013,73 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return fallbackRemoteName; } + // With several remotes and no `origin`, the first remote is a guess: clients ask the + // user (`pushRemoteChoices`) and pass the pick as `remoteName` instead. + const remoteNames: ReadonlyArray = yield* listRemoteNames(cwd).pipe( + Effect.orElseSucceed(() => []), + ); + if (remoteNames.length > 1 && !remoteNames.includes("origin")) { + return yield* new GitCommandError({ + ...gitCommandContext({ + operation: "GitVcsDriver.resolvePushRemoteName", + cwd, + args: ["push"], + }), + detail: "Choose which remote to push this branch to.", + }); + } return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.orElseSucceed(() => null)); }); + // Publishing retargets the upstream, so a branch tracking its base keeps that base first. + const preserveUpstreamAsBase = Effect.fn("preserveUpstreamAsBase")(function* ( + cwd: string, + branch: string, + upstream: { remoteName: string; upstreamRef: string; branchName: string }, + ) { + if ((yield* readBranchBase(cwd, branch)) !== null) return; + yield* writeConfigValue({ cwd, key: branchBaseConfigKey(branch), value: upstream.branchName }); + if (!(yield* readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`))) { + yield* writeConfigValue({ + cwd, + key: `branch.${branch}.t3-merge-base-ref`, + value: + upstream.remoteName === "." + ? `refs/heads/${upstream.branchName}` + : `refs/remotes/${upstream.upstreamRef}`, + }); + } + }); + + // Mirrors where `pushCurrentBranch` sends this branch; undefined while the choice is unclear. + const resolveStatusPushRemote = Effect.fn("resolveStatusPushRemote")(function* ( + cwd: string, + refName: string, + upstreamRef: string | null, + remoteNames: ReadonlyArray, + defaultPushRemote: string | undefined, + ) { + const upstream = upstreamRef + ? (parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ?? + parseUpstreamRefByFirstSeparator(upstreamRef)) + : null; + const branchPushRemote = yield* runGitStdout( + "GitVcsDriver.statusDetails.branchPushRemote", + cwd, + ["config", "--get", `branch.${refName}.pushRemote`], + true, + ).pipe( + Effect.map((stdout) => stdout.trim()), + Effect.orElseSucceed(() => ""), + ); + const configuredPushRemote = + (remoteNames.includes(branchPushRemote) ? branchPushRemote : undefined) ?? defaultPushRemote; + if (upstream && isAliasOfUpstreamHead(refName, upstream.branchName, upstream.upstreamRef)) { + return configuredPushRemote ?? upstream.remoteName; + } + return configuredPushRemote ?? (remoteNames.includes("origin") ? "origin" : undefined); + }); + const remoteRefContainsHead = (cwd: string, remoteRef: string) => executeGit( "GitVcsDriver.pushCurrentBranch.publishContainsHead", @@ -2472,7 +2549,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, ); // diff-index does not read status output, so both spawn together; a non-repository discards it. - const [statusResult, numstatResult, defaultBranch, hasPrimaryRemote] = yield* Effect.all( + const [statusResult, numstatResult, defaultBranch, remotes] = yield* Effect.all( [ readStatus, readNumstat("HEAD").pipe( @@ -2502,13 +2579,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? Cache.get(defaultBranchCache, statusCacheKey).pipe(Effect.orElseSucceed(() => null)) : resolvePrimaryDefaultBranchName(cwd).pipe(Effect.orElseSucceed(() => null)), statusCacheKey - ? Cache.get(primaryRemoteExistsCache, statusCacheKey).pipe( - Effect.orElseSucceed(() => false), + ? Cache.get(remotesCache, statusCacheKey).pipe( + Effect.orElseSucceed(() => NO_STATUS_REMOTES), ) - : listRemoteNames(cwd).pipe( - Effect.map((remoteNames) => remoteNames.length > 0), - Effect.orElseSucceed(() => false), - ), + : readStatusRemotes(cwd).pipe(Effect.orElseSucceed(() => NO_STATUS_REMOTES)), ], { concurrency: "unbounded" }, ); @@ -2676,9 +2750,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } files.sort((a, b) => a.path.localeCompare(b.path)); + const configuredPushDefault = remotes.names + ? yield* readConfigValue(cwd, "remote.pushDefault") + : null; + const defaultPushRemote = + configuredPushDefault !== null && remotes.names?.includes(configuredPushDefault) + ? configuredPushDefault + : undefined; + const pushRemoteChoices = + remotes.names && !remotes.names.includes("origin") && defaultPushRemote === undefined + ? remotes.names + : undefined; + const pushRemote = + remotes.names && refName + ? yield* resolveStatusPushRemote( + cwd, + refName, + upstreamRef, + remotes.names, + defaultPushRemote, + ) + : null; + return { isRepo: true, - hasOriginRemote: hasPrimaryRemote, + hasOriginRemote: remotes.hasRemote, + ...(remotes.names ? { remotes: remotes.names } : {}), + ...(pushRemote ? { pushRemote } : {}), + ...(pushRemoteChoices ? { pushRemoteChoices } : {}), isDefaultBranch, branch: refName, upstreamRef, @@ -2735,6 +2834,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((details) => ({ isRepo: details.isRepo, hasPrimaryRemote: details.hasOriginRemote, + ...(details.remotes ? { remotes: details.remotes } : {}), + ...(details.pushRemote ? { pushRemote: details.pushRemote } : {}), + ...(details.pushRemoteChoices ? { pushRemoteChoices: details.pushRemoteChoices } : {}), isDefaultRef: details.isDefaultBranch, refName: details.branch, hasWorkingTreeChanges: details.hasWorkingTreeChanges, @@ -3198,6 +3300,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), ); + // Clients send remote names; git would also accept a URL or path as a push target. + const requireRemote = Effect.fn("GitVcsDriver.requireRemote")(function* ( + cwd: string, + remoteName: string, + operation: string, + args: ReadonlyArray, + ) { + const remoteNames = yield* listRemoteNames(cwd); + if (!remoteNames.includes(remoteName)) { + return yield* new GitCommandError({ + ...gitCommandContext({ operation, cwd, args: [...args] }), + detail: `Remote '${remoteName}' does not exist.`, + }); + } + return remoteNames; + }); + // `publishes` is false only when HEAD goes to the head of its current `upstream`. const resolvePushDestination = Effect.fn("resolvePushDestination")(function* ( cwd: string, @@ -3279,9 +3398,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* pushRemote, }; } - const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( - Effect.orElseSucceed(() => null), - ); + const publishRemoteName = yield* resolvePushRemoteName(cwd, branch); const branchName = yield* resolvePublishBranchName(cwd, branch); return { remoteName: publishRemoteName ?? upstream.remoteName, @@ -3295,6 +3412,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const resolvePushTarget: GitVcsDriver.GitVcsDriver["Service"]["resolvePushTarget"] = Effect.fn( "resolvePushTarget", )(function* (cwd, current) { + const requestedRemoteName = current.remoteName?.trim(); + if (requestedRemoteName) { + return { + remoteName: requestedRemoteName, + branchName: yield* resolvePublishBranchName(cwd, current.branch), + viaPushRemote: false, + }; + } const destination = yield* resolvePushDestination(cwd, current.branch, current.hasUpstream); return destination ? { @@ -3305,6 +3430,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : null; }); + const setPushRemote: GitVcsDriver.GitVcsDriver["Service"]["setPushRemote"] = Effect.fn( + "setPushRemote", + )(function* ({ cwd, refName, remoteName }) { + yield* requireRemote(cwd, remoteName, "GitVcsDriver.setPushRemote", ["config"]); + const branchExists = yield* executeGit( + "GitVcsDriver.setPushRemote.branchExists", + cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${refName}`], + { allowNonZeroExit: true }, + ).pipe(Effect.map((result) => result.exitCode === 0)); + if (!branchExists) { + return yield* new GitCommandError({ + ...gitCommandContext({ operation: "GitVcsDriver.setPushRemote", cwd, args: ["config"] }), + detail: `Branch '${refName}' does not exist.`, + }); + } + // Tracking stays put: pushes follow `pushRemote`, and a fork branch keeps pulling from its upstream. + yield* writeConfigValue({ cwd, key: `branch.${refName}.pushRemote`, value: remoteName }); + }); + const pushCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pushCurrentBranch"] = Effect.fn( "pushCurrentBranch", )(function* (cwd, fallbackBranch, options) { @@ -3323,7 +3468,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const requestedRemoteName = options?.remoteName?.trim() || null; if (requestedRemoteName) { + yield* requireRemote(cwd, requestedRemoteName, "GitVcsDriver.pushCurrentBranch", ["push"]); const publishBranch = yield* resolvePublishBranchName(cwd, branch); + const currentUpstream = details.hasUpstream + ? yield* resolveCurrentUpstream(cwd).pipe(Effect.orElseSucceed(() => null)) + : null; + if ( + currentUpstream && + !isAliasOfUpstreamHead(branch, currentUpstream.branchName, currentUpstream.upstreamRef) + ) { + yield* preserveUpstreamAsBase(cwd, branch, currentUpstream); + } yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, @@ -3417,24 +3572,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (destination?.publishes) { const { remoteName, branchName: publishBranch, upstream } = destination; - // Publishing retargets the upstream, so preserve its comparison base first. - if (upstream && (yield* readBranchBase(cwd, branch)) === null) { - yield* writeConfigValue({ - cwd, - key: branchBaseConfigKey(branch), - value: upstream.branchName, - }); - if (!(yield* readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`))) { - yield* writeConfigValue({ - cwd, - key: `branch.${branch}.t3-merge-base-ref`, - value: - upstream.remoteName === "." - ? `refs/heads/${upstream.branchName}` - : `refs/remotes/${upstream.upstreamRef}`, - }); - } - } + if (upstream) yield* preserveUpstreamAsBase(cwd, branch, upstream); yield* executeGitWithStableDiagnostics( upstream ? "GitVcsDriver.pushCurrentBranch.pushOwnBranch" @@ -6431,6 +6569,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* withListRefsInvalidation(input.cwd, createBranch(input)); }), writeConfigValue, + setPushRemote: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, setPushRemote(input)); + }), removeWorktree: Effect.fnUntraced(function* (input) { return yield* withListRefsInvalidation(input.cwd, removeWorktree(input)); }), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 63d45c48816e4..ee1580bfd786f 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3235,6 +3235,8 @@ export const layerWsRpc = ( gitWorkflow .switchRef(input) .pipe(Effect.tap(() => vcsStatusBroadcaster.refreshAfterCheckout(input.cwd))), + [WS_METHODS.vcsSetPushRemote]: (input) => + gitWorkflow.setPushRemote(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.vcsInit]: (input) => vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.reviewGetBranchCommits]: (input) => review.getBranchCommits(input), diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index db8a3cc3bc71b..c47ccaf837b23 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -8,6 +8,7 @@ import * as Schema from "effect/Schema"; import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; import { readLocalApi } from "../localApi"; import { stackedThreadToast, toastManager } from "./ui/toast"; +import { BranchToolbarRemoteSelector } from "./BranchToolbarRemoteSelector"; import { ComposerContextLabel } from "./ComposerContextLabel"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; @@ -657,6 +658,8 @@ export const BranchToolbar = memo(function BranchToolbar({ const activeWorktreePath = forceNewWorktree ? null : worktreePath; const effectiveEnvMode = forceNewWorktree ? "worktree" : envMode; const envModeLocked = envLocked || (isServerThread && activeWorktreePath !== null); + // The branch a new worktree will get does not exist yet, so it has no remote to select. + const startsInNewWorktree = effectiveEnvMode === "worktree" && activeWorktreePath === null; const canUsePreviousWorktree = !isServerThread && !envModeLocked && !forceNewWorktree; const projectRefsForWorktreeLookup = canUsePreviousWorktree ? [activeProjectRef] : []; @@ -761,6 +764,13 @@ export const BranchToolbar = memo(function BranchToolbar({ {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})} /> ) : null} + {panelSection !== "workspace" && !startsInNewWorktree ? ( + + ) : null} ); } @@ -856,6 +866,12 @@ export const BranchToolbar = memo(function BranchToolbar({ {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})} /> ) : null} + {showGitControls && !startsInNewWorktree ? ( + + ) : null} {trailing} ); diff --git a/apps/web/src/components/BranchToolbarRemoteSelector.tsx b/apps/web/src/components/BranchToolbarRemoteSelector.tsx new file mode 100644 index 0000000000000..d6ab72cbd9da9 --- /dev/null +++ b/apps/web/src/components/BranchToolbarRemoteSelector.tsx @@ -0,0 +1,107 @@ +import { T, useGT } from "gt-react"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { AuthSourceControlWriteScope, type EnvironmentId } from "@t3tools/contracts"; +import { CloudIcon } from "lucide-react"; + +import { cn } from "../lib/utils"; +import { useEnvironmentQuery } from "../state/query"; +import { useEnvironmentScope } from "../state/session"; +import { useAtomCommand } from "../state/use-atom-command"; +import { vcsEnvironment } from "../state/vcs"; +import { ComposerControl } from "./chat/ComposerControl"; +import { useComposerMenuProps } from "./chat/composerEventScope"; +import { ThreadDetailsControl } from "./chat/ThreadDetailsControl"; +import { THREAD_DETAILS_PANEL_ICON_CLASS } from "./chat/threadDetailsPanelStyles"; +import { ComposerContextLabel } from "./ComposerContextLabel"; +import { + Menu, + MenuGroup, + MenuGroupLabel, + MenuPopup, + MenuRadioGroup, + MenuRadioItem, + MenuTrigger, +} from "./ui/menu"; +import { stackedThreadToast, toastManager } from "./ui/toast"; + +export function BranchToolbarRemoteSelector({ + cwd, + displayMode = "toolbar", + environmentId, +}: { + cwd: string; + displayMode?: "toolbar" | "panel"; + environmentId: EnvironmentId; +}) { + const gt = useGT(); + const isPanel = displayMode === "panel"; + const composerFloatingLayerProps = useComposerMenuProps(); + const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope); + const statusQuery = useEnvironmentQuery(vcsEnvironment.status({ environmentId, input: { cwd } })); + const setPushRemote = useAtomCommand(vcsEnvironment.setPushRemote, { reportFailure: false }); + + const { remotes, pushRemote, refName } = statusQuery.data ?? {}; + if (!remotes || !refName) return null; + + const selectRemote = async (remoteName: string) => { + if (remoteName === pushRemote) return; + const result = await setPushRemote({ + environmentId, + input: { cwd, refName, remoteName }, + }); + if (result._tag === "Success") { + statusQuery.refresh(); + } else if (!isAtomCommandInterrupted(result)) { + const cause = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: gt("Failed to change push remote."), + description: cause instanceof Error ? cause.message : gt("An error occurred."), + }), + ); + } + }; + + return ( + + : } + className={isPanel ? undefined : "min-w-0 flex-initial"} + disabled={!canWriteSourceControl} + aria-label={gt("Push remote: {remote}", { remote: pushRemote ?? gt("not chosen") })} + data-composer-context-control + > + + + {pushRemote ?? gt("Choose remote")} + + + + + + Push to + + void selectRemote(remoteName)} + > + {remotes.map((remoteName) => ( + + {remoteName} + + ))} + + + + + ); +} diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 897feb60e1e56..bac6e07b95c22 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -84,6 +84,13 @@ import { } from "~/components/ui/dialog"; import { Input } from "~/components/ui/input"; import { Menu, MenuItem, MenuItemLabel, MenuPopup, MenuTrigger } from "~/components/ui/menu"; +import { + Select, + SelectItem, + SelectPopup, + SelectTrigger, + SelectValue, +} from "~/components/ui/select"; import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; import { ScrollArea } from "~/components/ui/scroll-area"; import { Textarea } from "~/components/ui/textarea"; @@ -133,6 +140,7 @@ import { import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { scopeProjectRef } from "@t3tools/client-runtime/environment"; import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; +import { pushRemoteChoicesFor } from "@t3tools/client-runtime/state/vcs"; import { ChangeBreakdownGrid } from "./pullRequest/ChangeBreakdownGrid"; import { useOpenLink } from "~/browser/useOpenLink"; @@ -164,6 +172,7 @@ interface RunGitActionWithToastInput { statusOverride?: VcsStatusResult | null; featureBranch?: boolean; filePaths?: string[]; + pushRemote?: string; } interface InlineGitActionSuccess { @@ -962,6 +971,74 @@ export function PublishRepositoryDialog(props: PublishRepositoryDialogProps) { ); } +function PushRemoteDialog({ + choices, + canPush, + onClose, + onPush, +}: { + choices: ReadonlyArray | null; + canPush: boolean; + onClose: () => void; + onPush: (remoteName: string) => void; +}) { + const gt = useGT(); + const [remoteName, setRemoteName] = useState(null); + return ( + { + if (!open) onClose(); + }} + onOpenChangeComplete={(open) => { + if (!open) setRemoteName(null); + }} + > + + + + Push to which remote? + + + + This repository has several remotes and the branch has none chosen yet. It will track + the one you pick. + + + + + + + + + + + + + ); +} + export default function GitActionsControl({ gitCwd, activeThreadRef, @@ -1017,6 +1094,10 @@ export default function GitActionsControl({ const [inlineSuccess, setInlineSuccess] = useState(null); const [pendingDefaultBranchAction, setPendingDefaultBranchAction] = useState(null); + const [pendingPushRemoteAction, setPendingPushRemoteAction] = useState<{ + input: RunGitActionWithToastInput; + choices: ReadonlyArray; + } | null>(null); const sourceControlScope = { environmentId: activeEnvironmentId, cwd: gitCwd }; const vcsActionState = useAtomValue(vcsActionManager.stateAtom(sourceControlScope)); const inlineSuccessExpired = useDeadlinePassed(inlineSuccess?.expiresAtMs ?? null); @@ -1258,15 +1339,17 @@ export default function GitActionsControl({ ), ); - async function runGitActionWithToast({ - action, - commitMessage, - onConfirmed, - skipDefaultBranchPrompt = false, - statusOverride, - featureBranch = false, - filePaths, - }: RunGitActionWithToastInput) { + async function runGitActionWithToast(input: RunGitActionWithToastInput) { + const { + action, + commitMessage, + onConfirmed, + skipDefaultBranchPrompt = false, + statusOverride, + featureBranch = false, + filePaths, + pushRemote, + } = input; if ( activeEnvironmentId === null || !readEnvironmentScope(activeEnvironmentId, AuthSourceControlWriteScope) || @@ -1306,6 +1389,17 @@ export default function GitActionsControl({ }); return false; } + const pushRemoteChoices = pushRemoteChoicesFor( + { action, featureBranch, ...(pushRemote ? { pushRemote } : {}) }, + actionStatus ?? null, + ); + if (pushRemoteChoices) { + setPendingPushRemoteAction({ + input, + choices: pushRemoteChoices, + }); + return false; + } onConfirmed?.(); setInlineSuccess(null); @@ -1318,6 +1412,7 @@ export default function GitActionsControl({ ...(commitMessage ? { commitMessage } : {}), ...(featureBranch ? { featureBranch } : {}), ...(filePaths ? { filePaths } : {}), + ...(pushRemote ? { pushRemote } : {}), ...(activeServerThread ? { threadId: activeServerThread.id } : {}), ...(activeDraftThread ? { projectId: activeDraftThread.projectId } : {}), }); @@ -2106,6 +2201,18 @@ export default function GitActionsControl({ + + setPendingPushRemoteAction(null)} + onPush={(remoteName) => { + if (!pendingPushRemoteAction) return; + const { input } = pendingPushRemoteAction; + setPendingPushRemoteAction(null); + void runGitActionWithToast({ ...input, pushRemote: remoteName }); + }} + /> ); } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 46df7424ab0f2..91e00f4ec7134 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -1621,6 +1621,11 @@ ], "b77a2b4d9abda043": "Arbeitsbereich", "656e5640ed1b3e70": "Zu einem anderen Rechner hinzufügen", + "5f73e41e553c9a44": "Push-Remote konnte nicht geändert werden.", + "f1f79cc2176e78cf": "Push-Remote: {remote}", + "51cedd4eb8107a17": "nicht ausgewählt", + "5acc37f1d6e38012": "Remote auswählen", + "0a4603a2b21d2f44": "Push an", "3b4ca180fef92e21": "Erkenntnis", "cc8cdd1ece34cd75": "Hinweis", "19842b180a7e5a5f": "Tipp", @@ -2035,6 +2040,8 @@ "7b8eb81b6939c838": "Repository erstellt", "a16a5023fd3f7020": "{branch} ist jetzt auf {provider} verfügbar.", "b07e34ff280d5839": "Das Remote „{remote}“ ist eingerichtet. Erstelle einen Commit und pushe ihn, um deinen Code zu teilen.", + "5e8b5f680d43ceb4": "Remote", + "471f6cca2b22396e": "Remote auswählen", "8ea2c383ec1d8fc6": "vs. {ref}", "79394c44f351f604": "Diese Verbindung kann die Versionskontrolle nicht ändern.", "ff07cd3aef5acd21": "Diese Aktion ist derzeit nicht verfügbar.", @@ -2088,6 +2095,9 @@ "77b5f98f1f9a4ca7": "Weiter", "5148c9a30e4a5260": "Wird veröffentlicht...", "59bb4331e9a8536d": "Veröffentlichen", + "1bfda67456c96c4d": "An welches Remote pushen?", + "938cb93ed8cc07be": "Dieses Repository hat mehrere Remotes und für diesen Branch wurde noch keines ausgewählt. Er wird das ausgewählte Remote verfolgen.", + "e997516a93d245d7": "Push", "f22254f79a6d8ae3": "Repository veröffentlichen...", "895e269833827873": "Hinter dem Upstream. Zuerst pullen/rebasen.", "f1f3d81d2a97f0ed": "Wird initialisiert...", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e051..c78754f60746e 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -1622,6 +1622,11 @@ ], "b77a2b4d9abda043": "Workspace", "656e5640ed1b3e70": "Add to another machine", + "5f73e41e553c9a44": "Failed to change push remote.", + "f1f79cc2176e78cf": "Push remote: {remote}", + "51cedd4eb8107a17": "not chosen", + "5acc37f1d6e38012": "Choose remote", + "0a4603a2b21d2f44": "Push to", "3b4ca180fef92e21": "Insight", "cc8cdd1ece34cd75": "Note", "19842b180a7e5a5f": "Tip", @@ -2036,6 +2041,8 @@ "7b8eb81b6939c838": "Repository created", "a16a5023fd3f7020": "{branch} is now live on {provider}.", "b07e34ff280d5839": "Remote \"{remote}\" is set up. Make a commit and push it to share your code.", + "5e8b5f680d43ceb4": "Remote", + "471f6cca2b22396e": "Choose a remote", "8ea2c383ec1d8fc6": "vs {ref}", "79394c44f351f604": "This connection cannot change source control.", "ff07cd3aef5acd21": "This action is currently unavailable.", @@ -2088,6 +2095,9 @@ "77b5f98f1f9a4ca7": "Next", "5148c9a30e4a5260": "Publishing...", "59bb4331e9a8536d": "Publish", + "1bfda67456c96c4d": "Push to which remote?", + "938cb93ed8cc07be": "This repository has several remotes and the branch has none chosen yet. It will track the one you pick.", + "e997516a93d245d7": "Push", "f22254f79a6d8ae3": "Publish repository...", "895e269833827873": "Behind upstream. Pull/rebase first.", "f1f3d81d2a97f0ed": "Initializing...", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 797888016bd4a..dcdbe37daab1a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -1622,6 +1622,11 @@ ], "b77a2b4d9abda043": "Espacio de trabajo", "656e5640ed1b3e70": "Añadir a otra máquina", + "5f73e41e553c9a44": "No se pudo cambiar el remoto de push.", + "f1f79cc2176e78cf": "Remoto de push: {remote}", + "51cedd4eb8107a17": "sin elegir", + "5acc37f1d6e38012": "Elegir remoto", + "0a4603a2b21d2f44": "Enviar a", "3b4ca180fef92e21": "Observación", "cc8cdd1ece34cd75": "Nota", "19842b180a7e5a5f": "Consejo", @@ -2036,6 +2041,8 @@ "7b8eb81b6939c838": "Repositorio creado", "a16a5023fd3f7020": "{branch} ya está publicada en {provider}.", "b07e34ff280d5839": "El remoto \"{remote}\" está configurado. Haz un commit y un push para compartir tu código.", + "5e8b5f680d43ceb4": "Remoto", + "471f6cca2b22396e": "Elige un remoto", "8ea2c383ec1d8fc6": "vs. {ref}", "79394c44f351f604": "Esta conexión no puede cambiar el control de versiones.", "ff07cd3aef5acd21": "Esta acción no está disponible en este momento.", @@ -2088,6 +2095,9 @@ "77b5f98f1f9a4ca7": "Siguiente", "5148c9a30e4a5260": "Publicando...", "59bb4331e9a8536d": "Publicar", + "1bfda67456c96c4d": "¿A qué remoto enviar?", + "938cb93ed8cc07be": "Este repositorio tiene varios remotos y la rama aún no tiene uno elegido. Seguirá al que elijas.", + "e997516a93d245d7": "Enviar", "f22254f79a6d8ae3": "Publicar repositorio...", "895e269833827873": "Por detrás de upstream. Haz pull o rebase primero.", "f1f3d81d2a97f0ed": "Inicializando...", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e06cde54989bd..837dfe22cb103 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -1622,6 +1622,11 @@ ], "b77a2b4d9abda043": "Espace de travail", "656e5640ed1b3e70": "Ajouter à une autre machine", + "5f73e41e553c9a44": "Impossible de modifier le dépôt distant de push.", + "f1f79cc2176e78cf": "Dépôt distant de push : {remote}", + "51cedd4eb8107a17": "non choisi", + "5acc37f1d6e38012": "Choisir un dépôt distant", + "0a4603a2b21d2f44": "Pousser vers", "3b4ca180fef92e21": "Analyse", "cc8cdd1ece34cd75": "Remarque", "19842b180a7e5a5f": "Astuce", @@ -2036,6 +2041,8 @@ "7b8eb81b6939c838": "Dépôt créé", "a16a5023fd3f7020": "{branch} est maintenant en ligne sur {provider}.", "b07e34ff280d5839": "Le remote « {remote} » est configuré. Faites un commit et poussez-le pour partager votre code.", + "5e8b5f680d43ceb4": "Dépôt distant", + "471f6cca2b22396e": "Choisir un dépôt distant", "8ea2c383ec1d8fc6": "vs {ref}", "79394c44f351f604": "Cette connexion ne peut pas modifier la gestion de versions.", "ff07cd3aef5acd21": "Cette action est actuellement indisponible.", @@ -2088,6 +2095,9 @@ "77b5f98f1f9a4ca7": "Suivant", "5148c9a30e4a5260": "Publication...", "59bb4331e9a8536d": "Publier", + "1bfda67456c96c4d": "Vers quel dépôt distant pousser ?", + "938cb93ed8cc07be": "Ce dépôt a plusieurs dépôts distants et la branche n’en a pas encore choisi. Elle suivra celui que vous choisissez.", + "e997516a93d245d7": "Pousser", "f22254f79a6d8ae3": "Publier le dépôt...", "895e269833827873": "En retard sur l’upstream. Faites d’abord un pull ou un rebase.", "f1f3d81d2a97f0ed": "Initialisation...", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 4473bff3ddef1..9e7c1aca93be6 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -1621,6 +1621,11 @@ ], "b77a2b4d9abda043": "ワークスペース", "656e5640ed1b3e70": "別のマシンに追加", + "5f73e41e553c9a44": "プッシュ先リモートを変更できませんでした。", + "f1f79cc2176e78cf": "プッシュ先リモート: {remote}", + "51cedd4eb8107a17": "未選択", + "5acc37f1d6e38012": "リモートを選択", + "0a4603a2b21d2f44": "プッシュ先", "3b4ca180fef92e21": "インサイト", "cc8cdd1ece34cd75": "メモ", "19842b180a7e5a5f": "ヒント", @@ -2034,6 +2039,8 @@ "7b8eb81b6939c838": "リポジトリを作成しました", "a16a5023fd3f7020": "{branch} が {provider} で公開されました。", "b07e34ff280d5839": "リモート \"{remote}\" を設定しました。コードを共有するには、コミットしてプッシュしてください。", + "5e8b5f680d43ceb4": "リモート", + "471f6cca2b22396e": "リモートを選択", "8ea2c383ec1d8fc6": "vs {ref}", "79394c44f351f604": "この接続ではソース管理を変更できません。", "ff07cd3aef5acd21": "現在この操作は利用できません。", @@ -2086,6 +2093,9 @@ "77b5f98f1f9a4ca7": "次へ", "5148c9a30e4a5260": "公開しています...", "59bb4331e9a8536d": "公開", + "1bfda67456c96c4d": "どのリモートにプッシュしますか?", + "938cb93ed8cc07be": "このリポジトリには複数のリモートがあり、ブランチのリモートは未選択です。選択したリモートを追跡します。", + "e997516a93d245d7": "プッシュ", "f22254f79a6d8ae3": "リポジトリを公開...", "895e269833827873": "アップストリームより遅れています。先にプルまたはリベースしてください。", "f1f3d81d2a97f0ed": "初期化しています...", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 68f0b20794362..56734d00bd54a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -1621,6 +1621,11 @@ ], "b77a2b4d9abda043": "작업 영역", "656e5640ed1b3e70": "다른 머신에 추가", + "5f73e41e553c9a44": "푸시 원격 저장소를 변경하지 못했습니다.", + "f1f79cc2176e78cf": "푸시 원격 저장소: {remote}", + "51cedd4eb8107a17": "선택 안 함", + "5acc37f1d6e38012": "원격 저장소 선택", + "0a4603a2b21d2f44": "푸시 대상", "3b4ca180fef92e21": "인사이트", "cc8cdd1ece34cd75": "참고", "19842b180a7e5a5f": "팁", @@ -2036,6 +2041,8 @@ "7b8eb81b6939c838": "저장소 생성됨", "a16a5023fd3f7020": "{branch}이(가) 이제 {provider}에 게시되었습니다.", "b07e34ff280d5839": "원격 \"{remote}\"이(가) 설정되었습니다. 코드를 공유하려면 커밋하고 푸시하세요.", + "5e8b5f680d43ceb4": "원격 저장소", + "471f6cca2b22396e": "원격 저장소 선택", "8ea2c383ec1d8fc6": "vs {ref}", "79394c44f351f604": "이 연결로는 소스 제어를 변경할 수 없습니다.", "ff07cd3aef5acd21": "현재 이 작업을 사용할 수 없습니다.", @@ -2087,6 +2094,9 @@ "77b5f98f1f9a4ca7": "다음", "5148c9a30e4a5260": "게시하는 중...", "59bb4331e9a8536d": "게시", + "1bfda67456c96c4d": "어느 원격 저장소에 푸시할까요?", + "938cb93ed8cc07be": "이 저장소에는 여러 원격 저장소가 있으며 브랜치에 아직 선택된 원격 저장소가 없습니다. 선택한 원격 저장소를 추적합니다.", + "e997516a93d245d7": "푸시", "f22254f79a6d8ae3": "저장소 게시...", "895e269833827873": "업스트림보다 뒤처져 있습니다. 먼저 풀하거나 리베이스하세요.", "f1f3d81d2a97f0ed": "초기화하는 중...", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5a18a359ecb2a..67ea5a645ec21 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -1622,6 +1622,11 @@ ], "b77a2b4d9abda043": "Workspace", "656e5640ed1b3e70": "Adicionar a outra máquina", + "5f73e41e553c9a44": "Não foi possível alterar o remoto de push.", + "f1f79cc2176e78cf": "Remoto de push: {remote}", + "51cedd4eb8107a17": "não escolhido", + "5acc37f1d6e38012": "Escolher remoto", + "0a4603a2b21d2f44": "Enviar para", "3b4ca180fef92e21": "Insight", "cc8cdd1ece34cd75": "Nota", "19842b180a7e5a5f": "Dica", @@ -2036,6 +2041,8 @@ "7b8eb81b6939c838": "Repositório criado", "a16a5023fd3f7020": "{branch} já está publicado no {provider}.", "b07e34ff280d5839": "O remote \"{remote}\" está configurado. Faça um commit e um push para compartilhar seu código.", + "5e8b5f680d43ceb4": "Remoto", + "471f6cca2b22396e": "Escolha um remoto", "8ea2c383ec1d8fc6": "vs {ref}", "79394c44f351f604": "Esta conexão não pode alterar o controle de versão.", "ff07cd3aef5acd21": "Esta ação não está disponível no momento.", @@ -2088,6 +2095,9 @@ "77b5f98f1f9a4ca7": "Próximo", "5148c9a30e4a5260": "Publicando...", "59bb4331e9a8536d": "Publicar", + "1bfda67456c96c4d": "Para qual remoto enviar?", + "938cb93ed8cc07be": "Este repositório tem vários remotos e a branch ainda não tem um escolhido. Ela rastreará o que você escolher.", + "e997516a93d245d7": "Enviar", "f22254f79a6d8ae3": "Publicar repositório...", "895e269833827873": "Atrás do upstream. Faça pull/rebase primeiro.", "f1f3d81d2a97f0ed": "Inicializando...", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6c7fa00a15455..32ddfda78bf51 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -1622,6 +1622,11 @@ ], "b77a2b4d9abda043": "Рабочая область", "656e5640ed1b3e70": "Добавить на другую машину", + "5f73e41e553c9a44": "Не удалось изменить удалённый репозиторий для отправки.", + "f1f79cc2176e78cf": "Репозиторий для отправки: {remote}", + "51cedd4eb8107a17": "не выбран", + "5acc37f1d6e38012": "Выбрать репозиторий", + "0a4603a2b21d2f44": "Отправить в", "3b4ca180fef92e21": "Инсайт", "cc8cdd1ece34cd75": "Примечание", "19842b180a7e5a5f": "Совет", @@ -2036,6 +2041,8 @@ "7b8eb81b6939c838": "Репозиторий создан", "a16a5023fd3f7020": "{branch} теперь доступна на {provider}.", "b07e34ff280d5839": "Remote «{remote}» настроен. Сделайте коммит и пуш, чтобы поделиться кодом.", + "5e8b5f680d43ceb4": "Удалённый репозиторий", + "471f6cca2b22396e": "Выберите репозиторий", "8ea2c383ec1d8fc6": "vs {ref}", "79394c44f351f604": "Это подключение не может изменять контроль версий.", "ff07cd3aef5acd21": "Это действие сейчас недоступно.", @@ -2088,6 +2095,9 @@ "77b5f98f1f9a4ca7": "Далее", "5148c9a30e4a5260": "Публикация...", "59bb4331e9a8536d": "Опубликовать", + "1bfda67456c96c4d": "В какой репозиторий отправить?", + "938cb93ed8cc07be": "У этого репозитория несколько удалённых репозиториев, и для ветки ещё не выбран ни один. Она будет отслеживать выбранный вами.", + "e997516a93d245d7": "Отправить", "f22254f79a6d8ae3": "Опубликовать репозиторий...", "895e269833827873": "Отстаёт от upstream. Сначала выполните pull или rebase.", "f1f3d81d2a97f0ed": "Инициализация...", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d02de62557d73..f3d54678948f8 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -1622,6 +1622,11 @@ ], "b77a2b4d9abda043": "Arbetsyta", "656e5640ed1b3e70": "Lägg till på en annan dator", + "5f73e41e553c9a44": "Kunde inte ändra fjärrarkiv för push.", + "f1f79cc2176e78cf": "Fjärrarkiv för push: {remote}", + "51cedd4eb8107a17": "inte valt", + "5acc37f1d6e38012": "Välj fjärrarkiv", + "0a4603a2b21d2f44": "Pusha till", "3b4ca180fef92e21": "Insikt", "cc8cdd1ece34cd75": "Obs", "19842b180a7e5a5f": "Tips", @@ -2036,6 +2041,8 @@ "7b8eb81b6939c838": "Repot skapades", "a16a5023fd3f7020": "{branch} är nu publicerad på {provider}.", "b07e34ff280d5839": "Remoten ”{remote}” är konfigurerad. Gör en commit och pusha den för att dela din kod.", + "5e8b5f680d43ceb4": "Fjärrarkiv", + "471f6cca2b22396e": "Välj ett fjärrarkiv", "8ea2c383ec1d8fc6": "mot {ref}", "79394c44f351f604": "Den här anslutningen kan inte ändra versionshantering.", "ff07cd3aef5acd21": "Den här åtgärden är inte tillgänglig just nu.", @@ -2088,6 +2095,9 @@ "77b5f98f1f9a4ca7": "Nästa", "5148c9a30e4a5260": "Publicerar...", "59bb4331e9a8536d": "Publicera", + "1bfda67456c96c4d": "Till vilket fjärrarkiv vill du pusha?", + "938cb93ed8cc07be": "Det här arkivet har flera fjärrarkiv och grenen har inget valt ännu. Den kommer att spåra det du väljer.", + "e997516a93d245d7": "Pusha", "f22254f79a6d8ae3": "Publicera repo...", "895e269833827873": "Ligger efter upstream. Pulla/rebasa först.", "f1f3d81d2a97f0ed": "Initierar...", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index acf5ce3045376..bf85a2709c546 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -1622,6 +1622,11 @@ ], "b77a2b4d9abda043": "工作区", "656e5640ed1b3e70": "添加到另一台机器", + "5f73e41e553c9a44": "无法更改推送远程仓库。", + "f1f79cc2176e78cf": "推送远程仓库:{remote}", + "51cedd4eb8107a17": "未选择", + "5acc37f1d6e38012": "选择远程仓库", + "0a4603a2b21d2f44": "推送到", "3b4ca180fef92e21": "见解", "cc8cdd1ece34cd75": "注意", "19842b180a7e5a5f": "提示", @@ -2039,6 +2044,8 @@ "7b8eb81b6939c838": "已创建仓库", "a16a5023fd3f7020": "{branch} 已上线到 {provider}。", "b07e34ff280d5839": "已设置远端 “{remote}”。提交并推送即可分享你的代码。", + "5e8b5f680d43ceb4": "远程仓库", + "471f6cca2b22396e": "选择一个远程仓库", "8ea2c383ec1d8fc6": "对比 {ref}", "79394c44f351f604": "此连接无法更改版本控制。", "ff07cd3aef5acd21": "此操作当前不可用。", @@ -2092,6 +2099,9 @@ "77b5f98f1f9a4ca7": "下一步", "5148c9a30e4a5260": "正在发布…", "59bb4331e9a8536d": "发布", + "1bfda67456c96c4d": "推送到哪个远程仓库?", + "938cb93ed8cc07be": "此仓库有多个远程仓库,当前分支尚未选择。它将跟踪你选择的远程仓库。", + "e997516a93d245d7": "推送", "f22254f79a6d8ae3": "发布仓库…", "895e269833827873": "落后于上游。请先拉取或变基。", "f1f3d81d2a97f0ed": "正在初始化…", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index ce57f727ff6ae..992946cc78b24 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -181,6 +181,12 @@ Use a thread's Git actions to commit, push, and create a pull request. T3 Code c messages, review titles, and descriptions from your changes. Descriptions also draw on the work in the thread, including the checks it ran. +If a repository has several remotes, choose where a branch pushes with the remote selector next +to the branch selector. On mobile it is under the thread's Git options. The branch keeps pulling +from the remote it tracks, so a fork branch can pull from `origin` and push to your fork. If a branch +has no remote chosen and none is named `origin` or set as `remote.pushDefault`, T3 Code asks before +pushing it. + An existing fork PR can appear beside the branch even if you pushed without setting an upstream. If its badge is missing because several remotes hold that branch, set the branch's upstream to the intended remote with `git branch --set-upstream-to=/`. diff --git a/packages/client-runtime/src/state/gitActions.test.ts b/packages/client-runtime/src/state/gitActions.test.ts index 7418ed0df172b..8117654af2b5b 100644 --- a/packages/client-runtime/src/state/gitActions.test.ts +++ b/packages/client-runtime/src/state/gitActions.test.ts @@ -5,6 +5,7 @@ import { sourceControlClients } from "../sourceControlClients.ts"; import { buildMenuItems, getGitActionDisabledReason, + pushRemoteChoicesFor, resolveDefaultBranchActionDialogCopy, resolveQuickAction, } from "./gitActions.ts"; @@ -104,3 +105,25 @@ describe("git action copy", () => { ).toBe("Commit, push & create MR"); }); }); + +describe("pushRemoteChoicesFor", () => { + const choices = ["fork", "upstream"]; + const unclear = { pushRemoteChoices: choices }; + + it("asks before a push when the remote is unclear", () => { + expect(pushRemoteChoicesFor({ action: "commit_push_pr" }, unclear)).toEqual(choices); + expect(pushRemoteChoicesFor({ action: "commit" }, unclear)).toBeNull(); + expect(pushRemoteChoicesFor({ action: "push", pushRemote: "fork" }, unclear)).toBeNull(); + expect(pushRemoteChoicesFor({ action: "push" }, {})).toBeNull(); + expect(pushRemoteChoicesFor({ action: "push" }, { ...unclear, pushRemote: "fork" })).toBeNull(); + }); + + it("asks for a new feature branch even when the current branch has a push remote", () => { + expect( + pushRemoteChoicesFor( + { action: "commit_push", featureBranch: true }, + { ...unclear, pushRemote: "fork" }, + ), + ).toEqual(choices); + }); +}); diff --git a/packages/client-runtime/src/state/gitActions.ts b/packages/client-runtime/src/state/gitActions.ts index ece720c47d3a2..d1b733a1de1aa 100644 --- a/packages/client-runtime/src/state/gitActions.ts +++ b/packages/client-runtime/src/state/gitActions.ts @@ -42,7 +42,7 @@ export type DefaultBranchConfirmableAction = export type GitActionRequestInput = Pick< GitRunStackedActionInput, - "action" | "commitMessage" | "featureBranch" | "filePaths" + "action" | "commitMessage" | "featureBranch" | "filePaths" | "pushRemote" >; export function changeRequestTerminologyFor( @@ -426,6 +426,20 @@ export function requiresDefaultBranchConfirmation( ); } +/** + * The remotes to ask the user between before running `input`, or null when it pushes nowhere, + * already names a remote, or git knows where the branch goes. + */ +export function pushRemoteChoicesFor( + input: GitActionRequestInput, + gitStatus: Pick | null, +): ReadonlyArray | null { + if (input.action === "commit" || input.pushRemote || !gitStatus?.pushRemoteChoices) return null; + // A new feature branch starts without the current branch's selection. + if (input.featureBranch) return gitStatus.pushRemoteChoices; + return gitStatus.pushRemote ? null : gitStatus.pushRemoteChoices; +} + export function resolveDefaultBranchActionDialogCopy( input: { action: DefaultBranchConfirmableAction; diff --git a/packages/client-runtime/src/state/vcs.ts b/packages/client-runtime/src/state/vcs.ts index 310515ceb9915..a9079184488ff 100644 --- a/packages/client-runtime/src/state/vcs.ts +++ b/packages/client-runtime/src/state/vcs.ts @@ -385,6 +385,13 @@ export function createVcsEnvironmentAtoms( concurrency: vcsCommandConcurrency, onSettled: invalidateRefs, }), + setPushRemote: createEnvironmentRpcCommand(runtime, { + label: "environment-data:vcs:set-push-remote", + tag: WS_METHODS.vcsSetPushRemote, + scheduler: vcsCommandScheduler, + concurrency: vcsCommandConcurrency, + onSettled: invalidateRefs, + }), init: createEnvironmentRpcCommand(runtime, { label: "environment-data:vcs:init", tag: WS_METHODS.vcsInit, diff --git a/packages/client-runtime/src/state/vcsAction.test.ts b/packages/client-runtime/src/state/vcsAction.test.ts index 67e9253cba4f3..6e3b5362abf83 100644 --- a/packages/client-runtime/src/state/vcsAction.test.ts +++ b/packages/client-runtime/src/state/vcsAction.test.ts @@ -524,6 +524,7 @@ describe("vcsActionState", () => { manager.runStackedAction(targetKey).run(registry, { actionId: successfulActionId, action, + pushRemote: "fork", threadId, projectId, }), @@ -534,7 +535,14 @@ describe("vcsActionState", () => { expect(registry.get(state).revision).toBe(1); expect(removed).toEqual([`${environmentId}:*`]); expect(rpcInputs).toEqual([ - { actionId: successfulTransportActionId, cwd, action, threadId, projectId }, + { + actionId: successfulTransportActionId, + cwd, + action, + pushRemote: "fork", + threadId, + projectId, + }, ]); const failedResult = yield* Effect.promise(() => diff --git a/packages/client-runtime/src/state/vcsAction.ts b/packages/client-runtime/src/state/vcsAction.ts index 22f017dfaa1d1..84bf4f0f4b27e 100644 --- a/packages/client-runtime/src/state/vcsAction.ts +++ b/packages/client-runtime/src/state/vcsAction.ts @@ -82,6 +82,7 @@ export interface RunVcsStackedActionInput { readonly commitMessage?: string; readonly featureBranch?: boolean; readonly filePaths?: ReadonlyArray; + readonly pushRemote?: string; readonly threadId?: ThreadId; readonly projectId?: ProjectId; readonly onProgress?: (event: GitActionProgressEvent) => void; @@ -535,6 +536,7 @@ export function createVcsActionManager( ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}), ...(input.featureBranch ? { featureBranch: true } : {}), ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}), + ...(input.pushRemote ? { pushRemote: input.pushRemote } : {}), ...(input.threadId !== undefined ? { threadId: input.threadId } : {}), ...(input.projectId !== undefined ? { projectId: input.projectId } : {}), }; diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index 0b6164871a0ad..a93767f3427a5 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -68,6 +68,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.vcsRemoveWorktree]: AuthSourceControlWriteScope, [WS_METHODS.vcsCreateRef]: AuthSourceControlWriteScope, [WS_METHODS.vcsSwitchRef]: AuthSourceControlWriteScope, + [WS_METHODS.vcsSetPushRemote]: AuthSourceControlWriteScope, [WS_METHODS.vcsInit]: AuthSourceControlWriteScope, // Starts an agent session on this environment that can read its logs and database. diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 45d68c5e9ca44..7a971141dad1e 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -137,6 +137,8 @@ export const GitRunStackedActionInput = Schema.Struct({ commitMessage: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(10_000))), featureBranch: Schema.optional(Schema.Boolean), filePaths: Schema.optional(Schema.Array(GitFilePath).check(Schema.isMinLength(1))), + /** Remote for a branch without an upstream, picked from `pushRemoteChoices`. */ + pushRemote: Schema.optional(TrimmedNonEmptyStringSchema), threadId: Schema.optional(ThreadId), projectId: Schema.optional(ProjectId), }); @@ -203,6 +205,13 @@ export const VcsSwitchRefInput = Schema.Struct({ }); export type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type; +export const VcsSetPushRemoteInput = Schema.Struct({ + cwd: TrimmedNonEmptyStringSchema, + refName: TrimmedNonEmptyStringSchema, + remoteName: TrimmedNonEmptyStringSchema, +}); +export type VcsSetPushRemoteInput = typeof VcsSetPushRemoteInput.Type; + export const VcsInitInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, kind: Schema.optional(VcsDriverKind), @@ -224,6 +233,15 @@ const VcsStatusLocalShape = { isRepo: Schema.Boolean, sourceControlProvider: Schema.optional(SourceControlProviderInfo), hasPrimaryRemote: Schema.Boolean, + /** Every remote, present only when there are at least two to select between. */ + remotes: Schema.optional(Schema.Array(TrimmedNonEmptyStringSchema)), + /** Where the current branch pushes. Absent with one remote, or while the choice is unclear. */ + pushRemote: Schema.optional(TrimmedNonEmptyStringSchema), + /** + * Remotes to ask between before pushing a branch without an upstream: present only when + * there are several, none is `origin`, and `remote.pushDefault` names none of them. + */ + pushRemoteChoices: Schema.optional(Schema.Array(TrimmedNonEmptyStringSchema)), isDefaultRef: Schema.Boolean, refName: Schema.NullOr(TrimmedNonEmptyStringSchema), hasWorkingTreeChanges: Schema.Boolean, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 41733dae56417..1d8d226ca592c 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -127,6 +127,7 @@ import { } from "./worktreeSetup.ts"; import { GitActionProgressEvent, + VcsSetPushRemoteInput, VcsSwitchRefInput, VcsSwitchRefResult, GitCommandError, @@ -492,6 +493,7 @@ export const WS_METHODS = { vcsRemoveWorktree: "vcs.removeWorktree", vcsCreateRef: "vcs.createRef", vcsSwitchRef: "vcs.switchRef", + vcsSetPushRemote: "vcs.setPushRemote", vcsInit: "vcs.init", gitRunStackedAction: "git.runStackedAction", @@ -1759,6 +1761,11 @@ const WsVcsSwitchRefRpc = Rpc.make(WS_METHODS.vcsSwitchRef, { error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]), }); +const WsVcsSetPushRemoteRpc = Rpc.make(WS_METHODS.vcsSetPushRemote, { + payload: VcsSetPushRemoteInput, + error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]), +}); + const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, { payload: VcsInitInput, error: Schema.Union([VcsError, EnvironmentAuthorizationError]), @@ -2429,6 +2436,7 @@ export const WsRpcGroup = RpcGroup.make( WsVcsRemoveWorktreeRpc, WsVcsCreateRefRpc, WsVcsSwitchRefRpc, + WsVcsSetPushRemoteRpc, WsVcsInitRpc, WsReviewGetBranchCommitsRpc, WsReviewGetDiffPreviewRpc, diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index 7ef56875e34b5..86d3663e7eb93 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -371,6 +371,9 @@ function toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult { ? { sourceControlProvider: status.sourceControlProvider } : {}), hasPrimaryRemote: status.hasPrimaryRemote, + ...(status.remotes ? { remotes: status.remotes } : {}), + ...(status.pushRemote ? { pushRemote: status.pushRemote } : {}), + ...(status.pushRemoteChoices ? { pushRemoteChoices: status.pushRemoteChoices } : {}), isDefaultRef: status.isDefaultRef, refName: status.refName, hasWorkingTreeChanges: status.hasWorkingTreeChanges,