Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(settings): MUL-9467 manage multiple GitHub connections (#10804)
Multica Evea86a6c7b24f2
diff --git a/apps/docs/content/docs/github-integration.fr.mdx b/apps/docs/content/docs/github-integration.fr.mdxindex 1fa949d1ac..7cfb71c69e 100644--- a/apps/docs/content/docs/github-integration.fr.mdx+++ b/apps/docs/content/docs/github-integration.fr.mdx@@ -34,6 +34,10 @@ Revenez sur Multica une fois l'installation terminée.</Step></Steps>+Choisissez **Ajouter un compte ou une organisation** dans la ligne GitHub ou le menu **Ajouter un dépôt** pour connecter une autre installation sans déconnecter les précédentes. Chaque connexion affiche le compte et la personne qui l’a connectée ; le sélecteur de dépôts permet de changer de compte. **Mettre en pause les fonctionnalités GitHub** s’applique à toutes les connexions de l’espace de travail.++Si GitHub ne renvoie pas d’autorisation utilisateur, Multica ne peut pas vérifier une nouvelle connexion, même si l’App est déjà installée ou connectée à un autre espace. Reconnectez-vous et terminez l’autorisation ; si cela se répète, demandez à votre opérateur Multica de vérifier les réglages d’autorisation utilisateur de l’App. Modifier uniquement l’accès aux dépôts peut ne pas suffire.+L'état de la connexion s'affiche sur la même page. Les membres ordinaires peuvent consulter cet état, mais ne peuvent ni connecter, ni déconnecter, ni modifier les interrupteurs.<Callout type="info">@@ -123,7 +127,7 @@ Si un même identifiant correspond à une tâche dans plusieurs des espaces de t## Déconnecter-Choisir **Déconnecter** dans le menu **⋯** de la ligne GitHub, sur **Paramètres → Code**, supprime seulement la relation entre l'espace de travail Multica courant et l'installation ; cela ne désinstalle pas l'App de GitHub à votre place. Les enregistrements de PR existants sont conservés, et les nouveaux événements cessent d'arriver dans cet espace de travail.+Dans **Paramètres → Code**, choisissez **Déconnecter** à côté du compte à retirer. Seule la connexion de cette installation à l’espace courant est supprimée ; les autres continuent de recevoir des événements. L’App reste installée sur GitHub et les PR et liens existants sont conservés.Pour révoquer l'autorisation d'accès aux dépôts côté GitHub, désinstallez l'App ou ajustez son périmètre de dépôts depuis la page des installations de GitHub Apps de votre compte personnel ou de votre organisation. Après la désinstallation, tous les espaces de travail Multica liés à cette installation cessent de recevoir des événements.diff --git a/apps/docs/content/docs/github-integration.ja.mdx b/apps/docs/content/docs/github-integration.ja.mdxindex 693683c1b5..c29d080520 100644--- a/apps/docs/content/docs/github-integration.ja.mdx+++ b/apps/docs/content/docs/github-integration.ja.mdx@@ -34,6 +34,10 @@ GitHub でアカウントまたは organization を選び、すべてのリポ</Step></Steps>+GitHub の行または**リポジトリを追加** メニューで **アカウントまたは組織を追加** を選ぶと、既存の接続を解除せずに別のインストールを接続できます。各接続にはアカウントと接続した人が表示され、リポジトリ選択画面でアカウントを切り替えられます。**GitHub 機能を一時停止** はワークスペースの全接続に適用されます。++GitHub がユーザー認証を返さない場合、App がインストール済みでも、別のワークスペースに接続済みでも、新しい接続は検証できません。再接続して認証を完了してください。繰り返す場合は Multica の運用担当者に App のユーザー認証設定の確認を依頼してください。リポジトリの範囲変更だけでは新しい接続を完了できない場合があります。+接続状態は同じページに表示されます。通常のメンバーは状態を確認できますが、接続、切断、スイッチの変更はできません。<Callout type="info">@@ -121,7 +125,7 @@ PR の紐づけ方は結果に影響しません。タイトル、ブランチ## 接続を解除する-**設定 → コード** の GitHub の行で **⋯** メニューから**接続解除**を選ぶと、現在の Multica ワークスペースと installation の関係だけが削除されます。GitHub から App がアンインストールされることはありません。既存の PR 記録は保持されますが、新しいイベントはこのワークスペースに届かなくなります。+**設定 → コード** で、削除したいアカウントの横にある **接続解除** を選びます。対象のインストールと現在のワークスペースの接続だけが削除され、他の接続はイベントを受信し続けます。App は GitHub にインストールされたままで、既存の PR 記録とリンクは保持されます。GitHub 側のリポジトリアクセスを取り消す場合は、個人または organization の GitHub App installations ページで App をアンインストールするか、リポジトリの範囲を変更してください。App をアンインストールすると、その installation に接続していたすべての Multica ワークスペースがイベントを受信しなくなります。diff --git a/apps/docs/content/docs/github-integration.ko.mdx b/apps/docs/content/docs/github-integration.ko.mdxindex b55c3e974f..f3ad081006 100644--- a/apps/docs/content/docs/github-integration.ko.mdx+++ b/apps/docs/content/docs/github-integration.ko.mdx@@ -34,6 +34,10 @@ GitHub에서 계정 또는 조직을 선택하고 모든 저장소나 지정한</Step></Steps>+GitHub 행 또는 **저장소 추가** 메뉴에서 **계정 또는 조직 추가**를 선택하면 기존 연결을 해제하지 않고 다른 설치를 연결할 수 있습니다. 각 연결에는 계정과 연결한 사람이 표시되며 저장소 선택기에서 계정을 전환할 수 있습니다. **GitHub 기능 일시 중지**는 워크스페이스의 모든 연결에 적용됩니다.++GitHub에서 사용자 인증을 반환하지 않으면 App이 이미 설치되어 있거나 다른 워크스페이스에 연결되어 있어도 새 연결을 확인할 수 없습니다. 다시 연결하고 인증을 완료하세요. 반복되면 Multica 운영자에게 App의 사용자 인증 설정 확인을 요청하세요. 저장소 범위 변경만으로는 새 연결이 완료되지 않을 수 있습니다.+연결 상태는 같은 페이지에 표시됩니다. 일반 멤버는 상태를 볼 수 있지만 연결, 연결 해제, 스위치 변경은 할 수 없습니다.<Callout type="info">@@ -121,7 +125,7 @@ PR을 어떻게 연결했는지는 결과에 영향을 주지 않습니다. 제## 연결 해제-**설정 → 코드**의 GitHub 행에서 **⋯** 메뉴의 **연결 해제**를 선택하면 현재 Multica 워크스페이스와 해당 installation의 관계만 제거됩니다. GitHub에서 App을 대신 제거하지는 않습니다. 기존 PR 기록은 유지되고 새 이벤트만 해당 워크스페이스에 들어오지 않습니다.+**설정 → 코드**에서 제거할 계정 옆의 **연결 해제**를 선택하세요. 해당 설치와 현재 워크스페이스의 연결만 제거되며 다른 연결은 이벤트를 계속 수신합니다. App은 GitHub에 설치된 상태로 유지되고 기존 PR 기록과 링크도 보존됩니다.GitHub 측의 저장소 승인을 취소하려면 개인 또는 조직의 GitHub App installations 페이지에서 App을 제거하거나 저장소 범위를 조정해야 합니다. App을 제거하면 해당 installation에 연결된 모든 Multica 워크스페이스가 이벤트 수신을 중지합니다.diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdxindex 855d65bf20..270a421460 100644--- a/apps/docs/content/docs/github-integration.mdx+++ b/apps/docs/content/docs/github-integration.mdx@@ -34,6 +34,10 @@ Return to Multica after the installation completes.</Step></Steps>+Use **Add account or organization** in the GitHub row or the **Add repository** menu to connect another installation without disconnecting an existing one. Each connection lists its account and who connected it; the repository picker lets you switch between accounts. **Pause GitHub features** applies to all connections in the workspace.++If GitHub returns no user authorization, Multica cannot verify a new connection, even if the App is already installed or connected to another workspace. Retry connecting and complete authorization; if this repeats, ask your Multica operator to check the App’s user authorization settings. Changing repository access alone may not complete a new connection.+The connection status shows on the same page. Regular members can view the status but can't connect, disconnect, or change the switches.<Callout type="info">@@ -123,7 +127,7 @@ If one identifier matches an issue in more than one of the connected workspaces## Disconnect-Choosing **Disconnect** from the GitHub row's **⋯** menu on **Settings → Code** only removes the relationship between the current Multica workspace and the installation; it does not uninstall the App from GitHub for you. Existing PR records are kept, and new events stop flowing into that workspace.+On **Settings → Code**, choose **Disconnect** beside the account you want to remove. Only that installation’s connection to the current workspace is removed; other connections keep receiving events. The App remains installed on GitHub, and existing PR records and links are kept.To revoke repository authorization on the GitHub side, uninstall the App or adjust its repository scope from your personal or organization GitHub App installations page. After uninstalling, every Multica workspace linked to that installation stops receiving events.diff --git a/apps/docs/content/docs/github-integration.zh-Hant.mdx b/apps/docs/content/docs/github-integration.zh-Hant.mdxindex 4ebc1de628..a5abce8837 100644--- a/apps/docs/content/docs/github-integration.zh-Hant.mdx+++ b/apps/docs/content/docs/github-integration.zh-Hant.mdx@@ -34,6 +34,10 @@ GitHub 整合只讀取安裝時授權的倉庫,不會提交程式碼、評論</Step></Steps>+在 GitHub 一行或**新增倉庫** 選單中選擇 **新增帳號或組織**,即可連線另一個安裝,無需先斷開已有連線。每條連線分別顯示帳號和連線人;倉庫選擇器可切換帳號。**暫停 GitHub 功能** 對工作區內所有連線生效。++如果 GitHub 未傳回使用者授權,即使 App 已安裝或已連線其他工作區,Multica 也無法驗證新連線。請重新連線並完成授權;若反覆失敗,請聯絡 Multica 維運人員檢查 App 的使用者授權設定。僅修改倉庫範圍不一定能完成新連線。+連線狀態會顯示在同一頁面。普通成員可以檢視狀態,但不能連線、斷開或修改開關。<Callout type="info">@@ -123,7 +127,7 @@ PR 是怎麼關聯上的,不影響結果:標題、分支名和正文裡的 `## 斷開連線-在 **設定 → 程式碼** 的 GitHub 一行,從 **⋯** 選單選擇 **斷開**,只會移除當前 Multica 工作區與該 installation 的關係,不會替你從 GitHub 解除安裝 App。已有 PR 記錄會保留,新的事件不再進入該工作區。+在 **設定 → 程式碼** 中,點選目標帳號旁的 **斷開**。這只移除該安裝與目前工作區的連線,其他連線繼續接收事件。App 仍安裝在 GitHub,已有 PR 記錄與關聯會保留。撤銷 GitHub 側的倉庫授權,需到個人或組織的 GitHub App installations 頁面解除安裝或調整倉庫範圍。解除安裝後,與該 installation 關聯的所有 Multica 工作區都會停止接收事件。diff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdxindex 87c286f4b4..ebc8c0ca11 100644--- a/apps/docs/content/docs/github-integration.zh.mdx+++ b/apps/docs/content/docs/github-integration.zh.mdx@@ -34,6 +34,10 @@ GitHub 集成只读取安装时授权的仓库,不会提交代码、评论或</Step></Steps>+在 GitHub 一行或**添加仓库** 菜单中选择 **添加账号或组织**,即可连接另一个安装,无需先断开已有连接。每条连接分别显示账号和连接人;仓库选择器可切换账号。**暂停 GitHub 功能** 对工作区内所有连接生效。++如果 GitHub 未返回用户授权,即使 App 已安装或已连接其他工作区,Multica 也无法验证新连接。请重新连接并完成授权;若反复失败,请联系 Multica 运维人员检查 App 的用户授权设置。仅修改仓库范围不一定能完成新连接。+连接状态会显示在同一页面。普通成员可以查看状态,但不能连接、断开或修改开关。<Callout type="info">@@ -123,7 +127,7 @@ PR 是怎么关联上的,不影响结果:标题、分支名和正文里的 `## 断开连接-在 **设置 → 代码** 的 GitHub 一行,从 **⋯** 菜单选择 **断开**,只会移除当前 Multica 工作区与该 installation 的关系,不会替你从 GitHub 卸载 App。已有 PR 记录会保留,新的事件不再进入该工作区。+在 **设置 → 代码** 中,点击目标账号旁的 **断开**。这只移除该安装与当前工作区的连接,其他连接继续接收事件。App 仍安装在 GitHub,已有 PR 记录与关联会保留。撤销 GitHub 侧的仓库授权,需到个人或组织的 GitHub App installations 页面卸载或调整仓库范围。卸载后,与该 installation 关联的所有 Multica 工作区都会停止接收事件。diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex af6d609498..0b78b4e704 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -41,6 +41,15 @@ describe("ApiClient schema fallback", () => {});describe("GitHub repository import", () => {+ it("accepts attributed connections alongside legacy rows without a connector name", async () => {+ const installation = { id: "inst-1", workspace_id: "ws-1", account_login: "alice", account_type: "User", account_avatar_url: null, created_at: "2026-11-17T00:00:00Z" };+ stubFetchJson({ installations: [installation, { ...installation, id: "inst-2", account_login: "acme-org", connected_by: "Ada" }], can_manage: false });+ const response = await new ApiClient("https://api.example.test").listGitHubInstallations("ws-1");+ expect(response.installations).toEqual([installation, { ...installation, id: "inst-2", account_login: "acme-org", connected_by: "Ada" }]);+ expect(response.can_manage).toBe(false);+ expect(response.installations.every((row) => row.installation_id === undefined)).toBe(true);+ });+it("falls back safely when installation or repository responses are malformed", async () => {stubFetchJson({ installations: "not-an-array", configured: true });const client = new ApiClient("https://api.example.test");diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 74fcc4755b..8d41f83cee 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1030,7 +1030,7 @@"disconnect": "Disconnect","disconnecting": "Disconnecting…","disconnect_confirm_title": "Disconnect GitHub App",- "disconnect_confirm_description": "Multica will stop receiving webhooks for this installation. Existing PR mirrors and links are kept; reconnect any time to resume updates.",+ "disconnect_confirm_description": "Disconnect {{login}} from this workspace? Updates for this account will stop. Existing PR records and links are kept; other connections are unaffected.","disconnect_confirm_cancel": "Cancel","disconnect_confirm_action": "Disconnect","not_configured": "GitHub integration is not configured for this deployment. Operators must set",@@ -1051,7 +1051,18 @@"feature_auto_link_description": "Links a PR to the issue whose ID, e.g. {{example}}, is in its title or branch name, or follows “Closes” in its description.","status_paused": "Paused","pause": "Pause GitHub features",- "resume": "Resume GitHub features"+ "resume": "Resume GitHub features",+ "add_account": "Add account or organization",+ "disconnect_account": "Disconnect {{login}}",+ "errors": {+ "missing_authorization": "GitHub did not return user authorization. Retry connecting and complete authorization. If it repeats for an existing installation, ask your Multica operator for help.",+ "installation_not_authorized": "Use the owning GitHub account for a personal installation, or an account with admin access to every authorized repository for an organization. Select at least one repository.",+ "invalid_state": "This GitHub connection request expired or is invalid. Start the connection again from Settings → Code.",+ "incomplete_callback": "GitHub returned an incomplete connection response. Start the connection again from Settings → Code.",+ "bad_workspace": "Could not find the workspace for this connection. Open the intended workspace and retry from Settings → Code.",+ "verification_failed": "Could not verify your GitHub installation access. Retry connecting; if it repeats, ask your Multica operator to check the GitHub App configuration.",+ "persist_failed": "Could not save the GitHub connection. Retry from Settings → Code; if it repeats, contact your Multica operator."+ }},"vcs": {"section_title": "Self-hosted Git",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex a42d10696a..dc08f14e2b 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -1030,7 +1030,7 @@"disconnect": "Desconectar","disconnecting": "Desconectando…","disconnect_confirm_title": "Desconectar la GitHub App",- "disconnect_confirm_description": "Multica dejará de recibir webhooks de esta instalación. Los mirrors de PR y los enlaces existentes se conservan; vuelve a conectar cuando quieras para reanudar las actualizaciones.",+ "disconnect_confirm_description": "¿Desconectar {{login}} de este espacio de trabajo? Se detendrán las actualizaciones de esta cuenta. Se conservarán los PR y enlaces existentes; las demás conexiones no se verán afectadas.","disconnect_confirm_cancel": "Cancelar","disconnect_confirm_action": "Desconectar","not_configured": "La integración con GitHub no está configurada en esta instalación. Los operadores deben definir",@@ -1051,7 +1051,18 @@"feature_auto_link_description": "Enlaza un PR con la tarea cuyo ID, p. ej. {{example}}, aparece en su título o nombre de rama, o tras “Closes” en su descripción.","pause": "Pausar funciones de GitHub","resume": "Reanudar funciones de GitHub",- "status_paused": "En pausa"+ "status_paused": "En pausa",+ "add_account": "Añadir cuenta u organización",+ "disconnect_account": "Desconectar {{login}}",+ "errors": {+ "missing_authorization": "GitHub no devolvió la autorización del usuario. Vuelve a conectar y completa la autorización. Si se repite con una instalación existente, contacta con tu operador de Multica.",+ "installation_not_authorized": "Para una instalación personal, usa la cuenta de GitHub propietaria. Para una organización, usa una cuenta con permisos de administrador en todos los repositorios autorizados y selecciona al menos uno.",+ "invalid_state": "Esta solicitud de conexión de GitHub ha caducado o no es válida. Reinicia la conexión desde Configuración → Código.",+ "incomplete_callback": "GitHub devolvió una respuesta de conexión incompleta. Reinicia la conexión desde Configuración → Código.",+ "bad_workspace": "No se encontró el espacio de trabajo de esta conexión. Abre el espacio deseado y reintenta desde Configuración → Código.",+ "verification_failed": "No se pudo verificar tu acceso a la instalación de GitHub. Reintenta; si se repite, pide a tu operador de Multica que revise la configuración de la GitHub App.",+ "persist_failed": "No se pudo guardar la conexión de GitHub. Reintenta desde Configuración → Código; si se repite, contacta con tu operador de Multica."+ }},"vcs": {"section_title": "Proveedores de Git (self-hosted)",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 2473150015..ab7f103e96 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -1030,7 +1030,7 @@"disconnect": "Déconnecter","disconnecting": "Déconnexion…","disconnect_confirm_title": "Déconnecter la GitHub App",- "disconnect_confirm_description": "Multica cessera de recevoir les webhooks de cette installation. Les copies de PR et les liens existants sont conservés ; reconnectez à tout moment pour reprendre les mises à jour.",+ "disconnect_confirm_description": "Déconnecter {{login}} de cet espace de travail ? Les mises à jour de ce compte s’arrêteront. Les PR et liens existants seront conservés ; les autres connexions ne seront pas affectées.","disconnect_confirm_cancel": "Annuler","disconnect_confirm_action": "Déconnecter","not_configured": "L'intégration GitHub n'est pas configurée pour ce déploiement. Les opérateurs doivent définir",@@ -1051,7 +1051,18 @@"feature_auto_link_description": "Lie une PR à la tâche dont l’identifiant, par ex. {{example}}, figure dans son titre ou sa branche, ou suit « Closes » dans sa description.","status_paused": "En pause","pause": "Mettre en pause les fonctionnalités GitHub",- "resume": "Reprendre les fonctionnalités GitHub"+ "resume": "Reprendre les fonctionnalités GitHub",+ "add_account": "Ajouter un compte ou une organisation",+ "disconnect_account": "Déconnecter {{login}}",+ "errors": {+ "missing_authorization": "GitHub n’a pas renvoyé d’autorisation utilisateur. Reconnectez-vous et terminez l’autorisation. Si cela se répète pour une installation existante, contactez votre opérateur Multica.",+ "installation_not_authorized": "Pour une installation personnelle, utilisez le compte GitHub propriétaire. Pour une organisation, utilisez un compte administrateur de tous les dépôts autorisés et sélectionnez au moins un dépôt.",+ "invalid_state": "Cette demande de connexion GitHub a expiré ou est invalide. Recommencez depuis Paramètres → Code.",+ "incomplete_callback": "GitHub a renvoyé une réponse de connexion incomplète. Recommencez depuis Paramètres → Code.",+ "bad_workspace": "L’espace de travail de cette connexion est introuvable. Ouvrez l’espace souhaité et réessayez depuis Paramètres → Code.",+ "verification_failed": "Impossible de vérifier votre accès à l’installation GitHub. Réessayez ; si cela se répète, demandez à votre opérateur Multica de vérifier la configuration de la GitHub App.",+ "persist_failed": "Impossible d’enregistrer la connexion GitHub. Réessayez depuis Paramètres → Code ; si cela se répète, contactez votre opérateur Multica."+ }},"vcs": {"section_title": "Git auto-hébergé",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 171c5b1451..98464a9566 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1021,7 +1021,7 @@"disconnect": "接続解除","disconnecting": "接続解除中…","disconnect_confirm_title": "GitHub App の接続を解除",- "disconnect_confirm_description": "Multica はこのインストールの Webhook 受信を停止します。既存の PR ミラーとリンクは保持され、いつでも再接続して更新を再開できます。",+ "disconnect_confirm_description": "このワークスペースから {{login}} の接続を解除しますか?このアカウントの更新は停止します。既存の PR 記録とリンクは保持され、他の接続には影響しません。","disconnect_confirm_cancel": "キャンセル","disconnect_confirm_action": "接続解除","not_configured": "このデプロイには GitHub 連携が設定されていません。運営者が次の値を設定する必要があります:",@@ -1042,7 +1042,18 @@"feature_auto_link_description": "タイトルかブランチ名にタスク番号(例: {{example}})を含む PR、または説明に「Closes {{example}}」と書いた PR を、そのタスクに関連付けます。","status_paused": "一時停止中","pause": "GitHub 機能を一時停止",- "resume": "GitHub 機能を再開"+ "resume": "GitHub 機能を再開",+ "add_account": "アカウントまたは組織を追加",+ "disconnect_account": "{{login}} の接続を解除",+ "errors": {+ "missing_authorization": "GitHub からユーザー認証が返されませんでした。再接続して認証を完了してください。既存のインストールで繰り返す場合は、Multica の運用担当者に連絡してください。",+ "installation_not_authorized": "個人のインストールには所有者の GitHub アカウントを使用してください。組織の場合は、承認された全リポジトリの管理権限を持つアカウントを使用し、少なくとも 1 つのリポジトリを選択してください。",+ "invalid_state": "GitHub 接続リクエストの期限が切れているか、無効です。設定 → コードから再接続してください。",+ "incomplete_callback": "GitHub の接続応答が不完全です。設定 → コードから再接続してください。",+ "bad_workspace": "接続先のワークスペースが見つかりません。対象のワークスペースを開き、設定 → コードから再試行してください。",+ "verification_failed": "GitHub インストールへの管理権限を確認できませんでした。再接続し、繰り返す場合は Multica の運用担当者に GitHub App の設定確認を依頼してください。",+ "persist_failed": "GitHub 接続を保存できませんでした。設定 → コードから再試行し、繰り返す場合は Multica の運用担当者に連絡してください。"+ }},"vcs": {"section_title": "セルフホスト Git",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex e8960f4cfb..0d8ef13050 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -1021,7 +1021,7 @@"disconnect": "연결 해제","disconnecting": "연결 해제 중...","disconnect_confirm_title": "GitHub App 연결 해제",- "disconnect_confirm_description": "Multica가 이 설치의 Webhook 수신을 중단합니다. 기존 PR 미러와 연결은 유지되며, 언제든 다시 연결해 업데이트를 재개할 수 있습니다.",+ "disconnect_confirm_description": "이 워크스페이스에서 {{login}} 연결을 해제할까요? 이 계정의 업데이트가 중단됩니다. 기존 PR 기록과 링크는 유지되며 다른 연결에는 영향을 주지 않습니다.","disconnect_confirm_cancel": "취소","disconnect_confirm_action": "연결 해제","not_configured": "이 배포에는 GitHub 연동이 설정되어 있지 않습니다. 운영자가 다음 값을 설정해야 합니다:",@@ -1042,7 +1042,18 @@"feature_auto_link_description": "제목이나 브랜치 이름에 태스크 번호(예: {{example}})가 있거나 설명에 \"Closes {{example}}\"가 있는 PR을 해당 태스크에 연결합니다.","status_paused": "일시 중지됨","pause": "GitHub 기능 일시 중지",- "resume": "GitHub 기능 재개"+ "resume": "GitHub 기능 재개",+ "add_account": "계정 또는 조직 추가",+ "disconnect_account": "{{login}} 연결 해제",+ "errors": {+ "missing_authorization": "GitHub에서 사용자 인증을 반환하지 않았습니다. 다시 연결하고 인증을 완료하세요. 기존 설치에서 반복되면 Multica 운영자에게 문의하세요.",+ "installation_not_authorized": "개인 설치에는 소유자의 GitHub 계정을 사용하세요. 조직 설치에는 승인된 모든 저장소의 관리자 권한이 있는 계정을 사용하고 저장소를 하나 이상 선택하세요.",+ "invalid_state": "GitHub 연결 요청이 만료되었거나 유효하지 않습니다. 설정 → 코드에서 다시 연결하세요.",+ "incomplete_callback": "GitHub 연결 응답이 불완전합니다. 설정 → 코드에서 다시 연결하세요.",+ "bad_workspace": "연결할 워크스페이스를 찾을 수 없습니다. 대상 워크스페이스를 열고 설정 → 코드에서 다시 시도하세요.",+ "verification_failed": "GitHub 설치 관리 권한을 확인하지 못했습니다. 다시 연결하고 반복되면 Multica 운영자에게 GitHub App 설정 확인을 요청하세요.",+ "persist_failed": "GitHub 연결을 저장하지 못했습니다. 설정 → 코드에서 다시 시도하고 반복되면 Multica 운영자에게 문의하세요."+ }},"vcs": {"section_title": "셀프 호스팅 Git",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 51a0e797a6..569372a120 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -1047,7 +1047,7 @@"disconnect": "Отключить","disconnecting": "Отключение…","disconnect_confirm_title": "Отключить GitHub App",- "disconnect_confirm_description": "Multica перестанет получать вебхуки для этой установки. Существующие зеркала PR и связи сохранятся; вы можете переподключиться в любой момент, чтобы возобновить обновления.",+ "disconnect_confirm_description": "Отключить {{login}} от этого рабочего пространства? Обновления этого аккаунта прекратятся. Существующие PR и связи сохранятся; другие подключения не изменятся.","disconnect_confirm_cancel": "Отмена","disconnect_confirm_action": "Отключить","not_configured": "Интеграция с GitHub не настроена для этого развёртывания. Операторам необходимо задать",@@ -1068,7 +1068,18 @@"feature_auto_link_description": "Связывает PR с задачей, чей идентификатор (например, {{example}}) указан в заголовке PR или названии ветки, либо стоит после слова «Closes» в его описании.","status_paused": "Приостановлено","pause": "Приостановить функции GitHub",- "resume": "Возобновить функции GitHub"+ "resume": "Возобновить функции GitHub",+ "add_account": "Добавить аккаунт или организацию",+ "disconnect_account": "Отключить {{login}}",+ "errors": {+ "missing_authorization": "GitHub не вернул авторизацию пользователя. Подключитесь снова и завершите авторизацию. Если ошибка повторяется для существующей установки, обратитесь к оператору Multica.",+ "installation_not_authorized": "Для личной установки используйте аккаунт GitHub владельца. Для организации нужен аккаунт с правами администратора во всех разрешённых репозиториях. Выберите хотя бы один репозиторий.",+ "invalid_state": "Запрос подключения GitHub истёк или недействителен. Начните подключение заново в Настройки → Код.",+ "incomplete_callback": "GitHub вернул неполный ответ подключения. Начните подключение заново в Настройки → Код.",+ "bad_workspace": "Рабочее пространство для подключения не найдено. Откройте нужное пространство и повторите попытку в Настройки → Код.",+ "verification_failed": "Не удалось проверить ваш доступ к установке GitHub. Повторите попытку; если ошибка повторяется, попросите оператора Multica проверить настройки GitHub App.",+ "persist_failed": "Не удалось сохранить подключение GitHub. Повторите попытку в Настройки → Код; если ошибка повторяется, обратитесь к оператору Multica."+ }},"vcs": {"section_title": "Git (self-hosted)",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex be53a08788..3c6da882cb 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1021,7 +1021,7 @@"disconnect": "断开","disconnecting": "断开中...","disconnect_confirm_title": "断开 GitHub App",- "disconnect_confirm_description": "Multica 将不再接收该安装的 webhook。已有的 PR 镜像与关联会保留,再次连接即可恢复同步。",+ "disconnect_confirm_description": "要从此工作区断开 {{login}} 吗?此账号的更新将停止,已有 PR 记录与关联会保留,其他连接不受影响。","disconnect_confirm_cancel": "取消","disconnect_confirm_action": "断开","not_configured": "当前部署没有配置 GitHub 集成。运维需要设置",@@ -1042,7 +1042,18 @@"feature_auto_link_description": "PR 标题或分支名含任务编号(如 {{example}}),或正文里写了 \"Closes {{example}}\" 时,自动关联到对应任务。","status_paused": "已暂停","pause": "暂停 GitHub 功能",- "resume": "恢复 GitHub 功能"+ "resume": "恢复 GitHub 功能",+ "add_account": "添加账号或组织",+ "disconnect_account": "断开 {{login}}",+ "errors": {+ "missing_authorization": "GitHub 未返回用户授权。请重新连接并完成授权。如果已有安装反复出现此问题,请联系 Multica 运维人员。",+ "installation_not_authorized": "个人安装请使用所属的 GitHub 账号;组织安装请使用对所有已授权仓库都有管理员权限的账号,并至少选择一个仓库。",+ "invalid_state": "GitHub 连接请求已过期或无效。请从设置 → 代码重新连接。",+ "incomplete_callback": "GitHub 返回的连接信息不完整。请从设置 → 代码重新连接。",+ "bad_workspace": "找不到此次连接的工作区。请打开目标工作区,从设置 → 代码重试。",+ "verification_failed": "无法验证你对 GitHub 安装的管理权限。请重新连接;若仍失败,请联系 Multica 运维人员检查 GitHub App 配置。",+ "persist_failed": "无法保存 GitHub 连接。请从设置 → 代码重试;若仍失败,请联系 Multica 运维人员。"+ }},"vcs": {"section_title": "自托管 Git",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 932a1498f4..0e56c6d80f 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -1021,7 +1021,7 @@"disconnect": "斷開","disconnecting": "斷開中...","disconnect_confirm_title": "斷開 GitHub App",- "disconnect_confirm_description": "Multica 將不再接收該安裝的 webhook。已有的 PR 映象與關聯會保留,再次連線即可恢復同步。",+ "disconnect_confirm_description": "要從此工作區斷開 {{login}} 嗎?此帳號的更新將停止,已有 PR 記錄與關聯會保留,其他連線不受影響。","disconnect_confirm_cancel": "取消","disconnect_confirm_action": "斷開","not_configured": "當前部署沒有配置 GitHub 整合。運維需要設定",@@ -1042,7 +1042,18 @@"feature_auto_link_description": "PR 標題或分支名含任務編號(如 {{example}}),或正文裡寫了 \"Closes {{example}}\" 時,自動關聯到對應任務。","status_paused": "已暫停","pause": "暫停 GitHub 功能",- "resume": "恢復 GitHub 功能"+ "resume": "恢復 GitHub 功能",+ "add_account": "新增帳號或組織",+ "disconnect_account": "斷開 {{login}}",+ "errors": {+ "missing_authorization": "GitHub 未傳回使用者授權。請重新連線並完成授權。如果已有安裝反覆出現此問題,請聯絡 Multica 維運人員。",+ "installation_not_authorized": "個人安裝請使用所屬的 GitHub 帳號;組織安裝請使用對所有已授權倉庫都有管理員權限的帳號,並至少選取一個倉庫。",+ "invalid_state": "GitHub 連線請求已過期或無效。請從設定 → 程式碼重新連線。",+ "incomplete_callback": "GitHub 傳回的連線資訊不完整。請從設定 → 程式碼重新連線。",+ "bad_workspace": "找不到此次連線的工作區。請開啟目標工作區,從設定 → 程式碼重試。",+ "verification_failed": "無法驗證你對 GitHub 安裝的管理權限。請重新連線;若仍失敗,請聯絡 Multica 維運人員檢查 GitHub App 設定。",+ "persist_failed": "無法儲存 GitHub 連線。請從設定 → 程式碼重試;若仍失敗,請聯絡 Multica 維運人員。"+ }},"vcs": {"section_title": "自託管 Git",diff --git a/packages/views/settings/components/code-tab.test.tsx b/packages/views/settings/components/code-tab.test.tsxindex 3e8cb9a8e0..e0eac8ea92 100644--- a/packages/views/settings/components/code-tab.test.tsx+++ b/packages/views/settings/components/code-tab.test.tsx@@ -137,7 +137,53 @@ describe("CodeTab — GitHub", () => {render(<CodeTab />, { wrapper: Wrapper });expect(screen.getByText("Connected")).toBeInTheDocument();- expect(screen.getByText(/Connected to acme · Connected by Ada/)).toBeInTheDocument();+ expect(screen.getByText("Connected to acme")).toBeInTheDocument();+ expect(screen.getByText("Connected by Ada")).toBeInTheDocument();+ });++ it("keeps adding available with two connections and attributes each connection", async () => {+ connect();+ installationsRef.current.installations.push({ id: "inst-2", account_login: "other-org", connected_by: "Grace" });+ const user = userEvent.setup();+ render(<CodeTab />, { wrapper: Wrapper });++ expect(screen.getByText("Connected by Ada")).toBeInTheDocument();+ expect(screen.getByText("Connected by Grace")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Add account or organization" }));+ expect(mockConnectGitHub).toHaveBeenCalledOnce();+ expect(mockDeleteInstallation).not.toHaveBeenCalled();+ expect(mockUpdateWorkspace).not.toHaveBeenCalled();+ });++ it.each([["acme", "inst-1"], ["other-org", "inst-2"]])(+ "disconnects only %s and leaves the other connection and workspace settings intact",+ async (login, id) => {+ connect();+ installationsRef.current.installations.push({ id: "inst-2", account_login: "other-org", connected_by: "Grace" });+ const user = userEvent.setup();+ const { rerender } = render(<CodeTab />, { wrapper: Wrapper });++ await user.click(screen.getByRole("button", { name: `Disconnect ${login}` }));+ const dialog = await screen.findByRole("alertdialog");+ expect(dialog).toHaveTextContent(login!);+ expect(mockDeleteInstallation).not.toHaveBeenCalled();+ await user.click(within(dialog).getByRole("button", { name: "Disconnect" }));+ await waitFor(() => expect(mockDeleteInstallation).toHaveBeenCalledExactlyOnceWith("workspace-1", id));+ expect(mockUpdateWorkspace).not.toHaveBeenCalled();+ installationsRef.current.installations = installationsRef.current.installations.filter((installation) => installation.id !== id);+ rerender(<CodeTab />);+ expect(screen.getByText(id === "inst-1" ? "Connected to other-org" : "Connected to acme")).toBeInTheDocument();+ },+ );++ it("shows both connections without management controls when can_manage is false", () => {+ connect();+ installationsRef.current.installations.push({ id: "inst-2", account_login: "other-org", connected_by: "Grace" });+ installationsRef.current.can_manage = false;+ render(<CodeTab />, { wrapper: Wrapper });+ expect(screen.getByText("Connected to acme")).toBeInTheDocument();+ expect(screen.getByText("Connected to other-org")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /Disconnect|Add account|GitHub actions/ })).toBeNull();});it("pauses GitHub from the row menu, keeping the other settings", async () => {@@ -198,8 +244,7 @@ describe("CodeTab — GitHub", () => {const user = userEvent.setup();render(<CodeTab />, { wrapper: Wrapper });- await user.click(screen.getByRole("button", { name: "GitHub actions" }));- await user.click(await screen.findByRole("menuitem", { name: "Disconnect" }));+ await user.click(screen.getByRole("button", { name: "Disconnect acme" }));expect(mockDeleteInstallation).not.toHaveBeenCalled();const dialog = await screen.findByRole("alertdialog");await user.click(within(dialog).getByRole("button", { name: "Disconnect" }));@@ -209,6 +254,31 @@ describe("CodeTab — GitHub", () => {);});+ it.each(["cancel", "confirm"])("keeps the account name in the outgoing confirmation on %s", async (action) => {+ connect();+ installationsRef.current.installations.push({ id: "inst-2", account_login: "other-org" });+ mockDeleteInstallation.mockResolvedValue(undefined);+ const user = userEvent.setup();+ render(<CodeTab />, { wrapper: Wrapper });++ await user.click(screen.getByRole("button", { name: "Disconnect acme" }));+ const dialog = await screen.findByRole("alertdialog");+ // Keep the outgoing node: jsdom does not run the dialog's exit animation.+ const description = within(dialog).getByText(/^Disconnect acme from this workspace\?/);+ await user.click(within(dialog).getByRole("button", { name: action === "cancel" ? "Cancel" : "Disconnect" }));+ await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());++ expect(description).toHaveTextContent("Disconnect acme from this workspace?");+ if (action === "cancel") {+ expect(mockDeleteInstallation).not.toHaveBeenCalled();+ } else {+ expect(mockDeleteInstallation).toHaveBeenCalledExactlyOnceWith("workspace-1", "inst-1");+ }++ await user.click(screen.getByRole("button", { name: "Disconnect other-org" }));+ expect(await screen.findByRole("alertdialog")).toHaveTextContent("Disconnect other-org from this workspace?");+ });+it("shows members the connection read-only and who can change it", () => {connect();roleRef.current = "member";diff --git a/packages/views/settings/components/code-tab.tsx b/packages/views/settings/components/code-tab.tsxindex 97cffb7c81..0ce6d0e69e 100644--- a/packages/views/settings/components/code-tab.tsx+++ b/packages/views/settings/components/code-tab.tsx@@ -21,7 +21,6 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,- DropdownMenuSeparator,DropdownMenuTrigger,} from "@multica/ui/components/ui/dropdown-menu";import { useConfigStore } from "@multica/core/config";@@ -78,13 +77,14 @@ export function CodeTab() {const configured = installationData?.configured ?? false;const canManageGitHub = installationData?.can_manage === true;const connected = installations.length > 0;- const primaryInstallation = installations[0] ?? null;const flags = deriveGitHubSettings(workspace);const [savingKey, setSavingKey] = useState<GitHubSettingsKey | null>(null);const githubConnection = useConnectGitHub(wsId);const { connecting, connect: handleConnect } = githubConnection;- const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);+ const [disconnectOpen, setDisconnectOpen] = useState(false);+ // Retain the last target while the dialog animates out.+ const [disconnectTarget, setDisconnectTarget] = useState<(typeof installations)[number] | null>(null);const [disconnecting, setDisconnecting] = useState(false);async function persistSetting(key: GitHubSettingsKey, next: boolean) {@@ -110,10 +110,10 @@ export function CodeTab() {if (!disconnectTarget || disconnecting) return;setDisconnecting(true);try {- await api.deleteGitHubInstallation(wsId, disconnectTarget);+ await api.deleteGitHubInstallation(wsId, disconnectTarget.id);await qc.invalidateQueries({ queryKey: ["github", wsId] });toast.success(t(($) => $.github.toast_disconnected));- setDisconnectTarget(null);+ setDisconnectOpen(false);} catch (e) {toast.error(e instanceof Error ? e.message : t(($) => $.github.toast_disconnect_failed));} finally {@@ -134,17 +134,7 @@ export function CodeTab() {const pausedNote = !flags.enabled ? (<span className="block">{t(($) => $.github.master_description_off)}</span>) : null;- const githubDetail = connected ? (- <>- {t(($) => $.github.connected_to, {- login: installations.map((i) => i.account_login).join(", "),- })}- {primaryInstallation?.connected_by- ? ` · ${t(($) => $.github.connected_by, { name: primaryInstallation.connected_by })}`- : null}- {pausedNote}- </>- ) : !canManageGitHub ? (+ const githubDetail = connected ? pausedNote : !canManageGitHub ? (<>{t(($) => $.github.contact_admin_to_connect)}{pausedNote}@@ -176,6 +166,7 @@ export function CodeTab() {<SettingsCard><SettingsRowanchor="github"+ size="none"label={<span className="flex min-w-0 items-center gap-3"><HostMark>@@ -191,22 +182,21 @@ export function CodeTab() {>{canManageGitHub ? (<span className="flex items-center gap-1">- {connected ? null : (- <Button- variant="outline"- size="sm"- onClick={handleConnect}- disabled={connecting || !configured}- aria-busy={connecting || undefined}- >- {connecting- ? t(($) => $.github.connect_opening)+ <Button+ variant="outline"+ size="sm"+ onClick={handleConnect}+ disabled={connecting || !configured}+ aria-busy={connecting || undefined}+ >+ {connecting+ ? t(($) => $.github.connect_opening)+ : connected+ ? t(($) => $.github.add_account): t(($) => $.github.connect_github)}- </Button>- )}+ </Button>{/* Resume stays reachable after a disconnect: the pause is a- workspace setting, and Co-authored-by works without an App.- Only disconnecting needs an installation. */}+ workspace setting, and Co-authored-by works without an App. */}{connected || !flags.enabled ? (<DropdownMenu><DropdownMenuTrigger@@ -230,24 +220,41 @@ export function CodeTab() {? t(($) => $.github.pause): t(($) => $.github.resume)}</DropdownMenuItem>- {primaryInstallation ? (- <>- <DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- onClick={() => setDisconnectTarget(primaryInstallation.id)}- >- <Unplug />- {t(($) => $.github.disconnect)}- </DropdownMenuItem>- </>- ) : null}</DropdownMenuContent></DropdownMenu>) : null}</span>) : null}</SettingsRow>+ {installations.map((installation) => (+ <SettingsRow+ key={installation.id}+ className="pl-16"+ label={+ <span className="break-words">+ {t(($) => $.github.connected_to, { login: installation.account_login })}+ </span>+ }+ description={installation.connected_by+ ? t(($) => $.github.connected_by, { name: installation.connected_by })+ : undefined}+ >+ {canManageGitHub ? (+ <Button+ variant="ghost"+ size="sm"+ aria-label={t(($) => $.github.disconnect_account, { login: installation.account_login })}+ onClick={() => {+ setDisconnectTarget(installation);+ setDisconnectOpen(true);+ }}+ >+ <Unplug />+ {t(($) => $.github.disconnect)}+ </Button>+ ) : null}+ </SettingsRow>+ ))}{vcsAvailable ? <VCSConnectionRows /> : null}</SettingsCard></SettingsSection>@@ -310,16 +317,16 @@ export function CodeTab() {</SettingsSection><AlertDialog- open={!!disconnectTarget}+ open={disconnectOpen}onOpenChange={(v) => {- if (!v && !disconnecting) setDisconnectTarget(null);+ if (!v && !disconnecting) setDisconnectOpen(false);}}><AlertDialogContent><AlertDialogHeader><AlertDialogTitle>{t(($) => $.github.disconnect_confirm_title)}</AlertDialogTitle><AlertDialogDescription>- {t(($) => $.github.disconnect_confirm_description)}+ {t(($) => $.github.disconnect_confirm_description, { login: disconnectTarget?.account_login ?? "" })}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>diff --git a/packages/views/settings/components/repositories-section.test.tsx b/packages/views/settings/components/repositories-section.test.tsxindex fff2dce5e7..aa21ef8d97 100644--- a/packages/views/settings/components/repositories-section.test.tsx+++ b/packages/views/settings/components/repositories-section.test.tsx@@ -255,15 +255,59 @@ describe("RepositoriesSection", () => {expect(mockConnectGitHub).toHaveBeenCalledOnce();});+ it("keeps both browsing and adding an account available after connecting", async () => {+ githubRef.current.installations = [{ id: "existing", account_login: "alice" }];+ const user = userEvent.setup();+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });+ await openAddMenu(user);+ expect(await screen.findByRole("menuitem", { name: "Choose from GitHub" })).toBeInTheDocument();+ await user.click(screen.getByRole("menuitem", { name: "Add account or organization" }));+ expect(mockConnectGitHub).toHaveBeenCalledOnce();+ expect(mockUpdateWorkspace).not.toHaveBeenCalled();+ });++ it("honors can_manage for GitHub even when workspace editing is available", async () => {+ githubRef.current.can_manage = false;+ githubRef.current.installations = [{ id: "existing", account_login: "alice" }];+ const user = userEvent.setup();+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });+ await openAddMenu(user);+ expect(await screen.findByRole("menuitem", { name: "Enter a URL..." })).toBeInTheDocument();+ expect(screen.queryByRole("menuitem", { name: /GitHub|Add account/ })).toBeNull();+ });++ it.each([+ ["missing_authorization", /GitHub did not return user authorization/],+ ["installation_not_authorized", /admin access to every authorized repository/],+ ["invalid_state", /expired or is invalid/],+ ["missing_params", /incomplete/],+ ["bad_installation_id", /incomplete/],+ ["bad_workspace", /workspace/],+ ["verification_failed", /verify/],+ ["persist_failed", /save/],+ ["untrusted-value", /Could not connect GitHub/],+ ])("explains a %s callback without altering existing connections", async (code, message) => {+ githubRef.current.installations = [{ id: "existing", account_login: "alice" }];+ searchParamsRef.current = new URLSearchParams(`tab=code§ion=github&github_error=${code}`);+ render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith(expect.stringMatching(message)));+ expect(mockNavReplace).toHaveBeenCalledWith("/acme/settings?tab=code§ion=github");+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(mockConnectGitHub).not.toHaveBeenCalled();+ expect(mockUpdateWorkspace).not.toHaveBeenCalled();+ });+it("explains why GitHub import is unavailable when browsing is not configured", async () => {githubRef.current = { ...githubRef.current, repository_browse_configured: false };+ githubRef.current.installations = [{ id: "existing", account_login: "alice" }];const user = userEvent.setup();render(<RepositoriesSection connection={connection} />, { wrapper: Wrapper });await openAddMenu(user);- const item = await screen.findByRole("menuitem", { name: /Connect GitHub/ });+ const item = await screen.findByRole("menuitem", { name: /Choose from GitHub/ });expect(item).toHaveAttribute("aria-disabled", "true");expect(item).toHaveTextContent("GITHUB_APP_ID");+ expect(screen.getByRole("menuitem", { name: "Add account or organization" })).not.toHaveAttribute("aria-disabled", "true");});it("imports selected GitHub repositories and deduplicates HTTPS against SSH", async () => {diff --git a/packages/views/settings/components/repositories-section.tsx b/packages/views/settings/components/repositories-section.tsxindex c3c0b4195a..de523bee59 100644--- a/packages/views/settings/components/repositories-section.tsx+++ b/packages/views/settings/components/repositories-section.tsx@@ -174,13 +174,14 @@ export function RepositoriesSection({ connection }: { connection: ReturnType<typ[githubData?.installations],);const githubConnectConfigured = githubData?.configured === true;+ const canManageGitHub = canManageWorkspace && githubData?.can_manage === true;const githubBrowseConfigured =githubData?.repository_browse_configured === true;const githubRepositoriesQuery = useInfiniteQuery({...githubInstallationRepositoriesOptions(wsId, selectedInstallationID),enabled:githubPickerOpen &&- canManageWorkspace &&+ canManageGitHub &&githubBrowseConfigured &&!!selectedInstallationID,});@@ -228,7 +229,7 @@ export function RepositoriesSection({ connection }: { connection: ReturnType<typif (handledCallback.current === callbackKey) return;const connected = navigation.searchParams.get("github_connected") === "1";const githubError = navigation.searchParams.get("github_error");- if ((!connected && !githubError) || !canManageWorkspace) return;+ if ((!connected && !githubError) || !canManageGitHub) return;if (!githubError &&(githubInstallationsPending || githubInstallationsFetching)@@ -238,7 +239,32 @@ export function RepositoriesSection({ connection }: { connection: ReturnType<typhandledCallback.current = callbackKey;if (githubError) {- toast.error(t(($) => $.repositories.github_connect_failed));+ switch (githubError) {+ case "missing_authorization":+ toast.error(t(($) => $.github.errors.missing_authorization));+ break;+ case "installation_not_authorized":+ toast.error(t(($) => $.github.errors.installation_not_authorized));+ break;+ case "invalid_state":+ toast.error(t(($) => $.github.errors.invalid_state));+ break;+ case "missing_params":+ case "bad_installation_id":+ toast.error(t(($) => $.github.errors.incomplete_callback));+ break;+ case "bad_workspace":+ toast.error(t(($) => $.github.errors.bad_workspace));+ break;+ case "verification_failed":+ toast.error(t(($) => $.github.errors.verification_failed));+ break;+ case "persist_failed":+ toast.error(t(($) => $.github.errors.persist_failed));+ break;+ default:+ toast.error(t(($) => $.repositories.github_connect_failed));+ }} else if (githubInstallations.length > 0 && githubBrowseConfigured) {const installationID = navigation.searchParams.get("github_installation") ?? githubInstallations[0]!.id;if (githubInstallations.some((installation) => installation.id === installationID)) {@@ -258,7 +284,7 @@ export function RepositoriesSection({ connection }: { connection: ReturnType<typconst search = next.toString();navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}`);}, [- canManageWorkspace,+ canManageGitHub,githubBrowseConfigured,githubInstallations,githubInstallationsFetching,@@ -269,7 +295,7 @@ export function RepositoriesSection({ connection }: { connection: ReturnType<typuseEffect(() => {const installationID = connectedInstallationID;- if (!installationID || !canManageWorkspace || githubInstallationsPending || githubInstallationsFetching) return;+ if (!installationID || !canManageGitHub || githubInstallationsPending || githubInstallationsFetching) return;if (!githubInstallations.some((installation) => installation.id === installationID)) return;if (githubBrowseConfigured) {setSelectedInstallationID(installationID);@@ -280,7 +306,7 @@ export function RepositoriesSection({ connection }: { connection: ReturnType<typtoast.error(t(($) => $.repositories.github_browse_not_configured));}resetConnection();- }, [connectedInstallationID, resetConnection, canManageWorkspace, githubInstallations, githubInstallationsPending, githubInstallationsFetching, githubBrowseConfigured, t]);+ }, [connectedInstallationID, resetConnection, canManageGitHub, githubInstallations, githubInstallationsPending, githubInstallationsFetching, githubBrowseConfigured, t]);const preselectingRepositories = githubPickerOpen &&selectedInstallationID === preselectInstallationID &&@@ -420,11 +446,6 @@ export function RepositoriesSection({ connection }: { connection: ReturnType<typif (!workspace) return null;- const githubItemDisabled =- connectingGitHub ||- !githubBrowseConfigured ||- (!githubConnectConfigured && githubInstallations.length === 0);-return (<SettingsSectiontitle={t(($) => $.repositories.section_title)}@@ -438,32 +459,32 @@ export function RepositoriesSection({ connection }: { connection: ReturnType<typ<ChevronDown /></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-auto min-w-56">- <DropdownMenuItem- disabled={githubItemDisabled}- onClick={() =>- githubInstallations.length > 0- ? openGitHubPicker()- : void connectGitHub()- }- >- {connectingGitHub ? (- <LoaderCircle className="animate-spin" />- ) : (- <GitHubMark className="size-4" />- )}- <span className="flex flex-col">- <span>+ {canManageGitHub ? (+ <>+ {githubInstallations.length > 0 ? (+ <DropdownMenuItem disabled={!githubBrowseConfigured} onClick={openGitHubPicker}>+ <GitHubMark className="size-4" />+ <span className="flex flex-col">+ <span>{t(($) => $.repositories.choose_from_github)}</span>+ {!githubBrowseConfigured ? (+ <span className="text-caption text-muted-foreground">+ {t(($) => $.repositories.github_browse_not_configured)}+ </span>+ ) : null}+ </span>+ </DropdownMenuItem>+ ) : null}+ <DropdownMenuItem+ disabled={connectingGitHub || !githubConnectConfigured}+ onClick={() => void connectGitHub()}+ >+ {connectingGitHub ? <LoaderCircle className="animate-spin" /> : <GitHubMark className="size-4" />}{githubInstallations.length > 0- ? t(($) => $.repositories.choose_from_github)+ ? t(($) => $.github.add_account): t(($) => $.repositories.connect_github)}- </span>- {!githubBrowseConfigured ? (- <span className="text-caption text-muted-foreground">- {t(($) => $.repositories.github_browse_not_configured)}- </span>- ) : null}- </span>- </DropdownMenuItem>+ </DropdownMenuItem>+ </>+ ) : null}<DropdownMenuItemonClick={() => setDraft({ index: null, url: "", description: "" })}>diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex a4d2c5b464..1aee65321c 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -58,6 +58,7 @@ type GitHubInstallationResponse struct {AccountType string `json:"account_type"`AccountAvatarURL *string `json:"account_avatar_url"`CreatedAt string `json:"created_at"`+ ConnectedBy string `json:"connected_by,omitempty"`}type GitHubPullRequestResponse struct {@@ -738,14 +739,15 @@ func (h *Handler) ListGitHubInstallations(w http.ResponseWriter, r *http.Requestmember, _ := middleware.MemberFromContext(r.Context())canManage := roleAllowed(member.Role, "owner", "admin")- rows, err := h.Queries.ListGitHubInstallationsByWorkspace(r.Context(), wsUUID)+ rows, err := h.Queries.ListGitHubInstallationsWithConnectedBy(r.Context(), wsUUID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list installations")return}out := make([]GitHubInstallationResponse, 0, len(rows))for _, row := range rows {- resp := githubInstallationToResponse(row)+ resp := githubInstallationToResponse(row.GithubInstallation)+ resp.ConnectedBy = row.ConnectedByif !canManage {resp.InstallationID = nil}diff --git a/server/internal/handler/github_install_ownership.go b/server/internal/handler/github_install_ownership.goindex abfbc01f6a..84c835c69e 100644--- a/server/internal/handler/github_install_ownership.go+++ b/server/internal/handler/github_install_ownership.go@@ -60,9 +60,8 @@ func verifyGitHubInstallationOwnership(ctx context.Context, code string, install}// githubOwnershipErrorCode maps a verification failure to the `github_error`-// code carried back to Settings. The frontend renders one generic "connect-// failed" toast for all of them; the distinction is for operators reading-// logs and support tickets.+// code carried back to Settings, where known codes receive specific recovery+// instructions and unknown codes fall back to a generic connection error.func githubOwnershipErrorCode(err error) string {switch {case errors.Is(err, errGitHubInstallationNotAuthorized):diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.goindex 137e801843..df9ed9d780 100644--- a/server/internal/handler/github_test.go+++ b/server/internal/handler/github_test.go@@ -2065,6 +2065,65 @@ func TestListGitHubInstallations_RoleGating(t *testing.T) {})}+func TestGitHubInstallationConnectedByIsWorkspaceScoped(t *testing.T) {+ if testHandler == nil {+ t.Skip("handler test fixture not initialized (no DB?)")+ }+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "GitHub connection attribution", "slug": fmt.Sprintf("github-connectors-%d", time.Now().UnixNano()), "issue_prefix": "ATTR",+ })+ connectors := []struct {+ name string+ member bool+ }{+ {"Ada", true}, {"Grace", true}, {"Former member", false},+ }+ for index, connector := range connectors {+ userID := dbfx.Insert(t, "user", testutil.Cols{+ "name": connector.name, "email": fmt.Sprintf("github-connector-%s-%[email protected]", wsID, index),+ })+ if connector.member {+ dbfx.Insert(t, "member", testutil.Cols{"workspace_id": wsID, "user_id": userID, "role": "admin"})+ }+ dbfx.Insert(t, "github_installation", testutil.Cols{+ "workspace_id": wsID, "installation_id": 94670000 + index, "account_login": connector.name, "account_type": "User", "connected_by_id": userID,+ })+ }+ dbfx.Insert(t, "github_installation", testutil.Cols{+ "workspace_id": wsID, "installation_id": 94670003, "account_login": "legacy", "account_type": "User",+ })+ for _, role := range []string{"owner", "member"} {+ t.Run(role, func(t *testing.T) {+ req := withURLParam(httptest.NewRequest(http.MethodGet, "/", nil), "id", wsID)+ req = req.WithContext(middleware.SetMemberContext(req.Context(), wsID, db.Member{Role: role}))+ var out struct {+ Installations []map[string]any `json:"installations"`+ }+ testutil.Call(t, testHandler.ListGitHubInstallations, req).Want(http.StatusOK).JSON(&out)+ if len(out.Installations) != 4 {+ t.Fatalf("installations = %d, want 4", len(out.Installations))+ }+ for _, installation := range out.Installations {+ login := installation["account_login"]+ name, _ := installation["connected_by"].(string)+ if login == "Ada" || login == "Grace" {+ if name != login {+ t.Errorf("connected_by for %s = %q", login, name)+ }+ } else if _, present := installation["connected_by"]; present {+ t.Errorf("must omit attribution for absent workspace member: %v", installation)+ }+ if _, present := installation["connected_by_id"]; present {+ t.Error("connector user ID must not be exposed")+ }+ if _, present := installation["installation_id"]; role == "member" && present {+ t.Error("numeric installation ID must remain admin-only")+ }+ }+ })+ }+}+// TestGitHubRoutes_RoleGating exercises the router-level middleware split// introduced in MUL-2413: GET installations runs under// RequireWorkspaceMemberFromURL while connect / delete remain behinddiff --git a/server/pkg/db/generated/github.sql.go b/server/pkg/db/generated/github.sql.goindex 65c761dc63..e3bf712328 100644--- a/server/pkg/db/generated/github.sql.go+++ b/server/pkg/db/generated/github.sql.go@@ -508,6 +508,52 @@ func (q *Queries) ListGitHubInstallationsByWorkspace(ctx context.Context, workspreturn items, nil}+const listGitHubInstallationsWithConnectedBy = `-- name: ListGitHubInstallationsWithConnectedBy :many+SELECT gi.id, gi.workspace_id, gi.installation_id, gi.account_login, gi.account_type, gi.account_avatar_url, gi.connected_by_id, gi.created_at, gi.updated_at, COALESCE(u.name, '')::text AS connected_by+FROM github_installation gi+LEFT JOIN member m ON m.user_id = gi.connected_by_id AND m.workspace_id = gi.workspace_id+LEFT JOIN "user" u ON u.id = m.user_id+WHERE gi.workspace_id = $1+ORDER BY gi.created_at ASC+`++type ListGitHubInstallationsWithConnectedByRow struct {+ GithubInstallation GithubInstallation `json:"github_installation"`+ ConnectedBy string `json:"connected_by"`+}++// Only disclose the connector's display name while they belong to this workspace.+func (q *Queries) ListGitHubInstallationsWithConnectedBy(ctx context.Context, workspaceID pgtype.UUID) ([]ListGitHubInstallationsWithConnectedByRow, error) {+ rows, err := q.db.Query(ctx, listGitHubInstallationsWithConnectedBy, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListGitHubInstallationsWithConnectedByRow{}+ for rows.Next() {+ var i ListGitHubInstallationsWithConnectedByRow+ if err := rows.Scan(+ &i.GithubInstallation.ID,+ &i.GithubInstallation.WorkspaceID,+ &i.GithubInstallation.InstallationID,+ &i.GithubInstallation.AccountLogin,+ &i.GithubInstallation.AccountType,+ &i.GithubInstallation.AccountAvatarUrl,+ &i.GithubInstallation.ConnectedByID,+ &i.GithubInstallation.CreatedAt,+ &i.GithubInstallation.UpdatedAt,+ &i.ConnectedBy,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listIssueIDsForPullRequest = `-- name: ListIssueIDsForPullRequest :manySELECT issue_id FROM issue_pull_requestWHERE pull_request_id = $1diff --git a/server/pkg/db/queries/github.sql b/server/pkg/db/queries/github.sqlindex 72fca389d0..7a1b2c9142 100644--- a/server/pkg/db/queries/github.sql+++ b/server/pkg/db/queries/github.sql@@ -7,6 +7,15 @@ SELECT * FROM github_installationWHERE workspace_id = $1ORDER BY created_at ASC;+-- name: ListGitHubInstallationsWithConnectedBy :many+-- Only disclose the connector's display name while they belong to this workspace.+SELECT sqlc.embed(gi), COALESCE(u.name, '')::text AS connected_by+FROM github_installation gi+LEFT JOIN member m ON m.user_id = gi.connected_by_id AND m.workspace_id = gi.workspace_id+LEFT JOIN "user" u ON u.id = m.user_id+WHERE gi.workspace_id = $1+ORDER BY gi.created_at ASC;+-- name: ListGitHubInstallationsByInstallationID :many-- One installation_id can be bound to several workspaces; webhook routing lists-- every binding and fans the event out to each bound workspace. Ordered oldest