Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(settings): consolidate GitHub options under a dedicated Settings tab (MUL-2414)
Jiayuan Zhangcd37b4e3d676
diff --git a/.env.example b/.env.exampleindex c998c9003c..1c09af4454 100644--- a/.env.example+++ b/.env.example@@ -161,7 +161,7 @@ CORS_ALLOWED_ORIGINS=# `Authorization: Bearer <token>`.# REALTIME_METRICS_TOKEN=-# GitHub App integration (Settings → Integrations "Connect GitHub")+# GitHub App integration (Settings → GitHub "Connect GitHub")# Both must be set for the Connect button to enable and for webhooks to be# accepted; leave empty to disable the integration. See docs/github-integration.# GITHUB_APP_SLUG is the tail of https://github.com/apps/<slug>.diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex c3b4f5d4c7..32bf09f636 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -180,12 +180,12 @@ The [GitHub PR ↔ issue integration](/github-integration) needs two variables.| Variable | Default | Description ||---|---|---|-| `GITHUB_APP_SLUG` | empty | The slug of your GitHub App (the tail of `https://github.com/apps/<slug>`). Drives the Settings → Integrations install button URL |+| `GITHUB_APP_SLUG` | empty | The slug of your GitHub App (the tail of `https://github.com/apps/<slug>`). Drives the Settings → GitHub install button URL || `GITHUB_WEBHOOK_SECRET` | empty | The Webhook secret you set on the GitHub App. Used for HMAC-SHA256 verification of every `pull_request` / `installation` delivery, and as the HMAC key for the setup-callback state token |**Behavior when either is unset:**-- `Connect GitHub` in Settings → Integrations is **disabled** and shows a "not configured" hint to admins.+- `Connect GitHub` in Settings → GitHub is **disabled** and shows a "not configured" hint to admins.- The `/api/webhooks/github` endpoint returns **`503 github webhooks not configured`** — Multica refuses to process events with no secret rather than treating every signature as valid.**Note:** `GITHUB_WEBHOOK_SECRET` is reused as the signing key for the install-flow state token, so operators only need to manage one secret. It is **not** the GitHub App's *Client* secret — Client secrets are OAuth-related and not used by this integration. See [GitHub integration → Self-host setup](/github-integration#self-host-setup) for the full walkthrough.diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex b65d3a8a15..050a4d28c3 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -180,12 +180,12 @@ Multica 存储用户上传的附件(评论里的图片、文件等)。**优| 环境变量 | 默认值 | 说明 ||---|---|---|-| `GITHUB_APP_SLUG` | 空 | 你的 GitHub App slug(`https://github.com/apps/<slug>` 的尾部)。Settings → Integrations 里安装按钮的跳转 URL 用它拼 |+| `GITHUB_APP_SLUG` | 空 | 你的 GitHub App slug(`https://github.com/apps/<slug>` 的尾部)。Settings → GitHub 里安装按钮的跳转 URL 用它拼 || `GITHUB_WEBHOOK_SECRET` | 空 | 你在 GitHub App 上设置的 Webhook secret。每条 `pull_request` / `installation` delivery 都用它做 HMAC-SHA256 校验;同一个值也用作 setup 回调里 state token 的签名密钥 |**任一变量未设时:**-- Settings → Integrations 里 `Connect GitHub` 按钮 **disable**,对 admin 显示「not configured」提示+- Settings → GitHub 里 `Connect GitHub` 按钮 **disable**,对 admin 显示「not configured」提示- `/api/webhooks/github` 直接返回 **`503 github webhooks not configured`**——secret 没配置时 Multica 拒绝处理任何 webhook 事件,而不是把所有签名当 valid**注意:** `GITHUB_WEBHOOK_SECRET` 同时被复用为 install 流程里 state token 的签名密钥,所以运维只需要维护一个 secret。它**不是** GitHub App 的 *Client* secret——Client secret 是 OAuth 用的,和本集成无关。完整配置流程见 [GitHub 集成 → Self-Host 配置](/github-integration#self-host-配置)。diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdxindex 7816d29942..59ffad7171 100644--- a/apps/docs/content/docs/github-integration.mdx+++ b/apps/docs/content/docs/github-integration.mdx@@ -5,7 +5,7 @@ description: Connect a GitHub App once, then PRs whose branch, title, or body reimport { Callout } from "fumadocs-ui/components/callout";-Connect a GitHub account or organization once in **Settings → Integrations**. After that, any pull request whose branch name, title, or body contains an issue identifier (for example `MUL-123`) is **auto-linked** to that [issue](/issues), appears under **Pull requests** in the issue sidebar, and — when the PR is merged — moves the issue to **Done**.+Connect a GitHub account or organization once in **Settings → GitHub**. After that, any pull request whose branch name, title, or body contains an issue identifier (for example `MUL-123`) is **auto-linked** to that [issue](/issues), appears under **Pull requests** in the issue sidebar, and — when the PR is merged — moves the issue to **Done**.There is no per-issue setup. The whole flow is identifier-driven.@@ -13,7 +13,7 @@ There is no per-issue setup. The whole flow is identifier-driven.| Surface | Behavior ||---|---|-| **Settings → Integrations** | Workspace admins see a GitHub card with a **Connect GitHub** button. Clicking it opens GitHub's App install page; after install you bounce back to Settings. |+| **Settings → GitHub** | Workspace admins see the GitHub tab with a master toggle, **Connect GitHub** button, and feature switches (PR sidebar, Co-authored-by, auto-link). After install you bounce back to the GitHub tab. || **Issue sidebar → Pull requests** | Every PR auto-linked to this issue, with title, repo, state (`Open` / `Draft` / `Merged` / `Closed`), and author. Click a row to jump to the PR on GitHub. || **Webhook (background)** | On every `pull_request` event, Multica upserts the PR row, scans the PR for issue identifiers, and (re)builds the link rows. Idempotent — replaying a delivery is a no-op. || **Auto-status on merge** | When a PR transitions to `merged`, every linked issue not already `Done` or `Cancelled` is moved to `Done`. The status change is timeline-logged with source `github_pr_merged`. |@@ -56,10 +56,10 @@ The action is attributed to the `system` actor on the timeline. Subscribers of t## Disconnecting-In **Settings → Integrations** there is no installation list — you manage existing installations from GitHub directly:+In **Settings → GitHub** there is no installation list — you manage existing installations from GitHub directly:- **From GitHub** — uninstall the Multica GitHub App at `https://github.com/settings/installations` (personal) or `https://github.com/organizations/<org>/settings/installations` (org). Multica receives the `installation.deleted` webhook and drops the row in real time; any open Settings tab updates without a refresh.-- **Disconnect from inside Multica is admin-only** — the Settings card is hidden for non-admins.+- **Disconnect from inside Multica is admin-only** — the Disconnect control on the GitHub tab is hidden for non-admins. It stays available even when the master GitHub switch is off, so admins can still revoke a stale installation after one-click-disabling the feature.After disconnect, mirrored PR rows stay in the database so historical issue sidebars still show what was linked, but no new webhook events from that installation will be accepted.@@ -121,7 +121,7 @@ Both variables are required. If either is missing:- `Connect GitHub` in Settings is **disabled** and shows a "not configured" hint.- The `/api/webhooks/github` endpoint returns **`503 github webhooks not configured`** — Multica refuses to process events with no secret, rather than silently treating every signature as valid.-`FRONTEND_ORIGIN` must also be set (it already is for any production self-host); the setup callback bounces the user back to `<FRONTEND_ORIGIN>/settings` after install.+`FRONTEND_ORIGIN` must also be set (it already is for any production self-host); the setup callback bounces the user back to `<FRONTEND_ORIGIN>/settings?tab=github` after install.Restart the API after setting the env vars.@@ -139,10 +139,10 @@ Three tables get created: `github_installation`, `github_pull_request`, `issue_pIn Multica:-1. Open **Settings → Integrations** as an owner or admin.+1. Open **Settings → GitHub** as an owner or admin.2. Click **Connect GitHub**. GitHub opens in a new tab.3. Pick the repositories to grant access to and **Install**.-4. GitHub redirects back to `<api-host>/api/github/setup`, which records the installation and bounces you to `<FRONTEND_ORIGIN>/settings?github_connected=1`.+4. GitHub redirects back to `<api-host>/api/github/setup`, which records the installation and bounces you to `<FRONTEND_ORIGIN>/settings?tab=github&github_connected=1`.After that, open any PR whose branch / title / body contains an issue identifier — within a few seconds the Pull requests block appears on that issue's detail page.diff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdxindex 2e1064014a..7007ade91c 100644--- a/apps/docs/content/docs/github-integration.zh.mdx+++ b/apps/docs/content/docs/github-integration.zh.mdx@@ -5,7 +5,7 @@ description: 一次性连接 GitHub App,之后 PR 的分支名、标题或正import { Callout } from "fumadocs-ui/components/callout";-在 **Settings → Integrations** 里一次性连一个 GitHub 账号或组织。之后任何 PR 只要分支名、标题或正文里出现 issue 编号(例如 `MUL-123`),就会**自动关联**到那个 [issue](/issues),出现在 issue 详情页右侧的 **Pull requests** 区块里——PR 合并时,issue 自动转 **Done**。+在 **Settings → GitHub** 里一次性连一个 GitHub 账号或组织。之后任何 PR 只要分支名、标题或正文里出现 issue 编号(例如 `MUL-123`),就会**自动关联**到那个 [issue](/issues),出现在 issue 详情页右侧的 **Pull requests** 区块里——PR 合并时,issue 自动转 **Done**。没有 per-issue 的配置,整个流程是「编号驱动」的。@@ -13,7 +13,7 @@ import { Callout } from "fumadocs-ui/components/callout";| 出现位置 | 行为 ||---|---|-| **Settings → Integrations** | 工作区 owner / admin 看到一个 GitHub 卡片,里面有 **Connect GitHub** 按钮。点击会打开 GitHub 的 App 安装页;装好后跳回 Settings。 |+| **Settings → GitHub** | 工作区 owner / admin 看到 GitHub 这个 tab,里面有主开关、**Connect GitHub** 按钮,以及功能开关(PR 侧栏、Co-authored-by、auto-link)。点 Connect 会打开 GitHub 的 App 安装页;装好后跳回 GitHub tab。 || **Issue 详情侧栏 → Pull requests** | 列出所有自动关联到该 issue 的 PR,含标题、仓库、状态(`Open` / `Draft` / `Merged` / `Closed`)和作者。点一行跳到 GitHub。 || **Webhook(后台)** | 每次 `pull_request` 事件触发:upsert PR 行 → 扫描里面的 issue 编号 →(重新)建立 link。幂等——重投 delivery 不会产生重复记录。 || **Merge 自动改 status** | PR 转 `merged` 时,所有已关联且状态不是 `Done` / `Cancelled` 的 issue 会被推到 `Done`。时间线里以 source 为 `github_pr_merged` 记录。 |@@ -56,10 +56,10 @@ PR **关闭但没合并**——只更新 PR 卡片的状态为 `Closed`,issue## 断开连接-**Settings → Integrations** 里没有 installation 列表——现有 installation 直接到 GitHub 上管理:+**Settings → GitHub** 里没有 installation 列表——现有 installation 直接到 GitHub 上管理:- **从 GitHub 卸载** —— 个人在 `https://github.com/settings/installations`、组织在 `https://github.com/organizations/<org>/settings/installations` 卸载 Multica App。Multica 收到 `installation.deleted` webhook 后立刻删行;任何已打开的 Settings tab 实时更新,不用刷新-- **Multica 这边的断开是 admin only** —— 卡片对非 admin 不显示连接操作+- **Multica 这边的断开是 admin only** —— GitHub tab 上的 Disconnect 控件对非 admin 不显示;主开关关掉时 Disconnect 仍然可用,方便 admin 一键关闭功能后再单独清理已连接的 installation断开之后,已经镜像的 PR 行保留在数据库里——历史 issue 侧栏仍能显示当时关联的 PR,但来自这个 installation 的新 webhook 事件不再被接受。@@ -121,7 +121,7 @@ GITHUB_WEBHOOK_SECRET=<你刚生成的 webhook secret>- Settings 里 `Connect GitHub` 按钮会被 **disable**,并显示「not configured」提示- `/api/webhooks/github` 直接返回 **`503 github webhooks not configured`**——Multica 在 secret 没配置时拒绝处理事件,不会出现「没 secret 也接受 webhook」的安全坑-`FRONTEND_ORIGIN` 也必须设置(任何生产 self-host 都已经设了)——setup 回调结束后用它把用户跳回 `<FRONTEND_ORIGIN>/settings`。+`FRONTEND_ORIGIN` 也必须设置(任何生产 self-host 都已经设了)——setup 回调结束后用它把用户跳回 `<FRONTEND_ORIGIN>/settings?tab=github`。设完 env 重启 API。@@ -139,10 +139,10 @@ make migrate-up到 Multica:-1. 以 owner 或 admin 身份打开 **Settings → Integrations**+1. 以 owner 或 admin 身份打开 **Settings → GitHub**2. 点 **Connect GitHub**,GitHub 在新 tab 打开3. 选择要授权的仓库,点 **Install**-4. GitHub 跳回 `<api-host>/api/github/setup`,落库后再跳到 `<FRONTEND_ORIGIN>/settings?github_connected=1`+4. GitHub 跳回 `<api-host>/api/github/setup`,落库后再跳到 `<FRONTEND_ORIGIN>/settings?tab=github&github_connected=1`之后在任意一个仓库开一个分支 / 标题 / 正文带本工作区 issue 编号的 PR——几秒内对应 issue 的详情页上就能看到 Pull requests 区块。diff --git a/packages/core/github/index.ts b/packages/core/github/index.tsindex 3dd4aaff02..5602216d05 100644--- a/packages/core/github/index.ts+++ b/packages/core/github/index.ts@@ -1,2 +1,4 @@export * from "./queries";export * from "./pull-request-status";+export * from "./settings";+export * from "./use-github-settings";diff --git a/packages/core/github/settings.test.ts b/packages/core/github/settings.test.tsnew file mode 100644index 0000000000..d277dfaaf6--- /dev/null+++ b/packages/core/github/settings.test.ts@@ -0,0 +1,66 @@+import { describe, it, expect } from "vitest";+import { deriveGitHubSettings } from "./settings";+import type { Workspace } from "../types";++function ws(settings: Record<string, unknown>): Pick<Workspace, "settings"> {+ return { settings };+}++describe("deriveGitHubSettings", () => {+ it("defaults every flag to true when workspace is null", () => {+ expect(deriveGitHubSettings(null)).toEqual({+ enabled: true,+ prSidebar: true,+ coAuthor: true,+ autoLinkPRs: true,+ });+ });++ it("defaults every flag to true on empty settings", () => {+ expect(deriveGitHubSettings(ws({}))).toEqual({+ enabled: true,+ prSidebar: true,+ coAuthor: true,+ autoLinkPRs: true,+ });+ });++ it("master switch off forces every dependent flag off", () => {+ const got = deriveGitHubSettings(+ ws({+ github_enabled: false,+ github_pr_sidebar_enabled: true,+ co_authored_by_enabled: true,+ github_auto_link_prs_enabled: true,+ }),+ );+ expect(got).toEqual({+ enabled: false,+ prSidebar: false,+ coAuthor: false,+ autoLinkPRs: false,+ });+ });++ it("each sub-flag can be flipped independently when master is on", () => {+ expect(+ deriveGitHubSettings(ws({ github_pr_sidebar_enabled: false })),+ ).toMatchObject({ enabled: true, prSidebar: false, coAuthor: true, autoLinkPRs: true });++ expect(+ deriveGitHubSettings(ws({ co_authored_by_enabled: false })),+ ).toMatchObject({ enabled: true, prSidebar: true, coAuthor: false, autoLinkPRs: true });++ expect(+ deriveGitHubSettings(ws({ github_auto_link_prs_enabled: false })),+ ).toMatchObject({ enabled: true, prSidebar: true, coAuthor: true, autoLinkPRs: false });+ });++ it("treats non-false values (true, null, missing) as enabled", () => {+ expect(+ deriveGitHubSettings(+ ws({ github_enabled: true, github_pr_sidebar_enabled: null }),+ ),+ ).toMatchObject({ enabled: true, prSidebar: true });+ });+});diff --git a/packages/core/github/settings.ts b/packages/core/github/settings.tsnew file mode 100644index 0000000000..5a6c66d5cb--- /dev/null+++ b/packages/core/github/settings.ts@@ -0,0 +1,29 @@+import type { Workspace } from "../types";++export interface GitHubSettings {+ /** Master switch. When false, every UI affordance and side-effect is gated off. */+ enabled: boolean;+ /** Issue-detail PR sidebar visibility. Implies `enabled`. */+ prSidebar: boolean;+ /** Co-authored-by trailer in agent commits. Implies `enabled`. */+ coAuthor: boolean;+ /** Auto-link issues ↔ PRs from webhook payloads. Implies `enabled`. */+ autoLinkPRs: boolean;+}++/**+ * Pure derivation from a workspace's settings JSONB. Defaults every flag to+ * true so workspaces predating MUL-2414 keep the historical "all on" behavior.+ */+export function deriveGitHubSettings(+ workspace: Pick<Workspace, "settings"> | null | undefined,+): GitHubSettings {+ const s = (workspace?.settings ?? {}) as Record<string, unknown>;+ const enabled = s.github_enabled !== false;+ return {+ enabled,+ prSidebar: enabled && s.github_pr_sidebar_enabled !== false,+ coAuthor: enabled && s.co_authored_by_enabled !== false,+ autoLinkPRs: enabled && s.github_auto_link_prs_enabled !== false,+ };+}diff --git a/packages/core/github/use-github-settings.ts b/packages/core/github/use-github-settings.tsnew file mode 100644index 0000000000..beda09da04--- /dev/null+++ b/packages/core/github/use-github-settings.ts@@ -0,0 +1,16 @@+"use client";++import { useMemo } from "react";+import { useCurrentWorkspace } from "../paths";+import { deriveGitHubSettings, type GitHubSettings } from "./settings";++/**+ * Reads the GitHub feature flags off the current workspace's settings JSONB.+ * Components downstream should consult this hook rather than poking at+ * `workspace.settings` directly, so the per-flag fallback semantics+ * (see deriveGitHubSettings) stay consistent.+ */+export function useGitHubSettings(): GitHubSettings {+ const workspace = useCurrentWorkspace();+ return useMemo(() => deriveGitHubSettings(workspace), [workspace]);+}diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex e5324fb1a5..a5932a3656 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -55,6 +55,7 @@ import { collectThreadReplies } from "./thread-utils";import { AgentLiveCard } from "./agent-live-card";import { ExecutionLogSection } from "./execution-log-section";import { PullRequestList } from "./pull-request-list";+import { useGitHubSettings } from "@multica/core/github";import { useQuery } from "@tanstack/react-query";import { useAuthStore } from "@multica/core/auth";import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";@@ -649,6 +650,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trconst [parentIssueOpen, setParentIssueOpen] = useState(true);const [pullRequestsOpen, setPullRequestsOpen] = useState(true);const [tokenUsageOpen, setTokenUsageOpen] = useState(true);+ const githubSettings = useGitHubSettings();// Per-issue, per-session set of optional properties currently visible in// the sidebar Properties section. Seeded on issue switch with whichever@@ -1357,17 +1359,21 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr</div>)}- {/* Pull requests */}- <div>- <button- className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors mb-2 hover:bg-accent/70 ${pullRequestsOpen ? "" : "text-muted-foreground hover:text-foreground"}`}- onClick={() => setPullRequestsOpen(!pullRequestsOpen)}- >- {t(($) => $.detail.section_pull_requests)}- <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${pullRequestsOpen ? "rotate-90" : ""}`} />- </button>- {pullRequestsOpen && <div className="pl-2"><PullRequestList issueId={id} /></div>}- </div>+ {/* Pull requests — hidden when the workspace disables the PR sidebar+ (or the GitHub master switch is off). Backend data is kept either+ way so re-enabling restores the section instantly. */}+ {githubSettings.prSidebar && (+ <div>+ <button+ className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors mb-2 hover:bg-accent/70 ${pullRequestsOpen ? "" : "text-muted-foreground hover:text-foreground"}`}+ onClick={() => setPullRequestsOpen(!pullRequestsOpen)}+ >+ {t(($) => $.detail.section_pull_requests)}+ <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${pullRequestsOpen ? "rotate-90" : ""}`} />+ </button>+ {pullRequestsOpen && <div className="pl-2"><PullRequestList issueId={id} /></div>}+ </div>+ )}{/* Details */}<div>diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 3fe322eddd..ff0c7d7aab 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -24,6 +24,7 @@"tokens": "API Tokens","general": "General","repositories": "Repositories",+ "github": "GitHub","integrations": "Integrations","labs": "Labs","members": "Members"@@ -153,27 +154,56 @@"deleting": "Deleting..."},"labs": {- "section_git": "Git",- "co_authored_by_label": "Co-authored-by trailer",- "co_authored_by_description_prefix": "Automatically add",- "co_authored_by_description_suffix": "to commits made by agents.",+ "section_placeholder_title": "No experiments yet",+ "section_placeholder_description": "Experimental settings will land here as they ship. Today this tab is intentionally empty.","toast_failed": "Failed to update setting"},"integrations": {"section_title": "Integrations",- "github_title": "GitHub",- "github_description_prefix": "Link issues to pull requests automatically. When a PR with",- "github_description_suffix": "in its branch, title, or body is merged, the corresponding issue moves to",- "github_description_done": "Done",- "github_identifier_example": "MUL-123",+ "empty_title": "No third-party integrations yet",+ "empty_description": "Once Slack, Linear, and other integrations are wired up they will appear here. GitHub has moved to its own tab.",+ "manage_hint": "Only admins and owners can manage integrations."+ },+ "github": {+ "page_description": "Connect a GitHub App, control how Pull Requests show up inside Multica, and decide what your agents leave behind in commit history.",+ "section_master": "Enable GitHub features",+ "master_description_on": "When off, every GitHub UI affordance is hidden and no new side-effects are written. Existing data is kept on the backend. Not a development team? Just turn it off here.",+ "master_description_off": "GitHub features are turned off. The PR sidebar, co-author trailer, and auto-link are paused. Data on the backend is not deleted.",+ "section_connection": "Connection",+ "connection_title": "GitHub App",+ "connection_description_prefix": "Link issues to pull requests automatically. When a PR with",+ "connection_description_suffix": "in its branch, title, or body is merged, the corresponding issue moves to",+ "connection_description_done": "Done",+ "connection_identifier_example": "MUL-123",+ "connected_to": "Connected to {{login}}","connect_github": "Connect GitHub","connect_opening": "Opening…","connect_disabled_tooltip": "GitHub App is not configured on this server",+ "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_cancel": "Cancel",+ "disconnect_confirm_action": "Disconnect","not_configured": "GitHub integration is not configured for this deployment. Operators must set","not_configured_and": "and",- "manage_hint": "Only admins and owners can manage integrations.",+ "manage_hint": "Only admins and owners can manage the GitHub connection.","toast_not_configured": "GitHub integration is not configured for this deployment",- "toast_open_failed": "Failed to open GitHub install"+ "toast_open_failed": "Failed to open GitHub install",+ "toast_disconnect_failed": "Failed to disconnect GitHub App",+ "toast_disconnected": "GitHub App disconnected",+ "section_features": "Features",+ "feature_pr_sidebar_label": "Pull Request sidebar",+ "feature_pr_sidebar_description": "Show linked pull requests inside the issue detail sidebar.",+ "feature_co_author_label": "Co-authored-by trailer",+ "feature_co_author_description_prefix": "Append",+ "feature_co_author_description_suffix": "to commits authored by agents.",+ "feature_auto_link_label": "Auto-link issues and PRs",+ "feature_auto_link_description": "Match PR titles, bodies, and branch names against issue identifiers and create the link automatically.",+ "section_repositories": "Repositories",+ "repositories_shortcut_label": "Repository URLs live in the Repositories tab",+ "repositories_shortcut_link": "Manage repositories →",+ "toast_failed": "Failed to update GitHub settings"},"repositories": {"section_title": "Repositories",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 1449f1d76d..cf5d71f802 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -24,6 +24,7 @@"tokens": "API Token","general": "通用","repositories": "代码仓库",+ "github": "GitHub","integrations": "集成","labs": "实验室","members": "成员"@@ -153,27 +154,56 @@"deleting": "删除中..."},"labs": {- "section_git": "Git",- "co_authored_by_label": "Co-authored-by trailer",- "co_authored_by_description_prefix": "自动给智能体的 commit 加上",- "co_authored_by_description_suffix": "。",+ "section_placeholder_title": "暂无实验",+ "section_placeholder_description": "实验性功能上线后会出现在这里。当前实验室页面是空的。","toast_failed": "更新设置失败"},"integrations": {"section_title": "集成",- "github_title": "GitHub",- "github_description_prefix": "自动把 issue 关联到 Pull Request。当 PR 的分支、标题或正文中包含",- "github_description_suffix": "并被合并时,对应的 issue 会自动转为",- "github_description_done": "Done",- "github_identifier_example": "MUL-123",+ "empty_title": "暂无第三方集成",+ "empty_description": "Slack、Linear 等集成接入后会出现在这里。GitHub 已迁出到独立的标签页。",+ "manage_hint": "只有管理员和所有者可以管理集成。"+ },+ "github": {+ "page_description": "连接 GitHub App、控制 Pull Request 如何出现在 Multica 中,并决定智能体在 commit 记录里留下哪些痕迹。",+ "section_master": "启用 GitHub 功能",+ "master_description_on": "关闭后,所有 GitHub 入口都会被隐藏,也不再产生新的副作用。后台已有数据不会被删除。团队不使用 GitHub?在这里直接关掉即可。",+ "master_description_off": "GitHub 功能已关闭。PR 侧栏、Co-authored-by trailer 与自动关联都已暂停。后台数据未删除。",+ "section_connection": "Connection",+ "connection_title": "GitHub App",+ "connection_description_prefix": "自动把 issue 关联到 Pull Request。当 PR 的分支、标题或正文中包含",+ "connection_description_suffix": "并被合并时,对应的 issue 会自动转为",+ "connection_description_done": "Done",+ "connection_identifier_example": "MUL-123",+ "connected_to": "已连接到 {{login}}","connect_github": "连接 GitHub","connect_opening": "正在打开…","connect_disabled_tooltip": "服务端未配置 GitHub App",+ "disconnect": "断开",+ "disconnecting": "断开中…",+ "disconnect_confirm_title": "断开 GitHub App",+ "disconnect_confirm_description": "Multica 将不再接收该安装的 webhook。已有的 PR 镜像与关联会保留,再次连接即可恢复同步。",+ "disconnect_confirm_cancel": "取消",+ "disconnect_confirm_action": "断开","not_configured": "当前部署没有配置 GitHub 集成。运维需要设置","not_configured_and": "和",- "manage_hint": "只有管理员和所有者可以管理集成。",+ "manage_hint": "只有管理员和所有者可以管理 GitHub 连接。","toast_not_configured": "当前部署未配置 GitHub 集成",- "toast_open_failed": "打开 GitHub 安装页失败"+ "toast_open_failed": "打开 GitHub 安装页失败",+ "toast_disconnect_failed": "断开 GitHub App 失败",+ "toast_disconnected": "已断开 GitHub App",+ "section_features": "Features",+ "feature_pr_sidebar_label": "Pull Request 侧栏",+ "feature_pr_sidebar_description": "在 Issue 详情侧栏中展示关联的 Pull Request。",+ "feature_co_author_label": "Co-authored-by trailer",+ "feature_co_author_description_prefix": "在智能体提交的 commit 中追加",+ "feature_co_author_description_suffix": "。",+ "feature_auto_link_label": "Issue ↔ PR 自动关联",+ "feature_auto_link_description": "根据 PR 标题、正文和分支名匹配 issue 编号并自动建立链接。",+ "section_repositories": "Repositories",+ "repositories_shortcut_label": "仓库 URL 仍在 Repositories 标签页中管理",+ "repositories_shortcut_link": "前往管理 →",+ "toast_failed": "更新 GitHub 设置失败"},"repositories": {"section_title": "代码仓库",diff --git a/packages/views/settings/components/github-mark.tsx b/packages/views/settings/components/github-mark.tsxnew file mode 100644index 0000000000..ae175f194b--- /dev/null+++ b/packages/views/settings/components/github-mark.tsx@@ -0,0 +1,10 @@+// lucide-react v1.x dropped brand marks (including Github). Inline SVG of+// the official GitHub octocat mark so the GitHub settings tab keeps a+// recognizable icon in the sidebar and section headers.+export function GitHubMark({ className }: { className?: string }) {+ return (+ <svg viewBox="0 0 24 24" aria-hidden="true" className={className} fill="currentColor">+ <path d="M12 .5C5.6.5.5 5.6.5 12c0 5.1 3.3 9.4 7.9 10.9.6.1.8-.2.8-.6v-2.2c-3.2.7-3.9-1.5-3.9-1.5-.5-1.3-1.3-1.7-1.3-1.7-1.1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1 1.8 2.7 1.3 3.4 1 .1-.8.4-1.3.8-1.6-2.6-.3-5.3-1.3-5.3-5.7 0-1.3.5-2.3 1.2-3.1-.1-.3-.5-1.5.1-3.1 0 0 1-.3 3.3 1.2.9-.3 1.9-.4 2.9-.4s2 .1 2.9.4c2.3-1.5 3.3-1.2 3.3-1.2.6 1.6.2 2.8.1 3.1.7.8 1.2 1.8 1.2 3.1 0 4.4-2.7 5.4-5.3 5.7.4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6 4.6-1.5 7.9-5.8 7.9-10.9C23.5 5.6 18.4.5 12 .5z" />+ </svg>+ );+}diff --git a/packages/views/settings/components/github-tab.test.tsx b/packages/views/settings/components/github-tab.test.tsxnew file mode 100644index 0000000000..17560aa266--- /dev/null+++ b/packages/views/settings/components/github-tab.test.tsx@@ -0,0 +1,223 @@+import type { ReactNode } from "react";+import { describe, it, expect, beforeEach, vi } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../locales/en/common.json";+import enSettings from "../../locales/en/settings.json";++const mockUpdateWorkspace = vi.hoisted(() => vi.fn());+const mockDeleteInstallation = vi.hoisted(() => vi.fn());+const mockGetConnectURL = vi.hoisted(() => vi.fn());+const mockInvalidate = vi.hoisted(() => vi.fn());+const mockNavPush = vi.hoisted(() => vi.fn());+const mockSetQueryData = vi.hoisted(() => vi.fn());++const workspaceRef = vi.hoisted(() => ({+ current: {+ id: "workspace-1",+ name: "Acme",+ slug: "acme",+ settings: {} as Record<string, unknown>,+ repos: [{ url: "https://github.com/acme/api" }] as { url: string }[],+ },+}));+const membersRef = vi.hoisted(() => ({+ current: [{ user_id: "user-1", role: "owner" as const }],+}));+const installationsRef = vi.hoisted(() => ({+ current: { installations: [] as { id: string; account_login: string }[], configured: true },+}));++vi.mock("@tanstack/react-query", () => ({+ useQuery: (opts: { queryKey: unknown[] }) => {+ const key = JSON.stringify(opts.queryKey);+ if (key.includes("members")) return { data: membersRef.current };+ if (key.includes("installations")) return { data: installationsRef.current };+ return { data: undefined };+ },+ useQueryClient: () => ({+ setQueryData: mockSetQueryData,+ invalidateQueries: mockInvalidate,+ }),+ queryOptions: <T,>(opts: T) => opts,+}));++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "workspace-1",+}));++vi.mock("@multica/core/paths", () => ({+ useCurrentWorkspace: () => workspaceRef.current,+}));++vi.mock("@multica/core/workspace/queries", () => ({+ memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),+ workspaceKeys: { list: () => ["workspaces"] },+}));++vi.mock("@multica/core/github", async () => {+ const actual =+ await vi.importActual<typeof import("@multica/core/github")>("@multica/core/github");+ return {+ ...actual,+ githubInstallationsOptions: () => ({+ queryKey: ["github", "installations"],+ queryFn: vi.fn(),+ }),+ };+});++vi.mock("@multica/core/api", () => ({+ api: {+ updateWorkspace: mockUpdateWorkspace,+ deleteGitHubInstallation: mockDeleteInstallation,+ getGitHubConnectURL: mockGetConnectURL,+ },+}));++vi.mock("@multica/core/auth", () => {+ const useAuthStore = Object.assign(+ (sel?: (s: { user: { id: string } }) => unknown) =>+ sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },+ { getState: () => ({ user: { id: "user-1" } }) },+ );+ return { useAuthStore };+});++vi.mock("../../navigation", () => ({+ useNavigation: () => ({+ push: mockNavPush,+ replace: vi.fn(),+ back: vi.fn(),+ pathname: "/acme/settings",+ searchParams: new URLSearchParams("tab=github"),+ getShareableUrl: (p: string) => `https://app.example${p}`,+ }),+}));++vi.mock("sonner", () => ({+ toast: { success: vi.fn(), error: vi.fn() },+}));++import { GitHubTab } from "./github-tab";++const TEST_RESOURCES = {+ en: { common: enCommon, settings: enSettings },+};++function I18nWrapper({ children }: { children: ReactNode }) {+ return (+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ );+}++function resetFixtures() {+ vi.clearAllMocks();+ workspaceRef.current = {+ id: "workspace-1",+ name: "Acme",+ slug: "acme",+ settings: {},+ repos: [{ url: "https://github.com/acme/api" }],+ };+ membersRef.current = [{ user_id: "user-1", role: "owner" }];+ installationsRef.current = { installations: [], configured: true };+}++describe("GitHubTab", () => {+ beforeEach(resetFixtures);++ it("folds the non-dev hint into the master switch description (no separate callout)", () => {+ render(<GitHubTab />, { wrapper: I18nWrapper });+ expect(screen.getByText(/Not a development team\? Just turn it off here\./)).toBeTruthy();+ // The old standalone callout (title + dedicated "Turn GitHub off" button) is gone.+ expect(screen.queryByRole("button", { name: /^Turn GitHub off$/ })).toBeNull();+ });++ it("does not show the hint once the master switch is off", () => {+ workspaceRef.current.settings = { github_enabled: false };+ render(<GitHubTab />, { wrapper: I18nWrapper });+ expect(screen.queryByText(/Not a development team\?/)).toBeNull();+ });++ it("disables every feature switch when the master switch is off", () => {+ workspaceRef.current.settings = { github_enabled: false };+ render(<GitHubTab />, { wrapper: I18nWrapper });++ const master = screen.getByRole("switch", { name: /enable github features/i });+ expect(master.getAttribute("aria-checked")).toBe("false");++ const switches = screen.getAllByRole("switch");+ // First switch is master; remaining must be disabled (aria-disabled or disabled attr)+ const features = switches.slice(1);+ expect(features.length).toBeGreaterThan(0);+ for (const sw of features) {+ const ariaDisabled = sw.getAttribute("aria-disabled");+ const disabled = sw.hasAttribute("disabled");+ expect(ariaDisabled === "true" || disabled).toBe(true);+ }+ });++ it("flipping the master switch off persists github_enabled=false and merges existing settings", async () => {+ const user = userEvent.setup();+ workspaceRef.current.settings = { co_authored_by_enabled: true };+ mockUpdateWorkspace.mockResolvedValue({+ ...workspaceRef.current,+ settings: { co_authored_by_enabled: true, github_enabled: false },+ });++ render(<GitHubTab />, { wrapper: I18nWrapper });++ await user.click(screen.getByRole("switch", { name: /enable github features/i }));++ await waitFor(() => {+ expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {+ settings: { co_authored_by_enabled: true, github_enabled: false },+ });+ });+ });++ it("clicking Disconnect opens the confirmation and only fires on confirm", async () => {+ const user = userEvent.setup();+ installationsRef.current = {+ configured: true,+ installations: [{ id: "inst-42", account_login: "acme" }],+ };+ mockDeleteInstallation.mockResolvedValue(undefined);++ render(<GitHubTab />, { wrapper: I18nWrapper });++ await user.click(screen.getByRole("button", { name: /^Disconnect$/ }));+ expect(screen.getByText(/Multica will stop receiving webhooks/i)).toBeTruthy();+ expect(mockDeleteInstallation).not.toHaveBeenCalled();++ const dialogConfirm = screen+ .getAllByRole("button", { name: /^Disconnect$/ })+ .find((b) => b.getAttribute("data-slot")?.includes("alert-dialog"));+ await user.click(dialogConfirm ?? screen.getAllByRole("button", { name: /^Disconnect$/ })[1]!);++ await waitFor(() => {+ expect(mockDeleteInstallation).toHaveBeenCalledWith("workspace-1", "inst-42");+ });+ });++ it("Disconnect button is still visible when the master switch is off", () => {+ workspaceRef.current.settings = { github_enabled: false };+ installationsRef.current = {+ configured: true,+ installations: [{ id: "inst-1", account_login: "acme" }],+ };+ render(<GitHubTab />, { wrapper: I18nWrapper });+ expect(screen.getByRole("button", { name: /^Disconnect$/ })).toBeTruthy();+ });++ it("repositories shortcut navigates to the repositories tab", async () => {+ const user = userEvent.setup();+ render(<GitHubTab />, { wrapper: I18nWrapper });+ await user.click(screen.getByRole("button", { name: /Manage repositories/ }));+ expect(mockNavPush).toHaveBeenCalledWith("/acme/settings?tab=repositories");+ });+});diff --git a/packages/views/settings/components/github-tab.tsx b/packages/views/settings/components/github-tab.tsxnew file mode 100644index 0000000000..f1b0dd1843--- /dev/null+++ b/packages/views/settings/components/github-tab.tsx@@ -0,0 +1,386 @@+"use client";++import { useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { ExternalLink, GitCommitHorizontal, Link2, PanelRight } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Card, CardContent } from "@multica/ui/components/ui/card";+import { Label } from "@multica/ui/components/ui/label";+import { Switch } from "@multica/ui/components/ui/switch";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import { useAuthStore } from "@multica/core/auth";+import { useWorkspaceId } from "@multica/core/hooks";+import { useCurrentWorkspace } from "@multica/core/paths";+import { memberListOptions, workspaceKeys } from "@multica/core/workspace/queries";+import {+ deriveGitHubSettings,+ githubInstallationsOptions,+} from "@multica/core/github";+import { api } from "@multica/core/api";+import type { Workspace } from "@multica/core/types";+import { useNavigation } from "../../navigation";+import { useT } from "../../i18n";+import { GitHubMark } from "./github-mark";++type SettingsKey =+ | "github_enabled"+ | "github_pr_sidebar_enabled"+ | "co_authored_by_enabled"+ | "github_auto_link_prs_enabled";++export function GitHubTab() {+ const { t } = useT("settings");+ const workspace = useCurrentWorkspace();+ const wsId = useWorkspaceId();+ const qc = useQueryClient();+ const navigation = useNavigation();+ const user = useAuthStore((s) => s.user);++ const { data: members = [] } = useQuery(memberListOptions(wsId));+ const currentMember = members.find((m) => m.user_id === user?.id) ?? null;+ const canManage = currentMember?.role === "owner" || currentMember?.role === "admin";++ const { data: installationData } = useQuery({+ ...githubInstallationsOptions(wsId),+ enabled: !!wsId && canManage,+ });+ const installations = installationData?.installations ?? [];+ const configured = installationData?.configured ?? false;+ const connected = installations.length > 0;++ const flags = deriveGitHubSettings(workspace);+ const [savingKey, setSavingKey] = useState<SettingsKey | null>(null);+ const [connecting, setConnecting] = useState(false);+ const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);+ const [disconnecting, setDisconnecting] = useState(false);++ const githubRepoCount =+ workspace?.repos?.filter((r) => /github\.com/i.test(r.url ?? "")).length ?? 0;++ async function persistSetting(key: SettingsKey, next: boolean) {+ if (!workspace || savingKey) return;+ setSavingKey(key);+ try {+ const merged = {+ ...((workspace.settings as Record<string, unknown>) ?? {}),+ [key]: next,+ };+ const updated = await api.updateWorkspace(workspace.id, { settings: merged });+ qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>+ old?.map((ws) => (ws.id === updated.id ? updated : ws)),+ );+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.github.toast_failed));+ } finally {+ setSavingKey(null);+ }+ }++ async function handleConnect() {+ setConnecting(true);+ try {+ const resp = await api.getGitHubConnectURL(wsId);+ if (!resp.configured || !resp.url) {+ toast.error(t(($) => $.github.toast_not_configured));+ return;+ }+ window.open(resp.url, "_blank", "noopener");+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.github.toast_open_failed));+ } finally {+ setConnecting(false);+ }+ }++ async function handleDisconnect() {+ if (!disconnectTarget || disconnecting) return;+ setDisconnecting(true);+ try {+ await api.deleteGitHubInstallation(wsId, disconnectTarget);+ await qc.invalidateQueries({ queryKey: ["github", wsId] });+ toast.success(t(($) => $.github.toast_disconnected));+ setDisconnectTarget(null);+ } catch (e) {+ toast.error(e instanceof Error ? e.message : t(($) => $.github.toast_disconnect_failed));+ } finally {+ setDisconnecting(false);+ }+ }++ if (!workspace) return null;++ const repositoriesHref = `${navigation.pathname}?tab=repositories`;++ return (+ <div className="space-y-8">+ <section className="space-y-1">+ <p className="text-sm text-muted-foreground">+ {t(($) => $.github.page_description)}+ </p>+ </section>++ <section className="space-y-3">+ <Card>+ <CardContent>+ <div className="flex items-start justify-between gap-4">+ <div className="flex items-start gap-3">+ <div className="rounded-md border bg-muted/50 p-2 text-muted-foreground">+ <GitHubMark className="h-4 w-4" />+ </div>+ <div className="space-y-1">+ <Label htmlFor="github-master" className="text-sm font-medium">+ {t(($) => $.github.section_master)}+ </Label>+ <p className="text-sm text-muted-foreground">+ {flags.enabled+ ? t(($) => $.github.master_description_on)+ : t(($) => $.github.master_description_off)}+ </p>+ </div>+ </div>+ <Switch+ id="github-master"+ checked={flags.enabled}+ onCheckedChange={(v) => persistSetting("github_enabled", v)}+ disabled={!canManage || savingKey === "github_enabled"}+ />+ </div>+ </CardContent>+ </Card>+ </section>++ <section className="space-y-3">+ <h2 className="text-sm font-semibold">{t(($) => $.github.section_connection)}</h2>+ <Card>+ <CardContent className="space-y-4">+ <div className="flex items-start justify-between gap-4">+ <div className="flex items-start gap-3">+ <GitHubMark className="h-6 w-6 mt-0.5 shrink-0" />+ <div className="space-y-1">+ <p className="text-sm font-medium">{t(($) => $.github.connection_title)}</p>+ {connected ? (+ <p className="text-xs text-muted-foreground">+ {t(($) => $.github.connected_to, {+ login: installations.map((i) => i.account_login).join(", "),+ })}+ </p>+ ) : (+ <p className="text-xs text-muted-foreground">+ {t(($) => $.github.connection_description_prefix)}{" "}+ <code className="rounded bg-muted px-1 py-0.5 text-[10px]">+ {t(($) => $.github.connection_identifier_example)}+ </code>{" "}+ {t(($) => $.github.connection_description_suffix)}{" "}+ <strong>{t(($) => $.github.connection_description_done)}</strong>.+ </p>+ )}+ </div>+ </div>+ {canManage && (+ <div className="flex items-center gap-2">+ {connected && installations[0] ? (+ // Disconnect must stay reachable even when the master switch+ // is off — disconnect is a separate intent (revoke the App+ // grant) from hiding the feature.+ <Button+ variant="outline"+ size="sm"+ onClick={() => setDisconnectTarget(installations[0]!.id)}+ >+ {t(($) => $.github.disconnect)}+ </Button>+ ) : (+ <Button+ size="sm"+ onClick={handleConnect}+ disabled={connecting || !configured}+ title={+ !configured+ ? t(($) => $.github.connect_disabled_tooltip)+ : undefined+ }+ >+ {connecting+ ? t(($) => $.github.connect_opening)+ : t(($) => $.github.connect_github)}+ </Button>+ )}+ </div>+ )}+ </div>++ {canManage && !configured && (+ <p className="text-xs text-muted-foreground">+ {t(($) => $.github.not_configured)}{" "}+ <code className="rounded bg-muted px-1 py-0.5 text-[10px]">GITHUB_APP_SLUG</code>{" "}+ {t(($) => $.github.not_configured_and)}{" "}+ <code className="rounded bg-muted px-1 py-0.5 text-[10px]">GITHUB_WEBHOOK_SECRET</code>.+ </p>+ )}++ {!canManage && (+ <p className="text-xs text-muted-foreground">+ {t(($) => $.github.manage_hint)}+ </p>+ )}+ </CardContent>+ </Card>+ </section>++ <section className="space-y-3">+ <h2 className="text-sm font-semibold">{t(($) => $.github.section_features)}</h2>+ <Card>+ <CardContent className="space-y-4">+ <FeatureRow+ id="github-pr-sidebar"+ icon={<PanelRight className="h-4 w-4" />}+ label={t(($) => $.github.feature_pr_sidebar_label)}+ description={+ <p className="text-sm text-muted-foreground">+ {t(($) => $.github.feature_pr_sidebar_description)}+ </p>+ }+ checked={flags.prSidebar}+ disabled={!canManage || !flags.enabled || savingKey === "github_pr_sidebar_enabled"}+ onCheckedChange={(v) => persistSetting("github_pr_sidebar_enabled", v)}+ />++ <FeatureRow+ id="github-coauthor"+ icon={<GitCommitHorizontal className="h-4 w-4" />}+ label={t(($) => $.github.feature_co_author_label)}+ description={+ <p className="text-sm text-muted-foreground">+ {t(($) => $.github.feature_co_author_description_prefix)}{" "}+ <code className="rounded bg-muted px-1 py-0.5 text-xs">+ {"Co-authored-by: multica-agent <[email protected]>"}+ </code>{" "}+ {t(($) => $.github.feature_co_author_description_suffix)}+ </p>+ }+ checked={flags.coAuthor}+ disabled={!canManage || !flags.enabled || savingKey === "co_authored_by_enabled"}+ onCheckedChange={(v) => persistSetting("co_authored_by_enabled", v)}+ />++ <FeatureRow+ id="github-auto-link"+ icon={<Link2 className="h-4 w-4" />}+ label={t(($) => $.github.feature_auto_link_label)}+ description={+ <p className="text-sm text-muted-foreground">+ {t(($) => $.github.feature_auto_link_description)}+ </p>+ }+ checked={flags.autoLinkPRs}+ disabled={!canManage || !flags.enabled || savingKey === "github_auto_link_prs_enabled"}+ onCheckedChange={(v) => persistSetting("github_auto_link_prs_enabled", v)}+ />+ </CardContent>+ </Card>+ </section>++ <section className="space-y-3">+ <h2 className="text-sm font-semibold">{t(($) => $.github.section_repositories)}</h2>+ <Card>+ <CardContent>+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="space-y-1">+ <p className="text-sm font-medium">+ {t(($) => $.github.repositories_shortcut_label)}+ </p>+ <p className="text-xs text-muted-foreground tabular-nums">+ {githubRepoCount}+ </p>+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={() => navigation.push(repositoriesHref)}+ >+ <ExternalLink className="h-3 w-3" />+ {t(($) => $.github.repositories_shortcut_link)}+ </Button>+ </div>+ </CardContent>+ </Card>+ </section>++ <AlertDialog+ open={!!disconnectTarget}+ onOpenChange={(v) => {+ if (!v && !disconnecting) setDisconnectTarget(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t(($) => $.github.disconnect_confirm_title)}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $.github.disconnect_confirm_description)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={disconnecting}>+ {t(($) => $.github.disconnect_confirm_cancel)}+ </AlertDialogCancel>+ <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>+ {disconnecting+ ? t(($) => $.github.disconnecting)+ : t(($) => $.github.disconnect_confirm_action)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ );+}++function FeatureRow({+ id,+ icon,+ label,+ description,+ checked,+ disabled,+ onCheckedChange,+}: {+ id: string;+ icon: React.ReactNode;+ label: string;+ description: React.ReactNode;+ checked: boolean;+ disabled: boolean;+ onCheckedChange: (v: boolean) => void;+}) {+ return (+ <div className="flex items-start justify-between gap-4">+ <div className="flex items-start gap-3">+ <div className="rounded-md border bg-muted/50 p-2 text-muted-foreground">{icon}</div>+ <div className="space-y-1">+ <Label htmlFor={id} className="text-sm font-medium">+ {label}+ </Label>+ {description}+ </div>+ </div>+ <Switch+ id={id}+ checked={checked}+ disabled={disabled}+ onCheckedChange={onCheckedChange}+ />+ </div>+ );+}diff --git a/packages/views/settings/components/integrations-tab.tsx b/packages/views/settings/components/integrations-tab.tsxindex 93c29b645c..aa9b75f30a 100644--- a/packages/views/settings/components/integrations-tab.tsx+++ b/packages/views/settings/components/integrations-tab.tsx@@ -1,114 +1,41 @@"use client";-import { useState } from "react";-import { useQuery } from "@tanstack/react-query";-import { toast } from "sonner";-import { Button } from "@multica/ui/components/ui/button";-import { Card, CardContent } from "@multica/ui/components/ui/card";-import { useAuthStore } from "@multica/core/auth";-import { useWorkspaceId } from "@multica/core/hooks";-import { memberListOptions } from "@multica/core/workspace/queries";-import { githubInstallationsOptions } from "@multica/core/github/queries";-import { api } from "@multica/core/api";+import { Plug } from "lucide-react";+import {+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+} from "@multica/ui/components/ui/empty";import { useT } from "../../i18n";-// lucide-react v1.x dropped brand marks (including Github). Render an inline-// SVG of the official GitHub octocat mark so the card is still recognizable.-function GitHubMark({ className }: { className?: string }) {- return (- <svg viewBox="0 0 24 24" aria-hidden="true" className={className} fill="currentColor">- <path d="M12 .5C5.6.5.5 5.6.5 12c0 5.1 3.3 9.4 7.9 10.9.6.1.8-.2.8-.6v-2.2c-3.2.7-3.9-1.5-3.9-1.5-.5-1.3-1.3-1.7-1.3-1.7-1.1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1 1.8 2.7 1.3 3.4 1 .1-.8.4-1.3.8-1.6-2.6-.3-5.3-1.3-5.3-5.7 0-1.3.5-2.3 1.2-3.1-.1-.3-.5-1.5.1-3.1 0 0 1-.3 3.3 1.2.9-.3 1.9-.4 2.9-.4s2 .1 2.9.4c2.3-1.5 3.3-1.2 3.3-1.2.6 1.6.2 2.8.1 3.1.7.8 1.2 1.8 1.2 3.1 0 4.4-2.7 5.4-5.3 5.7.4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6 4.6-1.5 7.9-5.8 7.9-10.9C23.5 5.6 18.4.5 12 .5z" />- </svg>- );-}-+// GitHub now lives in its own Settings tab (see github-tab.tsx). Until other+// third-party integrations land, this tab is intentionally an empty state —+// it stays in the IA so deep links and muscle memory don't break.export function IntegrationsTab() {const { t } = useT("settings");- const wsId = useWorkspaceId();- const user = useAuthStore((s) => s.user);- const { data: members = [] } = useQuery(memberListOptions(wsId));- const [connecting, setConnecting] = useState(false);-- const currentMember = members.find((m) => m.user_id === user?.id) ?? null;- const canManage = currentMember?.role === "owner" || currentMember?.role === "admin";-- // Only used to gate the Connect button + show a "not configured" hint;- // we no longer render the installation list here — admins manage existing- // installations on GitHub directly via the Connect flow.- const { data } = useQuery({- ...githubInstallationsOptions(wsId),- enabled: !!wsId && canManage,- });- const configured = data?.configured ?? false;-- async function handleConnect() {- setConnecting(true);- try {- const resp = await api.getGitHubConnectURL(wsId);- if (!resp.configured || !resp.url) {- toast.error(t(($) => $.integrations.toast_not_configured));- return;- }- window.open(resp.url, "_blank", "noopener");- } catch (e) {- toast.error(e instanceof Error ? e.message : t(($) => $.integrations.toast_open_failed));- } finally {- setConnecting(false);- }- }-return (- <div className="space-y-8">+ <div className="space-y-4"><section className="space-y-4"><h2 className="text-sm font-semibold">{t(($) => $.integrations.section_title)}</h2>-- <Card>- <CardContent className="space-y-4">- <div className="flex items-start justify-between gap-4">- <div className="flex items-start gap-3">- <GitHubMark className="h-6 w-6 mt-0.5 shrink-0" />- <div className="space-y-1">- <p className="text-sm font-medium">{t(($) => $.integrations.github_title)}</p>- <p className="text-xs text-muted-foreground">- {t(($) => $.integrations.github_description_prefix)}{" "}- <code className="rounded bg-muted px-1 py-0.5 text-[10px]">- {t(($) => $.integrations.github_identifier_example)}- </code>{" "}- {t(($) => $.integrations.github_description_suffix)}{" "}- <strong>{t(($) => $.integrations.github_description_done)}</strong>.- </p>- </div>- </div>- {canManage && (- <Button- size="sm"- onClick={handleConnect}- disabled={connecting || !configured}- title={!configured ? t(($) => $.integrations.connect_disabled_tooltip) : undefined}- >- {connecting- ? t(($) => $.integrations.connect_opening)- : t(($) => $.integrations.connect_github)}- </Button>- )}- </div>-- {canManage && !configured && (- <p className="text-xs text-muted-foreground">- {t(($) => $.integrations.not_configured)}{" "}- <code className="rounded bg-muted px-1 py-0.5 text-[10px]">GITHUB_APP_SLUG</code>{" "}- {t(($) => $.integrations.not_configured_and)}{" "}- <code className="rounded bg-muted px-1 py-0.5 text-[10px]">GITHUB_WEBHOOK_SECRET</code>.- </p>- )}-- {!canManage && (- <p className="text-xs text-muted-foreground">- {t(($) => $.integrations.manage_hint)}- </p>- )}- </CardContent>- </Card>+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <Plug className="h-4 w-4" />+ </EmptyMedia>+ <EmptyTitle>{t(($) => $.integrations.empty_title)}</EmptyTitle>+ <EmptyDescription>+ {t(($) => $.integrations.empty_description)}+ </EmptyDescription>+ </EmptyHeader>+ <EmptyContent>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.integrations.manage_hint)}+ </p>+ </EmptyContent>+ </Empty></section></div>);diff --git a/packages/views/settings/components/labs-tab.tsx b/packages/views/settings/components/labs-tab.tsxindex a0593edf8d..0b0b0028a2 100644--- a/packages/views/settings/components/labs-tab.tsx+++ b/packages/views/settings/components/labs-tab.tsx@@ -1,89 +1,33 @@"use client";-import { useState } from "react";-import { GitCommitHorizontal } from "lucide-react";-import { Card, CardContent } from "@multica/ui/components/ui/card";-import { Switch } from "@multica/ui/components/ui/switch";-import { Label } from "@multica/ui/components/ui/label";-import { toast } from "sonner";-import { useQueryClient } from "@tanstack/react-query";-import { useCurrentWorkspace } from "@multica/core/paths";-import { workspaceKeys } from "@multica/core/workspace/queries";-import { api } from "@multica/core/api";-import type { Workspace } from "@multica/core/types";+import { FlaskConical } from "lucide-react";+import {+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyMedia,+ EmptyTitle,+} from "@multica/ui/components/ui/empty";import { useT } from "../../i18n";+// The Co-authored-by trailer toggle moved into the dedicated GitHub Settings+// tab (see github-tab.tsx). Labs is kept as a container for future+// experimental flags rather than removed from the IA.export function LabsTab() {const { t } = useT("settings");- const workspace = useCurrentWorkspace();- const qc = useQueryClient();- const [saving, setSaving] = useState(false);-- const coAuthoredByEnabled =- (workspace?.settings as Record<string, unknown>)?.co_authored_by_enabled !== false;-- const handleToggle = async (checked: boolean) => {- if (!workspace || saving) return;- setSaving(true);- try {- const updated = await api.updateWorkspace(workspace.id, {- settings: {- ...((workspace.settings as Record<string, unknown>) ?? {}),- co_authored_by_enabled: checked,- },- });- qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>- old?.map((ws) => (ws.id === updated.id ? updated : ws)),- );- } catch (e) {- toast.error(- e instanceof Error ? e.message : t(($) => $.labs.toast_failed),- );- } finally {- setSaving(false);- }- };-- if (!workspace) return null;-return (<div className="space-y-4">- <section className="space-y-4">- <h2 className="text-sm font-semibold">{t(($) => $.labs.section_git)}</h2>-- <Card>- <CardContent>- <div className="flex items-start justify-between gap-4">- <div className="flex items-start gap-3">- <div className="rounded-md border bg-muted/50 p-2 text-muted-foreground">- <GitCommitHorizontal className="h-4 w-4" />- </div>- <div className="space-y-1">- <Label- htmlFor="co-authored-by"- className="text-sm font-medium"- >- {t(($) => $.labs.co_authored_by_label)}- </Label>- <p className="text-sm text-muted-foreground">- {t(($) => $.labs.co_authored_by_description_prefix)}{" "}- <code className="rounded bg-muted px-1 py-0.5 text-xs">- {"Co-authored-by: multica-agent <[email protected]>"}- </code>{" "}- {t(($) => $.labs.co_authored_by_description_suffix)}- </p>- </div>- </div>- <Switch- id="co-authored-by"- checked={coAuthoredByEnabled}- onCheckedChange={handleToggle}- disabled={saving}- />- </div>- </CardContent>- </Card>- </section>+ <Empty>+ <EmptyHeader>+ <EmptyMedia variant="icon">+ <FlaskConical className="h-4 w-4" />+ </EmptyMedia>+ <EmptyTitle>{t(($) => $.labs.section_placeholder_title)}</EmptyTitle>+ <EmptyDescription>+ {t(($) => $.labs.section_placeholder_description)}+ </EmptyDescription>+ </EmptyHeader>+ </Empty></div>);}diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex 45ed26882c..f324e28345 100644--- a/packages/views/settings/components/settings-page.tsx+++ b/packages/views/settings/components/settings-page.tsx@@ -12,6 +12,7 @@ import {Bell,Plug,} from "lucide-react";+import { GitHubMark } from "./github-mark";import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";import { useCurrentWorkspace } from "@multica/core/paths";import { useNavigation } from "../../navigation";@@ -21,6 +22,7 @@ import { TokensTab } from "./tokens-tab";import { WorkspaceTab } from "./workspace-tab";import { MembersTab } from "./members-tab";import { RepositoriesTab } from "./repositories-tab";+import { GitHubTab } from "./github-tab";import { IntegrationsTab } from "./integrations-tab";import { LabsTab } from "./labs-tab";import { NotificationsTab } from "./notifications-tab";@@ -34,10 +36,18 @@ const ACCOUNT_TAB_ICONS = {tokens: Key,} as const;-const WORKSPACE_TAB_KEYS = ["general", "repositories", "integrations", "labs", "members"] as const;+const WORKSPACE_TAB_KEYS = [+ "general",+ "repositories",+ "github",+ "integrations",+ "labs",+ "members",+] as const;const WORKSPACE_TAB_VALUES = {general: "workspace",repositories: "repositories",+ github: "github",integrations: "integrations",labs: "labs",members: "members",@@ -45,6 +55,7 @@ const WORKSPACE_TAB_VALUES = {const WORKSPACE_TAB_ICONS = {general: Settings,repositories: FolderGit2,+ github: GitHubMark,integrations: Plug,labs: FlaskConical,members: Users,@@ -151,6 +162,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {<TabsContent value="tokens"><TokensTab /></TabsContent><TabsContent value="workspace"><WorkspaceTab /></TabsContent><TabsContent value="repositories"><RepositoriesTab /></TabsContent>+ <TabsContent value="github"><GitHubTab /></TabsContent><TabsContent value="integrations"><IntegrationsTab /></TabsContent><TabsContent value="labs"><LabsTab /></TabsContent><TabsContent value="members"><MembersTab /></TabsContent>diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex f9fefd15fd..45b4833cca 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -400,9 +400,10 @@ func (c *Client) Register(ctx context.Context, req map[string]any) (*RegisterRes}type WorkspaceReposResponse struct {- WorkspaceID string `json:"workspace_id"`- Repos []RepoData `json:"repos"`- ReposVersion string `json:"repos_version"`+ WorkspaceID string `json:"workspace_id"`+ Repos []RepoData `json:"repos"`+ ReposVersion string `json:"repos_version"`+ Settings json.RawMessage `json:"settings,omitempty"`}func (c *Client) GetWorkspaceRepos(ctx context.Context, workspaceID string) (*WorkspaceReposResponse, error) {diff --git a/server/internal/daemon/coauthor_enabled_test.go b/server/internal/daemon/coauthor_enabled_test.gonew file mode 100644index 0000000000..eb4320e974--- /dev/null+++ b/server/internal/daemon/coauthor_enabled_test.go@@ -0,0 +1,139 @@+package daemon++import (+ "context"+ "encoding/json"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"+)++// workspaceCoAuthoredByEnabled gates the prepare-commit-msg hook installed in+// agent worktrees. RFC MUL-2414 adds the `github_enabled` master switch:+// when it is explicitly false the hook must NOT be installed even if+// `co_authored_by_enabled` is true. The function also defaults to true+// whenever settings are absent or malformed so existing workspaces keep+// their historical behavior.+func TestWorkspaceCoAuthoredByEnabled(t *testing.T) {+ cases := []struct {+ name string+ register bool+ settings string+ want bool+ }{+ {"unknown workspace defaults on", false, "", true},+ {"registered workspace, nil settings defaults on", true, "", true},+ {"empty object defaults on", true, "{}", true},+ {"co_authored_by absent defaults on", true, `{"github_enabled":true}`, true},+ {"co_authored_by true", true, `{"co_authored_by_enabled":true}`, true},+ {"co_authored_by false", true, `{"co_authored_by_enabled":false}`, false},+ {+ "master off forces hook off even when co_authored_by true",+ true,+ `{"github_enabled":false,"co_authored_by_enabled":true}`,+ false,+ },+ {+ "master on lets co_authored_by decide",+ true,+ `{"github_enabled":true,"co_authored_by_enabled":false}`,+ false,+ },+ {"malformed settings defaults on", true, `not json`, true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ d := &Daemon{workspaces: make(map[string]*workspaceState)}+ if tc.register {+ var raw json.RawMessage+ if tc.settings != "" {+ raw = json.RawMessage(tc.settings)+ }+ d.workspaces["ws"] = newWorkspaceState("ws", nil, "", nil, raw)+ }+ if got := d.workspaceCoAuthoredByEnabled("ws"); got != tc.want {+ t.Fatalf("workspaceCoAuthoredByEnabled(%q) = %v, want %v",+ tc.settings, got, tc.want)+ }+ })+ }+}++// syncWorkspacesFromAPI must refresh the cached workspace settings on already-+// tracked workspaces so that toggling `co_authored_by_enabled` (or the+// `github_enabled` master switch) in the web UI takes effect on the next gated+// operation without a daemon restart. Reviewed in PR #2847 by Emacs — the+// original cut only wrote settings during registration, so a running daemon+// would keep installing the Co-authored-by hook on the next `repo checkout`+// even after the workspace flipped the switch off.+func TestSyncWorkspacesRefreshesSettingsOnExistingWorkspace(t *testing.T) {+ t.Parallel()++ const workspaceID = "ws-1"++ var settingsPayload atomic.Value+ settingsPayload.Store(json.RawMessage(`{"github_enabled":true,"co_authored_by_enabled":true}`))++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/workspaces":+ json.NewEncoder(w).Encode([]WorkspaceInfo{{ID: workspaceID, Name: "ws"}})+ case "/api/daemon/workspaces/" + workspaceID + "/repos":+ raw, _ := settingsPayload.Load().(json.RawMessage)+ json.NewEncoder(w).Encode(WorkspaceReposResponse{+ WorkspaceID: workspaceID,+ Repos: []RepoData{},+ ReposVersion: "v1",+ Settings: raw,+ })+ default:+ http.NotFound(w, r)+ }+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.Default(),+ workspaces: make(map[string]*workspaceState),+ runtimeIndex: make(map[string]Runtime),+ runtimeSet: newRuntimeSetWatcher(),+ }+ // Pretend the workspace was already registered with co-author ON. A live+ // runtime ID keeps workspaceNeedsRuntimeRecovery from short-circuiting the+ // sync into a re-register.+ d.workspaces[workspaceID] = newWorkspaceState(+ workspaceID,+ []string{"rt-1"},+ "v1",+ nil,+ json.RawMessage(`{"github_enabled":true,"co_authored_by_enabled":true}`),+ )++ if !d.workspaceCoAuthoredByEnabled(workspaceID) {+ t.Fatalf("precondition: expected co-author hook to start enabled")+ }++ // The user opens Settings → GitHub and turns the master switch off.+ settingsPayload.Store(json.RawMessage(`{"github_enabled":false,"co_authored_by_enabled":true}`))++ if err := d.syncWorkspacesFromAPI(context.Background()); err != nil {+ t.Fatalf("syncWorkspacesFromAPI: %v", err)+ }++ if d.workspaceCoAuthoredByEnabled(workspaceID) {+ t.Fatalf("expected co-author hook disabled after toggle; daemon is still using stale cached settings")+ }++ // Flipping the master switch back on must take effect the next sync too —+ // the refresh path is not one-way.+ settingsPayload.Store(json.RawMessage(`{"github_enabled":true,"co_authored_by_enabled":true}`))+ if err := d.syncWorkspacesFromAPI(context.Background()); err != nil {+ t.Fatalf("syncWorkspacesFromAPI (re-enable): %v", err)+ }+ if !d.workspaceCoAuthoredByEnabled(workspaceID) {+ t.Fatalf("expected co-author hook re-enabled after toggling back on")+ }+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex eb5556fd4c..d928658297 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -848,8 +848,13 @@ func (d *Daemon) workspaceLastRepoSyncErr(workspaceID string) string {}// workspaceCoAuthoredByEnabled returns whether the Co-authored-by hook should-// be installed for the given workspace. Defaults to true when the setting is-// absent (new workspaces, older servers that don't send settings).+// be installed for the given workspace. Defaults to true when either setting+// is absent (new workspaces, older servers that don't send settings).+//+// The hook is gated by BOTH the GitHub master switch (`github_enabled`) and+// the dedicated co-author switch (`co_authored_by_enabled`) so flipping the+// workspace's master GitHub toggle off also stops new trailers from landing+// in commits, matching the contract documented in RFC MUL-2414 §4.8.func (d *Daemon) workspaceCoAuthoredByEnabled(workspaceID string) bool {d.mu.Lock()defer d.mu.Unlock()@@ -858,9 +863,16 @@ func (d *Daemon) workspaceCoAuthoredByEnabled(workspaceID string) bool {return true // default: enabled}var s struct {+ GitHubEnabled *bool `json:"github_enabled"`CoAuthoredByEnabled *bool `json:"co_authored_by_enabled"`}- if err := json.Unmarshal(ws.settings, &s); err != nil || s.CoAuthoredByEnabled == nil {+ if err := json.Unmarshal(ws.settings, &s); err != nil {+ return true // default: enabled when payload is malformed+ }+ if s.GitHubEnabled != nil && !*s.GitHubEnabled {+ return false+ }+ if s.CoAuthoredByEnabled == nil {return true // default: enabled}return *s.CoAuthoredByEnabled@@ -966,6 +978,12 @@ func (d *Daemon) refreshWorkspaceRepos(ctx context.Context, workspaceID string)if ws, ok := d.workspaces[workspaceID]; ok {ws.reposVersion = resp.ReposVersionws.allowedRepoURLs = repoAllowlist(resp.Repos)+ // Keep the cached settings in sync with the server. The daemon's+ // feature gates (e.g. workspaceCoAuthoredByEnabled) read directly from+ // this field, so toggling a Setting in the web UI must update it here+ // without requiring a daemon restart. An empty payload from the server+ // clears the override and falls back to defaults.+ ws.settings = resp.Settings}d.mu.Unlock()@@ -986,14 +1004,26 @@ func (d *Daemon) ensureRepoReady(ctx context.Context, workspaceID, repoURL strinreturn fmt.Errorf("workspace is not watched by this daemon: %s", workspaceID)}- if d.workspaceRepoAllowed(workspaceID, repoURL) && d.repoCache.Lookup(workspaceID, repoURL) != "" {- return nil- }+ // Record whether the cache already had this repo before we took the+ // per-workspace mutex. The two states behave differently below:+ //+ // - cacheHitOnEntry=true: the repo is already cloned; we still must+ // refresh `workspaceState.settings` because the /repo/checkout+ // handler reads workspaceCoAuthoredByEnabled right after this and+ // the 30s workspaceSyncLoop tick is too slow for a freshly-flipped+ // GitHub master switch / `co_authored_by_enabled` toggle to feel+ // live (RFC MUL-2414 §4.8; PR #2847 review by Emacs).+ //+ // - cacheHitOnEntry=false but cache hit *after* we acquire the mutex:+ // a sibling goroutine on a concurrent cold-miss already refreshed+ // and populated the cache. We can skip the duplicate refresh — the+ // sibling's refresh is fresh enough for our gate read.+ cacheHitOnEntry := d.workspaceRepoAllowed(workspaceID, repoURL) && d.repoCache.Lookup(workspaceID, repoURL) != ""ws.repoRefreshMu.Lock()defer ws.repoRefreshMu.Unlock()- if d.workspaceRepoAllowed(workspaceID, repoURL) && d.repoCache.Lookup(workspaceID, repoURL) != "" {+ if !cacheHitOnEntry && d.workspaceRepoAllowed(workspaceID, repoURL) && d.repoCache.Lookup(workspaceID, repoURL) != "" {return nil}@@ -1006,6 +1036,10 @@ func (d *Daemon) ensureRepoReady(ctx context.Context, workspaceID, repoURL strinreturn ErrRepoNotConfigured}+ if d.repoCache.Lookup(workspaceID, repoURL) != "" {+ return nil+ }+d.syncWorkspaceRepos(workspaceID, resp.Repos)if d.repoCache.Lookup(workspaceID, repoURL) != "" {@@ -1069,11 +1103,19 @@ func (d *Daemon) syncWorkspacesFromAPI(ctx context.Context) error {var removed intfor id, name := range apiIDs {if currentIDs[id] {- // Already tracked: only intervene if the workspace lost all of- // its runtimes (most commonly because handleRuntimeGone pruned- // them and its inline re-register failed). The pointer is not- // replaced here either — ensureRepoReady holds repoRefreshMu- // from the original pointer.+ // Already tracked: refresh the cached workspace settings so+ // feature toggles flipped in the web UI take effect on the next+ // gated operation without a daemon restart (see RFC MUL-2414 §4.8;+ // reviewed in PR #2847). refreshWorkspaceRepos covers settings ++ // repos in a single round trip.+ if _, err := d.refreshWorkspaceRepos(ctx, id); err != nil {+ d.logger.Debug("workspace sync: refresh settings failed", "workspace_id", id, "error", err)+ }+ // Only intervene further if the workspace lost all of its+ // runtimes (most commonly because handleRuntimeGone pruned them+ // and its inline re-register failed). The pointer is not replaced+ // here either — ensureRepoReady holds repoRefreshMu from the+ // original pointer.if !d.workspaceNeedsRuntimeRecovery(id) {continue}diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex ededc95071..5beec5f4c2 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -1318,25 +1318,55 @@ func TestExecuteAndDrain_IdleWatchdog_FiresAfterToolResultIfBackendStaysSilent(t}}-func TestEnsureRepoReadyFastPathDoesNotRefresh(t *testing.T) {+// ensureRepoReady must refresh `workspaceState.settings` on every checkout —+// even when the repo cache already holds the URL. The /repo/checkout handler+// reads `workspaceCoAuthoredByEnabled` right after, and the 30s workspace+// sync tick is too slow to make a freshly-flipped GitHub toggle feel live.+// PR #2847 review by Emacs caught this fast-path regression; the test+// asserts the cached-repo path still issues exactly one refresh.+func TestEnsureRepoReadyCachedRepoStillRefreshesSettings(t *testing.T) {t.Parallel()sourceRepo := createDaemonTestRepo(t)var refreshCalls atomic.Int32d := newRepoReadyTestDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/api/daemon/workspaces/ws-1/repos" {+ http.NotFound(w, r)+ return+ }refreshCalls.Add(1)- http.Error(w, "unexpected refresh", http.StatusInternalServerError)+ json.NewEncoder(w).Encode(WorkspaceReposResponse{+ WorkspaceID: "ws-1",+ Repos: []RepoData{{URL: sourceRepo}},+ ReposVersion: "v2",+ Settings: json.RawMessage(`{"github_enabled":false,"co_authored_by_enabled":true}`),+ })})if err := d.repoCache.Sync("ws-1", []repocache.RepoInfo{{URL: sourceRepo}}); err != nil {t.Fatalf("seed repo cache: %v", err)}- d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "v1", []RepoData{{URL: sourceRepo}}, nil)+ // Workspace starts with the master switch ON. The server above will return+ // the user's just-flipped OFF state — ensureRepoReady must pick that up+ // before the handler reads workspaceCoAuthoredByEnabled.+ d.workspaces["ws-1"] = newWorkspaceState(+ "ws-1",+ nil,+ "v1",+ []RepoData{{URL: sourceRepo}},+ json.RawMessage(`{"github_enabled":true,"co_authored_by_enabled":true}`),+ )+ if !d.workspaceCoAuthoredByEnabled("ws-1") {+ t.Fatalf("precondition: expected co-author hook enabled before checkout")+ }if err := d.ensureRepoReady(context.Background(), "ws-1", sourceRepo); err != nil {t.Fatalf("ensureRepoReady: %v", err)}- if got := refreshCalls.Load(); got != 0 {- t.Fatalf("expected no refresh calls, got %d", got)+ if got := refreshCalls.Load(); got != 1 {+ t.Fatalf("expected exactly 1 refresh call on cached repo, got %d", got)+ }+ if d.workspaceCoAuthoredByEnabled("ws-1") {+ t.Fatalf("expected co-author hook disabled after server-side toggle; daemon used stale workspaceState.settings via cache fast path")}}@@ -1346,20 +1376,29 @@ func TestEnsureRepoReadyTrimsURL(t *testing.T) {sourceRepo := createDaemonTestRepo(t)var refreshCalls atomic.Int32d := newRepoReadyTestDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/api/daemon/workspaces/ws-1/repos" {+ http.NotFound(w, r)+ return+ }refreshCalls.Add(1)- http.Error(w, "unexpected refresh", http.StatusInternalServerError)+ json.NewEncoder(w).Encode(WorkspaceReposResponse{+ WorkspaceID: "ws-1",+ Repos: []RepoData{{URL: sourceRepo}},+ ReposVersion: "v2",+ })})if err := d.repoCache.Sync("ws-1", []repocache.RepoInfo{{URL: sourceRepo}}); err != nil {t.Fatalf("seed repo cache: %v", err)}d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "v1", []RepoData{{URL: sourceRepo}}, nil)- // URL with trailing whitespace should still hit the fast path.+ // URL with trailing whitespace should still resolve to the cached repo.if err := d.ensureRepoReady(context.Background(), "ws-1", " "+sourceRepo+" "); err != nil {t.Fatalf("ensureRepoReady with padded URL: %v", err)}- if got := refreshCalls.Load(); got != 0 {- t.Fatalf("expected no refresh calls for trimmed URL, got %d", got)+ // Even on cache hit we refresh settings once so toggle flips feel live.+ if got := refreshCalls.Load(); got != 1 {+ t.Fatalf("expected 1 refresh call for trimmed URL, got %d", got)}}@@ -1438,8 +1477,12 @@ func TestRegisterTaskReposAllowsProjectOnlyURL(t *testing.T) {if err := d.ensureRepoReady(context.Background(), "ws-1", sourceRepo); err != nil {t.Fatalf("ensureRepoReady: %v", err)}- if got := refreshCalls.Load(); got != 0 {- t.Fatalf("expected zero workspace-repos refreshes (URL came from project), got %d", got)+ // ensureRepoReady refreshes settings on every call (RFC MUL-2414 §4.8; PR+ // #2847 review by Emacs) so a freshly-flipped GitHub toggle takes effect+ // without waiting for the 30s sync tick. We expect exactly one refresh —+ // the project-only URL still skips re-cloning because the cache is warm.+ if got := refreshCalls.Load(); got != 1 {+ t.Fatalf("expected 1 workspace-repos refresh (settings live-refresh on checkout), got %d", got)}}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 7f806d5713..016d61b2bd 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -179,9 +179,10 @@ type DaemonRegisterRequest struct {}type daemonWorkspaceReposResponse struct {- WorkspaceID string `json:"workspace_id"`- Repos []RepoData `json:"repos"`- ReposVersion string `json:"repos_version"`+ WorkspaceID string `json:"workspace_id"`+ Repos []RepoData `json:"repos"`+ ReposVersion string `json:"repos_version"`+ Settings json.RawMessage `json:"settings,omitempty"`}// normalizeRuntimeTimezone validates and normalizes the IANA timezone string@@ -248,13 +249,17 @@ func parseWorkspaceRepos(raw []byte) []RepoData {return normalizeWorkspaceRepos(repos)}-func workspaceReposResponse(workspaceID string, raw []byte) daemonWorkspaceReposResponse {+func workspaceReposResponse(workspaceID string, raw []byte, settingsRaw []byte) daemonWorkspaceReposResponse {repos := parseWorkspaceRepos(raw)- return daemonWorkspaceReposResponse{+ resp := daemonWorkspaceReposResponse{WorkspaceID: workspaceID,Repos: repos,ReposVersion: workspaceReposVersion(repos),}+ if len(settingsRaw) > 0 {+ resp.Settings = json.RawMessage(settingsRaw)+ }+ return resp}func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {@@ -424,20 +429,13 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {"runtimes": resp,})- repoResp := workspaceReposResponse(req.WorkspaceID, ws.Repos)-- // Include workspace settings so the daemon can honour feature toggles- // (e.g. co_authored_by_enabled for the prepare-commit-msg hook).- var settings json.RawMessage- if len(ws.Settings) > 0 {- settings = json.RawMessage(ws.Settings)- }+ repoResp := workspaceReposResponse(req.WorkspaceID, ws.Repos, ws.Settings)writeJSON(w, http.StatusOK, map[string]any{"runtimes": resp,"repos": repoResp.Repos,"repos_version": repoResp.ReposVersion,- "settings": settings,+ "settings": repoResp.Settings,})}@@ -535,7 +533,7 @@ func (h *Handler) GetDaemonWorkspaceRepos(w http.ResponseWriter, r *http.Requestreturn}- writeJSON(w, http.StatusOK, workspaceReposResponse(workspaceID, ws.Repos))+ writeJSON(w, http.StatusOK, workspaceReposResponse(workspaceID, ws.Repos, ws.Settings))}// DaemonDeregister marks runtimes as offline when the daemon shuts down.diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex ef29fc201b..1eeda519e2 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -262,7 +262,10 @@ func (h *Handler) GitHubConnect(w http.ResponseWriter, r *http.Request) {// sends after a user installs (or re-authorizes) the App. We expect// ?installation_id=<id>&state=<signed token>. We persist the installation// row (workspace ↔ installation_id mapping), then bounce the user back to-// the Settings → Integrations page in the web app.+// the new Settings → GitHub tab in the web app (RFC MUL-2414 §4.1). The+// previous destination was the catch-all Settings page, which after the+// GitHub-tab split would land users on the default profile tab instead of+// the place that shows the connection they just completed.func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {q := r.URL.Query()installationIDStr := q.Get("installation_id")@@ -271,25 +274,25 @@ func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {if frontend == "" {frontend = "http://localhost:3000"}- settingsURL := strings.TrimRight(frontend, "/") + "/settings"+ settingsURL := strings.TrimRight(frontend, "/") + "/settings?tab=github"if installationIDStr == "" || state == "" {- http.Redirect(w, r, settingsURL+"?github_error=missing_params", http.StatusFound)+ http.Redirect(w, r, settingsURL+"&github_error=missing_params", http.StatusFound)return}workspaceID, ok := verifyState(state)if !ok {- http.Redirect(w, r, settingsURL+"?github_error=invalid_state", http.StatusFound)+ http.Redirect(w, r, settingsURL+"&github_error=invalid_state", http.StatusFound)return}installationID, err := strconv.ParseInt(installationIDStr, 10, 64)if err != nil {- http.Redirect(w, r, settingsURL+"?github_error=bad_installation_id", http.StatusFound)+ http.Redirect(w, r, settingsURL+"&github_error=bad_installation_id", http.StatusFound)return}wsUUID, err := parseStrictUUID(workspaceID)if err != nil {- http.Redirect(w, r, settingsURL+"?github_error=bad_workspace", http.StatusFound)+ http.Redirect(w, r, settingsURL+"&github_error=bad_workspace", http.StatusFound)return}// Resolve the installation against GitHub's API to capture display info.@@ -318,13 +321,13 @@ func (h *Handler) GitHubSetupCallback(w http.ResponseWriter, r *http.Request) {})if err != nil {slog.Error("github: failed to persist installation", "err", err, "installation_id", installationID)- http.Redirect(w, r, settingsURL+"?github_error=persist_failed", http.StatusFound)+ http.Redirect(w, r, settingsURL+"&github_error=persist_failed", http.StatusFound)return}h.publish(protocol.EventGitHubInstallationCreated, workspaceID, "system", "", map[string]any{"installation": githubInstallationToResponse(inst),})- http.Redirect(w, r, settingsURL+"?github_connected=1", http.StatusFound)+ http.Redirect(w, r, settingsURL+"&github_connected=1", http.StatusFound)}// fetchInstallationAccount tries to enrich the installation row with the@@ -655,46 +658,54 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {// Auto-link: scan title/body/branch for issue identifiers, look them// up in this workspace, attach the link rows. Idempotent (ON CONFLICT// DO NOTHING) so re-firing the webhook doesn't duplicate.- idents := extractIdentifiers(p.PullRequest.Title, p.PullRequest.Body, p.PullRequest.Head.Ref)- prefix := h.getIssuePrefix(ctx, inst.WorkspaceID)- linkedIssueIDs := make([]string, 0, len(idents))- for _, id := range idents {- issue, ok := h.lookupIssueByIdentifier(ctx, inst.WorkspaceID, prefix, id)- if !ok {- continue- }- if err := h.Queries.LinkIssueToPullRequest(ctx, db.LinkIssueToPullRequestParams{- IssueID: issue.ID,- PullRequestID: pr.ID,- LinkedByType: strToText("system"),- LinkedByID: pgtype.UUID{},- }); err != nil {- slog.Warn("github: link failed", "err", err)- continue- }- linkedIssueIDs = append(linkedIssueIDs, uuidToString(issue.ID))-- // A terminal PR event (`merged` or `closed`) may be the moment the- // last in-flight sibling resolves, so we re-evaluate the issue on- // both. We advance the issue to done when:- // 1. the issue isn't already terminal (`done` / `cancelled`);- // 2. no sibling PR is still `open` / `draft`;- // 3. at least one linked PR (this one or a sibling) is `merged`.- // Rule (3) prevents an "all closed-without-merge" sequence from- // silently auto-closing the issue — if nothing was ever delivered,- // the user should decide what to do manually.- if (state == "merged" || state == "closed") && issue.Status != "done" && issue.Status != "cancelled" {- counts, err := h.Queries.GetSiblingPullRequestStateCountsForIssue(ctx, db.GetSiblingPullRequestStateCountsForIssueParams{- IssueID: issue.ID,- ID: pr.ID,- })- if err != nil {- slog.Warn("github: count sibling pr states failed", "err", err, "issue_id", uuidToString(issue.ID))+ //+ // RFC MUL-2414 §4.8: the PR mirror upsert above always runs (so re-enabling+ // GitHub features restores history without backfill), but the link rows+ // are a "new side-effect" and must be gated by the workspace's auto-link+ // flag (which itself short-circuits when the master `github_enabled`+ // switch is off).+ linkedIssueIDs := make([]string, 0)+ if h.workspaceAutoLinkPRsEnabled(ctx, inst.WorkspaceID) {+ idents := extractIdentifiers(p.PullRequest.Title, p.PullRequest.Body, p.PullRequest.Head.Ref)+ prefix := h.getIssuePrefix(ctx, inst.WorkspaceID)+ for _, id := range idents {+ issue, ok := h.lookupIssueByIdentifier(ctx, inst.WorkspaceID, prefix, id)+ if !ok {continue}- anyMerged := state == "merged" || counts.MergedCount > 0- if counts.OpenCount == 0 && anyMerged {- h.advanceIssueToDone(ctx, issue, workspaceID)+ if err := h.Queries.LinkIssueToPullRequest(ctx, db.LinkIssueToPullRequestParams{+ IssueID: issue.ID,+ PullRequestID: pr.ID,+ LinkedByType: strToText("system"),+ LinkedByID: pgtype.UUID{},+ }); err != nil {+ slog.Warn("github: link failed", "err", err)+ continue+ }+ linkedIssueIDs = append(linkedIssueIDs, uuidToString(issue.ID))++ // A terminal PR event (`merged` or `closed`) may be the moment the+ // last in-flight sibling resolves, so we re-evaluate the issue on+ // both. We advance the issue to done when:+ // 1. the issue isn't already terminal (`done` / `cancelled`);+ // 2. no sibling PR is still `open` / `draft`;+ // 3. at least one linked PR (this one or a sibling) is `merged`.+ // Rule (3) prevents an "all closed-without-merge" sequence from+ // silently auto-closing the issue — if nothing was ever delivered,+ // the user should decide what to do manually.+ if (state == "merged" || state == "closed") && issue.Status != "done" && issue.Status != "cancelled" {+ counts, err := h.Queries.GetSiblingPullRequestStateCountsForIssue(ctx, db.GetSiblingPullRequestStateCountsForIssueParams{+ IssueID: issue.ID,+ ID: pr.ID,+ })+ if err != nil {+ slog.Warn("github: count sibling pr states failed", "err", err, "issue_id", uuidToString(issue.ID))+ continue+ }+ anyMerged := state == "merged" || counts.MergedCount > 0+ if counts.OpenCount == 0 && anyMerged {+ h.advanceIssueToDone(ctx, issue, workspaceID)+ }}}}@@ -937,6 +948,32 @@ func extractIdentifiers(parts ...string) []string {// lookupIssueByIdentifier looks up an issue in the given workspace by its// "PREFIX-NUMBER" identifier. Returns the row + true if the prefix matches+// workspaceAutoLinkPRsEnabled reports whether the workspace allows the+// GitHub webhook to create issue ↔ PR link rows. Defaults to true so that+// workspaces predating RFC MUL-2414 keep the historical "auto-link on"+// behavior, and short-circuits to false whenever the master GitHub switch+// is explicitly off — mirroring the precedence used on the client side.+func (h *Handler) workspaceAutoLinkPRsEnabled(ctx context.Context, workspaceID pgtype.UUID) bool {+ ws, err := h.Queries.GetWorkspace(ctx, workspaceID)+ if err != nil || len(ws.Settings) == 0 {+ return true+ }+ var s struct {+ GitHubEnabled *bool `json:"github_enabled"`+ GitHubAutoLinkPRsEnabled *bool `json:"github_auto_link_prs_enabled"`+ }+ if err := json.Unmarshal(ws.Settings, &s); err != nil {+ return true+ }+ if s.GitHubEnabled != nil && !*s.GitHubEnabled {+ return false+ }+ if s.GitHubAutoLinkPRsEnabled == nil {+ return true+ }+ return *s.GitHubAutoLinkPRsEnabled+}+// the workspace's configured prefix and the number resolves to a real issue.func (h *Handler) lookupIssueByIdentifier(ctx context.Context, workspaceID pgtype.UUID, prefix, identifier string) (db.Issue, bool) {idx := strings.LastIndex(identifier, "-")