Skip to content

Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.

fix: simplify GitHub connection and first-run deployment (#68)

Robert062259acccb6d9e2
diff --git a/.github/workflows/platform-image.yml b/.github/workflows/platform-image.yml
new file mode 100644
index 00000000..5dddc508
--- /dev/null
+++ b/.github/workflows/platform-image.yml
@@ -0,0 +1,37 @@
+name: platform-image
+on:
+ workflow_dispatch:
+ push:
+ tags: ['platform-v*']
+permissions:
+ contents: read
+ packages: write
+jobs:
+ image:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/[email protected]
+ - uses: docker/setup-buildx-action@v3
+ - uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - id: image
+ env:
+ REPOSITORY: ${{ github.repository }}
+ run: echo "name=ghcr.io/${REPOSITORY,,}" >> "$GITHUB_OUTPUT"
+ - uses: docker/metadata-action@v5
+ id: metadata
+ with:
+ images: ${{ steps.image.outputs.name }}
+ tags: |
+ type=sha,prefix=sha-,format=long
+ type=ref,event=tag
+ - uses: docker/build-push-action@v6
+ with:
+ context: .
+ push: true
+ tags: ${{ steps.metadata.outputs.tags }}
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
diff --git a/.github/workflows/platform.yml b/.github/workflows/platform.yml
index aac0a6a9..aaa7c870 100644
--- a/.github/workflows/platform.yml
+++ b/.github/workflows/platform.yml
@@ -19,6 +19,7 @@ jobs:
- uses: actions/[email protected]
with:
node-version: '22'
+ - run: python3 scripts/test-install.py -v
- name: Build and test the chatbot frontend embedded by the platform binary
run: bash scripts/build-chatbot.sh
- name: Let Chromium use its sandbox as an unprivileged user
diff --git a/Dockerfile b/Dockerfile
index 81e4c038..ac4dd2e3 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,20 +1,24 @@
FROM node:22-bookworm-slim AS chatbot
WORKDIR /src
COPY chatbot/package.json chatbot/package-lock.json chatbot/
-RUN npm --prefix chatbot ci --include=dev --no-audit --no-fund
+RUN --mount=type=cache,target=/root/.npm npm --prefix chatbot ci --include=dev --no-audit --no-fund
COPY chatbot/ chatbot/
COPY web/app/ web/app/
RUN npm --prefix chatbot run build && test -f web/native-chat/index.html
FROM golang:1.26.10-bookworm AS build
WORKDIR /src
-ENV GOMAXPROCS=2 GOFLAGS=-p=2
+# Empty lets build-binaries.sh size parallelism from the builder's CPUs and memory.
+ARG LOOPFORGE_BUILD_JOBS=
+ENV LOOPFORGE_BUILD_JOBS=${LOOPFORGE_BUILD_JOBS}
COPY go.mod go.sum ./
-RUN go mod download
+RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY . .
+# Helpers do not embed the web UI, so they compile while the chatbot stage builds.
+RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build bash scripts/build-binaries.sh --helpers /out
COPY --from=chatbot /src/web/native-chat/ web/native-chat/
-RUN --mount=type=cache,target=/root/.cache/go-build bash scripts/build-binaries.sh /out
-FROM node:22-bookworm-slim
-RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates git bash curl python3 ripgrep \
+RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build bash scripts/build-binaries.sh --platform /out
+FROM node:22-bookworm
+RUN --mount=type=cache,target=/root/.npm apt-get update && apt-get install -y --no-install-recommends ca-certificates git bash curl python3 ripgrep \
&& rm -rf /var/lib/apt/lists/* \
&& npm install -g @openai/[email protected] @anthropic-ai/[email protected] @tencent-ai/[email protected]
COPY --from=docker:27-cli /usr/local/bin/docker /usr/local/bin/docker
diff --git a/README.md b/README.md
index 754d91ea..00a798ea 100644
--- a/README.md
+++ b/README.md
@@ -67,7 +67,7 @@ Ask a coding agent to "fix this bug" and the result depends on that run. It migh
## Quick start
-Requires **Docker (with Compose)** and **Python 3**. The installer offers to install Docker if it is missing.
+Requires **Git, curl, Docker (with Compose)** and **Python 3**. On a fresh Ubuntu host, start with `sudo apt-get update && sudo apt-get install -y git curl python3`. The installer offers to install Docker if it is missing. Ordinary Linux users are supported through Docker group access or sudo.
```bash
git clone https://github.com/Tencent/LoopForge.git
@@ -75,7 +75,7 @@ cd LoopForge
bash scripts/install.sh
```
-Open **<http://localhost:8090>** and create your account; the first one becomes the administrator. The home page's quick-access guide walks you through adding a model key, connecting a repository and choosing an SOP.
+Open the URL printed by the installer and create your account; the first one becomes the administrator. For a cloud deployment, set `LOOPFORGE_PUBLIC_URL=https://your-domain` before the first run and allow the service port in your security group, or put an HTTPS reverse proxy in front. Restrict access to your own IP until the administrator account exists. The home page's quick-access guide walks you through adding a model key, connecting a repository and choosing an SOP.
### Try it without an API key
@@ -91,7 +91,7 @@ New accounts join the **LoopForge demo project**, which includes an SOP made onl
| --- | --- |
| Run the script + approval demo | Nothing |
| Chat with Main Bot, generate a document or a new project | An API key for the selected executor |
-| Change an existing repository (in chat or via an SOP) and open a PR | Model credentials, a GitHub repository and your Git token |
+| Change an existing repository (in chat or via an SOP) and open a PR | Model credentials and a GitHub repository (connect GitHub in personal settings) |
<details>
<summary><b>More setup details</b>: executors, GitHub, sandboxes, access model</summary>
@@ -100,9 +100,9 @@ New accounts join the **LoopForge demo project**, which includes an SOP made onl
- **Executors.** Pick **CodeBuddy, Codex or Claude Code** beside the home composer, then a model. Each executor uses its own credentials from personal settings, and every SOP role can choose its executor independently (built-in roles default to CodeBuddy). Requirement clarification, scheduled assistant tasks and AI notification summaries currently use CodeBuddy. The Docker image ships all three CLIs; [native deployments](docs/deployment.md#workers-and-runners) need the CLI for the executor you choose.
- **GitHub is optional.** All built-in generic SOPs run without a repository: product SOPs deliver documents, and new frontend/backend projects deliver source files in the task workspace. Bug fixes still need source code and reproduction details. Connect a repository when you work on existing code or want PRs.
-- **Delivering to a repository.** Add a GitHub repository, set your Git token and executor credentials in personal settings (or bind a local execution machine), then either run a project SOP or ask Main Bot to change the code and submit a PR/MR.
-- **Sandboxes.** In the default Compose installation, SOP runs and conversation workspaces both use Docker sandbox containers started through the host Docker socket. The sandbox image builds in the background after the first start (a few minutes). Docker socket access grants control of the host daemon, so this setup is for trusted teams, not untrusted multi-tenant isolation. See [deployment boundaries](docs/deployment.md#accounts). Re-running the installer keeps your data.
-- **Accounts and access.** The default deployment listens on localhost and is designed for a trusted team: signed-in users can read project data across the instance, and teammates can sign up from the login page (`AGENTFLOW_ALLOW_SIGNUP=false` in `.env` turns that off). Read the [account and access model](docs/deployment.md#accounts) before exposing it beyond your team.
+- **Delivering to a repository.** Choose **Connect GitHub** in personal settings, approve the device code on GitHub and pick your repository (the LoopForge OAuth App is built in; no PAT required, manual PAT entry still works). Set executor credentials (or bind a local execution machine), then either run a project SOP or ask Main Bot to change the code and submit a PR/MR.
+- **Sandboxes.** In the default Compose installation, SOP runs and conversation workspaces both use Docker sandbox containers started through the host Docker socket. Default sandboxes reuse the installed runtime image, so nothing extra is built after installation; custom Dockerfiles still build their own images. Docker socket access grants control of the host daemon, so this setup is for trusted teams, not untrusted multi-tenant isolation. See [deployment boundaries](docs/deployment.md#accounts). Re-running the installer keeps your data.
+- **Accounts and access.** New installations listen on all interfaces (existing bind settings are kept) and are designed for a trusted team: signed-in users can read project data across the instance, and teammates can sign up from the login page (`AGENTFLOW_ALLOW_SIGNUP=false` in `.env` turns that off). Read the [account and access model](docs/deployment.md#accounts) before exposing it beyond your team.
- **Remote access, HTTPS, separate workers.** See [Deployment](docs/deployment.md).
- **Hacking on LoopForge itself?** `bash scripts/dev.sh` runs it natively (Go 1.26.10+).
@@ -207,7 +207,7 @@ Those are general-purpose AI and automation workflow builders. LoopForge is buil
LoopForge doesn't replace them; it orchestrates them. Each agent step and each chat turn runs one of those CLIs. LoopForge adds what surrounds it: who does what, in which sandbox, in which order, with which checks, and who signs off.
**Is it safe to expose on the internet?**
-The default listens on localhost and targets a trusted team. Read the [account and access model](docs/deployment.md#accounts) and set up HTTPS before opening it up. Report vulnerabilities privately via the [security policy](SECURITY.md).
+New installations listen on all interfaces and target a trusted team. Read the [account and access model](docs/deployment.md#accounts) and set up HTTPS before opening it up. Report vulnerabilities privately via the [security policy](SECURITY.md).
## Documentation
diff --git a/README.zh-CN.md b/README.zh-CN.md
index aa1d95d8..6ea74598 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -67,7 +67,7 @@ https://github.com/user-attachments/assets/10b8ae2e-d7e7-4b78-8876-c45818d4a08f
## 快速开始
-需要 **Docker(含 Compose)** 和 **Python 3**。没装 Docker 时,安装脚本会询问并帮你安装。
+需要 **Git、curl、Docker(含 Compose)** 和 **Python 3**。全新 Ubuntu 可先运行 `sudo apt-get update && sudo apt-get install -y git curl python3`。没装 Docker 时,安装脚本会询问并帮你安装。支持普通用户运行,需要时通过 docker 组或 sudo 操作 Docker。
```bash
git clone https://github.com/Tencent/LoopForge.git
@@ -75,7 +75,7 @@ cd LoopForge
bash scripts/install.sh
```
-打开 **<http://localhost:8090>** 创建账号,第一个账号自动成为管理员。首页的「快速接入」会带你配置模型凭据、绑定仓库并选好默认 SOP。
+打开安装脚本输出的访问链接创建账号,第一个账号自动成为管理员。云端部署可在首次执行前设置 `LOOPFORGE_PUBLIC_URL=https://你的域名`,并放通安全组端口或配置 HTTPS 反向代理;管理员账号创建前,建议只允许你的 IP 访问。首页的「快速接入」会带你配置模型凭据、绑定仓库并选好默认 SOP。
### 免 API Key 体验
@@ -91,7 +91,7 @@ bash scripts/install.sh
| --- | --- |
| 跑通脚本 + 人工审批体验 | 什么都不需要 |
| 与 Main Bot 对话、生成文档或新项目 | 所选执行器的 API Key |
-| 修改已有仓库(通过对话或 SOP)并提交 PR | 模型凭据 + GitHub 仓库 + 你的 Git Token |
+| 修改已有仓库(通过对话或 SOP)并提交 PR | 模型凭据 + GitHub 仓库(在个人设置中连接 GitHub) |
<details>
<summary><b>更多配置说明</b>:执行器、GitHub、沙箱、访问模型</summary>
@@ -100,9 +100,9 @@ bash scripts/install.sh
- **执行器。** 在首页输入框旁选择 **CodeBuddy、Codex 或 Claude Code**,再选择模型;不同执行器分别使用个人设置里的对应凭据。每个 SOP 角色都可以独立选择执行器(内置角色默认 CodeBuddy)。需求澄清、定时助手任务和通知 AI 汇总目前使用 CodeBuddy。Docker 镜像内置三个 CLI;[原生部署](docs/deployment.md#workers-and-runners)需安装所选执行器的 CLI。
- **GitHub 可选。** 所有内置通用 SOP 都可以不绑定仓库运行:产品方案交付文档,前后端新项目在任务工作区交付源码;缺陷修复仍需提供待修代码和复现材料。需要修改已有代码或提交 PR 时再绑定仓库。
-- **交付到仓库。** 添加 GitHub 仓库,在个人设置中配置 Git Token 和执行器凭据(或绑定本机执行机器),之后既可以运行一条项目 SOP,也可以直接让 Main Bot 修改代码并提交 PR/MR。
-- **沙箱。** 默认 Compose 安装中,SOP 运行和对话工作区都使用 Docker 沙箱容器,由平台通过宿主机 Docker socket 启动;首次启动后平台会在后台构建沙箱镜像(需要几分钟)。Docker socket 赋予平台控制宿主机 Docker 的权限,因此只适用于可信团队,不构成不可信多租户隔离边界;详见[部署边界](docs/deployment.md#accounts)。重复执行安装脚本会保留已有数据。
-- **账号与访问。** 默认仅监听本机,面向可信团队:已登录用户可以读取实例内各项目的数据,团队成员可在登录页自助注册(在 `.env` 中设置 `AGENTFLOW_ALLOW_SIGNUP=false` 可关闭)。对团队以外开放前,请先阅读[账号与访问边界](docs/deployment.md#accounts)。
+- **交付到仓库。** 在个人设置中点击「连接 GitHub」,用设备码授权后选择自己的仓库(已内置 LoopForge 授权应用,无需申请 PAT,仍可手动填写 PAT),再配置执行器凭据(或绑定本机执行机器),之后既可以运行一条项目 SOP,也可以直接让 Main Bot 修改代码并提交 PR/MR。
+- **沙箱。** 默认 Compose 安装中,SOP 运行和对话工作区都使用 Docker 沙箱容器,由平台通过宿主机 Docker socket 启动;默认沙箱复用已安装的运行镜像,安装后无需再构建;自定义 Dockerfile 仍单独构建。Docker socket 赋予平台控制宿主机 Docker 的权限,因此只适用于可信团队,不构成不可信多租户隔离边界;详见[部署边界](docs/deployment.md#accounts)。重复执行安装脚本会保留已有数据。
+- **账号与访问。** 新安装默认监听所有网卡(已有安装保留原配置),面向可信团队:已登录用户可以读取实例内各项目的数据,团队成员可在登录页自助注册(在 `.env` 中设置 `AGENTFLOW_ALLOW_SIGNUP=false` 可关闭)。对团队以外开放前,请先阅读[账号与访问边界](docs/deployment.md#accounts)。
- **远程访问、HTTPS、独立 Worker。** 见[部署指南](docs/deployment.md)。
- **参与 LoopForge 本身的开发?** 用 `bash scripts/dev.sh` 原生运行(需要 Go 1.26.10+)。
@@ -207,7 +207,7 @@ npx -y loopforge-cli@latest install claude
LoopForge 不替代它们,而是编排它们。每个 Agent 步骤和每轮对话都运行这些 CLI 之一;LoopForge 补上外面的部分:谁来做、在哪个沙箱里、按什么顺序、经过哪些检查、由谁签字。
**可以直接暴露到公网吗?**
-默认只监听本机,面向可信团队。开放前请阅读[账号与访问边界](docs/deployment.md#accounts)并配置 HTTPS。安全漏洞请按[安全政策](SECURITY.zh-CN.md)私密报告。
+新安装默认监听所有网卡,面向可信团队。开放前请阅读[账号与访问边界](docs/deployment.md#accounts)并配置 HTTPS。安全漏洞请按[安全政策](SECURITY.zh-CN.md)私密报告。
## 文档
diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsx
index 796f9436..646f0049 100644
--- a/chatbot/src/App.jsx
+++ b/chatbot/src/App.jsx
@@ -140,6 +140,14 @@ function useTitleReveal(sessionId, title, revealId) {
}
const homeStarters = [
+ {
+ id: "welcome-demo",
+ icon: "workflow",
+ tone: "green",
+ title: "一键体验",
+ description: "无需 API Key 或 GitHub,运行真实脚本,体验人工审批和产物交付。",
+ steps: ["运行脚本", "人工审批", "查看产物"],
+ },
{
id: "quick-access",
icon: "sparkles",
@@ -456,6 +464,14 @@ export default function App() {
});
}
function handleStarter(starter) {
+ if (starter.id === "welcome-demo") {
+ if (window.parent !== window) {
+ window.parent.postMessage({ type: "agentflow-welcome-demo" }, location.origin);
+ } else {
+ location.href = "/#/sops";
+ }
+ return;
+ }
if (starter.id === "quick-access") {
setQuickAccessOpen(true);
return;
diff --git a/chatbot/src/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsx
index 634e6d81..6e313547 100644
--- a/chatbot/src/QuickAccessWizard.jsx
+++ b/chatbot/src/QuickAccessWizard.jsx
@@ -12,6 +12,7 @@ import HarnessIcon from "./HarnessIcon";
import SlidingTabs from "./SlidingTabs";
import { api, canChatInProject, write } from "./api";
import { usePanelPresence } from "./usePanelPresence";
+import { openCredentialSettings } from "./credentials";
import "./quick-access-wizard.css";
const DEFAULT_SOP_ID = "generic-backend-delivery";
@@ -1045,7 +1046,14 @@ export default function QuickAccessWizard({
.catch(() => {});
};
window.addEventListener("focus", refreshUser);
- return () => window.removeEventListener("focus", refreshUser);
+ const credentialsChanged = (event) => {
+ if (event.origin === location.origin && event.source === window.parent && event.data?.type === "agentflow-credentials-changed") refreshUser();
+ };
+ window.addEventListener("message", credentialsChanged);
+ return () => {
+ window.removeEventListener("focus", refreshUser);
+ window.removeEventListener("message", credentialsChanged);
+ };
}, [open, user?.id, verifyStoredGitToken]);
useEffect(() => {
@@ -1710,6 +1718,12 @@ export default function QuickAccessWizard({
<StatusPill ok={gitReady} />
</header>
<div className="qa-cred-body">
+ <button type="button" className="qa-btn qa-btn-primary qa-btn-sm" onClick={() => openCredentialSettings("gitToken")}>
+ {storedUser?.gitTokenConfigured ? "管理 GitHub 授权" : "连接 GitHub"}
+ </button>
+ <p className="qa-hint">在个人配置中完成授权,返回后继续;无需手动复制令牌。</p>
+ <details>
+ <summary>使用访问令牌(高级)</summary>
<div className="qa-input-row">
<input
type="password"
@@ -1758,6 +1772,7 @@ export default function QuickAccessWizard({
okText={`令牌有效${gitVerify.login ? `(${gitVerify.login})` : ""}`}
/>
) : null}
+ </details>
</div>
</section>
diff --git a/chatbot/src/credentials.js b/chatbot/src/credentials.js
index 3d4df058..aa97c0c0 100644
--- a/chatbot/src/credentials.js
+++ b/chatbot/src/credentials.js
@@ -12,12 +12,12 @@ export const CREDENTIALS = {
// assistantCredentialRules in internal/httpapi/assistant_run_view.go.
export const CREDENTIAL_GUIDES = {
gitToken: {
- url: "https://github.com/settings/tokens",
- link: "打开 GitHub 申请令牌",
+ url: "/#/settings",
+ link: "连接 GitHub",
steps: [
- "打开 GitHub「Settings → Developer settings → Personal access tokens」新建令牌",
- "为目标仓库授予 Contents 和 Pull requests 的读写权限,创建后立即复制 token",
- "到「个人配置 → GitHub Git Token」粘贴,点「校验并保存」",
+ "到「个人配置」点击「连接 GitHub」,复制设备码后前往 GitHub 授权",
+ "添加仓库时点击「选择我的 GitHub 仓库」,选择仓库与主分支",
+ "管理员尚未配置 GitHub 授权时,也可以手动填写有 Contents 和 Pull requests 读写权限的 PAT",
"回到这里点「重试节点」",
],
},
diff --git a/chatbot/src/home.css b/chatbot/src/home.css
index 2999a355..2f4aecf6 100644
--- a/chatbot/src/home.css
+++ b/chatbot/src/home.css
@@ -278,7 +278,7 @@
}
.home-starter-grid {
display: grid;
- grid-template-columns: repeat(3, minmax(0, 1fr));
+ grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.home-starter {
diff --git a/chatbot/src/useLocalConversations.js b/chatbot/src/useLocalConversations.js
index 51021fe6..4b299f23 100644
--- a/chatbot/src/useLocalConversations.js
+++ b/chatbot/src/useLocalConversations.js
@@ -34,7 +34,8 @@ export function useLocalConversations(real) {
const [generations, setGenerations] = useState({});
const generationsRef = useRef(generations);
const timers = useRef(new Map());
- const available = real.ready && !real.activeId && !real.sessions.length;
+ const previewEnabled = new URLSearchParams(location.search).get("localPreview") === "1";
+ const available = previewEnabled && real.ready && !real.activeId && !real.sessions.length;
const availableRef = useRef(available);
availableRef.current = available;
localIdRef.current = localId;
@@ -76,7 +77,7 @@ export function useLocalConversations(real) {
const saved = JSON.parse(localStorage.getItem(key));
if (Array.isArray(saved) && saved.every((row) => isLocalConversation(row?.id) && Array.isArray(row.messages))) sessions = saved;
} catch {}
- sessions ||= createLocalConversations(real.user, real.model);
+ sessions ||= previewEnabled ? createLocalConversations(real.user, real.model) : [];
// Browser-local replies run in this page. A persisted running row has no
// surviving timer after reload, so it must not keep advertising activity.
sessions = sessions.map((row) => row.generationStatus === "running"
@@ -99,7 +100,7 @@ export function useLocalConversations(real) {
}
} catch {}
}
- }, [real.ready, real.user?.id, key, real.model, available, selectLocal]);
+ }, [real.ready, real.user?.id, key, real.model, available, previewEnabled, selectLocal]);
useEffect(() => {
if (!available) selectLocal(null);
diff --git a/chatbot/tests/credentials.test.mjs b/chatbot/tests/credentials.test.mjs
index dbbbcda9..a3bd4593 100644
--- a/chatbot/tests/credentials.test.mjs
+++ b/chatbot/tests/credentials.test.mjs
@@ -67,10 +67,10 @@ test("MCP calls missing a GitHub token point at the Git token", () => {
assert.equal(credentialHint("MCP GitHub 需要 GitHub Git Token:请先在个人凭证中配置")?.field, "gitToken");
});
-test("the Git token guide points at GitHub", () => {
+test("the Git token guide opens the GitHub connection settings", () => {
const hint = credentialHint("git clone: exit status 128: Authentication failed");
assert.equal(hint.label, "GitHub Git Token");
- assert.equal(CREDENTIAL_GUIDES.gitToken.url, "https://github.com/settings/tokens");
+ assert.equal(CREDENTIAL_GUIDES.gitToken.url, "/#/settings");
});
test("unrelated errors do not suggest personal credentials", () => {
diff --git a/chatbot/tests/hooks.test.jsx b/chatbot/tests/hooks.test.jsx
index a3bfbd42..de21399b 100644
--- a/chatbot/tests/hooks.test.jsx
+++ b/chatbot/tests/hooks.test.jsx
@@ -184,6 +184,7 @@ describe("conversation hooks", () => {
});
test("provides local fixture conversations and completes a local reply", async () => {
+ history.replaceState({}, "", "/?localPreview=1");
vi.useFakeTimers();
const real = {
user: { id: 1, loginName: "tester", chineseName: "测试" },
@@ -213,6 +214,16 @@ describe("conversation hooks", () => {
await act(() => result.current.archive(forked.id, true));
await act(() => result.current.remove(local.id));
vi.useRealTimers();
+ history.replaceState({}, "", "/");
+ });
+
+ test("a new account has no fixture conversations unless explicitly previewing", async () => {
+ history.replaceState({}, "", "/");
+ const real = { user: { id: 99 }, ready: true, activeId: null, sessions: [], model: "m1" };
+ const { result } = renderHook(() => useLocalConversations(real));
+ await act(async () => {});
+ expect(result.current.sessions).toEqual([]);
+ expect(result.current.localSessions).toBe(false);
});
test("tracks opening and closing presence", () => {
diff --git a/chatbot/tests/quick-access-wizard.test.jsx b/chatbot/tests/quick-access-wizard.test.jsx
index af110c23..aeb05521 100644
--- a/chatbot/tests/quick-access-wizard.test.jsx
+++ b/chatbot/tests/quick-access-wizard.test.jsx
@@ -150,6 +150,7 @@ describe("QuickAccessWizard", () => {
await userAction.click(screen.getByRole("button", { name: "下一步" }));
expect(screen.getByText(/请至少填写 GitHub Git Token 与 CodeBuddy API Key/)).toBeInTheDocument();
expect(screen.queryByText(/工蜂/)).toBeNull();
+ await userAction.click(screen.getByText("使用访问令牌(高级)"));
await userAction.type(
screen.getByPlaceholderText(/GitHub personal access token/),
"token-value",
diff --git a/compose.yaml b/compose.yaml
index 84c95b85..cb14a07a 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -19,7 +19,11 @@ services:
retries: 60
platform:
profiles: [platform]
- build: .
+ image: ${LOOPFORGE_IMAGE:-loopforge-platform:local}
+ build:
+ context: .
+ args:
+ LOOPFORGE_BUILD_JOBS: ${LOOPFORGE_BUILD_JOBS:-}
ports:
- "${LOOPFORGE_BIND:-127.0.0.1}:${AGENTFLOW_HTTP_PORT:-8090}:8080"
environment:
@@ -29,6 +33,7 @@ services:
AGENTFLOW_AUTH_REQUIRED: "true"
AGENTFLOW_ALLOW_SIGNUP: ${AGENTFLOW_ALLOW_SIGNUP:-true}
AGENTFLOW_SECURE_COOKIES: ${AGENTFLOW_SECURE_COOKIES:-false}
+ AGENTFLOW_GITHUB_CLIENT_ID: ${AGENTFLOW_GITHUB_CLIENT_ID:-}
AGENTFLOW_ASSISTANT_SESSION_DIR: /data/assistant
AGENTFLOW_CLARIFY_SESSION_DIR: /data/clarify
AGENTFLOW_ASSISTANT_MODEL: ${AGENTFLOW_ASSISTANT_MODEL:-}
@@ -37,6 +42,7 @@ services:
AGENTFLOW_PLATFORM_MCP_URL: ${AGENTFLOW_PLATFORM_MCP_URL:-http://platform:8080}
AGENTFLOW_DOCKER_NETWORK: ${COMPOSE_PROJECT_NAME:-loopforge}_default
AGENTFLOW_LOCAL_SANDBOX: docker
+ AGENTFLOW_ISOLATED_IMAGE: ${LOOPFORGE_IMAGE:-loopforge-platform:local}
HOME: ${LOOPFORGE_DATA_DIR:?Run scripts/configure.sh first}/home
AGENTFLOW_RUNNER_BINARY: /app/bin/agentflow-runner-{os}-{arch}
AGENTFLOW_GATE_MCP_BINARY: /app/bin/agentflow-gate-mcp-{os}-{arch}
@@ -50,6 +56,12 @@ services:
depends_on:
mysql:
condition: service_healthy
+ healthcheck:
+ test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=2).close()"]
+ interval: 3s
+ timeout: 3s
+ retries: 60
+ start_period: 10s
restart: unless-stopped
volumes:
mysql-data:
diff --git a/docs/deployment.md b/docs/deployment.md
index 5c88d708..321260ea 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -27,15 +27,28 @@ bash scripts/install.sh
The installer checks Docker, Compose and Python (and offers to install Docker when it is missing; set `LOOPFORGE_YES=1` to accept without prompting), generates `.env` with unique secrets, builds and starts the containers, installs the observability columns and applies `migrations/seed/*.sql`. It is safe to re-run. Set `AGENTFLOW_HTTP_PORT` or `LOOPFORGE_MYSQL_PORT` in the environment before the first run (or edit `.env` later) when the default ports are taken.
+Run it as the installation owner, including an ordinary Linux user. If that user cannot access Docker directly, the installer validates sudo and uses `sudo -n docker` consistently for Compose, schema installation and seeds. Before each operation it checks whether sudo credentials expired during a long build, prompting again in a terminal or failing with instructions in unattended mode. It does not require adding the user to the Docker group or logging out. For unattended installations run `sudo -v` first; `LOOPFORGE_YES=1` accepts installation prompts but does not bypass operating-system permissions. Without sudo or Docker access it fails immediately with instructions. Rootless Docker uses its active context's Unix socket; remote Docker contexts need a separately configured deployment because sandbox workspaces are local bind mounts.
+
+Source builds reuse npm, Go module and Go compiler caches. For the fastest first installation, use an image published by your administrator:
+
+```bash
+LOOPFORGE_IMAGE=ghcr.io/YOUR_OWNER/loopforge:sha-YOUR_COMMIT \
+LOOPFORGE_PUBLIC_URL=https://loopforge.example.com bash scripts/install.sh
+```
+
+The `platform-image` workflow publishes a platform image when manually dispatched or when a `platform-v*` tag is pushed. Set the GHCR package visibility/access for your team before distributing the image. Images are pulled only when missing by default; use an immutable tag/digest, or set `LOOPFORGE_PULL_POLICY=always` when updating a mutable tag. Without `LOOPFORGE_IMAGE`, the installer builds this checkout. Existing `.env` values take precedence; change the saved image or URL there when updating an installation. Compose waits for the API's health check with a bounded timeout before installing schema extensions and seeds.
+
Open the platform and create the first account in the browser; it receives platform administration. Until that account exists the login page only offers this setup step.
-The container listener is published to `127.0.0.1` by default. Set `LOOPFORGE_BIND` or put an HTTPS reverse proxy in front of it when serving other machines. Proxy WebSocket and streaming requests. Set `AGENTFLOW_SECURE_COOKIES=true` when HTTPS terminates at the proxy. Keep `AGENTFLOW_SESSION_SECRET` stable across API instances and restarts.
+During initial setup, restrict the cloud security group or firewall to the operator's IP. Do not expose the first-account setup page to arbitrary Internet clients before the administrator account has been created.
+
+New installations save `LOOPFORGE_BIND=0.0.0.0` for team access. Set `LOOPFORGE_PUBLIC_URL` to the public IP/domain users actually visit; the installer prints that URL. Without one it prints detected host addresses, which may be private when a cloud NAT is in use, and explains how to configure the public URL. Allow the HTTP port in the cloud security group/firewall, or use an HTTPS reverse proxy. Existing `.env` files are preserved; older installations without a bind setting retain their loopback binding until explicitly changed. Local-only installations can set `LOOPFORGE_BIND=127.0.0.1`. Proxy WebSocket and streaming requests. Set `AGENTFLOW_SECURE_COOKIES=true` when HTTPS terminates at the proxy. Keep `AGENTFLOW_SESSION_SECRET` stable across API instances and restarts.
### Docker sandboxes
For native services running as an ordinary host user, default/root Docker images run with that service user's UID/GID so private workspaces remain accessible without relaxing their permissions or adding capabilities. Images that explicitly select a non-root user retain that identity; operators must arrange compatible bind-mount ownership for those images.
-The Compose deployment mounts the host Docker socket into the platform container so built-in AI SOPs run out of the box. On startup the platform builds the shared sandbox image in the background, so it is usually ready by the time the first SOP starts. For each run the platform reuses the image built for that Dockerfile and starts a sibling container on the Compose network with the run workspace mounted at `/workspace`. Because those bind mounts are resolved by the host Docker daemon, `LOOPFORGE_DATA_DIR` (written to `.env` by `scripts/configure.sh`, default `./.data`) is mounted into the platform container at the same absolute path; workspaces and CLI state live under it.
+The Compose deployment mounts the host Docker socket into the platform container so built-in AI SOPs run out of the box. `AGENTFLOW_ISOLATED_IMAGE` points to the installed platform image: default sandboxes start separate sibling containers from that same image, with no second CLI download or image build. They do not mount the Docker socket. Custom Dockerfiles still build and cache their own images. The run workspace is mounted at `/workspace` on the Compose network. Because bind mounts are resolved by the host Docker daemon, `LOOPFORGE_DATA_DIR` (written to `.env` by `scripts/configure.sh`, default `./.data`) is mounted into the platform container at the same absolute path; workspaces and CLI state live under it.
Access to the Docker socket is equivalent to root on the host. Two safeguards follow from that: the platform runs every task in a sandbox container, including SOPs configured for the `local` driver (`AGENTFLOW_LOCAL_SANDBOX=docker`), and only platform administrators can point a repository at a host source path. Even so, anyone who can run SOPs can execute code in containers on this host, so only give accounts to people you trust and do not expose the service to untrusted networks. To run without the socket, remove the `docker.sock` volume and the `AGENTFLOW_LOCAL_SANDBOX` setting from `compose.yaml`, then connect a separate Docker-capable worker or execution machine for AI SOPs; the script-only welcome SOP then runs inside the platform container.
@@ -82,6 +95,14 @@ This repeatable SQL changes only instruction fields that still match the origina
## GitHub credentials
+Users can choose **Connect GitHub** in personal credentials or while adding a repository, copy the displayed PIN, and approve it on GitHub. The platform saves the grant to that signed-in user's existing Git credential slot. The repository picker lists repositories owned by the account, shared with it, or accessible through its organizations, supports pagination and search over loaded repositories, and copies the selected repository's real default branch into the form. PAT entry remains available.
+
+New installations use the built-in LoopForge OAuth App. Users do not create applications, configure a Client ID, or request a PAT: choose **Connect GitHub**, copy the PIN and approve the LoopForge application on GitHub. GitHub's confirmation cannot be bypassed; device authorization is not a zero-interaction login.
+
+Application configuration is a deployment concern and is not shown in personal credentials. Operators who need their own application can register an OAuth App, enable **Device Flow**, keep token expiration disabled until refresh support is available, and set its public Client ID with `AGENTFLOW_GITHUB_CLIENT_ID` in `.env`. No client secret is needed. The deployment environment overrides the built-in application and any database override. The administrator-only `PUT /api/auth/github/config` endpoint remains available for an explicit database override; an empty Client ID explicitly disables device authorization rather than silently restoring the default. Existing explicit configurations are preserved.
+
+The flow requests the OAuth `repo` scope so private cloning, pushes, Issues and PR operations work. GitHub's OAuth scope covers accessible repositories; choosing a repository in LoopForge binds it to the project and does not narrow the OAuth grant. Organization SSO or third-party-app restrictions may require organization approval. See [GitHub's device authorization documentation](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#device-flow). Pending grants expire and are held only in API memory: use session affinity for `/api/auth/github/*` behind multiple API instances, and restart authorization after an API restart. Tokens and GitHub device codes are never sent to the browser.
+
GitHub Issue import and PR status synchronization use the project owner's Git token. Git operations and the optional GitHub MCP integration use the responsible user's token. Public reads may work without a token; private repositories and writes require repository access. GitHub MCP must be installed explicitly and sends credentials only to its official HTTPS endpoint.
Git commits created by the platform use the responsible local account name and a non-deliverable `@users.noreply.loopforge.invalid` email. A local account does not establish a corporate email or a verified GitHub identity.
@@ -100,4 +121,6 @@ Other dedicated/self-hosted configurations are described in the [official CodeBu
## Isolated container acceptance
+Run `python3 scripts/test-install.py -v` for installer regression tests covering sudo selection, direct Docker access, unattended permission failures, repeated installation, image mode and access URLs. With a locally built platform image, `LOOPFORGE_INSTALL_TEST_IMAGE=your-image bash scripts/test-install-live.sh` verifies real root and UID 65534 installations, non-loopback HTTP access, first-account creation and repeated installation in isolated Compose projects on random ports. This live test requires a Linux root test runner to drop privileges; it removes its own containers and volumes afterwards. To also exercise real sudo inside a disposable UID 1000 installer container, build `scripts/testdata/install-sudo.Dockerfile` with `--build-arg LOOPFORGE_TEST_BASE=your-image`, then pass that test image as `LOOPFORGE_INSTALL_SUDO_TEST_IMAGE`. The production installer itself does not require root.
+
From the repository root, run `bash scripts/test-container.sh` after installing `e2e/` dependencies and Chromium. It builds the production image, creates an isolated Compose project and database on ports 8093/33317, provisions test accounts, explicitly applies the observability baseline and public catalog, checks bundled CLIs and cross-platform runner/gate binaries, and runs the public browser suite. Its containers and volumes are removed afterwards. Override `LOOPFORGE_CONTAINER_TEST_PORT` and `LOOPFORGE_CONTAINER_MYSQL_PORT` when those ports are in use. Model calls are disabled for this clean-install check.
diff --git a/docs/proposals/github-sign-in.md b/docs/proposals/github-sign-in.md
new file mode 100644
index 00000000..669a36cb
--- /dev/null
+++ b/docs/proposals/github-sign-in.md
@@ -0,0 +1,67 @@
+# GitHub 登录与仓库授权统一方案
+
+状态:设计建议,尚未修改登录和账号创建逻辑。
+
+## 用户流程
+
+登录页提供「使用 GitHub 继续」作为推荐入口,账号密码作为其他登录方式保留。首次 GitHub 登录时,在部署允许注册的前提下自动建立平台账号;已有绑定的用户直接进入工作台。用户无需单独填写用户名、密码和确认密码。
+
+登录完成后可以立即体验不需要代码仓库的功能。用户添加仓库时,再按需连接 GitHub 仓库并选择仓库。不要为了进入平台,强制要求用户授予私有仓库读写权限。
+
+已有密码账号的用户先通过原方式登录,再明确选择「绑定 GitHub 登录」。绑定后仍保留原有项目、历史运行、权限和凭据。
+
+## 登录与代码访问的边界
+
+| 用途 | 结果 | 凭据处理 |
+| --- | --- | --- |
+| 登录平台 | 解析 GitHub 用户身份,建立或查找平台账号,签发平台自己的会话 Cookie | 不把仅用于登录的令牌写入 GitToken,不覆盖已有仓库凭据 |
+| 绑定登录方式 | 在当前已登录且重新验证过的用户与 GitHub 身份间建立关联 | 必须显式确认,不能通过同名或相同邮箱自动合并 |
+| 连接仓库 | 在当前用户明确同意后取得代码访问能力,列出可访问仓库 | 仓库令牌保留在用户凭据域,按实际返回的权限判断可用能力 |
+
+这两类用途可以使用同一个 GitHub OAuth App,并共享授权客户端、设备码、错误处理等基础设施;账号关联、平台会话、授权目的与令牌存储需要分别处理。不能把「取消仓库授权」解释为删除平台账号,取消平台登录绑定也不应隐式删除仓库凭据。
+
+## OAuth 网页跳转与 PIN 的选择
+
+- 固定域名的平台优先使用网页 OAuth:点击按钮、在 GitHub 同意、回到平台。注册无需另一个表单。服务端配置 Client ID、Client Secret、受信任回调地址,并校验 state、PKCE、浏览器发起状态和授权用途。
+- 自部署实例可提供 PIN 登录:无需为任意用户域名配置网页回调,也无需分发 Client Secret;复用当前设备码授权能力。
+- PIN 需要显示、复制和输入设备码,不等于免输码的一键网页登录。文案应明确「使用设备码登录」,避免承诺与实际操作不一致。
+- 同一个固定网页回调不能直接覆盖所有自部署域名。若未来提供统一登录中转服务,需要单独设计实例注册、受信任跳转和会话交付,不在当前本地授权方案中隐含引入。
+- 当前仓库连接已内置维护方注册的 LoopForge 应用公开 Client ID,不要求用户自行创建应用;这不代表本文提议的 GitHub 注册和登录已经实现。不得借用其他工具的 Client ID 或让用户填写 PAT 作为登录前置条件。
+
+## 当前代码需要调整的地方
+
+1. `internal/httpapi/github_auth.go` 当前要求已登录,并将授权结果直接保存到该用户的 GitToken。该流程是仓库连接,不能直接当成注册入口。
+2. 现有待授权记录以平台 user ID 为键。匿名登录必须绑定独立、短期、不可预测的浏览器发起状态,不能让所有匿名用户共用 user ID 0,也不能只凭浏览器提交的 GitHub 用户名或 flow ID 建立平台会话。
+3. `internal/httpapi/auth_tokens.go` 需要明确放行 GitHub 登录能力查询、登录开始和回调/轮询端点;这些端点自行验证来源、会话状态和授权目的。仓库连接仍要求已登录,不能整体放开认证相关 API。
+4. 在 UsersRepo 增加持久化外部身份映射,以 provider 与 GitHub 返回的数字 user ID 标识身份,并建立唯一约束。GitHub login、显示名和邮箱都不能作为自动关联已有账号的依据。Github 改名后也不能生成重复平台账号。
+5. `authSetup` 和 `authRegister` 目前只看 `LocalAccountCount()`。直接新增 GitHub 注册会导致已有 GitHub 账号时仍被判断为首次部署,后续密码注册可能错误取得管理员。应统一初始化状态和首位管理员判定,并保证跨登录方式、跨 API 实例并发时只产生一名初始化管理员。
+6. GitHub 自动建号必须服从现有注册开关。关闭注册时,已绑定账号仍可登录;未知身份不能自动加入实例。GitHub 身份验证成功不等于获得该部署的访问权限。
+7. 沿用平台现有用户 ID、项目归属、权限与签名 Cookie。后续 GitHub 登录不重新创建账号,不重置角色,不覆盖其他执行器凭据。用户名冲突应明确处理,不能静默接管同名本地账号。
+8. 登录授权与仓库令牌刷新分别处理。仓库令牌撤销或过期时显示「重新连接仓库」,不应让平台账号和本地密码一起失效。解除最后一种可用登录方式前要求设置替代登录方式。
+
+新增模型遵循 UsersRepo 领域归属;只使用现有增量建表机制或显式 SQL,不增加启动时的数据迁移和 seed。
+
+## 界面安排
+
+- 登录页:有可用 GitHub 配置时显示推荐按钮;未配置时保留密码入口,明确说明管理员尚未启用 GitHub 登录。不要出现点击后才报 503 的主按钮。
+- 配置具备网页回调时使用网页 OAuth;只有设备码配置时展示设备码流程和清楚的操作说明。
+- 首次登录:不强制配置模型 Key 或仓库,先给出免 Key 示例和可选的下一步。
+- 个人配置:分别显示「GitHub 登录已绑定」与「GitHub 仓库已连接」,说明切换/解绑影响。
+- 仓库选择:未连接时提供授权入口;已具备所需仓库权限时直接选择仓库,避免无意义的重复授权。GitHub 仓库选择只决定项目绑定,不代表缩小 OAuth repo 授权范围。
+
+## 验收重点
+
+- 全新 GitHub 身份完成注册和登录;同一身份重复登录仍是同一用户;GitHub 改名不改变平台用户 ID。
+- 同名本地账号不会被合并或接管;从本地账号绑定已归属其他用户的 GitHub 身份时明确拒绝。
+- 登录授权不会把低权限令牌写入 GitToken 或覆盖现有仓库授权。
+- 多个匿名浏览器、多个标签页、回调重放、用户拒绝、超时和服务重启均有确定结果。
+- 关闭注册后未知 GitHub 身份无法自动注册;已有绑定用户正常登录。
+- 密码注册与 GitHub 注册同时发生时,首次管理员判定正确;Github-only 部署不再显示首次密码初始化。
+- 网页 OAuth 与设备码使用同一身份映射;仓库授权使用明确不同的授权目的。
+- 真实 Client ID 配置后,分别验证真实网页登录、真实 PIN 登录和真实仓库选择;未配置时不声称已完成真实验收。
+
+## 官方参考
+
+- [GitHub OAuth 网页与设备码授权](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps)
+- [同一 OAuth App 可为登录和私有仓库访问使用不同权限的令牌](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#creating-multiple-tokens-for-oauth-apps)
+- [OAuth 权限范围](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps)
diff --git a/e2e/public/00-first-run.spec.mjs b/e2e/public/00-first-run.spec.mjs
index 6bf5e144..c7c4b80c 100644
--- a/e2e/public/00-first-run.spec.mjs
+++ b/e2e/public/00-first-run.spec.mjs
@@ -55,7 +55,7 @@ test('the home page guides a new account and explains the missing model key',asy
await expect(page.locator('#projectSwitcher option[value="welcome"]')).toHaveCount(1);
const input=await openHome(page);
const frame=chat(page);
- await expect(frame.locator('.home-starter')).toHaveCount(3);
+ await expect(frame.locator('.home-starter')).toHaveCount(4);
const notice=frame.locator('.credential-notice');
await expect(notice).toContainText('CodeBuddy API Key');
await input.fill('First question after installing');
diff --git a/e2e/public/github-setup.spec.mjs b/e2e/public/github-setup.spec.mjs
new file mode 100644
index 00000000..7d818353
--- /dev/null
+++ b/e2e/public/github-setup.spec.mjs
@@ -0,0 +1,44 @@
+import {test,expect} from '@playwright/test';
+import {password,appReady} from './helpers.mjs';
+
+test.use({trace:'off',screenshot:'off'});
+
+test('GitHub authorization stays in one credential row with a separate manual path',async({page},info)=>{
+ const errors=[],failed=[];
+ page.on('pageerror',error=>errors.push(error.message));
+ page.on('response',response=>{if(response.status()>=500)failed.push(response.status()+' '+response.url())});
+ await page.goto('/login.html');
+ await page.locator('[name="login"]').fill(process.env.LOOPFORGE_TEST_USER||'admin');
+ await page.locator('[name="password"]').fill(password());
+ await page.locator('#loginSubmit').click();
+ await appReady(page);
+ await page.waitForLoadState('networkidle');
+ const capability=await page.request.get('/api/auth/github').then(response=>response.json());
+ await page.goto('/#/settings');
+ await expect(page.locator('#personalSettingsContent > .personal-settings-card')).toHaveCount(0);
+ await expect(page.locator('[data-credential-row="gitToken"]')).toContainText('GitHub');
+ await page.screenshot({path:info.outputPath('github-settings.png'),fullPage:true});
+ await page.locator('[data-credential-row="gitToken"] [data-credential-act="setup"]').click();
+ const wizard=page.locator('#credentialWizard');
+ if(capability.enabled){
+ await expect(wizard.locator('[data-github-start]')).toBeVisible();
+ await expect(wizard.locator('[data-github-start]')).toBeEnabled();
+ }else{
+ await expect(wizard.locator('[data-github-start]')).toBeHidden();
+ await expect(wizard).toContainText('已停用');
+ }
+ await expect(wizard.locator('input[name="secret"]')).toHaveCount(0);
+ await expect(wizard.locator('.github-admin,[data-github-client]')).toHaveCount(0);
+ await expect(wizard).not.toContainText('Client ID');
+ await page.screenshot({path:info.outputPath('github-authorization.png'),fullPage:true});
+ await wizard.getByRole('tab',{name:'访问令牌'}).click();
+ await expect(wizard.locator('input[name="secret"]')).toBeVisible();
+ await expect(wizard.locator('[data-github-connect]')).toHaveCount(0);
+ await page.screenshot({path:info.outputPath('github-manual.png'),fullPage:true});
+ await page.setViewportSize({width:390,height:844});
+ expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);
+ await expect(wizard.locator('.credential-dialog')).toBeInViewport();
+ await page.screenshot({path:info.outputPath('github-mobile.png'),fullPage:true});
+ expect(errors).toEqual([]);
+ expect(failed).toEqual([]);
+});
diff --git a/e2e/public/welcome.spec.mjs b/e2e/public/welcome.spec.mjs
index 5f806144..1ccc6172 100644
--- a/e2e/public/welcome.spec.mjs
+++ b/e2e/public/welcome.spec.mjs
@@ -37,8 +37,8 @@ for(const variant of [
// A first conversation is personal until a project is picked.
await expect(frame.locator('.project-picker')).toHaveClass(/is-unset/);
const starters=frame.locator('.home-starter');
- await expect(starters).toHaveCount(3);
- for(let i=0;i<3;i++){await starters.nth(i).scrollIntoViewIfNeeded();await expect(starters.nth(i)).toBeInViewport()}
+ await expect(starters).toHaveCount(4);
+ for(let i=0;i<4;i++){await starters.nth(i).scrollIntoViewIfNeeded();await expect(starters.nth(i)).toBeInViewport()}
expect(await frame.locator('html').evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);
expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);
await page.screenshot({path:info.outputPath(`home-${variant.name}.png`)});
@@ -55,18 +55,16 @@ test('the welcome SOP needs no key, runs a real script and waits for approval in
test.setTimeout(120_000);
const errors=[];page.on('pageerror',e=>errors.push(e.message));
await signInUnconfigured(page);
- await switchProject(page,'welcome');
- await page.locator('.nav[data-view="sops"]').click();
- const card=page.locator('article.sop-card[data-sop="welcome-workflow"]');
- await expect(card).toBeVisible();
- await expect(card.locator('.sop-requirements .sop-badge')).toHaveCount(1);
- await expect(card.locator('.sop-requirements .sop-badge')).toHaveClass(/tone-success/);
+ await openHome(page);
+ await expect(chat(page).locator('.session-list [data-session-id^="local-preview-"]')).toHaveCount(0);
let runId='';
try{
- const created=await page.request.post('/api/runs',{data:{workflowId:'welcome-workflow',projectId:'welcome',input:'Browser acceptance: approve from the run view'}});
+ const pending=page.waitForResponse(response=>response.request().method()==='POST'&&new URL(response.url()).pathname==='/api/runs');
+ await chat(page).getByRole('button',{name:/一键体验/}).click();
+ const created=await pending;
expect(created.ok()).toBe(true);runId=(await created.json()).id;
const read=async()=>{const r=await page.request.get(`/api/runs/${runId}`);expect(r.ok()).toBe(true);return r.json()};
- await expect.poll(async()=>(await read()).status,{timeout:60_000}).toBe('waiting');
+ await expect.poll(async()=>(await read()).status,{timeout:30_000}).toBe('waiting');
const run=await read();
expect(run.nodes.prepare.status).toBe('succeeded');
expect(run.nodes.approve.status).not.toBe('succeeded');
@@ -199,6 +197,9 @@ for(const variant of [
await expect(modal).not.toHaveClass(/open/);
await expect(page).toHaveURL(/#\/settings/);
const wizard=page.locator('#credentialWizard');
+ await expect(wizard.getByRole('tab',{name:'GitHub 授权'})).toHaveAttribute('aria-selected','true');
+ await expect(wizard.locator('input[name="secret"]')).toHaveCount(0);
+ await wizard.getByRole('tab',{name:'访问令牌'}).click();
await expect(wizard.locator('.credential-pane:not(.is-leaving) input[name="secret"]')).toBeFocused();
await expect(wizard).toContainText('GitHub');
await page.keyboard.press('Escape');
diff --git a/go.mod b/go.mod
index da92b111..80c68b58 100644
--- a/go.mod
+++ b/go.mod
@@ -9,7 +9,7 @@ require (
github.com/go-sql-driver/mysql v1.8.1
github.com/goccy/go-yaml v1.19.2
github.com/gorilla/websocket v1.5.3
- github.com/klauspost/compress v1.20.2
+ github.com/klauspost/compress v1.20.3
golang.org/x/crypto v0.57.0
golang.org/x/net v0.60.0
golang.org/x/sys v0.48.0
diff --git a/go.sum b/go.sum
index ea5229d4..8fc461e5 100644
--- a/go.sum
+++ b/go.sum
@@ -54,8 +54,8 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
-github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo=
-github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
+github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4=
+github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
diff --git a/internal/domain/preview.go b/internal/domain/preview.go
index 98579ada..23465294 100644
--- a/internal/domain/preview.go
+++ b/internal/domain/preview.go
@@ -8,6 +8,15 @@ import (
"time"
)
+// PreviewID is the stable preview id for a run: one preview per run.
+func PreviewID(runID string) string {
+ runID = strings.TrimSpace(runID)
+ if runID == "" {
+ return "preview"
+ }
+ return "preview-" + runID
+}
+
// ErrInvalidPreviewBackendURL is returned when a preview session backend URL
// is not a credential-free http(s) origin.
var ErrInvalidPreviewBackendURL = errors.New("preview backendUrl must be an http(s) URL without credentials")
diff --git a/internal/httpapi/github_auth.go b/internal/httpapi/github_auth.go
new file mode 100644
index 00000000..e529efb7
--- /dev/null
+++ b/internal/httpapi/github_auth.go
@@ -0,0 +1,341 @@
+package httpapi
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "agentflow/internal/domain"
+ "agentflow/internal/gitwork"
+ "agentflow/internal/repo"
+
+ "github.com/gin-gonic/gin"
+)
+
+type githubGrant struct {
+ id, code string
+ clientID string
+ expires, next time.Time
+ interval time.Duration
+ busy bool
+}
+
+const defaultGitHubClientID = "Ov23liPWCuv7rBK2X6H0"
+
+type githubHandlers struct {
+ *deps
+ client *http.Client
+ mu sync.Mutex
+ grants map[int64]*githubGrant
+}
+
+func newGitHubHandlers(shared *deps) *githubHandlers {
+ return &githubHandlers{deps: shared, client: &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, grants: make(map[int64]*githubGrant)}
+}
+
+func (h *githubHandlers) current(c *gin.Context) (int64, bool) {
+ c.Header("Cache-Control", "no-store")
+ user, ok := h.requestUser(c.Request, false)
+ if !ok || user == nil || user.IsGuest || user.ID <= 0 {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录 LoopForge,再连接 GitHub"})
+ return 0, false
+ }
+ if c.Request.Method != http.MethodGet {
+ origin, err := url.Parse(c.GetHeader("Origin"))
+ if err != nil || origin.Host != c.Request.Host || (origin.Scheme != "http" && origin.Scheme != "https") {
+ c.JSON(http.StatusForbidden, gin.H{"error": "请求来源不允许"})
+ return 0, false
+ }
+ }
+ return user.ID, true
+}
+
+func (h *githubHandlers) status(c *gin.Context) {
+ if _, ok := h.current(c); !ok {
+ return
+ }
+ clientID, err := h.clientID()
+ if err != nil {
+ respond(c, err)
+ return
+ }
+ admin := h.isPlatformAdmin(c.Request)
+ result := gin.H{"enabled": clientID != "", "canConfigure": admin, "managed": strings.TrimSpace(os.Getenv("AGENTFLOW_GITHUB_CLIENT_ID")) != ""}
+ if admin {
+ result["clientId"] = clientID
+ }
+ c.JSON(http.StatusOK, result)
+}
+
+func (h *githubHandlers) clientID() (string, error) {
+ if clientID := strings.TrimSpace(os.Getenv("AGENTFLOW_GITHUB_CLIENT_ID")); clientID != "" {
+ return clientID, nil
+ }
+ return h.repo.UsersRepo.GitHubClientID(defaultGitHubClientID)
+}
+
+func (h *githubHandlers) configure(c *gin.Context) {
+ if _, ok := h.current(c); !ok {
+ return
+ }
+ if !h.isPlatformAdmin(c.Request) {
+ c.JSON(http.StatusForbidden, gin.H{"error": "仅平台管理员可以配置 GitHub 授权应用"})
+ return
+ }
+ if strings.TrimSpace(os.Getenv("AGENTFLOW_GITHUB_CLIENT_ID")) != "" {
+ c.JSON(http.StatusConflict, gin.H{"error": "此实例由环境变量管理,请在部署配置中修改 Client ID"})
+ return
+ }
+ var input struct {
+ ClientID string `json:"clientId"`
+ }
+ if err := c.ShouldBindJSON(&input); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "请填写 GitHub OAuth App 的 Client ID"})
+ return
+ }
+ input.ClientID = strings.TrimSpace(input.ClientID)
+ if input.ClientID != "" && !regexp.MustCompile(`^[A-Za-z0-9_.-]{10,80}$`).MatchString(input.ClientID) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Client ID 格式不正确;不要填写 Client Secret 或个人访问令牌"})
+ return
+ }
+ h.mu.Lock()
+ err := h.repo.UsersRepo.SetGitHubClientID(input.ClientID)
+ if err == nil {
+ clear(h.grants)
+ }
+ h.mu.Unlock()
+ if err != nil {
+ respond(c, err)
+ return
+ }
+ h.status(c)
+}
+
+func (h *githubHandlers) request(c *gin.Context, method, endpoint, token string, form url.Values, output any) error {
+ var body io.Reader
+ if form != nil {
+ body = strings.NewReader(form.Encode())
+ }
+ request, err := http.NewRequestWithContext(c.Request.Context(), method, endpoint, body)
+ if err != nil {
+ return err
+ }
+ request.Header.Set("Accept", "application/json")
+ request.Header.Set("User-Agent", "LoopForge")
+ if form != nil {
+ request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ }
+ if token != "" {
+ request.Header.Set("Authorization", "Bearer "+token)
+ }
+ response, err := h.client.Do(request)
+ if err != nil {
+ return errors.New("无法连接 GitHub,请稍后重试")
+ }
+ defer response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ return errors.New("GitHub 请求失败(HTTP " + strconv.Itoa(response.StatusCode) + "),请检查授权与组织访问策略")
+ }
+ if err := json.NewDecoder(io.LimitReader(response.Body, 2<<20)).Decode(output); err != nil {
+ return errors.New("GitHub 返回了无效响应")
+ }
+ return nil
+}
+
+func (h *githubHandlers) start(c *gin.Context) {
+ userID, ok := h.current(c)
+ if !ok {
+ return
+ }
+ clientID, err := h.clientID()
+ if err != nil {
+ respond(c, err)
+ return
+ }
+ if clientID == "" {
+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "请管理员配置 GitHub OAuth App 的 Client ID 并启用 Device Flow;用户无需申请 PAT"})
+ return
+ }
+ nonce := make([]byte, 24)
+ if _, err := rand.Read(nonce); err != nil {
+ respond(c, err)
+ return
+ }
+ grant := &githubGrant{id: hex.EncodeToString(nonce), clientID: clientID, expires: time.Now().Add(15 * time.Minute), next: time.Now().Add(10 * time.Second)}
+ h.mu.Lock()
+ currentClientID, configErr := h.clientID()
+ if configErr != nil || currentClientID != clientID {
+ h.mu.Unlock()
+ c.JSON(http.StatusConflict, gin.H{"error": "GitHub 应用配置已变更,请重新连接"})
+ return
+ }
+ for owner, pending := range h.grants {
+ if time.Now().After(pending.expires) {
+ delete(h.grants, owner)
+ }
+ }
+ if pending := h.grants[userID]; (pending != nil && (pending.busy || time.Now().Before(pending.next))) || len(h.grants) >= 1024 {
+ h.mu.Unlock()
+ c.JSON(http.StatusTooManyRequests, gin.H{"error": "请稍后再发起授权"})
+ return
+ }
+ grant.busy = true
+ h.grants[userID] = grant
+ h.mu.Unlock()
+ var device struct {
+ DeviceCode string `json:"device_code"`
+ UserCode string `json:"user_code"`
+ VerificationURI string `json:"verification_uri"`
+ ExpiresIn int `json:"expires_in"`
+ Interval int `json:"interval"`
+ }
+ err = h.request(c, http.MethodPost, "https://github.com/login/device/code", "", url.Values{"client_id": {clientID}, "scope": {"repo"}}, &device)
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if h.grants[userID] != grant {
+ c.JSON(http.StatusConflict, gin.H{"error": "GitHub 应用配置已变更,请重新连接"})
+ return
+ }
+ if err != nil || device.DeviceCode == "" || device.UserCode == "" || device.ExpiresIn <= 0 || device.ExpiresIn > 1800 || device.VerificationURI != "https://github.com/login/device" {
+ delete(h.grants, userID)
+ c.JSON(http.StatusBadGateway, gin.H{"error": "无法开始 GitHub 授权,请检查 OAuth App 是否启用 Device Flow 或稍后重试"})
+ return
+ }
+ grant.code = device.DeviceCode
+ grant.expires = time.Now().Add(time.Duration(device.ExpiresIn) * time.Second)
+ grant.interval = time.Duration(max(5, device.Interval)) * time.Second
+ grant.next = time.Now().Add(grant.interval)
+ grant.busy = false
+ c.JSON(http.StatusOK, gin.H{"flowId": grant.id, "userCode": device.UserCode, "verificationUri": device.VerificationURI, "expiresIn": device.ExpiresIn, "interval": int(grant.interval.Seconds())})
+}
+
+func (h *githubHandlers) poll(c *gin.Context) {
+ userID, ok := h.current(c)
+ if !ok {
+ return
+ }
+ var input struct {
+ FlowID string `json:"flowId"`
+ }
+ if !decode(c, &input) {
+ return
+ }
+ h.mu.Lock()
+ grant := h.grants[userID]
+ if grant == nil || grant.id != input.FlowID || time.Now().After(grant.expires) {
+ h.mu.Unlock()
+ c.JSON(http.StatusBadRequest, gin.H{"error": "授权已失效,请重新连接 GitHub"})
+ return
+ }
+ clientID, configErr := h.clientID()
+ if configErr != nil || clientID != grant.clientID {
+ delete(h.grants, userID)
+ h.mu.Unlock()
+ c.JSON(http.StatusConflict, gin.H{"error": "GitHub 应用配置已变更,请重新连接"})
+ return
+ }
+ if grant.busy || time.Now().Before(grant.next) {
+ interval := int(grant.interval.Seconds())
+ h.mu.Unlock()
+ c.JSON(http.StatusOK, gin.H{"status": "pending", "interval": interval})
+ return
+ }
+ grant.busy = true
+ grant.next = time.Now().Add(grant.interval)
+ h.mu.Unlock()
+ var result struct {
+ AccessToken string `json:"access_token"`
+ Error string `json:"error"`
+ ExpiresIn int `json:"expires_in"`
+ }
+ err := h.request(c, http.MethodPost, "https://github.com/login/oauth/access_token", "", url.Values{"client_id": {grant.clientID}, "device_code": {grant.code}, "grant_type": {"urn:ietf:params:oauth:grant-type:device_code"}}, &result)
+ var identity struct {
+ Login string `json:"login"`
+ }
+ if err == nil && result.AccessToken != "" {
+ err = h.request(c, http.MethodGet, "https://api.github.com/user", result.AccessToken, nil, &identity)
+ if identity.Login == "" && err == nil {
+ err = errors.New("GitHub 未返回账号信息")
+ }
+ }
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ grant.busy = false
+ if h.grants[userID] != grant || time.Now().After(grant.expires) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "授权已失效,请重新连接 GitHub"})
+ return
+ }
+ clientID, configErr = h.clientID()
+ if configErr != nil || clientID != grant.clientID {
+ delete(h.grants, userID)
+ c.JSON(http.StatusConflict, gin.H{"error": "GitHub 应用配置已变更,请重新连接"})
+ return
+ }
+ if err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
+ return
+ }
+ if result.Error == "authorization_pending" || result.Error == "slow_down" {
+ if result.Error == "slow_down" {
+ grant.interval += 5 * time.Second
+ }
+ grant.next = time.Now().Add(grant.interval)
+ c.JSON(http.StatusOK, gin.H{"status": "pending", "interval": int(grant.interval.Seconds())})
+ return
+ }
+ delete(h.grants, userID)
+ if result.AccessToken == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "GitHub 授权被拒绝或已过期,请重新连接"})
+ return
+ }
+ if result.ExpiresIn > 0 {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "当前仅支持非过期 OAuth 令牌,请管理员关闭 OAuth App 的令牌过期选项后重试"})
+ return
+ }
+ saved, err := h.repo.UpdateUserCredentials(userID, repo.UserCredentialUpdate{GitToken: result.AccessToken})
+ if err != nil {
+ respond(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"status": "connected", "login": identity.Login, "user": domain.PublicUser(saved)})
+}
+
+func (h *githubHandlers) repositories(c *gin.Context) {
+ userID, ok := h.current(c)
+ if !ok {
+ return
+ }
+ user, ok := h.repo.User(userID)
+ if !ok || user.GitToken == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "请先连接 GitHub"})
+ return
+ }
+ page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
+ if err != nil || page < 1 || page > 10000 {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "无效页码"})
+ return
+ }
+ var repositories []struct {
+ FullName string `json:"full_name"`
+ HTMLURL string `json:"html_url"`
+ DefaultBranch string `json:"default_branch"`
+ Private bool `json:"private"`
+ }
+ _, token := gitwork.SplitToken(user.GitToken)
+ err = h.request(c, http.MethodGet, "https://api.github.com/user/repos?per_page=100&sort=updated&affiliation=owner,collaborator,organization_member&page="+strconv.Itoa(page), token, nil, &repositories)
+ if err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"repositories": repositories, "hasMore": len(repositories) == 100, "page": page})
+}
diff --git a/internal/httpapi/github_auth_test.go b/internal/httpapi/github_auth_test.go
new file mode 100644
index 00000000..6aeefd7f
--- /dev/null
+++ b/internal/httpapi/github_auth_test.go
@@ -0,0 +1,348 @@
+package httpapi
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "agentflow/internal/auth"
+ "agentflow/internal/domain"
+ "agentflow/internal/repo"
+
+ "github.com/gin-gonic/gin"
+)
+
+type githubTestTransport func(*http.Request) (*http.Response, error)
+
+func (transport githubTestTransport) RoundTrip(request *http.Request) (*http.Response, error) {
+ return transport(request)
+}
+
+func githubTestHandler(t *testing.T) (*githubHandlers, int64) {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ t.Setenv("AGENTFLOW_GITHUB_CLIENT_ID", "test-client")
+ t.Setenv("AGENTFLOW_PREVIEW_LOCAL_LOGIN", "")
+ t.Setenv("AGENTFLOW_LOCAL_LOGIN_USER", "")
+ store, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(store.Close)
+ if err := store.PutUser(domain.User{LoginName: "github-owner"}); err != nil {
+ t.Fatal(err)
+ }
+ user, _ := store.UserByLoginName("github-owner")
+ return newGitHubHandlers(&deps{repo: store, authClient: auth.NewClient(auth.Config{SessionSecret: "github-test-secret"})}), user.ID
+}
+
+func githubTestContext(userID int64, method, endpoint, body string) (*gin.Context, *httptest.ResponseRecorder) {
+ recorder := httptest.NewRecorder()
+ current, _ := gin.CreateTestContext(recorder)
+ current.Request = httptest.NewRequest(method, "http://loopforge.test"+endpoint, strings.NewReader(body))
+ current.Request.Header.Set("Origin", "http://loopforge.test")
+ current.Request.Header.Set("Content-Type", "application/json")
+ if userID > 0 {
+ current.Request = current.Request.WithContext(context.WithValue(current.Request.Context(), requestUserContextKey{}, &auth.User{ID: userID, LoginName: "github-owner"}))
+ }
+ return current, recorder
+}
+
+func githubTestResponse(body string) *http.Response {
+ return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}
+}
+
+func TestGitHubDefaultApplicationAndExplicitOverrides(t *testing.T) {
+ handler, userID := githubTestHandler(t)
+ t.Setenv("AGENTFLOW_GITHUB_CLIENT_ID", "")
+ clientID, err := handler.clientID()
+ if err != nil || clientID != defaultGitHubClientID {
+ t.Fatalf("fresh installation: %q %v", clientID, err)
+ }
+ current, recorder := githubTestContext(userID, http.MethodGet, "/api/auth/github", "")
+ handler.status(current)
+ if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), `"enabled":true`) || strings.Contains(recorder.Body.String(), "clientId") {
+ t.Fatalf("default capability: %d %s", recorder.Code, recorder.Body)
+ }
+ for _, configured := range []string{"Iv1.custom-application", ""} {
+ if err := handler.repo.UsersRepo.SetGitHubClientID(configured); err != nil {
+ t.Fatal(err)
+ }
+ clientID, err := handler.clientID()
+ if err != nil || clientID != configured {
+ t.Fatalf("explicit configuration %q: %q %v", configured, clientID, err)
+ }
+ }
+ t.Setenv("AGENTFLOW_GITHUB_CLIENT_ID", "environment-client")
+ if clientID, err := handler.clientID(); err != nil || clientID != "environment-client" {
+ t.Fatalf("environment override: %q %v", clientID, err)
+ }
+}
+
+func TestGitHubApplicationConfiguration(t *testing.T) {
+ handler, userID := githubTestHandler(t)
+ t.Setenv("AGENTFLOW_GITHUB_CLIENT_ID", "")
+ current, recorder := githubTestContext(userID, http.MethodPut, "/api/auth/github/config", `{"clientId":"Iv1.testapplication"}`)
+ handler.configure(current)
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("non-admin changed application: %d", recorder.Code)
+ }
+ if _, err := handler.repo.GrantPlatformAdmin("github-owner"); err != nil {
+ t.Fatal(err)
+ }
+ current, recorder = githubTestContext(userID, http.MethodPut, "/api/auth/github/config", `{"clientId":"Iv1.testapplication"}`)
+ handler.configure(current)
+ if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), `"enabled":true`) {
+ t.Fatalf("configuration: %d %s", recorder.Code, recorder.Body)
+ }
+ restarted := newGitHubHandlers(handler.deps)
+ if clientID, err := restarted.clientID(); err != nil || clientID != "Iv1.testapplication" {
+ t.Fatalf("configuration not persisted: %q %v", clientID, err)
+ }
+ for _, scenario := range []struct {
+ origin, body string
+ expected int
+ }{
+ {"https://other.test", `{"clientId":"Iv1.otherapplication"}`, http.StatusForbidden},
+ {"http://loopforge.test", `{"clientId":"bad secret"}`, http.StatusBadRequest},
+ } {
+ current, recorder = githubTestContext(userID, http.MethodPut, "/api/auth/github/config", scenario.body)
+ current.Request.Header.Set("Origin", scenario.origin)
+ handler.configure(current)
+ if recorder.Code != scenario.expected {
+ t.Fatalf("configuration accepted invalid request: %d", recorder.Code)
+ }
+ }
+ t.Setenv("AGENTFLOW_GITHUB_CLIENT_ID", "environment-client")
+ current, recorder = githubTestContext(userID, http.MethodPut, "/api/auth/github/config", `{"clientId":"Iv1.otherapplication"}`)
+ handler.configure(current)
+ if recorder.Code != http.StatusConflict {
+ t.Fatalf("overwrote managed configuration: %d", recorder.Code)
+ }
+}
+
+func TestGitHubDeviceFlowStoresOnlyCurrentUsersGrant(t *testing.T) {
+ handler, userID := githubTestHandler(t)
+ tokenCalls := 0
+ handler.client.Transport = githubTestTransport(func(request *http.Request) (*http.Response, error) {
+ switch request.URL.String() {
+ case "https://github.com/login/device/code":
+ _ = request.ParseForm()
+ if request.Form.Get("client_id") != "test-client" || request.Form.Get("scope") != "repo" {
+ t.Fatalf("device form=%v", request.Form)
+ }
+ return githubTestResponse(`{"device_code":"server-only-code","user_code":"ABCD-EFGH","verification_uri":"https://github.com/login/device","expires_in":900,"interval":5}`), nil
+ case "https://github.com/login/oauth/access_token":
+ tokenCalls++
+ _ = request.ParseForm()
+ if request.Form.Get("device_code") != "server-only-code" {
+ t.Fatal("missing device code")
+ }
+ if tokenCalls == 1 {
+ return githubTestResponse(`{"error":"authorization_pending"}`), nil
+ }
+ if tokenCalls == 2 {
+ return githubTestResponse(`{"error":"slow_down"}`), nil
+ }
+ return githubTestResponse(`{"access_token":"test-private-token","token_type":"bearer"}`), nil
+ case "https://api.github.com/user":
+ if request.Header.Get("Authorization") != "Bearer test-private-token" {
+ t.Fatal("missing bearer")
+ }
+ return githubTestResponse(`{"login":"authorized-account"}`), nil
+ default:
+ t.Fatalf("unexpected endpoint %s", request.URL)
+ return nil, nil
+ }
+ })
+ current, recorder := githubTestContext(userID, http.MethodPost, "/api/auth/github/device", "{}")
+ handler.start(current)
+ if recorder.Code != http.StatusOK || bytes.Contains(recorder.Body.Bytes(), []byte("server-only-code")) {
+ t.Fatalf("start=%d %s", recorder.Code, recorder.Body.String())
+ }
+ grant := handler.grants[userID]
+ pollBody, _ := json.Marshal(map[string]string{"flowId": grant.id})
+ current, recorder = githubTestContext(userID+1, http.MethodPost, "/api/auth/github/poll", string(pollBody))
+ handler.poll(current)
+ if recorder.Code != http.StatusBadRequest {
+ t.Fatal("other user could poll this grant")
+ }
+ current, recorder = githubTestContext(userID, http.MethodPost, "/api/auth/github/poll", string(pollBody))
+ handler.poll(current)
+ if tokenCalls != 0 {
+ t.Fatal("polled GitHub before interval")
+ }
+ for attempt := 0; attempt < 3; attempt++ {
+ grant.next = time.Now().Add(-time.Second)
+ current, recorder = githubTestContext(userID, http.MethodPost, "/api/auth/github/poll", string(pollBody))
+ handler.poll(current)
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("poll %d: %d %s", attempt, recorder.Code, recorder.Body.String())
+ }
+ }
+ if grant.interval != 10*time.Second {
+ t.Fatalf("slow_down interval=%s", grant.interval)
+ }
+ if bytes.Contains(recorder.Body.Bytes(), []byte("test-private-token")) || !strings.Contains(recorder.Body.String(), "authorized-account") {
+ t.Fatalf("public result=%s", recorder.Body.String())
+ }
+ user, _ := handler.repo.User(userID)
+ if user.GitToken != "test-private-token" || user.GongfengRefreshToken != "" {
+ t.Fatal("grant not stored correctly")
+ }
+ if handler.grants[userID] != nil {
+ t.Fatal("completed grant can be replayed")
+ }
+}
+
+func TestGitHubReconfigurationCancelsInFlightGrants(t *testing.T) {
+ for _, stage := range []string{"start", "poll"} {
+ t.Run(stage, func(t *testing.T) {
+ handler, userID := githubTestHandler(t)
+ t.Setenv("AGENTFLOW_GITHUB_CLIENT_ID", "")
+ if _, err := handler.repo.GrantPlatformAdmin("github-owner"); err != nil {
+ t.Fatal(err)
+ }
+ if err := handler.repo.UsersRepo.SetGitHubClientID("Iv1.original-application"); err != nil {
+ t.Fatal(err)
+ }
+ disable := func() {
+ current, recorder := githubTestContext(userID, http.MethodPut, "/api/auth/github/config", `{"clientId":""}`)
+ handler.configure(current)
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("disable application: %d %s", recorder.Code, recorder.Body)
+ }
+ }
+ handler.client.Transport = githubTestTransport(func(request *http.Request) (*http.Response, error) {
+ switch request.URL.Path {
+ case "/login/device/code":
+ if stage == "start" {
+ disable()
+ }
+ return githubTestResponse(`{"device_code":"server-only-code","user_code":"ABCD-EFGH","verification_uri":"https://github.com/login/device","expires_in":900,"interval":5}`), nil
+ case "/login/oauth/access_token":
+ disable()
+ return githubTestResponse(`{"access_token":"must-not-be-saved"}`), nil
+ case "/user":
+ return githubTestResponse(`{"login":"github-account"}`), nil
+ default:
+ t.Fatalf("unexpected endpoint: %s", request.URL)
+ return nil, nil
+ }
+ })
+ current, recorder := githubTestContext(userID, http.MethodPost, "/api/auth/github/device", "{}")
+ handler.start(current)
+ if stage == "start" {
+ if recorder.Code != http.StatusConflict || strings.Contains(recorder.Body.String(), "ABCD-EFGH") {
+ t.Fatalf("disabled grant exposed: %d %s", recorder.Code, recorder.Body)
+ }
+ } else {
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("start: %d %s", recorder.Code, recorder.Body)
+ }
+ grant := handler.grants[userID]
+ grant.next = time.Now().Add(-time.Second)
+ payload, _ := json.Marshal(map[string]string{"flowId": grant.id})
+ current, recorder = githubTestContext(userID, http.MethodPost, "/api/auth/github/poll", string(payload))
+ handler.poll(current)
+ if recorder.Code != http.StatusBadRequest {
+ t.Fatalf("disabled grant completed: %d %s", recorder.Code, recorder.Body)
+ }
+ }
+ user, _ := handler.repo.User(userID)
+ if user.GitToken != "" || len(handler.grants) != 0 {
+ t.Fatal("disabled application retained a grant or saved its token")
+ }
+ })
+ }
+}
+
+func TestGitHubReplicaRejectsChangedApplication(t *testing.T) {
+ handler, userID := githubTestHandler(t)
+ t.Setenv("AGENTFLOW_GITHUB_CLIENT_ID", "")
+ if err := handler.repo.UsersRepo.SetGitHubClientID("Iv1.replacement-application"); err != nil {
+ t.Fatal(err)
+ }
+ handler.grants[userID] = &githubGrant{id: "flow", code: "old-app-code", clientID: "Iv1.original-application", expires: time.Now().Add(time.Minute)}
+ handler.client.Transport = githubTestTransport(func(*http.Request) (*http.Response, error) {
+ t.Fatal("a replica contacted GitHub with a disabled application grant")
+ return nil, nil
+ })
+ current, recorder := githubTestContext(userID, http.MethodPost, "/api/auth/github/poll", `{"flowId":"flow"}`)
+ handler.poll(current)
+ if recorder.Code != http.StatusConflict || len(handler.grants) != 0 {
+ t.Fatalf("stale replica grant accepted: %d %s", recorder.Code, recorder.Body)
+ }
+}
+
+func TestGitHubDeviceFlowRejectsInvalidRequests(t *testing.T) {
+ for _, scenario := range []string{"anonymous", "origin", "disabled", "expired", "denied", "expiring", "upstream"} {
+ t.Run(scenario, func(t *testing.T) {
+ handler, userID := githubTestHandler(t)
+ handler.grants[userID] = &githubGrant{id: "flow", code: "code", clientID: "test-client", expires: time.Now().Add(time.Minute), interval: 5 * time.Second}
+ handler.client.Transport = githubTestTransport(func(*http.Request) (*http.Response, error) {
+ if scenario == "upstream" {
+ return &http.Response{StatusCode: 502, Body: io.NopCloser(strings.NewReader("private upstream detail"))}, nil
+ }
+ if scenario == "expiring" {
+ return githubTestResponse(`{"access_token":"temporary-token","expires_in":28800,"login":"account"}`), nil
+ }
+ return githubTestResponse(`{"error":"access_denied"}`), nil
+ })
+ actor := userID
+ if scenario == "anonymous" {
+ actor = 0
+ }
+ current, recorder := githubTestContext(actor, http.MethodPost, "/api/auth/github/poll", `{"flowId":"flow"}`)
+ if scenario == "origin" {
+ current.Request.Header.Set("Origin", "https://other.test")
+ }
+ if scenario == "expired" {
+ handler.grants[userID].expires = time.Now().Add(-time.Second)
+ }
+ if scenario == "disabled" {
+ t.Setenv("AGENTFLOW_GITHUB_CLIENT_ID", "")
+ handler.start(current)
+ } else {
+ handler.poll(current)
+ }
+ if recorder.Code < 400 || strings.Contains(recorder.Body.String(), "private upstream detail") {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ user, _ := handler.repo.User(userID)
+ if user.GitToken != "" {
+ t.Fatal("invalid flow overwrote credentials")
+ }
+ })
+ }
+}
+
+func TestGitHubRepositoryPickerUsesCurrentUsersTokenAndPages(t *testing.T) {
+ handler, userID := githubTestHandler(t)
+ _, err := handler.repo.UpdateUserCredentials(userID, repo.UserCredentialUpdate{GitToken: "oauth2:owner-only-token"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ handler.client.Transport = githubTestTransport(func(request *http.Request) (*http.Response, error) {
+ if request.Header.Get("Authorization") != "Bearer owner-only-token" || request.URL.Query().Get("page") != "2" || request.URL.Query().Get("affiliation") != "owner,collaborator,organization_member" {
+ t.Fatalf("repository request=%s", request.URL)
+ }
+ return githubTestResponse(`[{"full_name":"team/private-repository","html_url":"https://github.com/team/private-repository","default_branch":"develop","private":true}]`), nil
+ })
+ current, recorder := githubTestContext(userID, http.MethodGet, "/api/auth/github/repositories?page=2", "")
+ handler.repositories(current)
+ if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), `"default_branch":"develop"`) || strings.Contains(recorder.Body.String(), "owner-only-token") {
+ t.Fatalf("repositories=%d %s", recorder.Code, recorder.Body.String())
+ }
+ current, recorder = githubTestContext(userID, http.MethodGet, "/api/auth/github/repositories?page=bad", "")
+ handler.repositories(current)
+ if recorder.Code != http.StatusBadRequest {
+ t.Fatal("invalid page accepted")
+ }
+}
diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go
index 268a5520..0cc8f2e7 100644
--- a/internal/httpapi/server.go
+++ b/internal/httpapi/server.go
@@ -66,7 +66,8 @@ func (d deps) getAuthClient() *auth.Client {
// 对所有领域可见;需要跨领域协作的领域(issues → tasks/stream)显式注入。
type Server struct {
*deps
- auth *authHandlers // auth.go
+ auth *authHandlers // auth.go
+ github *githubHandlers
users *usersHandlers // users.go
projects *projectsHandlers
insights *insightsHandlers
@@ -145,6 +146,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv
deps: d,
notifications: &notificationHandlers{deps: d, service: notifications},
auth: &authHandlers{deps: d},
+ github: newGitHubHandlers(d),
users: &usersHandlers{deps: d},
catalog: &catalogHandlers{deps: d},
businessDomains: &businessDomainsHandlers{deps: d},
@@ -237,6 +239,11 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv
g.GET("/api/auth/gongfeng", api.auth.gongfengOAuthStatus)
g.GET("/api/auth/gongfeng/start", api.auth.gongfengOAuthStart)
g.GET("/api/auth/gongfeng/callback", api.auth.gongfengOAuthCallback)
+ g.GET("/api/auth/github", api.github.status)
+ g.PUT("/api/auth/github/config", api.github.configure)
+ g.POST("/api/auth/github/device", api.github.start)
+ g.POST("/api/auth/github/poll", api.github.poll)
+ g.GET("/api/auth/github/repositories", api.github.repositories)
g.GET("/api/auth/exchange", api.auth.authExchange)
g.POST("/api/auth/exchange", api.auth.authExchange)
g.POST("/api/auth/logout", api.auth.authLogout)
diff --git a/internal/preview/repository.go b/internal/preview/repository.go
new file mode 100644
index 00000000..26742ddd
--- /dev/null
+++ b/internal/preview/repository.go
@@ -0,0 +1,41 @@
+package preview
+
+import (
+ "time"
+
+ "agentflow/internal/domain"
+)
+
+// Repository is the persistence the preview service needs; *repo.Store
+// satisfies it. Depending on an interface keeps the database layer (gorm and
+// the SQLite driver) out of agentflow-runner, which only uses ArchiveDir and
+// is cross-compiled for every execution-machine platform.
+type Repository interface {
+ BlobRepository
+ PutPreview(p domain.RunPreview) error
+ ClaimPreviewArchive(id string, now, until time.Time) (domain.RunPreview, bool, error)
+ MarkPreviewReadyIfArchiving(p domain.RunPreview) (bool, error)
+ FailPreviewIfOpen(id, errText string, now time.Time) (bool, error)
+ Preview(id string) (domain.RunPreview, bool)
+ PreviewByRun(runID string) (domain.RunPreview, bool)
+ PreviewsByStatus(status string) []domain.RunPreview
+ ExpiredReadyPreviews(now time.Time) []domain.RunPreview
+ MarkPreviewAccessed(id string, now time.Time) error
+ UpdatePreviewBackendURL(id, backendURL string) error
+ SetRunWorkspaceCleanupHold(runID string, until time.Time) error
+ ClearRunWorkspaceCleanupHold(runID string) error
+ PutPreviewSession(s domain.PreviewSession) error
+ PreviewSessionByTokenHash(hash string) (domain.PreviewSession, bool)
+ RevokePreviewSession(id string, now time.Time) error
+ TouchPreviewSession(id string, expiresAt, accessedAt time.Time) error
+ DeletePreview(id string) error
+ CountReadyStorageKey(key string) (int64, error)
+ Run(id string) (domain.Run, bool)
+}
+
+// BlobRepository stores content-addressed preview bundles.
+type BlobRepository interface {
+ PutPreviewBlob(sha256Hex string, content []byte) error
+ PreviewBlob(sha256Hex string) ([]byte, int64, bool)
+ DeletePreviewBlob(sha256Hex string) error
+}
diff --git a/internal/preview/service.go b/internal/preview/service.go
index 4d453c18..a25088f2 100644
--- a/internal/preview/service.go
+++ b/internal/preview/service.go
@@ -16,7 +16,6 @@ import (
"time"
"agentflow/internal/domain"
- "agentflow/internal/repo"
)
// Host is the engine-facing callback surface. The preview package never
@@ -33,7 +32,7 @@ type Host interface {
}
type Service struct {
- repo *repo.Store
+ repo Repository
store Store
cfg Config
host Host
@@ -44,7 +43,7 @@ type Service struct {
routed map[string]bool
}
-func NewService(st *repo.Store, store Store, cfg Config) *Service {
+func NewService(st Repository, store Store, cfg Config) *Service {
if store == nil {
store = NewDBStore(st)
}
@@ -105,7 +104,7 @@ func (s *Service) beginFinalization(run domain.Run, fromBuild bool) bool {
}
now := s.clock()
preview := domain.RunPreview{
- ID: repo.NewPreviewID(run.ID),
+ ID: domain.PreviewID(run.ID),
RunID: run.ID,
ProjectID: run.WorkflowSnapshot.ProjectID,
Kind: contract.KindOrStatic(),
@@ -435,7 +434,7 @@ func (s *Service) Skip(run domain.Run, reason string) {
reason = "工作区没有前端工程,已跳过预览"
}
preview := domain.RunPreview{
- ID: repo.NewPreviewID(run.ID),
+ ID: domain.PreviewID(run.ID),
RunID: run.ID,
ProjectID: run.WorkflowSnapshot.ProjectID,
Kind: contract.KindOrStatic(),
@@ -492,7 +491,7 @@ func (s *Service) Fail(preview domain.RunPreview, err error) {
func (s *Service) failNew(run domain.Run, contract *domain.PreviewContract, err error) {
preview := domain.RunPreview{
- ID: repo.NewPreviewID(run.ID), RunID: run.ID, ProjectID: run.WorkflowSnapshot.ProjectID,
+ ID: domain.PreviewID(run.ID), RunID: run.ID, ProjectID: run.WorkflowSnapshot.ProjectID,
Kind: contract.KindOrStatic(), Status: domain.PreviewFailed, SourcePath: contract.SourcePath,
EntryFile: contract.Index(), ErrorText: clipPreviewError(err.Error()),
CreatedAt: s.clock(), UpdatedAt: s.clock(),
diff --git a/internal/preview/store_db.go b/internal/preview/store_db.go
index f2cd60d2..062a5589 100644
--- a/internal/preview/store_db.go
+++ b/internal/preview/store_db.go
@@ -9,17 +9,15 @@ import (
"fmt"
"io"
"strings"
-
- "agentflow/internal/repo"
)
// DBStore keeps tar.zst blobs in MySQL (sqlite in tests). Serving reads the
// blob back out and extracts the requested member in memory; no shared disk.
type DBStore struct {
- repo *repo.Store
+ repo BlobRepository
}
-func NewDBStore(st *repo.Store) *DBStore {
+func NewDBStore(st BlobRepository) *DBStore {
return &DBStore{repo: st}
}
diff --git a/internal/repo/auth_integration.go b/internal/repo/auth_integration.go
new file mode 100644
index 00000000..795a4cf3
--- /dev/null
+++ b/internal/repo/auth_integration.go
@@ -0,0 +1,26 @@
+package repo
+
+import "gorm.io/gorm/clause"
+
+type authIntegrationRow struct {
+ Provider string `gorm:"primaryKey;size:32"`
+ ClientID string `gorm:"size:80"`
+}
+
+func (authIntegrationRow) TableName() string { return "auth_integrations" }
+
+func (r *UsersRepo) GitHubClientID(fallback string) (string, error) {
+ var config authIntegrationRow
+ result := r.DB.Where("provider = ?", "github").Limit(1).Find(&config)
+ if result.Error == nil && result.RowsAffected == 0 {
+ return fallback, nil
+ }
+ return config.ClientID, result.Error
+}
+
+func (r *UsersRepo) SetGitHubClientID(clientID string) error {
+ return r.DB.Clauses(clause.OnConflict{
+ Columns: []clause.Column{{Name: "provider"}},
+ DoUpdates: clause.AssignmentColumns([]string{"client_id"}),
+ }).Create(&authIntegrationRow{Provider: "github", ClientID: clientID}).Error
+}
diff --git a/internal/repo/models.go b/internal/repo/models.go
index 441793a1..9ee035c5 100644
--- a/internal/repo/models.go
+++ b/internal/repo/models.go
@@ -675,7 +675,7 @@ func (knowledgeSubmissionRow) TableName() string { return "knowledge_submissions
// allModels lists every table for the sqlite test schema (AutoMigrate).
func allModels() []any {
return []any{domain.BotUserBinding{}, domain.BotBindingChallenge{}, domain.BotConnection{}, domain.BotConversation{}, domain.BotInteraction{}, notificationBotRow{}, botCredentialRow{}, domain.NotificationDelivery{},
- userRow{}, localAccountRow{}, userConfigRow{}, apiTokenRow{}, genericTemplateRow{},
+ userRow{}, localAccountRow{}, userConfigRow{}, authIntegrationRow{}, apiTokenRow{}, genericTemplateRow{},
insightSourceRow{}, insightExecutionRow{},
projectRow{}, projectMemberRow{}, repositoryRow{}, businessDomainRow{}, businessDomainAssignmentRow{},
agentRow{}, ruleRow{}, skillRow{}, skillFileRow{}, mcpServerRow{}, mcpFileRow{}, executorRow{},
diff --git a/internal/repo/previews.go b/internal/repo/previews.go
index 41502d2f..5fc87f2f 100644
--- a/internal/repo/previews.go
+++ b/internal/repo/previews.go
@@ -309,11 +309,7 @@ func (r *PreviewsRepo) DeletePreview(id string) error {
}
func NewPreviewID(runID string) string {
- runID = strings.TrimSpace(runID)
- if runID == "" {
- return "preview"
- }
- return "preview-" + runID
+ return domain.PreviewID(runID)
}
func (r *PreviewsRepo) CountReadyStorageKey(key string) (int64, error) {
diff --git a/internal/runtime/isolated_image_test.go b/internal/runtime/isolated_image_test.go
new file mode 100644
index 00000000..33fa8115
--- /dev/null
+++ b/internal/runtime/isolated_image_test.go
@@ -0,0 +1,56 @@
+package runtime
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "agentflow/internal/domain"
+)
+
+func TestIsolatedRuntimeImageReusesInstalledImage(t *testing.T) {
+ t.Setenv("AGENTFLOW_ISOLATED_IMAGE", "loopforge-platform:tested")
+ workspace := t.TempDir()
+ logfile := filepath.Join(t.TempDir(), "docker.log")
+ bin := t.TempDir()
+ script := `#!/bin/sh
+printf '%s\n' "$*" >> "$DOCKER_TEST_LOG"
+case "$*" in
+ "image inspect loopforge-platform:tested") exit 0 ;;
+ "inspect "*) exit 1 ;;
+ "exec "*) echo /workspace ;;
+ "build "*) exit 99 ;;
+esac
+`
+ if err := os.WriteFile(filepath.Join(bin, "docker"), []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
+ t.Setenv("DOCKER_TEST_LOG", logfile)
+ definition := domain.DockerfileDefinition{Content: IsolatedDockerfile}
+ if !DockerImageCached(context.Background(), definition) {
+ t.Fatal("installed runtime image is incorrectly reported as requiring a build")
+ }
+ image, err := ensureDockerImage(context.Background(), workspace, definition)
+ if err != nil || image != "loopforge-platform:tested" {
+ t.Fatalf("runtime image: %q %v", image, err)
+ }
+ sandbox := &dockerSandbox{id: "reuse-test", name: "agentflow-reuse-test", workspace: workspace, dockerfile: definition}
+ if err := sandbox.ensureStarted(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ commands, err := os.ReadFile(logfile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(commands), "build ") || !strings.Contains(string(commands), "--entrypoint sh loopforge-platform:tested -lc") {
+ t.Fatalf("unexpected sandbox commands: %s", commands)
+ }
+ for _, custom := range []domain.DockerfileDefinition{{Content: "FROM custom\n"}, {Content: IsolatedDockerfile, Files: map[string]string{"custom.txt": "keep"}}} {
+ if isolatedRuntimeImage(custom) != "" {
+ t.Fatal("custom environment replaced by platform runtime")
+ }
+ }
+}
diff --git a/internal/runtime/sandbox_docker.go b/internal/runtime/sandbox_docker.go
index 40f758e0..52809601 100644
--- a/internal/runtime/sandbox_docker.go
+++ b/internal/runtime/sandbox_docker.go
@@ -479,6 +479,9 @@ func DockerImageCached(ctx context.Context, dockerfile domain.DockerfileDefiniti
if strings.TrimSpace(dockerfile.Content) == "" {
return false
}
+ if image := isolatedRuntimeImage(dockerfile); image != "" {
+ return dockerImageExists(ctx, image)
+ }
return dockerImageExists(ctx, cachedDockerImageName(dockerfile))
}
@@ -629,7 +632,11 @@ func (s *dockerSandbox) ensureStarted(ctx context.Context) error {
if p.ReadOnlyRootFS {
args = append(args, "--read-only", "--tmpfs", "/tmp:rw,noexec,nosuid,size=256m")
}
- args = append(args, image, "sh", "-lc", "trap : TERM INT; sleep infinity & wait")
+ if image == isolatedRuntimeImage(s.dockerfile) {
+ args = append(args, "--entrypoint", "sh", image, "-lc", "trap : TERM INT; sleep infinity & wait")
+ } else {
+ args = append(args, image, "sh", "-lc", "trap : TERM INT; sleep infinity & wait")
+ }
if out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput(); err != nil {
dropEphemeralDockerImage(s.builtImage)
s.builtImage = ""
@@ -715,6 +722,12 @@ func prepareDockerfileBuildContext(workspace string, dockerfile domain.Dockerfil
}
func ensureDockerImage(ctx context.Context, workspace string, dockerfile domain.DockerfileDefinition) (string, error) {
+ if image := isolatedRuntimeImage(dockerfile); image != "" {
+ if !dockerImageExists(ctx, image) {
+ return "", fmt.Errorf("isolated runtime image %q is not available in the sandbox Docker daemon", image)
+ }
+ return image, nil
+ }
image := cachedDockerImageName(dockerfile)
if dockerImageExists(ctx, image) {
return image, nil
@@ -730,6 +743,13 @@ func ensureDockerImage(ctx context.Context, workspace string, dockerfile domain.
return image, nil
}
+func isolatedRuntimeImage(dockerfile domain.DockerfileDefinition) string {
+ if dockerfile.Content != IsolatedDockerfile || len(dockerfile.Files) != 0 {
+ return ""
+ }
+ return strings.TrimSpace(os.Getenv("AGENTFLOW_ISOLATED_IMAGE"))
+}
+
// IsolatedDockerfile matches the public "generic-backend" environment so both
// share one cached image.
const IsolatedDockerfile = "FROM node:22-bookworm\nRUN apt-get update && apt-get install -y --no-install-recommends git python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\nRUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\nWORKDIR /workspace\n"
diff --git a/migrations/022_auth_integrations.sql b/migrations/022_auth_integrations.sql
new file mode 100644
index 00000000..bc7520a7
--- /dev/null
+++ b/migrations/022_auth_integrations.sql
@@ -0,0 +1,4 @@
+CREATE TABLE IF NOT EXISTS auth_integrations (
+ provider VARCHAR(32) NOT NULL PRIMARY KEY,
+ client_id VARCHAR(80) NOT NULL
+);
diff --git a/scripts/build-binaries.sh b/scripts/build-binaries.sh
index 457ef106..2d25b5aa 100644
--- a/scripts/build-binaries.sh
+++ b/scripts/build-binaries.sh
@@ -1,28 +1,70 @@
#!/usr/bin/env bash
# Build helpers with the same toolchain as the server. Installed agents and
# execution machines must not depend on a different Go found on service PATH.
+# build-binaries.sh [--helpers|--platform] [output-dir]
+# --helpers builds everything that does not embed the web UI, so Docker can
+# compile it while the chatbot bundle is still building; --platform builds the
+# server, which embeds web/native-chat. Without a flag both are built.
set -euo pipefail
cd "$(dirname "$0")/.."
+mode=all
+case "${1:-}" in
+ --helpers|--platform) mode="${1#--}"; shift ;;
+esac
output="${1:-$PWD/.local/bin}"
mkdir -p "$output"
output="$(cd "$output" && pwd)"
-# The platform binary embeds web/native-chat; Docker builds it in its own stage.
-if [[ ! -f web/native-chat/index.html ]]; then
+if [[ $mode != helpers && ! -f web/native-chat/index.html ]]; then
npm --prefix chatbot ci --include=dev --no-audit --no-fund
npm --prefix chatbot run build
fi
+
+# One compile job per CPU, but at most one per GiB of memory so small hosts do
+# not run out of memory (a cold build peaks near 1.3 GiB total with 4 jobs).
+# LOOPFORGE_BUILD_JOBS overrides the estimate.
+build_jobs() {
+ local cpus memory_kib limit
+ cpus=$(nproc 2>/dev/null || echo 2)
+ memory_kib=$(awk '/^MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null || true)
+ limit=$(cat /sys/fs/cgroup/memory.max /sys/fs/cgroup/memory/memory.limit_in_bytes 2>/dev/null | head -1 || true)
+ if [[ $limit =~ ^[0-9]+$ ]] && { [[ -z $memory_kib ]] || (( limit / 1024 < memory_kib )); }; then
+ memory_kib=$((limit / 1024))
+ fi
+ local by_memory=$(( ${memory_kib:-2097152} / 1048576 ))
+ local jobs=$(( cpus < by_memory ? cpus : by_memory ))
+ echo $(( jobs < 1 ? 1 : jobs ))
+}
+jobs="${LOOPFORGE_BUILD_JOBS:-$(build_jobs)}"
+[[ $jobs =~ ^[1-9][0-9]*$ ]] || { echo "LOOPFORGE_BUILD_JOBS must be a positive integer" >&2; exit 1; }
export CGO_ENABLED=0
-export GOMAXPROCS="${GOMAXPROCS:-2}"
-for command in agentflow agentflow-mcp loopforge-account; do
- go build -p=2 -o "$output/$command.next" "./cmd/$command"
- mv "$output/$command.next" "$output/$command"
-done
-for target_os in linux darwin; do
- for target_arch in amd64 arm64; do
- for command in agentflow-runner agentflow-gate-mcp; do
- target="$output/$command-$target_os-$target_arch"
- GOOS="$target_os" GOARCH="$target_arch" go build -p=2 -o "$target.next" "./cmd/$command"
- mv "$target.next" "$target"
+flags=(-p="$jobs" -trimpath -ldflags=-s\ -w)
+
+# build TARGET_SUFFIX PACKAGE... builds every package in one go invocation so
+# shared dependencies compile and the links run in parallel.
+build() {
+ local suffix="$1"; shift
+ local staging
+ staging="$(mktemp -d "$output/.build.XXXXXX")"
+ go build "${flags[@]}" -o "$staging/" "$@" || { rm -rf "$staging"; return 1; }
+ local package
+ for package in "$@"; do
+ mv "$staging/${package##*/}" "$output/${package##*/}$suffix"
+ done
+ rmdir "$staging"
+}
+
+printf 'Building with %s parallel jobs\n' "$jobs"
+if [[ $mode != platform ]]; then
+ printf '\nBuilding agentflow-mcp and loopforge-account for the platform…\n'
+ build '' ./cmd/agentflow-mcp ./cmd/loopforge-account
+ for target_os in linux darwin; do
+ for target_arch in amd64 arm64; do
+ printf '\nBuilding agentflow-runner and agentflow-gate-mcp (%s/%s)…\n' "$target_os" "$target_arch"
+ GOOS="$target_os" GOARCH="$target_arch" build "-$target_os-$target_arch" ./cmd/agentflow-runner ./cmd/agentflow-gate-mcp
done
done
-done
+fi
+if [[ $mode != helpers ]]; then
+ printf '\nBuilding agentflow for the platform…\n'
+ build '' ./cmd/agentflow
+fi
diff --git a/scripts/configure.sh b/scripts/configure.sh
index 3e0f7dba..165dbcda 100755
--- a/scripts/configure.sh
+++ b/scripts/configure.sh
@@ -2,21 +2,21 @@
set -euo pipefail
cd "$(dirname "$0")/.."
python3 - <<'PY'
-import os,secrets,pathlib
+import os,secrets,pathlib,shlex
p=pathlib.Path('.env')
data_dir=os.path.abspath(os.environ.get('LOOPFORGE_DATA_DIR','.data'))
if p.exists():
text=p.read_text()
if 'LOOPFORGE_DATA_DIR=' not in text:
- with p.open('a') as f: f.write(f'LOOPFORGE_DATA_DIR="{data_dir}"\n')
+ with p.open('a') as f: f.write(f'\nLOOPFORGE_DATA_DIR={shlex.quote(data_dir)}\n')
print('Added LOOPFORGE_DATA_DIR to existing .env')
else:
print('Keeping existing .env')
else:
password=secrets.token_hex(24)
http_port=os.environ.get('AGENTFLOW_HTTP_PORT','8090');mysql_port=os.environ.get('LOOPFORGE_MYSQL_PORT','33315')
- data={'LOOPFORGE_DB_PASSWORD':password,'LOOPFORGE_DB_ROOT_PASSWORD':secrets.token_hex(24),'LOOPFORGE_MYSQL_PORT':mysql_port,'COMPOSE_PROJECT_NAME':os.environ.get('COMPOSE_PROJECT_NAME','loopforge'),'AGENTFLOW_HTTP_PORT':http_port,'AGENTFLOW_MYSQL_DSN':f'loopforge:{password}@tcp(127.0.0.1:{mysql_port})/loopforge','AGENTFLOW_SESSION_SECRET':secrets.token_hex(32),'AGENTFLOW_AUTH_REQUIRED':'true','LOOPFORGE_DATA_DIR':data_dir}
+ data={'LOOPFORGE_DB_PASSWORD':password,'LOOPFORGE_DB_ROOT_PASSWORD':secrets.token_hex(24),'LOOPFORGE_MYSQL_PORT':mysql_port,'COMPOSE_PROJECT_NAME':os.environ.get('COMPOSE_PROJECT_NAME','loopforge'),'AGENTFLOW_HTTP_PORT':http_port,'AGENTFLOW_MYSQL_DSN':f'loopforge:{password}@tcp(127.0.0.1:{mysql_port})/loopforge','AGENTFLOW_SESSION_SECRET':secrets.token_hex(32),'AGENTFLOW_AUTH_REQUIRED':'true','LOOPFORGE_DATA_DIR':data_dir,'LOOPFORGE_BIND':os.environ.get('LOOPFORGE_BIND','0.0.0.0'),'LOOPFORGE_PUBLIC_URL':os.environ.get('LOOPFORGE_PUBLIC_URL',''),'LOOPFORGE_IMAGE':os.environ.get('LOOPFORGE_IMAGE',''),'AGENTFLOW_GITHUB_CLIENT_ID':os.environ.get('AGENTFLOW_GITHUB_CLIENT_ID','')}
fd=os.open(str(p),os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600)
- with os.fdopen(fd,'w') as f: f.write(''.join(f'{k}="{v}"\n' for k,v in data.items()))
+ with os.fdopen(fd,'w') as f: f.write(''.join(f'{k}={shlex.quote(v)}\n' for k,v in data.items()))
print('Created .env with unique local secrets')
PY
diff --git a/scripts/docker-access.sh b/scripts/docker-access.sh
new file mode 100644
index 00000000..34863ab4
--- /dev/null
+++ b/scripts/docker-access.sh
@@ -0,0 +1,44 @@
+#!/usr/bin/env bash
+
+docker_access() {
+ if [[ "${LOOPFORGE_DOCKER_USE_SUDO:-0}" == 1 ]]; then
+ require_sudo
+ command sudo -n docker "$@"
+ else
+ command docker "$@"
+ fi
+}
+
+docker_access_fail() {
+ printf '\n✗ %s\n' "$1" >&2
+ exit 1
+}
+
+require_sudo() {
+ command -v sudo >/dev/null || docker_access_fail 'Administrator access is required for Docker. Install sudo or ask an administrator to grant Docker access.'
+ if ! sudo -n true 2>/dev/null; then
+ [[ -t 0 ]] || docker_access_fail 'Docker requires sudo. Run sudo -v in a terminal first, then rerun the installer; or configure rootless Docker.'
+ sudo -v || docker_access_fail 'Could not obtain administrator access for Docker.'
+ fi
+}
+
+as_root() {
+ if [[ $(id -u) -eq 0 ]]; then
+ "$@"
+ else
+ require_sudo
+ sudo -n "$@"
+ fi
+}
+
+select_docker_access() {
+ docker_access info >/dev/null 2>&1 && return 0
+ if [[ $(uname -s) == Linux && $(id -u) -ne 0 ]]; then
+ require_sudo
+ if sudo -n docker info >/dev/null 2>&1; then
+ export LOOPFORGE_DOCKER_USE_SUDO=1
+ return 0
+ fi
+ fi
+ return 1
+}
diff --git a/scripts/install-address.py b/scripts/install-address.py
new file mode 100644
index 00000000..0262c59c
--- /dev/null
+++ b/scripts/install-address.py
@@ -0,0 +1,103 @@
+import ipaddress
+import os
+import socket
+import sys
+import shlex
+from pathlib import Path
+from urllib.parse import urlsplit
+
+
+def container_host():
+ if Path('/.dockerenv').exists() or Path('/run/.containerenv').exists():
+ return True
+ try:
+ return any(marker in Path('/proc/1/cgroup').read_text() for marker in ('/docker/', '/kubepods/', '/lxc/'))
+ except OSError:
+ return False
+
+
+def access_addresses(port, environ=os.environ):
+ bind = environ.get('LOOPFORGE_BIND', '0.0.0.0')
+ public = environ.get('LOOPFORGE_PUBLIC_URL', '').rstrip('/')
+ if public:
+ parsed = urlsplit(public)
+ if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('', '/'):
+ raise ValueError('LOOPFORGE_PUBLIC_URL must be an HTTP(S) URL without credentials, query or fragment')
+ parsed.port
+ try:
+ address = ipaddress.ip_address(parsed.hostname)
+ except ValueError:
+ address = None
+ if parsed.hostname in ('0.0.0.0', '::') or address and (address.is_unspecified or address.is_link_local):
+ raise ValueError('Use a reachable server IP/domain, not a listening or link-local address')
+ if (parsed.hostname == 'localhost' or address and address.is_loopback) and bind not in ('127.0.0.1', 'localhost', '::1'):
+ raise ValueError('Team access cannot use localhost/127.0.0.1; enter the server IP/domain users visit')
+ if bind in ('127.0.0.1', 'localhost', '::1'):
+ return [public], 'Loopback binding: the public URL requires a reverse proxy on this server.'
+ return [public], 'Allow the service port in the cloud security group/firewall, or route it through your HTTPS reverse proxy.'
+ if bind in ('127.0.0.1', 'localhost', '::1'):
+ host = f'[{bind}]' if ':' in bind else bind
+ return [f'http://{host}:{port}'], 'Local access only. Set LOOPFORGE_BIND=0.0.0.0 and LOOPFORGE_PUBLIC_URL in .env for team access.'
+ if container_host():
+ return [], 'Installation is inside a container. Its IP/port are not the host access address. Set LOOPFORGE_PUBLIC_URL to the host IP/domain and published port.'
+ if bind not in ('0.0.0.0', '::', '[::]'):
+ hosts = [bind.strip('[]')]
+ else:
+ hosts = []
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe:
+ probe.connect(('192.0.2.1', 80))
+ hosts.append(probe.getsockname()[0])
+ except OSError:
+ pass
+ try:
+ hosts.extend(socket.gethostbyname_ex(socket.gethostname())[2])
+ except OSError:
+ pass
+ hosts = list(dict.fromkeys(host for host in hosts if not ipaddress.ip_address(host).is_loopback and not ipaddress.ip_address(host).is_unspecified and not ipaddress.ip_address(host).is_link_local))
+ addresses = [f'http://[{host}]:{port}' if ':' in host else f'http://{host}:{port}' for host in hosts]
+ return addresses, 'Cloud NAT public addresses cannot be inferred reliably. Set LOOPFORGE_PUBLIC_URL to your public IP/domain and allow the service port in the security group/firewall.'
+
+
+def prepare_address(port, environ=os.environ):
+ addresses, note = access_addresses(port, environ)
+ public = environ.get('LOOPFORGE_PUBLIC_URL', '').rstrip('/')
+ local = environ.get('LOOPFORGE_BIND') in ('127.0.0.1', 'localhost', '::1')
+ if not public and not local:
+ if sys.stdin.isatty() and environ.get('LOOPFORGE_YES') != '1':
+ suggestion = addresses[0] if addresses else ''
+ print('\nTeam access: use the IP/domain and port that teammates actually visit.')
+ print('For cloud NAT, use the public IP/domain from your cloud console. For containers, use the host published port.')
+ public = input(f'Team URL [{suggestion}]: ').strip() or suggestion
+ elif addresses:
+ # The first address is the one carrying the default route.
+ public = addresses[0]
+ if not public:
+ raise ValueError('No host access URL can be inferred safely. Set LOOPFORGE_PUBLIC_URL=http://SERVER_IP:PUBLISHED_PORT and rerun; no images have been built. '+note)
+ access_addresses(port, dict(environ, LOOPFORGE_PUBLIC_URL=public))
+ if public:
+ config = Path('.env')
+ lines = config.read_text().splitlines()
+ replacement = 'LOOPFORGE_PUBLIC_URL='+shlex.quote(public)
+ updated = [replacement if line.startswith('LOOPFORGE_PUBLIC_URL=') else line for line in lines]
+ if not any(line.startswith('LOOPFORGE_PUBLIC_URL=') for line in lines):
+ updated.append(replacement)
+ if updated != lines:
+ with config.open('w') as handle:
+ handle.write('\n'.join(updated)+'\n')
+
+
+if __name__ == '__main__':
+ if sys.argv[1] == '--prepare':
+ try:
+ prepare_address(sys.argv[2])
+ except (ValueError, EOFError) as error:
+ sys.exit(str(error))
+ sys.exit(0)
+ addresses, note = access_addresses(sys.argv[1])
+ print('\n✓ LoopForge is running')
+ for address in addresses:
+ print(f' {"Access" if os.environ.get("LOOPFORGE_PUBLIC_URL") else "Server address (may be LAN-only)"}: {address}')
+ if not addresses:
+ print(' Set LOOPFORGE_PUBLIC_URL in .env to your reachable server IP/domain.')
+ print(f' {note}')
diff --git a/scripts/install-observability-schema.sh b/scripts/install-observability-schema.sh
index 374e338e..d26400ae 100755
--- a/scripts/install-observability-schema.sh
+++ b/scripts/install-observability-schema.sh
@@ -3,9 +3,10 @@
# Apply each absent generated-column definition from the upstream migration.
set -euo pipefail
cd "$(dirname "$0")/.."
+source scripts/docker-access.sh
mysql_query() {
- docker compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" exec mysql --batch --skip-column-names -u loopforge loopforge'
+ docker_access compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" exec mysql --batch --skip-column-names -u loopforge loopforge'
}
for entry in 'run_telemetry adapter' 'run_logs level'; do
diff --git a/scripts/install.sh b/scripts/install.sh
index 1d80ab1c..a2628909 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -7,6 +7,7 @@ cd "$(dirname "$0")/.."
fail() { printf '\n✗ %s\n' "$1" >&2; exit 1; }
step() { printf '\n▸ %s\n' "$1"; }
+source scripts/docker-access.sh
confirm() {
[[ "${LOOPFORGE_YES:-}" == 1 ]] && return 0
@@ -14,7 +15,6 @@ confirm() {
read -r -p "$1 [Y/n] " answer
[[ -z "$answer" || "$answer" =~ ^[Yy] ]]
}
-as_root() { if [[ $(id -u) -eq 0 ]]; then "$@"; else sudo "$@"; fi; }
install_docker() {
case "$(uname -s)" in
@@ -22,7 +22,10 @@ install_docker() {
confirm 'Docker is not installed. Install it now with the official script (get.docker.com)?' \
|| fail 'Docker is required. Install it from https://docs.docker.com/engine/install/ or rerun with LOOPFORGE_YES=1.'
command -v curl >/dev/null || fail 'curl is required to install Docker.'
- curl -fsSL https://get.docker.com | as_root sh
+ installer=$(mktemp)
+ curl --connect-timeout 10 --max-time 120 -fsSL https://get.docker.com -o "$installer" || { rm -f "$installer"; fail 'Could not download the Docker installer.'; }
+ as_root sh "$installer"
+ rm -f "$installer"
as_root systemctl enable --now docker 2>/dev/null || as_root service docker start
;;
Darwin)
@@ -36,58 +39,88 @@ install_docker() {
}
wait_for_docker() {
- for _ in $(seq 1 60); do docker info >/dev/null 2>&1 && return 0; sleep 2; done
+ for _ in $(seq 1 30); do select_docker_access && return 0; sleep 2; done
return 1
}
step 'Checking prerequisites'
+if ! command -v python3 >/dev/null; then
+ if command -v apt-get >/dev/null && confirm 'Python 3 is required. Install it now?'; then
+ as_root apt-get update
+ as_root apt-get install -y python3
+ else
+ fail 'Install Python 3, then rerun this script. No deployment has been started.'
+ fi
+fi
command -v docker >/dev/null || install_docker
-if ! docker info >/dev/null 2>&1; then
+if ! select_docker_access; then
case "$(uname -s)" in
Linux) as_root systemctl start docker 2>/dev/null || as_root service docker start 2>/dev/null || true ;;
Darwin) open -a Docker 2>/dev/null || true ;;
esac
wait_for_docker || fail 'Docker is installed but not running, or this user cannot access it (try: sudo usermod -aG docker "$USER", then log in again).'
fi
-docker compose version >/dev/null 2>&1 || fail 'Docker Compose v2 is required (the "docker compose" command).'
-command -v python3 >/dev/null || fail 'Python 3 is required to generate local secrets.'
+docker_access compose version >/dev/null 2>&1 || fail 'Docker Compose v2 is required (the "docker compose" command).'
+requested_public_url="${LOOPFORGE_PUBLIC_URL:-}"
+[[ ! -e .env || -r .env ]] || fail 'The existing .env is not readable by this user. Use the installation owner or ask an administrator to correct its ownership.'
bash scripts/configure.sh
+[[ -r .env ]] || fail 'The existing .env is not readable by this user. Use the installation owner or ask an administrator to correct its ownership.'
+set -a; source .env; set +a
+export LOOPFORGE_BIND="${LOOPFORGE_BIND:-127.0.0.1}"
+if [[ -n "$requested_public_url" ]]; then export LOOPFORGE_PUBLIC_URL="$requested_public_url"; fi
+python3 scripts/install-address.py --prepare "${AGENTFLOW_HTTP_PORT:-8090}"
set -a; source .env; set +a
-mkdir -p "$LOOPFORGE_DATA_DIR/home" "$LOOPFORGE_DATA_DIR/workspaces"
+if [[ -z "${LOOPFORGE_DOCKER_SOCKET:-}" ]]; then
+ docker_host="${DOCKER_HOST:-$(docker_access context inspect --format '{{(index .Endpoints "docker").Host}}' 2>/dev/null || true)}"
+ case "$docker_host" in
+ unix://*) export LOOPFORGE_DOCKER_SOCKET="${docker_host#unix://}" ;;
+ '') export LOOPFORGE_DOCKER_SOCKET=/var/run/docker.sock ;;
+ *) fail 'This installer requires a local Docker socket for sandbox bind mounts. Select a local/rootless Docker context or configure remote workers manually.' ;;
+ esac
+ python3 - <<'PY'
+import os,pathlib,shlex
+with pathlib.Path('.env').open('a') as config:
+ config.write('\nLOOPFORGE_DOCKER_SOCKET='+shlex.quote(os.environ['LOOPFORGE_DOCKER_SOCKET'])+'\n')
+PY
+fi
+python3 - <<'PY'
+import runpy
+runpy.run_path('scripts/install-address.py')['access_addresses']('8090')
+PY
+mkdir -p "$LOOPFORGE_DATA_DIR/home" "$LOOPFORGE_DATA_DIR/workspaces" || fail 'The data directory is not writable. Set LOOPFORGE_DATA_DIR in .env to a directory owned by this user.'
port="${AGENTFLOW_HTTP_PORT:-8090}"
-if ! docker compose ps --status running --services 2>/dev/null | grep -qx platform; then
+if ! docker_access compose ps --status running --services 2>/dev/null | grep -qx platform; then
if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then
fail "Port $port is already in use. Set AGENTFLOW_HTTP_PORT in .env to a free port and run again."
fi
fi
-step 'Building and starting LoopForge (the first build takes a few minutes)'
-docker compose --profile platform up -d --build --wait
-# The schema exists once the API listens; seeds must not run before that.
-python3 - "$port" <<'PY' || fail 'LoopForge did not become ready. Inspect: docker compose logs platform'
-import sys,time,urllib.request
-for _ in range(120):
- try:
- urllib.request.urlopen(f'http://127.0.0.1:{sys.argv[1]}/api/health',timeout=2); sys.exit(0)
- except Exception: time.sleep(1)
-sys.exit(1)
-PY
-
+if [[ -n "${LOOPFORGE_IMAGE:-}" ]]; then
+ step 'Pulling the prebuilt LoopForge image'
+ docker_access compose --profile platform pull --policy "${LOOPFORGE_PULL_POLICY:-missing}" platform mysql
+ docker_access compose --profile platform up -d --no-build --wait --wait-timeout 180
+else
+ step 'Building LoopForge from source (first install takes several minutes; frontend, Go and runtime stages build in parallel)'
+ # Download MySQL while the platform image builds instead of afterwards.
+ docker_access compose pull --quiet --policy missing mysql >/dev/null 2>&1 &
+ mysql_pull=$!
+ docker_access compose --profile platform build platform
+ wait "$mysql_pull" || true
+ step 'Starting LoopForge'
+ docker_access compose --profile platform up -d --no-build --wait --wait-timeout 180
+fi
step 'Installing the schema extensions and the starter catalog'
bash scripts/install-observability-schema.sh
-for seed in migrations/seed/*.sql; do
- docker compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" mysql -u loopforge loopforge' < "$seed"
-done
+cat migrations/seed/*.sql | docker_access compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" mysql -u loopforge loopforge'
-host="${LOOPFORGE_BIND:-127.0.0.1}"
-[[ "$host" == 0.0.0.0 ]] && host=localhost
-printf '\n✓ LoopForge is running at http://%s:%s\n' "$host" "$port"
-users=$(docker compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" mysql -N -u loopforge loopforge -e "select count(*) from users"' 2>/dev/null || echo 0)
+python3 scripts/install-address.py "$port"
+users=$(docker_access compose exec -T mysql sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" mysql -N -u loopforge loopforge -e "select count(*) from users"' 2>/dev/null || echo 0)
if [[ "${users//[^0-9]/}" == 0 ]]; then
printf ' Open it in your browser and create the administrator account.\n'
else
printf ' Open it in your browser and sign in.\n'
fi
-printf ' AI SOPs run in Docker sandboxes; the sandbox image is building in the background (a few minutes on first install).\n'
+printf ' Open “一键体验” on the home page to run a real SOP without an API key.\n'
+printf ' Default sandboxes reuse the installed runtime image; no second CLI image build is needed.\n'
printf ' Stop: docker compose --profile platform stop · Logs: docker compose logs -f platform\n'
diff --git a/scripts/test-container.sh b/scripts/test-container.sh
index 90e22fd5..c3a3e6bc 100755
--- a/scripts/test-container.sh
+++ b/scripts/test-container.sh
@@ -57,7 +57,7 @@ LOOPFORGE_FRESH_INSTALL=1 npx --prefix e2e playwright test --config e2e/public/p
"${COMPOSE[@]}" exec -T platform test -s /app/LICENSE
"${COMPOSE[@]}" exec -T platform test -s /app/THIRD_PARTY_NOTICES.md
"${COMPOSE[@]}" exec -T platform test -s /app/third_party/go/THIRD_PARTY_NOTICES.txt
-"${COMPOSE[@]}" exec -T platform sh -c 'codebuddy --version && codex --version && claude --version'
+bash scripts/test-runtime-image.sh "$("${COMPOSE[@]}" images -q platform)"
for task_os in linux darwin; do
for task_arch in amd64 arm64; do
"${COMPOSE[@]}" exec -T platform test -x "/app/bin/agentflow-runner-$task_os-$task_arch"
diff --git a/scripts/test-install-live.sh b/scripts/test-install-live.sh
new file mode 100644
index 00000000..06a75347
--- /dev/null
+++ b/scripts/test-install-live.sh
@@ -0,0 +1,73 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+root="$PWD"
+image="${LOOPFORGE_INSTALL_TEST_IMAGE:?Set LOOPFORGE_INSTALL_TEST_IMAGE to the locally built platform image}"
+task_dir=$(mktemp -d /tmp/loopforge-install-live.XXXXXX)
+chmod 755 "$task_dir"
+docker_socket="${LOOPFORGE_DOCKER_SOCKET:-/var/run/docker.sock}"
+cleanup() {
+ for fixture in "$task_dir"/*; do
+ [[ -f "$fixture/.env" ]] || continue
+ docker compose -f "$root/compose.yaml" --env-file "$fixture/.env" --profile platform down --volumes --remove-orphans >/dev/null 2>&1 || true
+ done
+ rm -rf "$task_dir"
+}
+trap cleanup EXIT
+
+actors=(root nonroot)
+[[ -z "${LOOPFORGE_INSTALL_SUDO_TEST_IMAGE:-}" ]] || actors+=(sudo)
+for actor in "${actors[@]}"; do
+ fixture="$task_dir/$actor"
+ mkdir -p "$fixture/scripts" "$fixture/migrations/seed" "$fixture/user-home"
+ cp scripts/{install.sh,configure.sh,docker-access.sh,install-address.py,install-observability-schema.sh} "$fixture/scripts/"
+ cp migrations/001_run_obs_generated_columns.sql "$fixture/migrations/"
+ cp migrations/seed/*.sql "$fixture/migrations/seed/"
+ cp compose.yaml "$fixture/"
+ read -r http_port mysql_port < <(python3 - <<'PY'
+import socket
+with socket.socket() as http, socket.socket() as mysql:
+ http.bind(('0.0.0.0',0)); mysql.bind(('127.0.0.1',0))
+ print(http.getsockname()[1],mysql.getsockname()[1])
+PY
+)
+ prefix=()
+ if [[ "$actor" == nonroot ]]; then
+ [[ $(id -u) == 0 ]] || { echo 'Non-root live check requires root to change only the fixture ownership and drop privileges.' >&2; exit 1; }
+ chown -R 65534:65534 "$fixture"
+ prefix=(setpriv --reuid=65534 --regid="$(stat -c %g "$docker_socket")" --clear-groups)
+ elif [[ "$actor" == sudo ]]; then
+ chown -R 1000:1000 "$fixture"
+ prefix=(docker run --rm --network host --user 1000:1000 -v "$fixture:$fixture" -v "$docker_socket:$docker_socket" -v "${LOOPFORGE_TEST_COMPOSE_PLUGIN:-/usr/libexec/docker/cli-plugins/docker-compose}:/usr/local/lib/docker/cli-plugins/docker-compose:ro" -w "$fixture" --entrypoint /usr/bin/env "$LOOPFORGE_INSTALL_SUDO_TEST_IMAGE")
+ "${prefix[@]}" bash -c 'if docker info >/dev/null 2>&1; then exit 1; fi; sudo -n docker info >/dev/null'
+ fi
+ started=$SECONDS
+ for attempt in first repeat; do
+ "${prefix[@]}" env HOME="$fixture/user-home" PATH=/usr/local/bin:/usr/bin:/bin COMPOSE_PROJECT_NAME="lf-install-${actor}-$$" LOOPFORGE_IMAGE="$image" LOOPFORGE_DATA_DIR="$fixture/data" LOOPFORGE_BIND=0.0.0.0 LOOPFORGE_PUBLIC_URL="http://192.0.2.10:$http_port" LOOPFORGE_DOCKER_SOCKET="$docker_socket" AGENTFLOW_HTTP_PORT="$http_port" LOOPFORGE_MYSQL_PORT="$mysql_port" bash "$fixture/scripts/install.sh" > "$fixture/$attempt.log" 2>&1 || { cat "$fixture/$attempt.log"; exit 1; }
+ grep -q "Access: http://192.0.2.10:$http_port" "$fixture/$attempt.log"
+ curl -fsS "http://127.0.0.1:$http_port/api/health" >/dev/null
+ if [[ "$attempt" == first ]]; then
+ cp "$fixture/.env" "$fixture/initial.env"
+ else
+ cmp "$fixture/initial.env" "$fixture/.env"
+ fi
+ done
+ docker compose -f "$fixture/compose.yaml" --env-file "$fixture/.env" --profile platform port platform 8080 | grep -q "0.0.0.0:$http_port"
+ python3 - "$http_port" <<'PY'
+import json,secrets,socket,sys,urllib.request
+base='http://127.0.0.1:'+sys.argv[1]
+setup=json.load(urllib.request.urlopen(base+'/api/auth/setup'))
+assert setup['needsSetup'],setup
+assert urllib.request.urlopen(base+'/app/github-connect.js').status==200
+with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as probe:
+ probe.connect(('192.0.2.1',80))
+ address=probe.getsockname()[0]
+direct=urllib.request.build_opener(urllib.request.ProxyHandler({}))
+assert direct.open('http://'+address+':'+sys.argv[1]+'/api/health').status==200
+request=urllib.request.Request(base+'/api/auth/register',data=json.dumps({'login':'install-test-admin','password':secrets.token_urlsafe(24)}).encode(),headers={'Content-Type':'application/json','Origin':base})
+result=json.load(urllib.request.urlopen(request))
+assert result['admin'],result
+print('Verified non-loopback HTTP access, first-account creation and GitHub connection UI')
+PY
+ printf '%s install + repeat: %ss (UID %s)\n' "$actor" "$((SECONDS-started))" "$("${prefix[@]}" id -u)"
+done
diff --git a/scripts/test-install.py b/scripts/test-install.py
new file mode 100644
index 00000000..1d41b854
--- /dev/null
+++ b/scripts/test-install.py
@@ -0,0 +1,214 @@
+import importlib.util
+import os
+import pty
+import select
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import time
+import unittest
+from unittest.mock import patch
+
+
+ROOT = Path(__file__).resolve().parents[1]
+spec = importlib.util.spec_from_file_location('install_address', ROOT / 'scripts/install-address.py')
+address = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(address)
+
+
+class InstallerTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ (self.root / 'scripts').mkdir()
+ (self.root / 'migrations/seed').mkdir(parents=True)
+ for name in ('install.sh', 'configure.sh', 'docker-access.sh', 'install-address.py', 'install-observability-schema.sh'):
+ shutil.copyfile(ROOT / 'scripts' / name, self.root / 'scripts' / name)
+ (self.root / 'migrations/seed/001_test.sql').write_text('SELECT 1;\n')
+ (self.root / 'mock').mkdir()
+ self.executable('docker', '''#!/usr/bin/env bash
+printf '%s %s\\n' "${MOCK_PRIVILEGED:-0}" "$*" >> "$MOCK_LOG"
+if [[ "$1" == info ]]; then
+ [[ "${MOCK_USER:-0}" == 0 || "${MOCK_PRIVILEGED:-0}" == 1 || "${MOCK_DIRECT:-0}" == 1 ]]
+ exit
+fi
+if [[ "$*" == *'ps --status running'* ]]; then echo platform; fi
+if [[ "${MOCK_EXPIRE_AFTER_BUILD:-0}" == 1 && "$*" == *'build platform'* ]]; then touch "$MOCK_SUDO_EXPIRED_FILE"; fi
+if [[ "$*" == *'exec -T mysql'* ]]; then
+ if [[ "$*" == *'count(*) from users'* ]]; then echo 0; exit 0; fi
+ query=$(cat)
+ if [[ "$query" == *'information_schema.columns'* ]]; then echo 1; fi
+ if [[ "$*" == *'count(*) from users'* ]]; then echo 0; fi
+fi
+''')
+ self.executable('id', '#!/usr/bin/env bash\nif [[ "$1" == -u ]]; then echo "${MOCK_USER:-0}"; else /usr/bin/id "$@"; fi\n')
+ self.executable('sudo', '''#!/usr/bin/env bash
+[[ "${MOCK_SUDO_DENIED:-0}" != 1 ]] || exit 1
+[[ -z "${MOCK_SUDO_EXPIRED_FILE:-}" || ! -e "$MOCK_SUDO_EXPIRED_FILE" ]] || exit 1
+[[ "$1" == -n ]] && shift
+export MOCK_PRIVILEGED=1
+exec "$@"
+''')
+ self.environ = dict(os.environ, PATH=str(self.root / 'mock') + ':' + os.environ['PATH'], MOCK_LOG=str(self.root / 'docker.log'), AGENTFLOW_HTTP_PORT='18765', LOOPFORGE_PUBLIC_URL='https://team.example.test', LOOPFORGE_BIND='0.0.0.0')
+ for name in ('LOOPFORGE_DOCKER_USE_SUDO', 'LOOPFORGE_DATA_DIR', 'LOOPFORGE_IMAGE', 'MOCK_USER', 'MOCK_DIRECT', 'MOCK_SUDO_DENIED'):
+ self.environ.pop(name, None)
+
+ def executable(self, name, contents):
+ target = self.root / 'mock' / name
+ target.write_text(contents)
+ target.chmod(0o755)
+
+ def install(self, **values):
+ return subprocess.run(['bash', 'scripts/install.sh'], cwd=self.root, env=dict(self.environ, **values), text=True, capture_output=True, stdin=subprocess.DEVNULL, timeout=15)
+
+ def assert_success(self, result):
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn('https://team.example.test', result.stdout)
+ self.assertNotIn('running at http://127.0.0.1', result.stdout)
+
+ def test_root_install_and_repeat_preserve_secrets(self):
+ self.assert_success(self.install())
+ secrets = (self.root / '.env').read_text()
+ self.assert_success(self.install())
+ self.assertEqual((self.root / '.env').read_text(), secrets)
+ self.assertEqual((self.root / '.env').stat().st_mode & 0o777, 0o600)
+
+ def test_non_root_without_docker_group_uses_sudo_everywhere(self):
+ self.assert_success(self.install(MOCK_USER='1000'))
+ lines = (self.root / 'docker.log').read_text().splitlines()
+ operations = [line for line in lines if 'compose' in line]
+ self.assertTrue(operations)
+ self.assertTrue(all(line.startswith('1 ') for line in operations), operations)
+ self.assertTrue(any('exec -T mysql' in line for line in operations))
+
+ def test_non_root_with_direct_access_never_uses_sudo(self):
+ self.assert_success(self.install(MOCK_USER='1000', MOCK_DIRECT='1', MOCK_SUDO_DENIED='1'))
+ self.assertNotIn('1 compose', (self.root / 'docker.log').read_text())
+
+ def test_noninteractive_without_sudo_fails_immediately(self):
+ result = self.install(MOCK_USER='1000', MOCK_SUDO_DENIED='1')
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn('sudo -v', result.stderr)
+ self.assertFalse((self.root / '.env').exists())
+
+ def test_expired_sudo_after_build_has_actionable_error(self):
+ result = self.install(MOCK_USER='1000', MOCK_EXPIRE_AFTER_BUILD='1', MOCK_SUDO_EXPIRED_FILE=str(self.root / 'sudo-expired'))
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn('sudo -v', result.stderr)
+ self.assertNotIn('up -d --no-build', (self.root / 'docker.log').read_text())
+
+ def test_prebuilt_image_skips_build(self):
+ self.assert_success(self.install(LOOPFORGE_IMAGE='registry.example.test/loopforge:tested'))
+ log = (self.root / 'docker.log').read_text()
+ self.assertIn('pull --policy missing platform mysql', log)
+ self.assertNotIn('build platform', log)
+ self.assertIn('--no-build --wait --wait-timeout 180', log)
+
+ def test_invalid_public_url_fails_before_build(self):
+ result = self.install(LOOPFORGE_PUBLIC_URL='javascript:alert(1)')
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn('build platform', (self.root / 'docker.log').read_text())
+
+ def test_invalid_public_port_fails_before_build(self):
+ result = self.install(LOOPFORGE_PUBLIC_URL='https://team.example.test:invalid')
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn('build platform', (self.root / 'docker.log').read_text())
+
+ def test_public_url_with_unsupported_subpath_fails_before_build(self):
+ result = self.install(LOOPFORGE_PUBLIC_URL='https://team.example.test/loopforge')
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn('build platform', (self.root / 'docker.log').read_text())
+
+ def test_configuration_quotes_paths_without_shell_execution(self):
+ data = str(self.root / 'spaces $(touch should-not-exist)')
+ self.assert_success(self.install(LOOPFORGE_DATA_DIR=data))
+ self.assertTrue(Path(data, 'home').is_dir())
+ self.assertFalse((self.root / 'should-not-exist').exists())
+
+ def test_interactive_install_persists_team_url(self):
+ master, slave = pty.openpty()
+ process = subprocess.Popen(['bash', 'scripts/install.sh'], cwd=self.root,
+ env=dict(self.environ, LOOPFORGE_PUBLIC_URL='', LOOPFORGE_YES='', MOCK_USER='1000', MOCK_DIRECT='1'),
+ stdin=slave, stdout=slave, stderr=slave)
+ os.close(slave)
+ output, answered = b'', False
+ try:
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline:
+ readable, _, _ = select.select([master], [], [], 0.2)
+ if readable:
+ try:
+ chunk = os.read(master, 65536)
+ except OSError:
+ break
+ if not chunk:
+ break
+ output += chunk
+ if b'Team URL [' in output and not answered:
+ os.write(master, b'https://team.example.test\n')
+ answered = True
+ elif process.poll() is not None:
+ break
+ process.wait(timeout=2)
+ self.assertEqual(process.returncode, 0, output.decode())
+ self.assertTrue(answered)
+ self.assertIn(b'Access: https://team.example.test', output)
+ self.assertIn('LOOPFORGE_PUBLIC_URL=https://team.example.test', (self.root / '.env').read_text())
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait()
+ os.close(master)
+
+ def test_existing_empty_url_can_be_set_without_rotating_secrets(self):
+ self.assert_success(self.install())
+ config = self.root / '.env'
+ original = config.read_text()
+ config.write_text(original.replace('https://team.example.test', "''"))
+ self.assert_success(self.install())
+ self.assertEqual(config.read_text(), original)
+
+ def test_team_url_rejects_loopback_and_listening_addresses(self):
+ for url in ('http://127.0.0.1:8090', 'http://localhost:8090', 'http://0.0.0.0:8090', 'http://[::]:8090', 'http://169.254.1.2:8090'):
+ with self.subTest(url=url):
+ result = self.install(LOOPFORGE_PUBLIC_URL=url)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn('build platform', (self.root / 'docker.log').read_text())
+
+ def test_unknown_container_url_fails_before_build(self):
+ result = self.install(LOOPFORGE_PUBLIC_URL='', LOOPFORGE_YES='1')
+ if address.container_host():
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn('LOOPFORGE_PUBLIC_URL', result.stderr)
+ self.assertNotIn('build platform', (self.root / 'docker.log').read_text())
+
+
+class AddressTests(unittest.TestCase):
+ def test_public_url_and_loopback_proxy(self):
+ urls, note = address.access_addresses('8090', {'LOOPFORGE_BIND': '127.0.0.1', 'LOOPFORGE_PUBLIC_URL': 'https://team.example.test/'})
+ self.assertEqual(urls, ['https://team.example.test'])
+ self.assertIn('reverse proxy', note)
+
+ def test_ipv6_and_local_mode(self):
+ self.assertEqual(address.access_addresses('8090', {'LOOPFORGE_BIND': '2001:db8::1'})[0], ['http://[2001:db8::1]:8090'])
+ urls, note = address.access_addresses('8090', {'LOOPFORGE_BIND': '127.0.0.1'})
+ self.assertEqual(urls, ['http://127.0.0.1:8090'])
+ self.assertIn('Local access only', note)
+
+ def test_cloud_address_is_not_claimed_to_be_public(self):
+ with patch.object(address, 'container_host', return_value=False), patch.object(address.socket, 'socket', side_effect=OSError), patch.object(address.socket, 'gethostbyname_ex', return_value=('host', [], ['127.0.0.1', '192.168.1.2'])):
+ urls, note = address.access_addresses('8090', {})
+ self.assertEqual(urls, ['http://192.168.1.2:8090'])
+ self.assertIn('NAT', note)
+
+ def test_container_does_not_publish_its_bridge_address(self):
+ with patch.object(address, 'container_host', return_value=True):
+ urls, note = address.access_addresses('8090', {})
+ self.assertEqual(urls, [])
+ self.assertIn('published port', note)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/test-runtime-image.sh b/scripts/test-runtime-image.sh
new file mode 100755
index 00000000..7d82fbe5
--- /dev/null
+++ b/scripts/test-runtime-image.sh
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+set -euo pipefail
+image="${1:?Usage: bash scripts/test-runtime-image.sh IMAGE}"
+docker run --rm -i --network none --read-only --tmpfs /tmp:rw,exec,nosuid,size=128m --entrypoint sh "$image" -eu <<'CHECK'
+export HOME=/tmp/home
+mkdir -p "$HOME"
+cd /tmp
+for command in node npm git bash curl python3 rg gcc g++ make pkg-config ssh unzip; do
+ command -v "$command" >/dev/null || { printf 'Missing sandbox tool: %s\n' "$command" >&2; exit 1; }
+done
+printf 'int main(void) { return 0; }\n' > check.c
+printf 'int main() { return 0; }\n' > check.cpp
+gcc check.c -o check-c
+g++ check.cpp -o check-cpp
+./check-c
+./check-cpp
+printf 'check:\n\t./check-c\n\t./check-cpp\n' > Makefile
+make check
+node -e 'if (2 + 2 !== 4) process.exit(1)'
+python3 -c 'assert 2 + 2 == 4'
+git --version
+ssh -V
+unzip -v >/dev/null
+codex --version
+claude --version
+codebuddy --version
+printf 'Runtime image compatibility checks passed.\n'
+CHECK
diff --git a/scripts/testdata/install-sudo.Dockerfile b/scripts/testdata/install-sudo.Dockerfile
new file mode 100644
index 00000000..ca057bfa
--- /dev/null
+++ b/scripts/testdata/install-sudo.Dockerfile
@@ -0,0 +1,8 @@
+ARG LOOPFORGE_TEST_BASE=loopforge-platform:local
+FROM ${LOOPFORGE_TEST_BASE}
+RUN apt-get update && apt-get install -y --no-install-recommends sudo \
+ && rm -rf /var/lib/apt/lists/* \
+ && printf 'node ALL=(root) NOPASSWD: /usr/bin/true, /usr/local/bin/docker\n' > /etc/sudoers.d/installer \
+ && chmod 440 /etc/sudoers.d/installer
+ENTRYPOINT []
+USER node
diff --git a/third_party/go/THIRD_PARTY_NOTICES.txt b/third_party/go/THIRD_PARTY_NOTICES.txt
index 64e1d269..cbb1b626 100644
--- a/third_party/go/THIRD_PARTY_NOTICES.txt
+++ b/third_party/go/THIRD_PARTY_NOTICES.txt
@@ -3033,7 +3033,7 @@ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
==============================================================================
-github.com/klauspost/compress v1.20.2
+github.com/klauspost/compress v1.20.3
--- LICENSE ---
Copyright (c) 2012 The Go Authors. All rights reserved.
diff --git a/web/app.js b/web/app.js
index 9183dc91..4eab91ae 100644
--- a/web/app.js
+++ b/web/app.js
@@ -1540,6 +1540,12 @@ function mountNativeChat(){
else reloadShellProjects().then(follow).catch(()=>{});
}
if(message.type==='agentflow-projects-changed')reloadShellProjects().catch(()=>{});
+ if(message.type==='agentflow-welcome-demo'&&!frame.dataset.demoBusy){
+ frame.dataset.demoBusy='true';
+ api('/api/runs',{method:'POST',body:JSON.stringify({workflowId:'welcome-workflow',projectId:'welcome',input:'首次体验:运行脚本、审批并交付产物'})}).then(run=>{
+ location.hash='#/runs/'+encodeURIComponent(run.id);
+ }).catch(error=>toast(error.message)).finally(()=>{delete frame.dataset.demoBusy});
+ }
if(message.type==='agentflow-quick-access-completed'){
api('/api/bootstrap',{silent:true}).then(shell=>{
Object.assign(state.data,shell);
diff --git a/web/app/access.js b/web/app/access.js
index 7dbef5b9..97ea2131 100644
--- a/web/app/access.js
+++ b/web/app/access.js
@@ -170,7 +170,7 @@ function renderGuideSetupBody(body,user,isGuest){
const allReady=credReady&&projReady&&sopReady;
const credDone=[modelReady,gfReady].filter(Boolean).length;
const badge=ready=>`<span class="setup-status ${ready?'ready':'missing'}">${ready?'✓ 已就绪':'未完成'}</span>`;
- const subItem=(name,label,ready,applyUrl,hint)=>`<div class="setup-sub ${ready?'is-ready':''}"><div class="setup-sub-info"><b>${label}</b>${hint?`<small>${hint}</small>`:''}</div>${ready?'':`<a class="setup-mini" href="${applyUrl}" target="_blank" rel="noopener noreferrer">申请 ↗</a>`}<button type="button" class="setup-mini" data-setup-cred="${name}">${ready?'查看':'去填写'} →</button></div>`;
+ const subItem=(name,label,ready,applyUrl,hint)=>`<div class="setup-sub ${ready?'is-ready':''}"><div class="setup-sub-info"><b>${label}</b>${hint?`<small>${hint}</small>`:''}</div>${ready?'':`<a class="setup-mini" href="${applyUrl}" target="_blank" rel="noopener noreferrer">${name==='gitToken'?'授权':'申请'} ↗</a>`}<button type="button" class="setup-mini" data-setup-cred="${name}">${ready?'查看':name==='gitToken'?'去连接':'去填写'} →</button></div>`;
// 第 1 步:三张个人凭据一次性配齐
const credCard=`<div class="setup-card ${credReady?'is-ready':''}"><div class="setup-card-head"><b>① 配个人凭据</b><small>个人配置 · 一次配齐</small>${badge(credReady)}</div>
<p>${lfT('在<b>个人配置</b>中配置 CodeBuddy API Key 与 GitHub Token,或绑定本机 CLI。Main Bot 和内置 SOP 默认都使用 CodeBuddy。','Configure your CodeBuddy API key and GitHub token in <b>Settings</b>, or connect a local CLI. Main Bot and the built-in SOPs use CodeBuddy by default.')}</p>
@@ -178,7 +178,7 @@ function renderGuideSetupBody(body,user,isGuest){
${subItem('codeBuddyApiKey','CodeBuddy API Key',cbOwn,'https://www.codebuddy.ai/',cbShared?'未配置时对话和 SOP 都用平台共享模型 Deepseek-V4.1-Flash;配置后可使用其他模型':'Agent 调模型执行任务')}
${subItem('codexApiKey','Codex API Key',!!stored.codexApiKeyConfigured,'https://platform.openai.com/api-keys','公共 SOP 默认执行器')}
${subItem('claudeCodeApiKey','Claude Code API Key',!!stored.claudeCodeApiKeyConfigured,'https://console.anthropic.com/','可按角色选择的执行器')}
- ${subItem('gitToken','GitHub Git Token',gfReady,'https://github.com/settings/tokens','目标仓库需要 Contents 和 Pull requests 读写权限')}
+ ${subItem('gitToken','GitHub Git Token',gfReady,'/#/settings','用 GitHub 设备码授权后选择仓库,也支持手动配置 PAT')}
</div>
<button type="button" class="button primary small" data-setup-cred="gitToken" style="margin-top:12px">打开个人配置 →</button></div>`;
// 第 2 步:加入已有项目或新建项目
diff --git a/web/app/github-connect.js b/web/app/github-connect.js
new file mode 100644
index 00000000..20d4bedf
--- /dev/null
+++ b/web/app/github-connect.js
@@ -0,0 +1,118 @@
+function githubConnectHTML(){
+ return '<div class="github-connect" data-github-connect><p class="github-connect-intro">在 GitHub 确认授权后,即可选择你的仓库。无需复制令牌。</p><button type="button" class="credential-btn primary" data-github-start disabled>连接 GitHub</button><div class="github-connect-status" role="status" aria-live="polite" data-github-status>正在检查授权服务…</div></div>';
+}
+
+async function hydrateGitHubConnections(root=document){
+ const hosts=[...(root.matches?.('[data-github-connect]')?[root]:[]),...root.querySelectorAll('[data-github-connect]')];
+ if(!hosts.length)return;
+ try{
+ const capability=await api('/api/auth/github',{silent:true});
+ for(const host of hosts){
+ if(!host.isConnected||host.dataset.busy==='true')continue;
+ host.dataset.enabled=String(!!capability.enabled);
+ const button=host.querySelector('[data-github-start]'),status=host.querySelector('[data-github-status]');
+ button.hidden=!capability.enabled;button.disabled=!capability.enabled;
+ button.textContent='连接 GitHub';
+ status.textContent=capability.enabled?'授权仅用于当前账号,可随时撤销。':'此实例已停用 GitHub 授权,可使用「访问令牌」连接仓库。';
+ }
+ }catch(error){
+ for(const host of hosts){host.querySelector('[data-github-status]').textContent='暂时无法检查授权服务,请稍后重试。';const button=host.querySelector('[data-github-start]');button.hidden=false;button.disabled=false;button.textContent='重新检查';host.dataset.enabled='false'}
+ }
+}
+
+async function startGitHubConnect(host){
+ if(host.dataset.busy==='true')return;
+ if(host.dataset.enabled!=='true'){await hydrateGitHubConnections(host);return}
+ const button=host.querySelector('[data-github-start]'),status=host.querySelector('[data-github-status]');
+ const actor=Number(state.currentUser?.id);
+ host.dataset.busy='true';button.disabled=true;
+ let timer,flow,deadline,active=true;
+ const finish=()=>{active=false;clearTimeout(timer);host.dataset.busy='false';button.disabled=false};
+ const fail=error=>{status.textContent=error.message;finish()};
+ const poll=async()=>{
+ if(!active)return;
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor){finish();return}
+ if(Date.now()>=deadline){fail(new Error('授权已过期,请重新连接'));return}
+ try{
+ const result=await api('/api/auth/github/poll',{method:'POST',body:JSON.stringify({flowId:flow.flowId})});
+ if(!active)return;
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor){finish();return}
+ if(result.status==='connected'){
+ if(typeof storeCredentialUser==='function')storeCredentialUser(result.user);
+ if(typeof notifyCredentialsChanged==='function')notifyCredentialsChanged();
+ state.gitTokenVerify=null;
+ status.textContent=`已连接 GitHub · ${result.login}`;
+ finish();
+ host.dispatchEvent(new CustomEvent('github-connected',{bubbles:true}));
+ if(typeof credentialWizard!=='undefined'&&credentialWizard?.kind==='gitToken')closeCredentialWizard(true);
+ if(document.querySelector('#credentialPanel')&&typeof renderCredentialPanel==='function')renderCredentialPanel();
+ toast(`GitHub 授权已保存 · ${result.login}`,'ok');
+ return;
+ }
+ timer=setTimeout(poll,Math.max(5,result.interval||5)*1000);
+ }catch(error){fail(error)}
+ };
+ try{
+ status.textContent='正在获取 GitHub 授权码…';
+ flow=await api('/api/auth/github/device',{method:'POST',body:'{}'});
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor){finish();return}
+ deadline=Date.now()+flow.expiresIn*1000;
+ status.replaceChildren();
+ const instruction=document.createElement('p');instruction.textContent='复制授权码,然后在 GitHub 确认:';
+ const code=document.createElement('strong');code.className='github-device-code';code.textContent=flow.userCode;instruction.append(code);
+ const copy=document.createElement('button');copy.type='button';copy.className='button ghost small';copy.textContent='复制授权码';
+ copy.onclick=async()=>{try{await navigator.clipboard.writeText(flow.userCode);copy.textContent='已复制'}catch{copy.textContent='请选中授权码复制'}};
+ const link=document.createElement('a');link.href='https://github.com/login/device';link.target='_blank';link.rel='noopener noreferrer';link.className='button primary small';link.textContent='复制并前往 GitHub 授权';link.onclick=()=>{navigator.clipboard?.writeText(flow.userCode).then(()=>{copy.textContent='已复制'},()=>{})};
+ const cancel=document.createElement('button');cancel.type='button';cancel.className='button ghost small';cancel.textContent='取消';cancel.onclick=()=>{finish();status.replaceChildren()};
+ status.append(instruction,copy,link,cancel);
+ timer=setTimeout(poll,Math.max(5,flow.interval)*1000);
+ }catch(error){fail(error)}
+}
+
+function mountGitHubRepoPicker(host,onSelect){
+ if(!host)return;
+ const connected=!!userById(state.currentUser?.id)?.gitTokenConfigured;
+ host.innerHTML=(connected?'':githubConnectHTML())+`<button type="button" class="button ghost small" data-github-load${connected?'':' hidden'}>选择我的 GitHub 仓库</button><p data-github-repo-hint${connected?' hidden':''}>连接后可选择自己的仓库;公开仓库也可直接填写地址。访问令牌可在个人配置中设置。</p><div data-github-repo-list></div>`;
+ hydrateGitHubConnections(host);
+ const load=host.querySelector('[data-github-load]'),list=host.querySelector('[data-github-repo-list]');
+ let repositories=[],page=1,busy=false;
+ const paint=hasMore=>{
+ list.innerHTML='<label class="pa-field"><span>搜索已加载的仓库</span><input class="pa-input" type="search" data-github-search placeholder="仓库名 / 组织名"></label><label class="pa-field"><span>选择仓库</span><select class="pa-input" data-github-repo aria-label="我的 GitHub 仓库"><option value="">请选择仓库</option></select></label><p data-github-repo-empty hidden>未找到仓库,可手动填写地址;组织仓库可能需要管理员批准授权。</p>'+(hasMore?'<button type="button" class="button ghost small" data-github-more>加载更多仓库</button>':'');
+ const select=list.querySelector('[data-github-repo]'),search=list.querySelector('[data-github-search]'),empty=list.querySelector('[data-github-repo-empty]');
+ const filter=()=>{
+ select.replaceChildren(new Option('请选择仓库',''));
+ const visible=repositories.filter(repo=>repo.full_name.toLowerCase().includes(search.value.toLowerCase()));
+ for(const repository of visible){const option=document.createElement('option');option.value=repository.full_name;option.textContent=repository.full_name+(repository.private?' · 私有':'');select.append(option)}
+ empty.hidden=visible.length>0;
+ };
+ search.oninput=filter;
+ select.onchange=()=>{const repository=repositories.find(repo=>repo.full_name===select.value);if(repository)onSelect(repository)};
+ const more=list.querySelector('[data-github-more]');if(more)more.onclick=()=>fetchPage(page+1);
+ filter();
+ };
+ const fetchPage=async requested=>{
+ if(busy)return;
+ busy=true;load.disabled=true;
+ const actor=Number(state.currentUser?.id);
+ const more=list.querySelector('[data-github-more]');if(more)more.disabled=true;
+ try{
+ const result=await api('/api/auth/github/repositories?page='+requested);
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor)return;
+ page=requested;repositories=requested===1?result.repositories:repositories.concat(result.repositories);
+ paint(result.hasMore);
+ }catch(error){list.textContent=error.message}
+ finally{busy=false;load.disabled=false;if(more)more.disabled=false}
+ };
+ load.onclick=()=>fetchPage(1);
+ host.addEventListener('github-connected',()=>{
+ host.querySelector('[data-github-connect]')?.remove();
+ host.querySelector('[data-github-repo-hint]').hidden=true;
+ load.hidden=false;
+ fetchPage(1);
+ });
+}
+
+document.addEventListener('click',event=>{
+ const start=event.target.closest('[data-github-start]');
+ if(start)startGitHubConnect(start.closest('[data-github-connect]'));
+});
diff --git a/web/app/project-wizard.js b/web/app/project-wizard.js
index b08ff855..dede1342 100644
--- a/web/app/project-wizard.js
+++ b/web/app/project-wizard.js
@@ -254,6 +254,7 @@ function projectWizardReposHTML(w){
const project=projectWizardProject()||{},repos=projectWizardRepos();
const list=repos.map(r=>{const path=r.gongfengProjectId||'',name=r.name||path||r.id,shown=repoDisplayPath(parseGongfengRepoURL(r.webUrl||r.cloneUrl||path),path);return `<div class="pw-repo" data-pw-repo="${escapeHTML(r.id)}"><span class="pw-repo-ic">${pwIcon('repo',14,1.9)}</span><b title="${escapeHTML(name)}">${escapeHTML(name)}</b><code title="${escapeHTML(shown)}">${escapeHTML(shown)}</code><small>${escapeHTML(r.defaultBranch||'main')}</small>${r.integrateBranch?`<small title="集成分支">${escapeHTML(r.integrateBranch)}</small>`:''}${r.id===project.defaultRepositoryId?'<small class="is-def">默认</small>':''}<button type="button" class="pw-repo-rm" data-pw-repo-remove="${escapeHTML(r.id)}" title="移除" aria-label="移除仓库 ${escapeHTML(name)}">${pwIcon('x',14)}</button></div>`}).join('');
const body=(list?`<div class="pw-repo-list">${list}</div>`:'')
+ +'<div data-github-repositories></div>'
+pwField('GitHub 仓库地址',`<input class="pw-input pw-mono" id="pwRepoUrl" name="repoUrl" value="${escapeHTML(w.repo.url)}" placeholder="https://github.com/owner/repo" spellcheck="false" autocomplete="off">`,{for:'pwRepoUrl',hint:projectWizardRepoHint(w.repo.url),hintAttrs:' data-pw-repo-hint'})
+`<div class="pw-row2">${pwField('主分支',`<input class="pw-input pw-mono" id="pwRepoBranch" name="repoBranch" value="${escapeHTML(w.repo.branch)}" placeholder="main" spellcheck="false">`,{for:'pwRepoBranch'})}${pwField('集成分支',`<input class="pw-input pw-mono" id="pwRepoIntegrate" name="repoIntegrate" value="${escapeHTML(w.repo.integrate)}" placeholder="可选" spellcheck="false">`,{for:'pwRepoIntegrate'})}</div>`
+`<div><button type="button" class="pw-btn pw-btn-outline pw-btn-sm" data-pw-action="add-repo"${w.saving?' disabled':''}>+ 添加仓库</button></div>`;
@@ -338,6 +339,11 @@ function renderProjectWizard(){
}
document.body?.classList?.add('pw-open');
bindUserSearches(host);
+ if(w.step==='repos'&&typeof mountGitHubRepoPicker==='function')mountGitHubRepoPicker(host.querySelector('[data-github-repositories]'),repository=>{
+ w.repo.url=repository.html_url;w.repo.branch=repository.default_branch||'main';
+ const url=host.querySelector('[name="repoUrl"]'),branch=host.querySelector('[name="repoBranch"]');
+ url.value=w.repo.url;branch.value=w.repo.branch;syncProjectWizardField(url);
+ });
focusProjectWizard();
}
function focusProjectWizard(){
diff --git a/web/app/repo_drawer.js b/web/app/repo_drawer.js
index 2ad3aec1..158957c6 100644
--- a/web/app/repo_drawer.js
+++ b/web/app/repo_drawer.js
@@ -43,6 +43,11 @@ function openRepoDrawer(repoId=''){
const drawer=$('#repoDrawer');
drawer.inert=false;drawer.setAttribute('aria-hidden','false');
drawer.classList.add('open');$('#repoDrawerScrim').classList.add('open');
+ if(typeof mountGitHubRepoPicker==='function')mountGitHubRepoPicker(drawer.querySelector('[data-github-repositories]'),repository=>{
+ f.elements.repoUrl.value=repository.html_url;
+ f.elements.defaultBranch.value=repository.default_branch||'main';
+ syncRepoDrawerDetect();
+ });
setTimeout(()=>f.elements.repoUrl.focus(),120);
}
function closeRepoDrawer(opt){
diff --git a/web/app/workbench.js b/web/app/workbench.js
index 7b2d40d7..cdd8a1bf 100644
--- a/web/app/workbench.js
+++ b/web/app/workbench.js
@@ -33,7 +33,7 @@ const CREDENTIAL_GROUPS=[
{id:'model',name:'模型与执行',sub:'AI 对话与编码 CLI',icon:'sparkles'},
];
const CREDENTIAL_KINDS=[
- {key:'gitToken',group:'platform',name:'代码仓库',short:'GitHub Git Token',logo:'gongfeng',
+ {key:'gitToken',group:'platform',name:'GitHub',short:'仓库授权',logo:'github',monochrome:true,
use:'克隆私有仓库、创建任务分支、推送交付产物',
description:'用于克隆私有仓库、创建任务分支及推送交付产物。',
guide:[['打开 GitHub「Settings → Developer settings → Personal access tokens」','https://github.com/settings/tokens','前往 GitHub 申请个人访问令牌'],['新建令牌,为目标仓库授予 <code>Contents</code> 和 <code>Pull requests</code> 的读写权限'],['复制令牌粘贴到下方,保存前会自动校验权限']],
@@ -134,7 +134,7 @@ function credentialFieldHTML({label,note='',name,type='password',value='',placeh
return `<label class="credential-field"><span>${escapeHTML(label)}${note?`<em>${escapeHTML(note)}</em>`:''}</span><div class="credential-input${secret?'':' is-plain'}"><input${id?` id="${id}"`:''} name="${name}" type="${type}" ${secret?'autocomplete="new-password"':'autocomplete="off" spellcheck="false"'}${secret?'':` value="${escapeHTML(value)}"`} placeholder="${escapeHTML(placeholder)}">${secret?`<button type="button" class="credential-eye" data-credential-eye aria-label="显示">${credentialGlyph('eye',15)}</button>`:''}</div>${hint!==null?`<small data-credential-hint="${name}">${escapeHTML(hint)}</small>`:''}</label>`;
}
function credentialOAuthHTML(label,note){
- return `<div class="credential-oauth" data-gongfeng-oauth${state.gongfengOAuthEnabled?'':' hidden'}><a class="credential-btn secondary credential-ink" href="/api/auth/gongfeng/start" target="_blank" rel="noopener noreferrer">${credentialLogo(credentialKind('gitToken'),'is-mini')}<span>${label}</span></a><small>${note}</small></div>`;
+ return (typeof githubConnectHTML==='function'?githubConnectHTML():'')+`<div class="credential-oauth" data-gongfeng-oauth${state.gongfengOAuthEnabled?'':' hidden'}><a class="credential-btn secondary credential-ink" href="/api/auth/gongfeng/start" target="_blank" rel="noopener noreferrer">${credentialLogo(credentialKind('gitToken'),'is-mini')}<span>${label}</span></a><small>${note}</small></div>`;
}
function credentialPatWarningHTML(show){return `<div class="credential-note is-warn git-token-pat-warning"${show?'':' hidden'}>${credentialGlyph('alert',14)}<span>${CREDENTIAL_PAT_WARNING}</span></div>`}
const GIT_TOKEN_REPLACE_HINT='保存后替换当前的令牌,对下一次任务生效';
@@ -155,7 +155,7 @@ function gitTokenDetailHTML(kind,user){
:result.error?`<span class="is-err">${escapeHTML(result.error)}</span>${ago}`
:!result.valid?`<span class="is-err">令牌有效但缺少权限 ${escapeHTML(missing.join('、'))}</span>${ago}`
:`<span class="is-ok">令牌有效</span>${ago}`;
- return `<dl class="credential-kv" data-git-detail><dt>来源</dt><dd>${user.gitTokenOAuth?'工蜂授权 · 到期自动续期':'个人访问令牌'}</dd><dt>权限</dt><dd>${scopes||'<span class="is-muted">校验后显示</span>'}</dd><dt>最近校验</dt><dd>${checked}</dd><dt>用于</dt><dd>${escapeHTML(kind.description)}</dd></dl>`;
+ return `<dl class="credential-kv" data-git-detail><dt>来源</dt><dd>${user.gitTokenOAuth?'工蜂授权 · 到期自动续期':'GitHub 授权 / 个人访问令牌'}</dd><dt>权限</dt><dd>${scopes||'<span class="is-muted">校验后显示</span>'}</dd><dt>最近校验</dt><dd>${checked}</dd><dt>用于</dt><dd>${escapeHTML(kind.description)}</dd></dl>`;
}
function gitTokenEditorHTML(kind,user){
const failure=gitTokenFailure(gitTokenVerifyFor({id:state.currentUser?.id})?.result);
@@ -231,6 +231,7 @@ function renderCredentialPanel(){
const panel=$('#credentialPanel');if(!panel)return;
const user=credentialUser();
panel.innerHTML=credentialPanelHTML(user);
+ if(typeof hydrateGitHubConnections==='function')hydrateGitHubConnections(panel);
applyCredentialFilter(panel,user);
hydrateCredentialIcons(panel);
}
@@ -526,11 +527,14 @@ function credentialWizardStepOneHTML(user){
function credentialWizardStepTwoHTML(kind){
const wizard=credentialWizard;
const guide=kind.guide.map(([text,href,label],index)=>`<li class="${wizard.guide[index]?'is-done':''}" data-wizard-guide="${index}"><span class="credential-guide-no">${wizard.guide[index]?credentialGlyph('check-draw',10):index+1}</span><span>${text}${href?`<a href="${href}" target="_blank" rel="noopener noreferrer" data-wizard-link="${index}">${escapeHTML(label)} ↗</a>`:''}</span></li>`).join('');
- const gongfeng=kind.key==='gitToken'?`${credentialOAuthHTML('一键用工蜂授权','推荐 · 授权后自动续期')}${state.gongfengOAuthEnabled?'<div class="credential-or">或手动填写个人访问令牌</div>':''}${credentialPatWarningHTML(true)}`:'';
+ const github=kind.key==='gitToken';
+ const manual=wizard.githubMethod==='manual';
+ const methods=github?`<div class="github-methods" role="tablist" aria-label="GitHub 连接方式"><button type="button" role="tab" data-github-method="oauth" aria-selected="${!manual}">GitHub 授权</button><button type="button" role="tab" data-github-method="manual" aria-selected="${manual}">访问令牌</button></div>`:'';
+ if(github&&!manual)return `<div class="credential-question">${credentialLogo(kind,'is-mini')}<span>连接 GitHub</span><small class="credential-description">连接后可选择仓库,用于克隆代码、创建分支和推送交付产物。</small></div>${methods}${credentialOAuthHTML('用工蜂授权','')}`;
const validity=credentialWizardValid();
const secretHint=validity.error&&credentialSecretError(kind,wizard.secret)?validity.error:validity.ok?'格式正确':(kind.hint||'只在你负责的任务运行时注入,保存后不再明文展示');
- return `<div class="credential-question">${credentialLogo(kind,'is-mini')}<span>配置 ${escapeHTML(kind.short)}</span><small class="credential-description">${escapeHTML(kind.description)}</small></div>${gongfeng}<ol class="credential-guide">${guide}</ol><div class="credential-fields">
- ${credentialFieldHTML({label:kind.short,name:'secret',id:'credentialWizardSecret',placeholder:kind.placeholder,hint:secretHint})}
+ return `<div class="credential-question">${credentialLogo(kind,'is-mini')}<span>${github?'使用访问令牌':'配置 '+escapeHTML(kind.short)}</span><small class="credential-description">${escapeHTML(kind.description)}</small></div>${methods}<ol class="credential-guide">${guide}</ol><div class="credential-fields">
+ ${credentialFieldHTML({label:github?'个人访问令牌(PAT)':kind.short,name:'secret',id:'credentialWizardSecret',placeholder:kind.placeholder,hint:secretHint})}
${kind.extra?credentialFieldHTML({label:kind.extra.label,note:kind.extra.url?'可选 · 留空使用官方地址':'',name:'extra',type:kind.extra.url?'url':'text',value:wizard.extra,placeholder:kind.extra.placeholder,hint:''}):''}
</div>`;
}
@@ -545,6 +549,7 @@ function credentialWizardStepThreeHTML(kind){
}
function credentialWizardFootHTML(){
const wizard=credentialWizard;
+ if(wizard.step===2&&wizard.kind==='gitToken'&&wizard.githubMethod!=='manual')return '<span class="credential-kbd"><kbd>Esc</kbd> 关闭</span><span class="github-private-note">仅为当前账号授权</span>';
if(wizard.done)return `<span></span><button type="button" class="credential-btn primary credential-ink" data-wizard-done>完成</button>`;
const back=wizard.step===1||(wizard.direct&&wizard.step===2)
?'<span class="credential-kbd"><kbd>Esc</kbd> 关闭</span>'
@@ -578,6 +583,8 @@ function paintCredentialWizard(direction){
scrim.querySelector('[data-wizard-close]').disabled=wizard.saving;
scrim.querySelector('.credential-dialog-foot').innerHTML=credentialWizardFootHTML();
hydrateCredentialIcons(scrim);
+ if(typeof hydrateGitHubConnections==='function')hydrateGitHubConnections(pane);
+ pane.querySelectorAll('[data-github-method]').forEach(button=>{button.onclick=()=>{wizard.githubMethod=button.dataset.githubMethod;paintCredentialWizard(0);focusCredentialWizard()}});
}
function refreshCredentialWizardFoot(){
const scrim=$('#credentialWizard');if(!scrim||!credentialWizard)return;
diff --git a/web/images/credentials/README.md b/web/images/credentials/README.md
new file mode 100644
index 00000000..d4978e3d
--- /dev/null
+++ b/web/images/credentials/README.md
@@ -0,0 +1,7 @@
+# Credential artwork
+
+`github.svg` is copied from `chatbot/src/assets/provider-logos/github.svg`.
+Its source is [Simple Icons](https://github.com/simple-icons/simple-icons),
+distributed under CC0 1.0. See the bundled provider-logo README and SOURCE.md
+for the existing artwork attribution. Brand names and marks belong to their
+respective owners.
diff --git a/web/images/credentials/github.svg b/web/images/credentials/github.svg
new file mode 100644
index 00000000..23349765
--- /dev/null
+++ b/web/images/credentials/github.svg
@@ -0,0 +1 @@
+<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>GitHub</title><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>
diff --git a/web/index.html b/web/index.html
index f77ec0b4..c38d8151 100644
--- a/web/index.html
+++ b/web/index.html
@@ -1067,6 +1067,7 @@
<input type="hidden" name="id">
<div class="pa-fs">
<h5>仓库地址</h5>
+ <div data-github-repositories></div>
<label class="pa-field"><span class="pa-field-l">GitHub 仓库地址</span>
<input class="pa-input mono" name="repoUrl" spellcheck="false" placeholder="https://github.com/owner/repo">
<span class="pa-fmt"><code>https://github.com/owner/repo</code><code>[email protected]:owner/repo.git</code><code>git clone …</code></span>
@@ -1347,6 +1348,7 @@
<script src="/app/sops.js"></script>
<script src="/app/issue-model.js"></script>
<script src="/app/projects.js"></script>
+ <script src="/app/github-connect.js"></script>
<script src="/app/project-wizard.js"></script>
<script src="/app/repo_drawer.js"></script>
<script src="/app/business-domains.js"></script>
diff --git a/web/platform.css b/web/platform.css
index d27b22b3..3e2f415f 100644
--- a/web/platform.css
+++ b/web/platform.css
@@ -2161,7 +2161,7 @@ html[data-theme="light"] body{color-scheme:light}html[data-theme="light"] .platf
.obs-card>.pager{margin:10px 0 2px;border:0;background:transparent;padding:8px 0 0}
/* ================= 个人凭证(harness-ui 设计语言) ================= */
-#personalSettingsContent,.credential-scrim{
+#personalSettingsContent,.credential-scrim,.github-connect{
--cr-accent:var(--hui-accent);--cr-accent-hover:var(--hui-accent-hover);
--cr-surface:var(--hui-surface);--cr-canvas:var(--hui-canvas);--cr-elevated:var(--hui-soft);
--cr-text:var(--hui-text);--cr-text-2:var(--hui-secondary);--cr-muted:var(--hui-muted);--cr-tertiary:var(--hui-tertiary);
@@ -2317,6 +2317,16 @@ html[data-theme="dark"] .credential-logo.monochrome img{filter:invert(1)}
.credential-eye:hover{background:var(--cr-hover);color:var(--cr-text)}
.credential-oauth{display:flex;align-items:center;flex-wrap:wrap;gap:10px}
.credential-oauth[hidden]{display:none}
+.github-methods{display:flex;gap:4px;padding:4px;margin:20px 0;background:var(--cr-elevated);border-radius:10px}
+.github-methods button{flex:1;padding:9px 12px;border:0;border-radius:7px;background:transparent;color:var(--cr-muted);font:inherit;cursor:pointer}
+.github-methods button[aria-selected="true"]{background:var(--cr-surface);color:var(--cr-text);box-shadow:0 1px 4px #00000012}
+.github-connect{width:100%;min-width:0}
+.github-connect-intro{font-size:13px;line-height:1.7;color:var(--cr-muted);margin:0 0 16px}
+.github-connect-status{font-size:12px;line-height:1.7;color:var(--cr-muted);margin-top:12px;overflow-wrap:anywhere}
+.github-connect-status:empty{display:none}
+.github-connect-status .button{margin:8px 6px 0 0}
+.github-device-code{display:block;font:600 26px/1.8 monospace;letter-spacing:3px;color:var(--cr-text)}
+.github-private-note{font-size:12px;color:var(--cr-muted)}
.credential-oauth small{color:var(--cr-muted);font-size:11.5px}
.credential-note{display:flex;gap:8px;padding:9px 11px;border:1px solid var(--cr-line);border-radius:8px;background:var(--cr-canvas);color:var(--cr-muted);font-size:12px;line-height:1.6}
.credential-note[hidden]{display:none}
diff --git a/webtest/tests/github-connect.test.mjs b/webtest/tests/github-connect.test.mjs
new file mode 100644
index 00000000..4d1e3d12
--- /dev/null
+++ b/webtest/tests/github-connect.test.mjs
@@ -0,0 +1,93 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { loadApp, settle } from '../lib/load-app.mjs';
+
+test('GitHub connection displays a PIN, honors slow polling, and stores the connected public user', async (t) => {
+ const app = await loadApp();
+ t.after(app.close);
+ app.router.get('/api/auth/github', { enabled: true });
+ app.router.post('/api/auth/github/device', { flowId: 'opaque-flow', userCode: 'ABCD-EFGH', expiresIn: 900, interval: 5 });
+ app.router.post('/api/auth/github/poll', { status: 'connected', login: 'my-github-account', user: { id: 1, loginName: 'owner', gitTokenConfigured: true } });
+ app.evaluate(`
+ state.currentUser={id:1,loginName:'owner'};
+ const host=document.createElement('div');host.id='github-test';host.innerHTML=githubConnectHTML();document.body.append(host);
+ window.githubTimers=[];window.setTimeout=(callback,delay)=>{window.githubTimers.push({callback,delay});return window.githubTimers.length};
+ `);
+ const host = app.document.querySelector('#github-test');
+ await app.evaluate('hydrateGitHubConnections(document)');
+ host.querySelector('[data-github-start]').click();
+ await settle(5);
+ assert.match(host.textContent, /ABCD-EFGH/);
+ assert.equal(host.querySelector('a').href, 'https://github.com/login/device');
+ assert.equal(app.router.calls.filter(call => call.path === '/api/auth/github/poll').length, 0);
+ assert.equal(app.window.githubTimers.at(-1).delay, 5000);
+ await app.window.githubTimers.at(-1).callback();
+ assert.match(host.textContent, /已连接 GitHub · my-github-account/);
+ assert.equal(app.evaluate('userById(1).gitTokenConfigured'), true);
+ assert.equal(host.querySelector('[data-github-start]').disabled, false);
+ const call = app.router.calls.find(call => call.path === '/api/auth/github/poll');
+ assert.deepEqual(call.body, { flowId: 'opaque-flow' });
+});
+
+test('GitHub repository picker loads pages, filters names, and fills the actual default branch', async (t) => {
+ const app = await loadApp();
+ t.after(app.close);
+ app.router.get('/api/auth/github/repositories?page=1', { repositories: [{ full_name: 'team/private', html_url: 'https://github.com/team/private', default_branch: 'develop', private: true }], hasMore: true });
+ app.router.get('/api/auth/github/repositories?page=2', { repositories: [{ full_name: 'me/public', html_url: 'https://github.com/me/public', default_branch: 'trunk', private: false }], hasMore: false });
+ app.evaluate(`
+ state.currentUser={id:1,loginName:'owner'};
+ const host=document.createElement('div');host.id='github-picker-test';document.body.append(host);
+ state.data.users=[{id:1,gitTokenConfigured:true}];
+ mountGitHubRepoPicker(host,repository=>{window.githubSelected=repository});
+ `);
+ const host = app.document.querySelector('#github-picker-test');
+ host.querySelector('[data-github-load]').click();
+ await settle(5);
+ assert.match(host.textContent, /team\/private · 私有/);
+ host.querySelector('[data-github-more]').click();
+ await settle(5);
+ const search = host.querySelector('[data-github-search]');
+ search.value = 'me/';
+ search.dispatchEvent(new app.window.Event('input'));
+ const select = host.querySelector('[data-github-repo]');
+ assert.equal(select.options.length, 2);
+ select.options[1].selected = true;
+ select.dispatchEvent(new app.window.Event('change'));
+ assert.equal(app.window.githubSelected.full_name, 'me/public');
+ assert.equal(app.window.githubSelected.default_branch, 'trunk');
+ assert.equal(host.querySelector('[data-github-more]'), null);
+});
+
+test('GitHub setup keeps deployment configuration out of personal authorization', async (t) => {
+ const app = await loadApp();
+ t.after(app.close);
+ app.router.get('/api/auth/github', { enabled: true, canConfigure: true, clientId: 'configured-client' });
+ app.evaluate(`
+ state.currentUser={id:1,loginName:'owner'};
+ const host=document.createElement('div');host.id='github-error-test';host.innerHTML=githubConnectHTML();document.body.append(host);
+ `);
+ const host = app.document.querySelector('#github-error-test');
+ await app.evaluate('hydrateGitHubConnections(document)');
+ await settle(5);
+ assert.doesNotMatch(host.textContent, /管理员|Client ID|configured-client/);
+ assert.equal(host.querySelector('[data-github-client]'), null);
+ assert.equal(host.querySelector('[data-github-start]').disabled, false);
+ assert.equal(host.querySelector('[data-github-start]').hidden, false);
+ assert.equal(app.router.calls.some(call=>call.path==='/api/auth/github/device'), false);
+ assert.equal(app.router.calls.some(call=>call.path==='/api/auth/github/config'), false);
+});
+
+test('GitHub settings has a single row and separates authorization from manual secrets', async (t) => {
+ const app=await loadApp();t.after(app.close);
+ app.router.get('/api/auth/github',{enabled:false,canConfigure:false});
+ app.evaluate(`state.currentUser={id:1,isGuest:false};state.data.users[0]={id:1};renderPersonalSettings();openCredentialWizard('gitToken')`);
+ await settle(4);
+ assert.equal(app.document.querySelector('#personalSettingsContent > .personal-settings-card'),null);
+ const wizard=app.document.querySelector('#credentialWizard');
+ assert.equal(wizard.querySelector('input[name="secret"]'),null);
+ assert.match(wizard.textContent,/已停用/);
+ assert.equal(wizard.querySelector('[data-github-start]').hidden,true);
+ wizard.querySelector('[data-github-method="manual"]').click();
+ assert.ok(wizard.querySelector('input[name="secret"]'));
+ assert.equal(wizard.querySelector('[data-github-connect]'),null);
+});