mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-10-28 01:03:50 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36043c0ac1 | ||
|
|
de7a668b32 | ||
|
|
bdf0e68644 | ||
|
|
316889f76a | ||
|
|
6c940f4403 | ||
|
|
f5c99f4866 | ||
|
|
4bec88fc7f | ||
|
|
9d8598c91b | ||
|
|
d2ff24d1af | ||
|
|
53d9f0d5d1 | ||
|
|
db371be93c | ||
|
|
6a3d39e969 | ||
|
|
e94a7d472b | ||
|
|
5f3a92a1f1 | ||
|
|
36eb5c5e89 | ||
|
|
bfc5e6236e | ||
|
|
d2e7e3a8a7 | ||
|
|
23446606a4 | ||
|
|
b9b137dc91 | ||
|
|
bd0ba56c82 | ||
|
|
600007873c |
No files matched your search
@@ -0,0 +1,210 @@
|
||||
name: deploy-demo
|
||||
|
||||
on:
|
||||
# 网页手工发布的正式版;Actions 自己发布的版本由 workflow_call 接入。
|
||||
release:
|
||||
types: [published]
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag:
|
||||
required: true
|
||||
type: string
|
||||
commit:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
VERCEL_TOKEN:
|
||||
required: true
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "已发布的最新正式版标签;留空自动选择最新正式版"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# 不中断正在上传的部署;旧版本在构建前和上线前都会检查是否仍为 latest。
|
||||
concurrency:
|
||||
group: demo-production
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
if: github.event_name != 'release' || github.event.release.prerelease == false
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
env:
|
||||
VERCEL_ORG_ID: ${{ vars.VERCEL_ORG_ID }}
|
||||
VERCEL_PROJECT_ID: ${{ vars.VERCEL_PROJECT_ID }}
|
||||
DEMO_URL: ${{ vars.DEMO_URL }}
|
||||
NEXT_PUBLIC_MOCK: "1"
|
||||
NEXT_TELEMETRY_DISABLED: "1"
|
||||
steps:
|
||||
- name: Select a published, complete, latest release
|
||||
id: release
|
||||
uses: actions/github-script@v7
|
||||
env:
|
||||
REQUESTED_TAG: ${{ inputs.tag || github.event.release.tag_name }}
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const { data: latest } = await github.rest.repos.getLatestRelease({ owner, repo });
|
||||
const tag = process.env.REQUESTED_TAG || latest.tag_name;
|
||||
if (!/^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(tag)) {
|
||||
throw new Error('只允许 v主版本.次版本.修订号 的正式标签');
|
||||
}
|
||||
const { data: release } = await github.rest.repos.getReleaseByTag({ owner, repo, tag });
|
||||
if (release.draft || release.prerelease) throw new Error('草稿和预发布版本不可部署');
|
||||
const version = tag.slice(1);
|
||||
const assets = new Set(release.assets.map(asset => asset.name));
|
||||
for (const platform of ['linux-amd64', 'linux-arm64', 'darwin-amd64', 'darwin-arm64', 'windows-amd64']) {
|
||||
if (!assets.has(`artex-${version}-${platform}.zip`)) throw new Error(`缺少 ${platform} 发布包`);
|
||||
}
|
||||
if (!assets.has('SHA256SUMS')) throw new Error('缺少发布校验文件');
|
||||
core.setOutput('tag', tag);
|
||||
core.setOutput('current', String(tag === latest.tag_name));
|
||||
if (tag !== latest.tag_name) {
|
||||
core.notice(`${tag} 已被 ${latest.tag_name} 替代,跳过以免覆盖新版 Demo`);
|
||||
}
|
||||
|
||||
- name: Check deployment configuration
|
||||
if: steps.release.outputs.current == 'true'
|
||||
env:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
run: |
|
||||
for name in VERCEL_ORG_ID VERCEL_PROJECT_ID VERCEL_TOKEN DEMO_URL; do
|
||||
if [ -z "${!name}" ]; then
|
||||
echo "::error::请先在仓库 Actions 中配置 $name,参见 README 的在线 Demo 部署说明"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [[ ! "$DEMO_URL" =~ ^https://[a-zA-Z0-9][a-zA-Z0-9.-]+/?$ ]]; then
|
||||
echo "::error::DEMO_URL 必须是 HTTPS 生产域名,不能含路径、查询参数或凭据"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
if: steps.release.outputs.current == 'true'
|
||||
with:
|
||||
ref: refs/tags/${{ steps.release.outputs.tag }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Verify the released commit and write deployment metadata
|
||||
if: steps.release.outputs.current == 'true'
|
||||
env:
|
||||
EXPECTED_COMMIT: ${{ inputs.commit }}
|
||||
RELEASE_TAG: ${{ steps.release.outputs.tag }}
|
||||
run: |
|
||||
commit=$(git rev-parse HEAD)
|
||||
if [ -n "$EXPECTED_COMMIT" ] && [ "$commit" != "$EXPECTED_COMMIT" ]; then
|
||||
echo "::error::发布标签已移动,拒绝部署与 Release 构建不同的提交"
|
||||
exit 1
|
||||
fi
|
||||
mkdir -p web/public
|
||||
jq -n --arg tag "$RELEASE_TAG" --arg commit "$commit" \
|
||||
--arg release "https://github.com/$GITHUB_REPOSITORY/releases/tag/$RELEASE_TAG" \
|
||||
'{tag: $tag, commit: $commit, release: $release, mock: true}' > web/public/demo-version.json
|
||||
# 兼容首次部署尚未含此配置的历史正式版;CLI 部署不受此开关影响。
|
||||
jq -n '{"$schema":"https://openapi.vercel.sh/vercel.json", framework:"nextjs", installCommand:"npm ci", buildCommand:"npm run build", git:{deploymentEnabled:false}}' > web/vercel.json
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
if: steps.release.outputs.current == 'true'
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
cache-dependency-path: web/package-lock.json
|
||||
|
||||
- name: Install Vercel CLI
|
||||
if: steps.release.outputs.current == 'true'
|
||||
run: npm install --global [email protected]
|
||||
|
||||
- name: Configure the dedicated demo project
|
||||
if: steps.release.outputs.current == 'true'
|
||||
env:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
run: |
|
||||
# CLI 以 web/ 为项目根;设置与 runner 一致的 Node 主版本。
|
||||
curl --fail-with-body --silent --show-error --request PATCH \
|
||||
--header "Authorization: Bearer $VERCEL_TOKEN" --header 'Content-Type: application/json' \
|
||||
--data '{"framework":"nextjs","nodeVersion":"22.x","rootDirectory":null,"installCommand":"npm ci","buildCommand":"npm run build"}' \
|
||||
"https://api.vercel.com/v9/projects/$VERCEL_PROJECT_ID?teamId=$VERCEL_ORG_ID" \
|
||||
--output /tmp/demo-project.json
|
||||
curl --fail-with-body --silent --show-error --request POST \
|
||||
--header "Authorization: Bearer $VERCEL_TOKEN" --header 'Content-Type: application/json' \
|
||||
--data '{"key":"NEXT_PUBLIC_MOCK","value":"1","type":"plain","target":["production"]}' \
|
||||
"https://api.vercel.com/v10/projects/$VERCEL_PROJECT_ID/env?teamId=$VERCEL_ORG_ID&upsert=true" \
|
||||
--output /tmp/demo-env.json
|
||||
jq -e '(.failed // []) | length == 0' /tmp/demo-env.json
|
||||
# 项目令牌无法调用 CLI alias 依赖的用户信息接口,直接配置项目域名。
|
||||
# 将域名关联到项目后,--prod 会随每次发布自动更新该域名。
|
||||
domain="${DEMO_URL#https://}"
|
||||
domain="${domain%/}"
|
||||
status=$(curl --silent --show-error --write-out '%{http_code}' \
|
||||
--header "Authorization: Bearer $VERCEL_TOKEN" \
|
||||
"https://api.vercel.com/v9/projects/$VERCEL_PROJECT_ID/domains/$domain?teamId=$VERCEL_ORG_ID" \
|
||||
--output /tmp/demo-domain.json)
|
||||
if [ "$status" = "404" ]; then
|
||||
jq -n --arg name "$domain" '{name:$name}' > /tmp/demo-domain-input.json
|
||||
curl --fail-with-body --silent --show-error --request POST \
|
||||
--header "Authorization: Bearer $VERCEL_TOKEN" --header 'Content-Type: application/json' \
|
||||
--data-binary @/tmp/demo-domain-input.json \
|
||||
"https://api.vercel.com/v10/projects/$VERCEL_PROJECT_ID/domains?teamId=$VERCEL_ORG_ID" \
|
||||
--output /tmp/demo-domain.json
|
||||
elif [ "$status" != "200" ]; then
|
||||
jq '.error' /tmp/demo-domain.json
|
||||
exit 1
|
||||
fi
|
||||
jq -e --arg domain "$domain" '.name == $domain and .verified == true' /tmp/demo-domain.json
|
||||
|
||||
- name: Pull production project settings
|
||||
if: steps.release.outputs.current == 'true'
|
||||
working-directory: web
|
||||
env:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
run: vercel pull --yes --environment=production --token="$VERCEL_TOKEN"
|
||||
|
||||
- name: Build the mock demo
|
||||
if: steps.release.outputs.current == 'true'
|
||||
working-directory: web
|
||||
env:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
run: vercel build --prod --token="$VERCEL_TOKEN"
|
||||
|
||||
- name: Check latest release again before publishing
|
||||
if: steps.release.outputs.current == 'true'
|
||||
id: publish
|
||||
uses: actions/github-script@v7
|
||||
env:
|
||||
RELEASE_TAG: ${{ steps.release.outputs.tag }}
|
||||
with:
|
||||
script: |
|
||||
const { data: latest } = await github.rest.repos.getLatestRelease(context.repo);
|
||||
const current = latest.tag_name === process.env.RELEASE_TAG;
|
||||
core.setOutput('current', String(current));
|
||||
if (!current) core.notice('构建期间已有更新的正式版发布,保留线上版本,等待新版部署');
|
||||
|
||||
- name: Deploy the prebuilt demo to production
|
||||
if: steps.publish.outputs.current == 'true'
|
||||
id: deploy
|
||||
working-directory: web
|
||||
env:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
run: |
|
||||
url=$(vercel deploy --prebuilt --prod --yes --token="$VERCEL_TOKEN")
|
||||
echo "url=$url" >> "$GITHUB_OUTPUT"
|
||||
echo "### Demo 已部署" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- 正式版本:${{ steps.release.outputs.tag }}" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- 固定网址:$DEMO_URL" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- 部署地址:$url" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Verify production version metadata
|
||||
if: steps.publish.outputs.current == 'true'
|
||||
env:
|
||||
RELEASE_TAG: ${{ steps.release.outputs.tag }}
|
||||
run: |
|
||||
# 检查公开的生产域名;Vercel 可单独保护部署专属的随机域名。
|
||||
curl --fail --silent --show-error --retry 5 --retry-all-errors --retry-delay 3 \
|
||||
"${DEMO_URL%/}/demo-version.json" -o /tmp/demo-version.json
|
||||
jq -e --arg tag "$RELEASE_TAG" '.tag == $tag and .mock == true' /tmp/demo-version.json
|
||||
@@ -181,6 +181,17 @@ jobs:
|
||||
- name: Publish complete release
|
||||
run: gh release edit "$RELEASE_TAG" --draft=false --latest
|
||||
|
||||
# GITHUB_TOKEN 发布的 Release 不会再次触发 release: published 工作流。
|
||||
# 直接依赖发布 job,保证 ZIP、校验文件和镜像全部发布成功后才更新 Demo。
|
||||
demo:
|
||||
needs: [prepare, release]
|
||||
uses: ./.github/workflows/demo.yml
|
||||
with:
|
||||
tag: ${{ needs.prepare.outputs.tag }}
|
||||
commit: ${{ needs.prepare.outputs.commit }}
|
||||
secrets:
|
||||
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
|
||||
|
||||
# ④ 在原生 AMD64 / ARM64 runner 上构建和测试,再推送架构镜像。
|
||||
docker:
|
||||
needs: [prepare, binaries]
|
||||
|
||||
+3
-1
@@ -14,6 +14,8 @@ web/node_modules/
|
||||
web/.next/
|
||||
web/tsconfig.tsbuildinfo
|
||||
web/next-env.d.ts
|
||||
.vercel/
|
||||
web/public/demo-version.json
|
||||
*.local
|
||||
|
||||
# development tools
|
||||
@@ -57,4 +59,4 @@ Thumbs.db
|
||||
# bench 基准测试相关(本地产物,不提交)
|
||||
/bench/
|
||||
/Dockerfile.bench
|
||||
/Dockerfile.bench.v2
|
||||
/Dockerfile.bench.v2
|
||||
@@ -5,7 +5,7 @@
|
||||
AI 自主渗透测试系统(Go 后端 + Next.js 前端)
|
||||
|
||||
|
||||
🌐 **在线 Demo**: [https://artex-demo.vercel.app/](https://artex-demo.vercel.app/)
|
||||
🌐 **在线 Demo**: [https://artex-demo-ruoji6.vercel.app/](https://artex-demo-ruoji6.vercel.app/)
|
||||
|
||||
</div>
|
||||
|
||||
@@ -15,7 +15,7 @@ AI 自主渗透测试系统(Go 后端 + Next.js 前端)
|
||||
|
||||
## 截图预览
|
||||
|
||||
> 完整交互见[在线 Demo](https://artex-demo.vercel.app/)。
|
||||
> 完整交互见[在线 Demo](https://artex-demo-ruoji6.vercel.app/)。
|
||||
|
||||
| 仪表盘(总览 / Token 消耗 / 活动流) | 任务列表 |
|
||||
| :---: | :---: |
|
||||
@@ -64,6 +64,42 @@ AI 自主渗透测试系统(Go 后端 + Next.js 前端)
|
||||
|
||||
---
|
||||
|
||||
## 部署自己的在线 Demo(随正式 Release 自动更新)
|
||||
|
||||
Demo 只运行 `web/` 前端,构建时启用 `NEXT_PUBLIC_MOCK=1`,不需要 Go、PostgreSQL 或模型密钥。界面使用模拟数据,不执行真实扫描。
|
||||
|
||||
发布链路:正式版本的程序包、`SHA256SUMS` 和 Docker 镜像全部成功发布 → `release.yml` 的 `demo` job 调用 `demo.yml` → 检出该版本标签的提交 → 构建 Mock 前端 → 部署至 Vercel 的固定生产域名。普通 main 推送、仅创建标签、失败的发布、草稿和预发布版本都不会更新 Demo。新版本功能的演示数据仍需由维护者同步维护 `web/src/lib/mock/`。
|
||||
|
||||
### 首次配置 Vercel
|
||||
|
||||
1. 在自己的 Vercel 账号创建空项目,设置名称(例如 `artex-demo-ruoji6`)。保持 **Git 未连接**,避免每次提交都自动部署。`web/vercel.json` 也禁用了 Git 自动部署。
|
||||
2. 在 **Settings → Build and Deployment** 中选择 **Next.js**、Node.js **22.x**,安装命令可覆盖为 `npm ci`,构建命令为 `npm run build`,Output Directory 保持默认。**Root Directory 留空**:此工作流从检出的 `web/` 目录调用 Vercel CLI,不能再填一层 `web`。
|
||||
3. 在项目的 **Environment Variables** 中添加 `NEXT_PUBLIC_MOCK=1`,至少应用于 **Production**。不要设置 `NEXT_EXPORT=1`,也不要填写数据库连接或模型密钥。
|
||||
4. 在项目 **Settings → General** 复制 **Project ID**;在团队 **Settings → General** 复制 **Team ID**(对应 `VERCEL_ORG_ID`)。确认 **Domains** 中有准备使用的生产域名。
|
||||
5. 在 Vercel **Account Settings → Tokens** 创建部署 Token,范围选择项目所在团队,并设置适当有效期。将其直接保存到 GitHub 仓库 **Settings → Secrets and variables → Actions → Secrets**,名称为 `VERCEL_TOKEN`。令牌不要写入仓库、README 或聊天;到期后更新这个 Secret。
|
||||
|
||||
在同一 GitHub 设置页的 **Variables** 中添加:
|
||||
|
||||
| 变量 | 值 |
|
||||
| --- | --- |
|
||||
| `VERCEL_ORG_ID` | Vercel Team ID |
|
||||
| `VERCEL_PROJECT_ID` | Vercel Project ID |
|
||||
| `DEMO_URL` | 固定公开生产网址,含 `https://`,例如 `https://artex-demo-ruoji6.vercel.app` |
|
||||
|
||||
### 首次部署与重试
|
||||
|
||||
将配置合并到默认分支后,打开 **Actions → deploy-demo → Run workflow**,分支选 `main`,tag 留空或填写当前最新正式版(例如 `v0.3.21`)。工作流只接受已发布且包含五个平台程序包和校验文件的最新正式版,也能部署尚未包含此工作流的历史正式版。无需重新发 Release 或移动已有标签。
|
||||
|
||||
工作流会将这个专用 Demo 项目的框架设为 Next.js、Node 设为 22.x、根目录设为空、安装命令设为 `npm ci`、构建命令设为 `npm run build`,并确保 Production 环境的 `NEXT_PUBLIC_MOCK=1`,随后绑定 `DEMO_URL` 指定的域名。请使用独立项目;后续部署会继续维护这些配置。
|
||||
|
||||
成功后访问生产域名,并检查 `/demo-version.json` 中的 `tag`、`commit` 和 `mock: true`。确认可访问后,将 README 顶部和截图区域的旧 Demo 链接一起改为自己的生产域名。
|
||||
|
||||
此后按正常流程发布更高版本即可自动更新 Demo。若 Demo 部署失败,已发布的程序包和镜像仍然有效,旧 Demo 通常继续提供服务;修复设置后单独重跑 `deploy-demo`,不必重新发布整个 Release。两个版本同时发布时,部署串行执行,并在构建前、上线前检查 latest,避免已过期的构建覆盖新版。
|
||||
|
||||
这里采用发布流程直接调用部署 job,是因为使用 `GITHUB_TOKEN` 创建的 Release 不会继续触发另一个 `release: published` 工作流。`demo.yml` 也监听网页手工发布的 Release,经过同样的正式版、完整发布包和 latest 检查后部署;手工重试则运行 `deploy-demo`。
|
||||
|
||||
---
|
||||
|
||||
## 安装
|
||||
|
||||
> 依赖数据库 **PostgreSQL**;探索需配置 **LLM**(`ANTHROPIC_API_KEY` 或 `OPENAI_API_KEY`,也可在 UI 里配)。
|
||||
@@ -161,7 +197,8 @@ ARTEX_TARGETS=linux/amd64,windows/amd64 ./build.sh --release
|
||||
- **更新会中断正在运行的任务**——更新即重启,请在空闲时进行。
|
||||
- **开发构建不给更新**:版本号是 `dev` 或 `git describe` 带后缀时禁用,避免正式版覆盖掉本地调试的二进制。
|
||||
- **Docker 下只换程序、不换镜像**:镜像里的 playwright / nmap 等工具链不会跟着升级,且 `docker compose up -d` 重建容器后会退回镜像自带的版本。要连镜像一起升级仍请用 `docker compose pull artex && docker compose up -d artex`。
|
||||
- 访问 GitHub 需要代理时,在同一页面配置**全局代理**即可,更新链路会走它。更新只从 GitHub 域名下载并强制 HTTPS。
|
||||
- **更新代理(可选)**与其他代理设置使用相同的「地址输入框 + 保存」方式。填写独立更新代理后保存,例如 `http://127.0.0.1:7897`;支持 `http://`、`https://`、`socks5://`、`socks5h://` 及用户名密码认证。清空并保存即为直连,不受全局代理或 `HTTP_PROXY` / `HTTPS_PROXY` 环境变量影响。保存后自动重新检查,检查版本、校验和下载和发布包下载使用同一个出口。更新只从 GitHub 域名下载并强制 HTTPS。
|
||||
- 代理地址由 **ARTEX 服务端**访问。Docker 内的 `127.0.0.1` 指容器自身;代理运行在宿主机时,应使用容器可达地址(Docker Desktop 通常为 `http://host.docker.internal:7897`),并允许容器访问代理端口。
|
||||
|
||||
### 维护者:通过 GitHub Actions 发布在线更新
|
||||
|
||||
|
||||
+21
-6
@@ -250,14 +250,30 @@ func (c Config) Provider() string {
|
||||
return "anthropic"
|
||||
}
|
||||
|
||||
// NewProvider builds an llm.Provider from the config. When a rate is set, the
|
||||
// limiter lives on the single provider instance — so planner + all workers +
|
||||
// main agent (which share this provider) are bounded by one shared rate limit.
|
||||
// NewProvider builds a provider with its own HTTP request limiter. Every HTTP
|
||||
// attempt, including SDK retries, counts toward both rolling rate windows.
|
||||
func (c Config) NewProvider() (llm.Provider, error) {
|
||||
return c.NewProviderWithLimiter(&RequestLimiter{})
|
||||
}
|
||||
|
||||
// NewProviderWithLimiter reuses quota history across provider rebuilds. Callers
|
||||
// sharing a profile must retain the same limiter outside their provider cache.
|
||||
func (c Config) NewProviderWithLimiter(limiter *RequestLimiter) (llm.Provider, error) {
|
||||
client, err := quotaAwareHTTPClient(c.Proxy, c.SessionHeaderKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.newProvider(client, limiter)
|
||||
}
|
||||
|
||||
func (c Config) newProvider(client *http.Client, limiter *RequestLimiter) (llm.Provider, error) {
|
||||
if limiter == nil {
|
||||
limiter = &RequestLimiter{}
|
||||
}
|
||||
if err := limiter.configure(c.RatePerSecond, c.RatePerMinute); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client.Transport = rateLimitedTransport{base: client.Transport, limiter: limiter}
|
||||
lc := llm.Config{
|
||||
Format: c.Format,
|
||||
BaseURL: c.BaseURL,
|
||||
@@ -277,9 +293,8 @@ func (c Config) NewProvider() (llm.Provider, error) {
|
||||
lc.RetryInterval = c.Retry.ConnectInterval
|
||||
lc.EmptyResponseRetries = c.Retry.EmptyAttempts
|
||||
lc.EmptyResponseInterval = c.Retry.EmptyInterval
|
||||
if c.RatePerSecond > 0 || c.RatePerMinute > 0 {
|
||||
lc.RateLimit = &llm.RateLimit{PerSecond: c.RatePerSecond, PerMinute: c.RatePerMinute}
|
||||
}
|
||||
// Norma's limiter allows a full-window burst and excludes establishment
|
||||
// retries. Enforce limits on HTTP attempts instead; do not also enable it.
|
||||
return llm.NewProvider(lc)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RequestLimiter counts HTTP attempts in rolling second/minute windows. Keep it
|
||||
// outside provider caches so rebuilding a provider does not reset its quota.
|
||||
// Its zero value is ready for use; limits are set by NewProviderWithLimiter.
|
||||
type RequestLimiter struct {
|
||||
mu sync.Mutex
|
||||
windows [2]requestWindow
|
||||
sent []time.Time
|
||||
changed chan struct{}
|
||||
}
|
||||
|
||||
type requestWindow struct {
|
||||
period time.Duration
|
||||
limit float64
|
||||
}
|
||||
|
||||
func (l *RequestLimiter) configure(perSecond, perMinute float64) error {
|
||||
var windows [2]requestWindow
|
||||
for i, rate := range [2]float64{perSecond, perMinute} {
|
||||
if math.IsNaN(rate) || math.IsInf(rate, 0) {
|
||||
return fmt.Errorf("LLM request rate must be finite")
|
||||
}
|
||||
if rate <= 0 {
|
||||
continue
|
||||
}
|
||||
period := [2]time.Duration{time.Second, time.Minute}[i]
|
||||
// Whole HTTP attempts cannot exceed a fractional window capacity.
|
||||
limit := math.Floor(rate)
|
||||
if rate < 1 {
|
||||
// Preserve fractional rates such as 0.5/s as one attempt per 2s.
|
||||
d := math.Ceil(float64(period) / rate)
|
||||
if d >= float64(math.MaxInt64) {
|
||||
return fmt.Errorf("LLM request rate is too small")
|
||||
}
|
||||
period, limit = time.Duration(d), 1
|
||||
}
|
||||
windows[i] = requestWindow{period: period, limit: limit}
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.windows = windows
|
||||
if l.changed != nil {
|
||||
close(l.changed)
|
||||
}
|
||||
l.changed = make(chan struct{})
|
||||
return nil
|
||||
}
|
||||
|
||||
// wait counts a request only when it may actually proceed. Waiters recheck both
|
||||
// windows under the same lock, so concurrency and cancellation cannot overbook
|
||||
// capacity. Requests in (now-period, now] count toward each rolling window.
|
||||
func (l *RequestLimiter) wait(ctx context.Context) error {
|
||||
if l == nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
for {
|
||||
l.mu.Lock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
l.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
// Retain at least a minute across limit changes, including while limits
|
||||
// are disabled. Fractional rates may need a longer history.
|
||||
retention := time.Minute
|
||||
for _, w := range l.windows {
|
||||
if w.period > retention {
|
||||
retention = w.period
|
||||
}
|
||||
}
|
||||
first := 0
|
||||
// Keep the last attempt even when older than retention: a subsequent
|
||||
// switch to a fractional rate may need to space requests further apart.
|
||||
for first+1 < len(l.sent) && !l.sent[first].After(now.Add(-retention)) {
|
||||
first++
|
||||
}
|
||||
l.sent = l.sent[first:]
|
||||
var delay time.Duration
|
||||
for _, w := range l.windows {
|
||||
if w.limit == 0 {
|
||||
continue
|
||||
}
|
||||
start := len(l.sent)
|
||||
for start > 0 && l.sent[start-1].After(now.Add(-w.period)) {
|
||||
start--
|
||||
}
|
||||
count := len(l.sent) - start
|
||||
if float64(count) >= w.limit {
|
||||
// If a limit was lowered, enough old requests must expire to
|
||||
// leave room for this attempt, not just the oldest request.
|
||||
d := l.sent[len(l.sent)-int(w.limit)].Add(w.period).Sub(now)
|
||||
if d > delay {
|
||||
delay = d
|
||||
}
|
||||
}
|
||||
}
|
||||
if delay <= 0 {
|
||||
l.sent = append(l.sent, now)
|
||||
l.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
changed := l.changed
|
||||
l.mu.Unlock()
|
||||
timer := time.NewTimer(delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-changed:
|
||||
timer.Stop()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type rateLimitedTransport struct {
|
||||
base http.RoundTripper
|
||||
limiter *RequestLimiter
|
||||
}
|
||||
|
||||
func (t rateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
if err := t.limiter.wait(req.Context()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t.base.RoundTrip(req)
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
func TestRequestLimiterRollingWindows(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rps, rpm float64
|
||||
capacity int
|
||||
window time.Duration
|
||||
}{
|
||||
{"second", 10, 0, 10, time.Second},
|
||||
{"minute_45", 0, 45, 45, time.Minute},
|
||||
{"fractional_second", .5, 0, 1, 2 * time.Second},
|
||||
{"fractional_minute", 0, .5, 1, 2 * time.Minute},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
l := &RequestLimiter{}
|
||||
if err := l.configure(tc.rps, tc.rpm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := time.Now()
|
||||
for i := 0; i < tc.capacity; i++ {
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), tc.window-time.Nanosecond)
|
||||
defer cancel()
|
||||
if err := l.wait(ctx); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("extra attempt before window expired: %v", err)
|
||||
}
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed != tc.window {
|
||||
t.Fatalf("next attempt at %s, want %s; cancelled wait must not consume quota", elapsed, tc.window)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestLimiterBothWindowsAndConcurrentCallers(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
l := &RequestLimiter{}
|
||||
if err := l.configure(3, 5); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var sent []time.Time
|
||||
var wg sync.WaitGroup
|
||||
start := time.Now()
|
||||
for i := 0; i < 12; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
sent = append(sent, time.Now())
|
||||
mu.Unlock()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if elapsed := time.Since(start); elapsed != 2*time.Minute {
|
||||
t.Fatalf("12 requests under 3/s and 5/min took %s, want 2m", elapsed)
|
||||
}
|
||||
assertRollingRequestCounts(t, sent, time.Second, 3)
|
||||
assertRollingRequestCounts(t, sent, time.Minute, 5)
|
||||
})
|
||||
}
|
||||
|
||||
func assertRollingRequestCounts(t *testing.T, sent []time.Time, window time.Duration, limit int) {
|
||||
t.Helper()
|
||||
for _, end := range sent {
|
||||
count := 0
|
||||
for _, ts := range sent {
|
||||
if ts.After(end.Add(-window)) && !ts.After(end) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count > limit {
|
||||
t.Fatalf("%d attempts in rolling %s, limit %d", count, window, limit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestLimiterReconfiguration(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
l := &RequestLimiter{}
|
||||
if err := l.configure(0, 5); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
start := time.Now()
|
||||
if err := l.configure(0, 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- l.wait(context.Background()) }()
|
||||
synctest.Wait()
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("lowering limit reset history: %v", err)
|
||||
default:
|
||||
}
|
||||
// A change must wake waiting requests rather than leave them sleeping
|
||||
// until the old minute window expires.
|
||||
if err := l.configure(0, 6); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if time.Since(start) != 0 {
|
||||
t.Fatal("waiter did not wake on limit increase")
|
||||
}
|
||||
if err := l.configure(0, 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if time.Since(start) != time.Minute {
|
||||
t.Fatal("lower limit did not retain previous attempts")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRequestLimiterDisabledAndCancelled(t *testing.T) {
|
||||
l := &RequestLimiter{}
|
||||
if err := l.configure(0, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 100; i++ {
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := l.wait(ctx); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
if len(l.sent) != 100 {
|
||||
t.Fatal("cancelled request consumed quota")
|
||||
}
|
||||
for _, rate := range []float64{math.NaN(), math.Inf(1), math.Inf(-1), math.SmallestNonzeroFloat64} {
|
||||
if err := l.configure(rate, 0); err == nil {
|
||||
t.Errorf("accepted invalid rate %v", rate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exercise the actual Norma retry loops for all formats and both completion
|
||||
// modes. In-memory HTTP responses let synctest advance a full minute instantly.
|
||||
func TestProviderRateLimitCountsHTTPRetries(t *testing.T) {
|
||||
for _, format := range []string{"openai", "anthropic", "openai-responses"} {
|
||||
for _, streaming := range []bool{false, true} {
|
||||
mode := "complete"
|
||||
if streaming {
|
||||
mode = "stream"
|
||||
}
|
||||
t.Run(format+"/"+mode, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
var sent []time.Time
|
||||
client := &http.Client{Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
sent = append(sent, time.Now())
|
||||
return &http.Response{StatusCode: 500, Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"message":"temporary error"}}`))}, nil
|
||||
})}
|
||||
cfg := ConfigFrom(format, "test-model", "http://example.invalid", "test-key", "")
|
||||
cfg.RatePerSecond, cfg.RatePerMinute = 1, 2
|
||||
cfg.Retry.ConnectInterval = time.Millisecond
|
||||
prov, err := cfg.newProvider(client, &RequestLimiter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := time.Now()
|
||||
req := llm.CompletionRequest{Messages: []llm.Message{llm.UserText("ping")}}
|
||||
if streaming {
|
||||
for _, streamErr := range prov.Stream(context.Background(), req) {
|
||||
err = streamErr
|
||||
}
|
||||
} else {
|
||||
_, _, _, err = prov.Complete(context.Background(), req)
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("expected upstream 500")
|
||||
}
|
||||
if len(sent) != 4 {
|
||||
t.Fatalf("HTTP attempts=%d, want initial+3 retries", len(sent))
|
||||
}
|
||||
assertRollingRequestCounts(t, sent, time.Second, 1)
|
||||
assertRollingRequestCounts(t, sent, time.Minute, 2)
|
||||
if elapsed := time.Since(start); elapsed != time.Minute+time.Second {
|
||||
t.Fatalf("retry attempts took %s, want 1m1s", elapsed)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderRebuildPreservesRateLimit(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
l := &RequestLimiter{}
|
||||
var sent []time.Time
|
||||
cfg := ConfigFrom("openai", "test-model", "http://example.invalid", "test-key", "")
|
||||
cfg.RatePerMinute = 1
|
||||
cfg.Retry.ConnectAttempts = -1
|
||||
for i := 0; i < 2; i++ {
|
||||
client := &http.Client{Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
sent = append(sent, time.Now())
|
||||
return &http.Response{StatusCode: 500, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("error"))}, nil
|
||||
})}
|
||||
prov, err := cfg.newProvider(client, l)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prov.Complete(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("ping")}})
|
||||
}
|
||||
if len(sent) != 2 || sent[1].Sub(sent[0]) != time.Minute {
|
||||
t.Fatalf("provider rebuild reset quota: %v", sent)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestProviderRateLimitSuccessfulRequests(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
rps, rpm float64
|
||||
calls int
|
||||
window time.Duration
|
||||
limit int
|
||||
}{
|
||||
{"minute_45_requests_60", 0, 45, 60, time.Minute, 45},
|
||||
{"second_10_requests_15", 10, 0, 15, time.Second, 10},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
var sent []time.Time
|
||||
client := &http.Client{Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
sent = append(sent, time.Now())
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(
|
||||
`{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`))}, nil
|
||||
})}
|
||||
cfg := ConfigFrom("openai", "test-model", "http://example.invalid", "test-key", "")
|
||||
cfg.RatePerSecond, cfg.RatePerMinute = tc.rps, tc.rpm
|
||||
prov, err := cfg.newProvider(client, &RequestLimiter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := time.Now()
|
||||
for i := 0; i < tc.calls; i++ {
|
||||
_, _, _, err := prov.Complete(context.Background(), llm.CompletionRequest{Messages: []llm.Message{llm.UserText("ping")}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if len(sent) != tc.calls || time.Since(start) != tc.window {
|
||||
t.Fatalf("sent %d attempts in %s, want %d in %s", len(sent), time.Since(start), tc.calls, tc.window)
|
||||
}
|
||||
assertRollingRequestCounts(t, sent, tc.window, tc.limit)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderRateLimitCountsEmptyResponseRetries(t *testing.T) {
|
||||
for _, streaming := range []bool{false, true} {
|
||||
name := "complete"
|
||||
if streaming {
|
||||
name = "stream"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
var sent []time.Time
|
||||
client := &http.Client{Transport: roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
sent = append(sent, time.Now())
|
||||
body := `{"choices":[{"message":{"role":"assistant","content":""},"finish_reason":"stop"}]}`
|
||||
if streaming {
|
||||
body = "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
cfg := ConfigFrom("openai", "test-model", "http://example.invalid", "test-key", "")
|
||||
cfg.RatePerMinute = 1
|
||||
cfg.Retry.EmptyInterval = time.Millisecond
|
||||
prov, err := cfg.newProvider(client, &RequestLimiter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := llm.CompletionRequest{Messages: []llm.Message{llm.UserText("ping")}}
|
||||
if streaming {
|
||||
for range prov.Stream(context.Background(), req) {
|
||||
}
|
||||
} else {
|
||||
prov.Complete(context.Background(), req)
|
||||
}
|
||||
if len(sent) != 3 {
|
||||
t.Fatalf("attempts=%d, want initial + 2 empty retries", len(sent))
|
||||
}
|
||||
assertRollingRequestCounts(t, sent, time.Minute, 1)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestLimiterUsesRollingHistory(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
l := &RequestLimiter{}
|
||||
if err := l.configure(3, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := time.Now()
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
time.Sleep(750 * time.Millisecond)
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(350 * time.Millisecond)
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Only the two t=0 attempts expired. The one at t=.75 still counts.
|
||||
if err := l.wait(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if time.Since(start) != 1750*time.Millisecond {
|
||||
t.Fatal("window reset lost an unexpired attempt")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRateLimitedTransportCancellationDoesNotSend(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
l := &RequestLimiter{}
|
||||
if err := l.configure(0, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := 0
|
||||
tr := rateLimitedTransport{limiter: l, base: roundTripperFunc(func(*http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return &http.Response{StatusCode: 200, Body: http.NoBody}, nil
|
||||
})}
|
||||
req, err := http.NewRequest("POST", "http://example.invalid", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tr.RoundTrip(req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if _, err := tr.RoundTrip(req.WithContext(ctx)); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("cancelled waiter sent HTTP request: %d", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestProviderRateLimitPublicFactory(t *testing.T) {
|
||||
for _, format := range []string{"openai", "anthropic", "openai-responses"} {
|
||||
for _, streaming := range []bool{false, true} {
|
||||
mode := "complete"
|
||||
if streaming {
|
||||
mode = "stream"
|
||||
}
|
||||
t.Run(format+"/"+mode, func(t *testing.T) {
|
||||
var requests atomic.Int32
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
io.WriteString(w, `{"error":{"message":"temporary error"}}`)
|
||||
}))
|
||||
defer upstream.Close()
|
||||
cfg := ConfigFrom(format, "test-model", upstream.URL, "test-key", "")
|
||||
cfg.RatePerSecond, cfg.RatePerMinute = 1, 1
|
||||
cfg.Retry.ConnectAttempts = -1
|
||||
limiter := &RequestLimiter{}
|
||||
req := llm.CompletionRequest{Messages: []llm.Message{llm.UserText("ping")}}
|
||||
for i := 0; i < 2; i++ {
|
||||
// A new public provider factory call must keep the old quota.
|
||||
prov, err := cfg.NewProviderWithLimiter(limiter)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
if i == 1 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, 50*time.Millisecond)
|
||||
defer cancel()
|
||||
}
|
||||
if streaming {
|
||||
for _, streamErr := range prov.Stream(ctx, req) {
|
||||
err = streamErr
|
||||
}
|
||||
} else {
|
||||
_, _, _, err = prov.Complete(ctx, req)
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("expected upstream error or quota wait cancellation")
|
||||
}
|
||||
if i == 1 && !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("got %v, want quota wait deadline", err)
|
||||
}
|
||||
}
|
||||
if got := requests.Load(); got != 1 {
|
||||
t.Fatalf("provider rebuild sent %d HTTP requests under 1/min", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
-2
@@ -14,6 +14,7 @@ import (
|
||||
type TaskSchedule struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Remark string `json:"remark"`
|
||||
Enabled bool `json:"enabled"`
|
||||
TimezoneMode string `json:"timezone_mode"`
|
||||
ScheduleType string `json:"schedule_type"`
|
||||
@@ -46,7 +47,7 @@ type TaskScheduleInput struct {
|
||||
TaskIDs []int64
|
||||
}
|
||||
|
||||
const scheduleCols = `id,name,enabled,timezone_mode,schedule_type,
|
||||
const scheduleCols = `id,name,remark,enabled,timezone_mode,schedule_type,
|
||||
COALESCE(to_char(run_date,'YYYY-MM-DD'),''),weekdays,to_char(start_time,'HH24:MI:SS'),
|
||||
COALESCE(to_char(end_date,'YYYY-MM-DD'),''),
|
||||
COALESCE(to_char(end_time,'HH24:MI:SS'),''),start_immediately,status,last_window_key,
|
||||
@@ -63,7 +64,7 @@ func marshalWeekdays(days []int) string {
|
||||
func scanSchedule(sc interface{ Scan(...any) error }) (*TaskSchedule, error) {
|
||||
var s TaskSchedule
|
||||
var rawDays string
|
||||
if err := sc.Scan(&s.ID, &s.Name, &s.Enabled, &s.TimezoneMode, &s.ScheduleType,
|
||||
if err := sc.Scan(&s.ID, &s.Name, &s.Remark, &s.Enabled, &s.TimezoneMode, &s.ScheduleType,
|
||||
&s.RunDate, &rawDays, &s.StartTime, &s.EndDate, &s.EndTime, &s.StartImmediately,
|
||||
&s.Status, &s.LastWindowKey, &s.LastTransitionAt, &s.LastError,
|
||||
&s.CreatedAt, &s.UpdatedAt); err != nil {
|
||||
@@ -403,3 +404,29 @@ func (d *DB) ListScheduleHistory(id int64) ([]ScheduleHistory, error) {
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
// TaskSchedulePatch changes list metadata without resetting execution windows.
|
||||
type TaskSchedulePatch struct {
|
||||
Name *string
|
||||
Remark *string
|
||||
}
|
||||
|
||||
// UpdateTaskScheduleRemark leaves calendar state and task bindings untouched.
|
||||
func (d *DB) UpdateTaskScheduleRemark(id int64, remark string) (*TaskSchedule, error) {
|
||||
return d.UpdateTaskScheduleMetadata(id, TaskSchedulePatch{Remark: &remark})
|
||||
}
|
||||
|
||||
func (d *DB) UpdateTaskScheduleMetadata(id int64, patch TaskSchedulePatch) (*TaskSchedule, error) {
|
||||
item, err := scanSchedule(d.QueryRow(`UPDATE task_schedules SET
|
||||
name=CASE WHEN $2::boolean THEN $3 ELSE name END,
|
||||
remark=CASE WHEN $4::boolean THEN $5 ELSE remark END
|
||||
WHERE id=$1 RETURNING `+scheduleCols, id, patch.Name != nil, patch.Name, patch.Remark != nil, patch.Remark))
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
item.TaskIDs, err = d.scheduleTaskIDs(id)
|
||||
return item, err
|
||||
}
|
||||
@@ -553,6 +553,7 @@ ALTER TABLE tasks ADD COLUMN IF NOT EXISTS queued_at TIMESTAMPTZ;
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS queue_mode TEXT NOT NULL DEFAULT '';
|
||||
-- 可选的任务名称;补旧库。空串=未命名,前端展示时回退到描述。
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS name TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS remark TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS category_id BIGINT REFERENCES task_categories(id) ON DELETE SET NULL;
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS pinned_at TIMESTAMPTZ;
|
||||
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS active_llm_profile_id BIGINT REFERENCES llm_profiles(id) ON DELETE SET NULL;
|
||||
@@ -1057,6 +1058,7 @@ CREATE TABLE IF NOT EXISTS task_schedules (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_task_schedules_enabled ON task_schedules(enabled, id);
|
||||
ALTER TABLE task_schedules ADD COLUMN IF NOT EXISTS end_date DATE;
|
||||
ALTER TABLE task_schedules ADD COLUMN IF NOT EXISTS remark TEXT NOT NULL DEFAULT '';
|
||||
DROP TRIGGER IF EXISTS trg_task_schedules_upd ON task_schedules;
|
||||
CREATE TRIGGER trg_task_schedules_upd BEFORE UPDATE ON task_schedules
|
||||
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
|
||||
|
||||
@@ -119,7 +119,7 @@ AND NOT EXISTS (
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE tasks SET
|
||||
name='',category_id=NULL,description='',goal='',paused=true,queued=false,queued_at=NULL,queue_mode='',
|
||||
name='',remark='',category_id=NULL,description='',goal='',paused=true,queued=false,queued_at=NULL,queue_mode='',
|
||||
llm_profile_id=NULL,active_llm_profile_id=NULL,llm_chain_revision=llm_chain_revision+1,
|
||||
company_id=NULL,parent_ref=NULL,timeout_seconds=0,coverage_enabled=true,pinned_at=NULL,
|
||||
first_run_at=NULL,deadline_at=NULL,archived_at=now(),deleted_at=now()
|
||||
@@ -316,7 +316,7 @@ func restoreTaskStub(tx *sql.Tx, row map[string]any, taskID, remaining int64) er
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(`UPDATE tasks current SET
|
||||
name=archived.name,category_id=archived.category_id,description=archived.description,goal=archived.goal,
|
||||
name=archived.name,remark=COALESCE(archived.remark,''),category_id=archived.category_id,description=archived.description,goal=archived.goal,
|
||||
status=archived.status,paused=archived.paused,queued=false,queued_at=NULL,queue_mode='',
|
||||
llm_profile_id=archived.llm_profile_id,active_llm_profile_id=archived.active_llm_profile_id,
|
||||
llm_chain_revision=archived.llm_chain_revision,company_id=archived.company_id,parent_ref=archived.parent_ref,
|
||||
|
||||
@@ -136,6 +136,10 @@ func TestTaskArchiveDatabaseRoundTrip(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remark := "归档后保留的备注 📝"
|
||||
if _, err := d.UpdateTask(task.ID, TaskPatch{Remark: &remark}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var companyID, llmProfileID int64
|
||||
if err := d.QueryRow(`INSERT INTO companies(name,nkey) VALUES($1,$2) RETURNING id`,
|
||||
fmt.Sprintf("archive-company-%d", task.ID), fmt.Sprintf("archive-company-%d", task.ID)).Scan(&companyID); err != nil {
|
||||
@@ -282,7 +286,7 @@ VALUES($1,$2,0,'quota_exhausted','balance exhausted',$3,$4,$3)`, task.ID, llmPro
|
||||
if err != nil || live == nil {
|
||||
t.Fatalf("restored task = %+v, %v", live, err)
|
||||
}
|
||||
if live.Name != "cold task" || !live.Paused {
|
||||
if live.Name != "cold task" || live.Remark != remark || !live.Paused {
|
||||
t.Fatalf("restored task metadata mismatch: %+v", live)
|
||||
}
|
||||
if err := d.QueryRow(`SELECT count(*) FROM exploration_nodes WHERE exploration_id=$1`, task.ExplorationID).Scan(&nodes); err != nil {
|
||||
|
||||
+7
-4
@@ -13,6 +13,7 @@ import (
|
||||
type Task struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"` // 可选任务名称;空=未命名
|
||||
Remark string `json:"remark"`
|
||||
CategoryID *int64 `json:"category_id,omitempty"`
|
||||
CategoryName string `json:"category_name,omitempty"`
|
||||
Pinned bool `json:"pinned"`
|
||||
@@ -360,13 +361,13 @@ func insertTaskLLMProfiles(tx *sql.Tx, taskID int64, profileIDs []int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
const taskCols = `id, COALESCE(name,''), category_id,
|
||||
const taskCols = `id, COALESCE(name,''), remark, category_id,
|
||||
COALESCE((SELECT category.name FROM task_categories category WHERE category.id=tasks.category_id),''),
|
||||
description, goal, exploration_id, status, paused, queued, queued_at, COALESCE(queue_mode,''), llm_profile_id, active_llm_profile_id, COALESCE(parent_ref,''), pinned_at, created_at, completed_at, COALESCE(timeout_seconds,0), COALESCE(plan_heartbeat_seconds,300), COALESCE(coverage_enabled,true), first_run_at, deadline_at`
|
||||
|
||||
func scanTask(sc interface{ Scan(...any) error }) (*Task, error) {
|
||||
var t Task
|
||||
if err := sc.Scan(&t.ID, &t.Name, &t.CategoryID, &t.CategoryName, &t.Description, &t.Goal, &t.ExplorationID, &t.Status, &t.Paused, &t.Queued, &t.QueuedAt, &t.QueueMode, &t.LLMProfileID, &t.ActiveLLMProfileID, &t.ParentRef, &t.PinnedAt, &t.CreatedAt, &t.CompletedAt, &t.TimeoutSeconds, &t.PlanHeartbeatSeconds, &t.CoverageEnabled, &t.FirstRunAt, &t.DeadlineAt); err != nil {
|
||||
if err := sc.Scan(&t.ID, &t.Name, &t.Remark, &t.CategoryID, &t.CategoryName, &t.Description, &t.Goal, &t.ExplorationID, &t.Status, &t.Paused, &t.Queued, &t.QueuedAt, &t.QueueMode, &t.LLMProfileID, &t.ActiveLLMProfileID, &t.ParentRef, &t.PinnedAt, &t.CreatedAt, &t.CompletedAt, &t.TimeoutSeconds, &t.PlanHeartbeatSeconds, &t.CoverageEnabled, &t.FirstRunAt, &t.DeadlineAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Pinned = t.PinnedAt != nil
|
||||
@@ -409,21 +410,23 @@ ORDER BY (pinned_at IS NOT NULL) DESC, pinned_at DESC NULLS LAST, id DESC`)
|
||||
// TaskPatch updates task list metadata without changing execution state.
|
||||
type TaskPatch struct {
|
||||
Name *string
|
||||
Remark *string
|
||||
Pinned *bool
|
||||
}
|
||||
|
||||
// UpdateTask applies a partial task name/pin mutation and returns the updated row.
|
||||
// UpdateTask applies a partial task name/remark/pin mutation and returns the updated row.
|
||||
// Re-pinning an already pinned task preserves its original position.
|
||||
func (d *DB) UpdateTask(id int64, patch TaskPatch) (*Task, error) {
|
||||
task, err := scanTask(d.QueryRow(`UPDATE tasks SET
|
||||
name = CASE WHEN $2::boolean THEN $3 ELSE name END,
|
||||
remark = CASE WHEN $5::boolean THEN $6 ELSE remark END,
|
||||
pinned_at = CASE
|
||||
WHEN $4::boolean IS NULL THEN pinned_at
|
||||
WHEN $4::boolean THEN COALESCE(pinned_at, now())
|
||||
ELSE NULL
|
||||
END
|
||||
WHERE id=$1 AND deleted_at IS NULL
|
||||
RETURNING `+taskCols, id, patch.Name != nil, patch.Name, patch.Pinned))
|
||||
RETURNING `+taskCols, id, patch.Name != nil, patch.Name, patch.Pinned, patch.Remark != nil, patch.Remark))
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
+21
-5
@@ -305,6 +305,8 @@ const (
|
||||
settingJudgeProfileID = "llm_judge_profile_id"
|
||||
settingJudgePrompt = "llm_judge_prompt"
|
||||
settingJudgeTimeoutSecs = "llm_judge_timeout_seconds"
|
||||
settingJudgeRetryCount = "llm_judge_retry_count"
|
||||
settingJudgeRetryIntervalMS = "llm_judge_retry_interval_ms"
|
||||
settingJudgeFailAction = "llm_judge_fail_action"
|
||||
settingJudgeAskTimeoutSecs = "llm_judge_ask_timeout_seconds"
|
||||
settingJudgeAskTimeoutAction = "llm_judge_ask_timeout_action"
|
||||
@@ -327,7 +329,9 @@ type JudgeConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ProfileID int64 `json:"profile_id"` // 0 = follow active/default
|
||||
Prompt string `json:"prompt"`
|
||||
TimeoutSeconds int `json:"timeout_seconds"`
|
||||
TimeoutSeconds int `json:"timeout_seconds"` // per attempt
|
||||
RetryCount int `json:"retry_count"` // additional attempts; 0 = disabled
|
||||
RetryIntervalMS int `json:"retry_interval_ms"`
|
||||
FailAction string `json:"fail_action"` // allow|ask|deny
|
||||
AskTimeoutSeconds int `json:"ask_timeout_seconds"`
|
||||
AskTimeoutAction string `json:"ask_timeout_action"` // allow|deny
|
||||
@@ -342,6 +346,8 @@ func (i *Interceptor) judgeConfig() JudgeConfig {
|
||||
Enabled: i.db.GetBool(settingJudgeEnabled, false),
|
||||
ProfileID: int64(i.getSettingInt(settingJudgeProfileID, 0)),
|
||||
TimeoutSeconds: i.getSettingInt(settingJudgeTimeoutSecs, defaultJudgeTimeoutSecs),
|
||||
RetryCount: min(max(i.getSettingInt(settingJudgeRetryCount, 0), 0), MaxJudgeRetryCount),
|
||||
RetryIntervalMS: min(max(i.getSettingInt(settingJudgeRetryIntervalMS, defaultJudgeRetryIntervalMS), 0), MaxJudgeRetryIntervalMS),
|
||||
FailAction: i.getSettingChoice(settingJudgeFailAction, defaultJudgeFailAction, "allow", "ask", "deny"),
|
||||
AskTimeoutSeconds: i.getSettingInt(settingJudgeAskTimeoutSecs, defaultJudgeAskTimeoutSecs),
|
||||
AskTimeoutAction: i.getSettingChoice(settingJudgeAskTimeoutAction, defaultJudgeAskTimeoutAction, "allow", "deny"),
|
||||
@@ -395,6 +401,9 @@ func (i *Interceptor) GetJudgeConfig() JudgeConfig { return i.judgeConfig() }
|
||||
// SetJudgeConfig persists the judge configuration. An empty Prompt clears the
|
||||
// override (the built-in template is used again).
|
||||
func (i *Interceptor) SetJudgeConfig(c JudgeConfig) error {
|
||||
if err := c.ValidateRetry(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := i.db.SetBool(settingJudgeEnabled, c.Enabled); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -413,6 +422,12 @@ func (i *Interceptor) SetJudgeConfig(c JudgeConfig) error {
|
||||
if err := i.db.SetSetting(settingJudgeTimeoutSecs, strconv.Itoa(c.TimeoutSeconds)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := i.db.SetSetting(settingJudgeRetryCount, strconv.Itoa(c.RetryCount)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := i.db.SetSetting(settingJudgeRetryIntervalMS, strconv.Itoa(c.RetryIntervalMS)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := i.db.SetSetting(settingJudgeFailAction, c.FailAction); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -432,7 +447,8 @@ func (i *Interceptor) SetJudgeConfig(c JudgeConfig) error {
|
||||
// returns (Decision, true) when the judge produced a terminal verdict, or
|
||||
// (Decision{}, false) when the fallback is disabled or not wired (caller then
|
||||
// keeps the current behavior: allow). On model error or an unparseable reply it
|
||||
// falls back to the configured FailAction. Ask verdicts carry the human-approval
|
||||
// retries up to RetryCount times, then falls back to the configured FailAction.
|
||||
// Ask verdicts carry the human-approval
|
||||
// timeout so the existing HandleAsk consumes them unchanged.
|
||||
func (i *Interceptor) Judge(ctx context.Context, tool string, arguments json.RawMessage) (Decision, bool) {
|
||||
cfg := i.judgeConfig()
|
||||
@@ -444,13 +460,13 @@ func (i *Interceptor) Judge(ctx context.Context, tool string, arguments json.Raw
|
||||
}
|
||||
|
||||
cctx := ctx
|
||||
cancel := func() {}
|
||||
if cfg.TimeoutSeconds > 0 {
|
||||
var cancel context.CancelFunc
|
||||
cctx, cancel = context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
input, contextErr := BuildReviewInput(cctx, tool, arguments)
|
||||
cancel() // Capture once; each model attempt gets its own timeout below.
|
||||
cfg.Prompt = EffectiveJudgePrompt(cfg.Prompt)
|
||||
var out Decision
|
||||
var err error
|
||||
@@ -461,7 +477,7 @@ func (i *Interceptor) Judge(ctx context.Context, tool string, arguments json.Raw
|
||||
out = Decision{Action: "ask", ModelFallback: true, Message: "审查上下文不完整,需要人工确认:" + contextErr.Error()}
|
||||
} else {
|
||||
modelInput, _ = json.Marshal(input)
|
||||
out, err = rv(cctx, cfg.ProfileID, cfg.Prompt, input)
|
||||
out, err = reviewWithRetry(ctx, cfg, rv, input)
|
||||
}
|
||||
if err != nil {
|
||||
out = Decision{ProfileID: out.ProfileID, ModelFallback: true, Action: cfg.FailAction, Message: "模型审批失败,按失败策略处理: " + err.Error()}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxJudgeRetryCount = 20
|
||||
MaxJudgeRetryIntervalMS = 3600_000
|
||||
defaultJudgeRetryIntervalMS = 1000
|
||||
)
|
||||
|
||||
// ValidateRetry rejects invalid settings before any judge configuration is saved.
|
||||
func (c JudgeConfig) ValidateRetry() error {
|
||||
if c.RetryCount < 0 || c.RetryCount > MaxJudgeRetryCount {
|
||||
return fmt.Errorf("retry_count 必须在 0 到 %d 之间", MaxJudgeRetryCount)
|
||||
}
|
||||
if c.RetryIntervalMS < 0 || c.RetryIntervalMS > MaxJudgeRetryIntervalMS {
|
||||
return fmt.Errorf("retry_interval_ms 必须在 0 到 %d 之间", MaxJudgeRetryIntervalMS)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// reviewWithRetry retries failed classifications, including invalid verdicts.
|
||||
// The captured input stays identical across attempts. A valid deny/ask verdict
|
||||
// is final, and parent cancellation interrupts both requests and the retry wait.
|
||||
// Provider-level connection/empty-response retries still run within each attempt.
|
||||
func reviewWithRetry(ctx context.Context, cfg JudgeConfig, rv Reviewer, input ReviewInput) (out Decision, err error) {
|
||||
for attempt := 0; attempt <= cfg.RetryCount; attempt++ {
|
||||
if ctx.Err() != nil {
|
||||
return out, ctx.Err()
|
||||
}
|
||||
if attempt > 0 && cfg.RetryIntervalMS > 0 {
|
||||
timer := time.NewTimer(time.Duration(cfg.RetryIntervalMS) * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return out, ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return out, ctx.Err()
|
||||
}
|
||||
attemptCtx := ctx
|
||||
cancel := func() {}
|
||||
if cfg.TimeoutSeconds > 0 {
|
||||
attemptCtx, cancel = context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second)
|
||||
}
|
||||
out, err = rv(attemptCtx, cfg.ProfileID, cfg.Prompt, input)
|
||||
if attemptCtx.Err() != nil {
|
||||
err = attemptCtx.Err()
|
||||
}
|
||||
cancel()
|
||||
if err == nil {
|
||||
switch out.Action {
|
||||
case "allow", "ask", "deny":
|
||||
return out, nil
|
||||
default:
|
||||
err = fmt.Errorf("模型输出无法解析")
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func retryTestInterceptor(t *testing.T, settings map[string]string) *Interceptor {
|
||||
t.Helper()
|
||||
d, err := sql.Open("sqlite", ":memory:")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
if _, err := d.Exec(`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for key, value := range settings {
|
||||
if _, err := d.Exec(`INSERT INTO settings(key,value) VALUES (?,?)`, key, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return New(&db.DB{DB: d})
|
||||
}
|
||||
|
||||
func TestJudgeRetryConfigDefaultsAndBounds(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
settings map[string]string
|
||||
count, interval int
|
||||
}{
|
||||
{"legacy", nil, 0, 1000},
|
||||
{"configured", map[string]string{settingJudgeRetryCount: "3", settingJudgeRetryIntervalMS: "25"}, 3, 25},
|
||||
{"immediate", map[string]string{settingJudgeRetryCount: "1", settingJudgeRetryIntervalMS: "0"}, 1, 0},
|
||||
{"malformed", map[string]string{settingJudgeRetryCount: "bad", settingJudgeRetryIntervalMS: "bad"}, 0, 1000},
|
||||
{"negative", map[string]string{settingJudgeRetryCount: "-1", settingJudgeRetryIntervalMS: "-1"}, 0, 0},
|
||||
{"excessive", map[string]string{settingJudgeRetryCount: "999", settingJudgeRetryIntervalMS: "999999999"}, 20, 3600000},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := retryTestInterceptor(t, tc.settings).GetJudgeConfig()
|
||||
if cfg.RetryCount != tc.count || cfg.RetryIntervalMS != tc.interval {
|
||||
t.Fatalf("config=%+v", cfg)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeRetriesBeforeApplyingFailurePolicy(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, failAction, verdict string
|
||||
failures, wantCalls int
|
||||
wantAction string
|
||||
wantFallback bool
|
||||
}{
|
||||
{"recover", "deny", "allow", 2, 3, "allow", false},
|
||||
{"valid_deny_is_final", "allow", "deny", 0, 1, "deny", false},
|
||||
{"valid_ask_is_final", "allow", "ask", 0, 1, "ask", false},
|
||||
{"exhaust_allow", "allow", "allow", 9, 3, "allow", true},
|
||||
{"exhaust_ask", "ask", "allow", 9, 3, "ask", true},
|
||||
{"exhaust_deny", "deny", "allow", 9, 3, "deny", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
i := retryTestInterceptor(t, map[string]string{
|
||||
settingJudgeEnabled: "true", settingJudgeRetryCount: "2", settingJudgeRetryIntervalMS: "0", settingJudgeFailAction: tc.failAction,
|
||||
})
|
||||
calls := 0
|
||||
var first ReviewInput
|
||||
i.SetReviewer(func(ctx context.Context, id int64, prompt string, input ReviewInput) (Decision, error) {
|
||||
calls++
|
||||
if ctx.Err() != nil || prompt == "" {
|
||||
t.Fatal("invalid request context")
|
||||
}
|
||||
if calls == 1 {
|
||||
first = input
|
||||
} else if !reflect.DeepEqual(input, first) {
|
||||
t.Fatal("review input changed on retry")
|
||||
}
|
||||
out := Decision{Action: tc.verdict, ProfileID: 42, Message: "review result"}
|
||||
if calls <= tc.failures {
|
||||
return out, errors.New("temporary model failure")
|
||||
}
|
||||
return out, nil
|
||||
})
|
||||
got, ok := i.Judge(t.Context(), "Bash", json.RawMessage(`{"command":"echo ok"}`))
|
||||
if !ok || calls != tc.wantCalls || got.Action != tc.wantAction || got.ModelFallback != tc.wantFallback || got.ProfileID != 42 {
|
||||
t.Fatalf("calls=%d decision=%+v ok=%v", calls, got, ok)
|
||||
}
|
||||
if got.RuleID != 0 || len(got.ModelInput) == 0 || got.ModelInputDigest == "" || got.ConfigDigest == "" {
|
||||
t.Fatalf("missing audit data: %+v", got)
|
||||
}
|
||||
if got.Action == "ask" && (!got.TimeoutEnabled || got.TimeoutSeconds != 300 || got.TimeoutAction != "deny") {
|
||||
t.Fatal("human approval timeout lost")
|
||||
}
|
||||
if tc.wantFallback && !strings.Contains(got.Message, "temporary model failure") {
|
||||
t.Fatal("last failure lost")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeRetriesInvalidVerdict(t *testing.T) {
|
||||
for _, invalid := range []string{"", "invalid"} {
|
||||
calls := 0
|
||||
out, err := reviewWithRetry(t.Context(), JudgeConfig{RetryCount: 1}, func(context.Context, int64, string, ReviewInput) (Decision, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return Decision{Action: invalid}, nil
|
||||
}
|
||||
return Decision{Action: "deny"}, nil
|
||||
}, ReviewInput{})
|
||||
if err != nil || out.Action != "deny" || calls != 2 {
|
||||
t.Fatalf("calls=%d out=%+v err=%v", calls, out, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeLegacyConfigDoesNotRetry(t *testing.T) {
|
||||
i := retryTestInterceptor(t, map[string]string{settingJudgeEnabled: "true", settingJudgeFailAction: "deny"})
|
||||
calls := 0
|
||||
i.SetReviewer(func(context.Context, int64, string, ReviewInput) (Decision, error) {
|
||||
calls++
|
||||
return Decision{}, errors.New("failed")
|
||||
})
|
||||
got, _ := i.Judge(t.Context(), "Bash", json.RawMessage(`{"command":"echo ok"}`))
|
||||
if calls != 1 || got.Action != "deny" || !got.ModelFallback {
|
||||
t.Fatalf("calls=%d out=%+v", calls, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeRetryTimeoutGetsFreshContext(t *testing.T) {
|
||||
calls := 0
|
||||
var previous context.Context
|
||||
out, err := reviewWithRetry(t.Context(), JudgeConfig{RetryCount: 1, TimeoutSeconds: 1}, func(ctx context.Context, _ int64, _ string, _ ReviewInput) (Decision, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
previous = ctx
|
||||
<-ctx.Done()
|
||||
return Decision{}, ctx.Err()
|
||||
}
|
||||
if previous.Err() != context.DeadlineExceeded || ctx.Err() != nil {
|
||||
t.Fatal("retry reused expired context")
|
||||
}
|
||||
if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) < 500*time.Millisecond {
|
||||
t.Fatal("retry has no fresh timeout")
|
||||
}
|
||||
return Decision{Action: "allow"}, nil
|
||||
}, ReviewInput{})
|
||||
if calls != 2 || err != nil || out.Action != "allow" {
|
||||
t.Fatalf("calls=%d out=%+v err=%v", calls, out, err)
|
||||
}
|
||||
if previous.Err() == nil {
|
||||
t.Fatal("attempt context was not released")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeRetryCancellationInterruptsWait(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
started := make(chan struct{})
|
||||
done := make(chan error, 1)
|
||||
calls := 0
|
||||
go func() {
|
||||
_, err := reviewWithRetry(ctx, JudgeConfig{RetryCount: 20, RetryIntervalMS: 3600000}, func(context.Context, int64, string, ReviewInput) (Decision, error) {
|
||||
calls++
|
||||
close(started)
|
||||
return Decision{}, errors.New("failed")
|
||||
}, ReviewInput{})
|
||||
done <- err
|
||||
}()
|
||||
<-started
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) || calls != 1 {
|
||||
t.Fatalf("calls=%d err=%v", calls, err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("cancellation did not interrupt retry wait")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeRetryDoesNotCallCanceledOrDisabledReviewer(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
_, err := reviewWithRetry(ctx, JudgeConfig{RetryCount: 2}, func(context.Context, int64, string, ReviewInput) (Decision, error) {
|
||||
t.Fatal("called after cancellation")
|
||||
return Decision{}, nil
|
||||
}, ReviewInput{})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
i := retryTestInterceptor(t, nil)
|
||||
i.SetReviewer(func(context.Context, int64, string, ReviewInput) (Decision, error) {
|
||||
t.Fatal("called disabled reviewer")
|
||||
return Decision{}, nil
|
||||
})
|
||||
if _, ok := i.Judge(t.Context(), "Bash", json.RawMessage(`{}`)); ok {
|
||||
t.Fatal("disabled judge returned verdict")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeRetryWaitsBetweenFailures(t *testing.T) {
|
||||
var first time.Time
|
||||
calls := 0
|
||||
_, err := reviewWithRetry(t.Context(), JudgeConfig{RetryCount: 1, RetryIntervalMS: 20}, func(context.Context, int64, string, ReviewInput) (Decision, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
first = time.Now()
|
||||
return Decision{}, errors.New("failed")
|
||||
}
|
||||
if time.Since(first) < 20*time.Millisecond {
|
||||
t.Fatal("retry skipped configured interval")
|
||||
}
|
||||
return Decision{Action: "allow"}, nil
|
||||
}, ReviewInput{})
|
||||
if err != nil || calls != 2 {
|
||||
t.Fatalf("calls=%d err=%v", calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeInvalidArgumentsDoNotCallReviewer(t *testing.T) {
|
||||
i := retryTestInterceptor(t, map[string]string{settingJudgeEnabled: "true", settingJudgeRetryCount: "2"})
|
||||
i.SetReviewer(func(context.Context, int64, string, ReviewInput) (Decision, error) {
|
||||
t.Fatal("invalid input must go straight to human review")
|
||||
return Decision{}, nil
|
||||
})
|
||||
got, ok := i.Judge(t.Context(), "Bash", json.RawMessage(`{broken`))
|
||||
if !ok || got.Action != "ask" || !got.ModelFallback {
|
||||
t.Fatalf("out=%+v ok=%v", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeRejectsInvalidRetryBeforeWritingSettings(t *testing.T) {
|
||||
for _, cfg := range []JudgeConfig{{RetryCount: -1}, {RetryCount: 21}, {RetryIntervalMS: -1}, {RetryIntervalMS: 3600001}} {
|
||||
if err := New(nil).SetJudgeConfig(cfg); err == nil {
|
||||
t.Fatalf("accepted invalid retry: %+v", cfg)
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
-11
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -47,20 +48,50 @@ type Asset struct {
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
// NewClient 构造一个只认 GitHub 域名的 HTTP 客户端。proxy 为空则直连。
|
||||
//
|
||||
// 刻意不复用默认 Transport:升级链路必须强制走 TLS 且校验证书,不能被别处
|
||||
// 设置的 InsecureSkipVerify 之类影响到。
|
||||
func NewClient(proxy string) *http.Client {
|
||||
// ParseProxy validates an optional update proxy without including credentials in errors.
|
||||
func ParseProxy(raw string) (*url.URL, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("代理地址格式无效")
|
||||
}
|
||||
switch u.Scheme {
|
||||
case "http", "https", "socks5", "socks5h":
|
||||
default:
|
||||
return nil, fmt.Errorf("代理协议须为 http、https、socks5 或 socks5h")
|
||||
}
|
||||
if u.Hostname() == "" || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, fmt.Errorf("代理地址须包含主机,且不能包含路径、查询或片段")
|
||||
}
|
||||
if port := u.Port(); port != "" {
|
||||
n, err := strconv.Atoi(port)
|
||||
if err != nil || n < 1 || n > 65535 {
|
||||
return nil, fmt.Errorf("代理端口须在 1–65535 之间")
|
||||
}
|
||||
} else if strings.HasSuffix(u.Host, ":") {
|
||||
return nil, fmt.Errorf("代理端口不能为空")
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// NewClient validates the proxy before opening any connection. Empty means direct,
|
||||
// regardless of HTTP_PROXY / HTTPS_PROXY in the process environment.
|
||||
func NewClient(proxy string) (*http.Client, error) {
|
||||
pu, err := ParseProxy(proxy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tr := &http.Transport{
|
||||
ForceAttemptHTTP2: true,
|
||||
TLSHandshakeTimeout: 15 * time.Second,
|
||||
}
|
||||
if p := strings.TrimSpace(proxy); p != "" {
|
||||
if pu, err := url.Parse(p); err == nil {
|
||||
tr.Proxy = http.ProxyURL(pu)
|
||||
}
|
||||
if pu != nil {
|
||||
tr.Proxy = http.ProxyURL(pu)
|
||||
}
|
||||
|
||||
return &http.Client{
|
||||
Transport: tr,
|
||||
Timeout: 30 * time.Minute, // 下载整包,不能按请求级超时卡死
|
||||
@@ -70,7 +101,7 @@ func NewClient(proxy string) *http.Client {
|
||||
}
|
||||
return checkURL(req.URL)
|
||||
},
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
|
||||
// checkURL 强制 https + 域名白名单。
|
||||
@@ -98,7 +129,7 @@ func FetchLatest(ctx context.Context, c *http.Client) (*Release, error) {
|
||||
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("访问 GitHub 失败(可在系统设置里配置全局代理): %w", err)
|
||||
return nil, fmt.Errorf("访问 GitHub 失败(可在版本与更新中配置更新代理): %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package selfupdate
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestProxyValidation(t *testing.T) {
|
||||
for _, raw := range []string{"", " ", "http://127.0.0.1:7897", "https://user:[email protected]:443", "socks5://localhost:1080", "socks5h://[::1]:1080"} {
|
||||
if _, err := NewClient(raw); err != nil {
|
||||
t.Errorf("valid proxy rejected: %v", err)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{"127.0.0.1:7897", "ftp://proxy", "http://", "http://:7897", "http://proxy:0", "http://proxy:65536", "http://proxy:", "http://proxy/path", "http://proxy?x=1", "http://proxy#fragment", "http://user:secret@proxy:bad"} {
|
||||
if _, err := NewClient(raw); err == nil {
|
||||
t.Error("invalid proxy accepted")
|
||||
} else if strings.Contains(err.Error(), "secret") {
|
||||
t.Fatal("proxy validation leaked password")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectClientIgnoresEnvironmentProxy(t *testing.T) {
|
||||
t.Setenv("HTTP_PROXY", "http://127.0.0.1:1")
|
||||
t.Setenv("HTTPS_PROXY", "http://127.0.0.1:1")
|
||||
c, err := NewClient("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.CloseIdleConnections()
|
||||
transport := c.Transport.(*http.Transport)
|
||||
if transport.Proxy != nil {
|
||||
t.Fatal("direct client must not consult environment proxies")
|
||||
}
|
||||
if transport.TLSClientConfig != nil && transport.TLSClientConfig.InsecureSkipVerify {
|
||||
t.Fatal("TLS verification disabled")
|
||||
}
|
||||
}
|
||||
|
||||
// Exercise real HTTP CONNECT routing for metadata, checksum and archive requests.
|
||||
// The proxy returns a sentinel error; none of these requests may fall back direct.
|
||||
func TestUpdateRequestsUseProxy(t *testing.T) {
|
||||
var hosts []string
|
||||
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodConnect {
|
||||
t.Errorf("expected CONNECT, got %s", r.Method)
|
||||
}
|
||||
hosts = append(hosts, r.Host)
|
||||
http.Error(w, "test proxy refuses tunnel", http.StatusBadGateway)
|
||||
}))
|
||||
defer proxy.Close()
|
||||
c, err := NewClient(proxy.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.CloseIdleConnections()
|
||||
if _, err := FetchLatest(t.Context(), c); err == nil {
|
||||
t.Fatal("expected proxy error")
|
||||
}
|
||||
for _, name := range []string{"SHA256SUMS", "artex-0.3.21-linux-arm64.zip"} {
|
||||
if _, err := get(t.Context(), c, "https://github.com/"+Repo+"/releases/download/v0.3.21/"+name); err == nil {
|
||||
t.Fatal("expected proxy error")
|
||||
}
|
||||
}
|
||||
if len(hosts) != 3 || hosts[0] != "api.github.com:443" || hosts[1] != "github.com:443" || hosts[2] != "github.com:443" {
|
||||
t.Fatalf("unexpected proxy requests: %v", hosts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientRejectsUnsafeRedirect(t *testing.T) {
|
||||
target := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "https://example.com/untrusted", http.StatusFound)
|
||||
}))
|
||||
defer target.Close()
|
||||
c, _ := NewClient("")
|
||||
defer c.CloseIdleConnections()
|
||||
c.Transport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: target.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs}
|
||||
resp, err := c.Get(target.URL)
|
||||
if resp != nil {
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), "拒绝非 GitHub") {
|
||||
t.Fatalf("unsafe redirect accepted: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,11 @@ func Stage(ctx context.Context, c *http.Client, rel *Release, currentVersion str
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return stageAt(ctx, c, rel, currentVersion, prog, p)
|
||||
}
|
||||
|
||||
// stageAt keeps downloads and executable replacement testable in an isolated directory.
|
||||
func stageAt(ctx context.Context, c *http.Client, rel *Release, currentVersion string, prog Progress, p Paths) error {
|
||||
if err := checkWritable(p.Dir); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package selfupdate
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestStageDownloadAndVerify(t *testing.T) {
|
||||
requireUnix(t)
|
||||
var archive bytes.Buffer
|
||||
zw := zip.NewWriter(&archive)
|
||||
f, err := zw.Create("artex")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Write([]byte("#!/bin/sh\necho new-version\nexit 0\n"))
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, corrupt := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("corrupt=%v", corrupt), func(t *testing.T) {
|
||||
p := testPaths(t)
|
||||
fakeBin(t, p.Current, "old-version", 0)
|
||||
name := AssetName("v0.3.21", runtime.GOOS, runtime.GOARCH)
|
||||
rel := &Release{TagName: "v0.3.21", Assets: []Asset{
|
||||
{Name: name, URL: "https://github.com/" + name, Size: int64(archive.Len())},
|
||||
{Name: sumsAsset, URL: "https://github.com/SHA256SUMS"},
|
||||
}}
|
||||
sum := fmt.Sprintf("%x", sha256.Sum256(archive.Bytes()))
|
||||
if corrupt {
|
||||
sum = strings.Repeat("0", 64)
|
||||
}
|
||||
client := &http.Client{Transport: releaseTransport(func(r *http.Request) (*http.Response, error) {
|
||||
body := archive.Bytes()
|
||||
if strings.HasSuffix(r.URL.Path, sumsAsset) {
|
||||
body = []byte(sum + " " + name + "\n")
|
||||
}
|
||||
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewReader(body))}, nil
|
||||
})}
|
||||
var phases []Phase
|
||||
err := stageAt(t.Context(), client, rel, "0.3.20", func(p Phase, _ int, _ string) { phases = append(phases, p) }, p)
|
||||
if !strings.Contains(readAll(t, p.Current), "old-version") {
|
||||
t.Fatal("running binary changed before bootstrap")
|
||||
}
|
||||
if corrupt {
|
||||
if err == nil || !strings.Contains(err.Error(), "SHA256") {
|
||||
t.Fatalf("corrupt archive accepted: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(p.New); !os.IsNotExist(err) {
|
||||
t.Fatal("corrupt binary staged")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(phases) == 0 || phases[len(phases)-1] != PhaseStaged {
|
||||
t.Fatalf("phases: %v", phases)
|
||||
}
|
||||
if !strings.Contains(readAll(t, p.New), "new-version") {
|
||||
t.Fatal("new binary not staged")
|
||||
}
|
||||
if m, ok := readMarker(p.Marker); !ok || m.From != "0.3.20" || m.To != "0.3.21" {
|
||||
t.Fatalf("invalid rollback marker: %+v", m)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+32
-21
@@ -15,6 +15,7 @@ type scheduleWindow struct {
|
||||
active bool
|
||||
complete bool
|
||||
key string
|
||||
start time.Time
|
||||
nextStart *time.Time
|
||||
nextEnd *time.Time
|
||||
}
|
||||
@@ -81,7 +82,7 @@ func evaluateScheduleWindow(s *db.TaskSchedule, now time.Time) scheduleWindow {
|
||||
if s.EndDate != "" {
|
||||
key += ":" + s.EndDate
|
||||
}
|
||||
w := scheduleWindow{active: active, complete: complete, key: key, nextEnd: end}
|
||||
w := scheduleWindow{active: active, complete: complete, key: key, start: start, nextEnd: end}
|
||||
if now.Before(start) {
|
||||
w.key = ""
|
||||
w.nextStart = &start
|
||||
@@ -109,6 +110,7 @@ func evaluateScheduleWindow(s *db.TaskSchedule, now time.Time) scheduleWindow {
|
||||
start, end := windowBounds(day, s, loc)
|
||||
if !now.Before(start) && (end == nil || now.Before(*end)) {
|
||||
w.active = true
|
||||
w.start = start
|
||||
w.key = "active:" + start.Format("2006-01-02T15:04")
|
||||
w.nextEnd = end
|
||||
// Do not pause between adjacent windows (e.g. Saturday + Sunday full days).
|
||||
@@ -124,6 +126,34 @@ func evaluateScheduleWindow(s *db.TaskSchedule, now time.Time) scheduleWindow {
|
||||
return w
|
||||
}
|
||||
|
||||
// evaluateRuntimeScheduleWindow applies startup/manual state to a calendar
|
||||
// window. A plan's creation date says nothing about when its next window opens.
|
||||
func evaluateRuntimeScheduleWindow(item *db.TaskSchedule, now, startedAt time.Time) scheduleWindow {
|
||||
w := evaluateScheduleWindow(item, now)
|
||||
if !item.Enabled || item.Status == "completed" {
|
||||
w.active = false
|
||||
return w
|
||||
}
|
||||
// Only suppress an unrecorded window that was already open at startup.
|
||||
// An explicit configuration edit clears LastWindowKey and advances UpdatedAt;
|
||||
// allow such edits (as well as newly-created plans) to enter the current window.
|
||||
if w.active && item.LastWindowKey == "" && item.CreatedAt.Before(startedAt) &&
|
||||
!item.UpdatedAt.After(startedAt) && !w.start.IsZero() && w.start.Before(startedAt) {
|
||||
w.active = false
|
||||
w.key = "missed:" + w.key
|
||||
}
|
||||
if strings.HasPrefix(item.LastWindowKey, "missed:") && item.LastWindowKey == "missed:"+w.key {
|
||||
w.active = false
|
||||
w.key = item.LastWindowKey
|
||||
}
|
||||
if item.LastWindowKey == "manual" && !w.active {
|
||||
w.active = true
|
||||
w.key = "manual"
|
||||
w.complete = false
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func (sc *Scheduler) fireTaskSchedules() {
|
||||
sc.s.scheduleMu.Lock()
|
||||
defer sc.s.scheduleMu.Unlock()
|
||||
@@ -135,26 +165,7 @@ func (sc *Scheduler) fireTaskSchedules() {
|
||||
open := map[int64]bool{}
|
||||
windows := map[int64]scheduleWindow{}
|
||||
for _, item := range items {
|
||||
w := evaluateScheduleWindow(item, now)
|
||||
// A service restart must not replay a window that started while the
|
||||
// service was down. Newly-created schedules are allowed to enter an
|
||||
// already-open window because their creation is an explicit user action.
|
||||
if w.active && item.LastWindowKey == "" && item.CreatedAt.Before(sc.startedAt) {
|
||||
w.active = false
|
||||
w.key = "missed:" + w.key
|
||||
}
|
||||
if strings.HasPrefix(item.LastWindowKey, "missed:") && item.LastWindowKey == "missed:"+w.key {
|
||||
w.active = false
|
||||
w.key = item.LastWindowKey
|
||||
}
|
||||
if item.LastWindowKey == "manual" && !w.active {
|
||||
w.active = true
|
||||
w.key = "manual"
|
||||
w.complete = false
|
||||
}
|
||||
if !item.Enabled || item.Status == "completed" {
|
||||
w.active = false
|
||||
}
|
||||
w := evaluateRuntimeScheduleWindow(item, now, sc.startedAt)
|
||||
windows[item.ID] = w
|
||||
if w.active {
|
||||
for _, id := range item.TaskIDs {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func calendarTestTime(s string) time.Time {
|
||||
v, err := time.Parse(time.RFC3339, s)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func TestRuntimeScheduleStartupBoundaries(t *testing.T) {
|
||||
old := calendarTestTime("2026-10-15T12:11:17+08:00")
|
||||
for _, tc := range []struct {
|
||||
name, now, boot string
|
||||
change func(*db.TaskSchedule)
|
||||
active, missed bool
|
||||
}{
|
||||
{"future weekday after restart", "2026-10-16T18:00:06+08:00", "2026-10-15T19:36:05+08:00", nil, true, false},
|
||||
{"window starts exactly with service", "2026-10-16T18:00:05+08:00", "2026-10-16T18:00:00+08:00", nil, true, false},
|
||||
{"already open before restart", "2026-10-16T18:10:05+08:00", "2026-10-16T18:10:00+08:00", nil, false, true},
|
||||
{"new plan inside current window", "2026-10-16T18:12:00+08:00", "2026-10-16T18:10:00+08:00", func(s *db.TaskSchedule) { s.CreatedAt = calendarTestTime("2026-10-16T18:11:00+08:00") }, true, false},
|
||||
{"explicit edit inside current window", "2026-10-16T18:12:00+08:00", "2026-10-16T18:10:00+08:00", func(s *db.TaskSchedule) { s.UpdatedAt = calendarTestTime("2026-10-16T18:11:00+08:00") }, true, false},
|
||||
{"recorded window survives restart", "2026-10-16T18:12:00+08:00", "2026-10-16T18:10:00+08:00", func(s *db.TaskSchedule) { s.LastWindowKey = "active:2026-10-16T18:00" }, true, false},
|
||||
{"same missed window remains blocked", "2026-10-16T18:12:00+08:00", "2026-10-16T18:10:00+08:00", func(s *db.TaskSchedule) {
|
||||
s.LastWindowKey = "missed:active:2026-10-16T18:00"
|
||||
s.UpdatedAt = calendarTestTime("2026-10-16T18:11:00+08:00")
|
||||
}, false, true},
|
||||
{"previous missed window does not block next", "2026-10-19T18:00:05+08:00", "2026-10-15T19:36:05+08:00", func(s *db.TaskSchedule) { s.LastWindowKey = "missed:active:2026-10-16T18:00" }, true, false},
|
||||
{"disabled plan does not acquire missed state", "2026-10-16T18:12:00+08:00", "2026-10-16T18:10:00+08:00", func(s *db.TaskSchedule) { s.Enabled = false }, false, false},
|
||||
{"manual run outside window", "2026-10-16T17:00:00+08:00", "2026-10-15T19:36:05+08:00", func(s *db.TaskSchedule) { s.LastWindowKey = "manual" }, true, false},
|
||||
{"once future boundary", "2026-10-16T18:00:05+08:00", "2026-10-15T19:36:05+08:00", func(s *db.TaskSchedule) { s.ScheduleType = "once"; s.RunDate = "2026-10-16" }, true, false},
|
||||
{"once missed boundary", "2026-10-16T18:12:00+08:00", "2026-10-16T18:10:00+08:00", func(s *db.TaskSchedule) { s.ScheduleType = "once"; s.RunDate = "2026-10-16" }, false, true},
|
||||
{"completed plan remains stopped", "2026-10-16T18:12:00+08:00", "2026-10-15T19:36:05+08:00", func(s *db.TaskSchedule) { s.Status = "completed" }, false, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := &db.TaskSchedule{Enabled: true, ScheduleType: "weekly", TimezoneMode: "beijing", Weekdays: []int{1, 2, 3, 4, 5}, StartTime: "18:00:00", EndTime: "00:00:00", CreatedAt: old, UpdatedAt: old}
|
||||
if tc.change != nil {
|
||||
tc.change(s)
|
||||
}
|
||||
w := evaluateRuntimeScheduleWindow(s, calendarTestTime(tc.now), calendarTestTime(tc.boot))
|
||||
if w.active != tc.active || strings.HasPrefix(w.key, "missed:") != tc.missed {
|
||||
t.Fatalf("active=%v key=%q, want active=%v missed=%v", w.active, w.key, tc.active, tc.missed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeScheduleWeekendAndAdjacentWindows(t *testing.T) {
|
||||
old := calendarTestTime("2026-10-15T12:11:37+08:00")
|
||||
boot := calendarTestTime("2026-10-16T18:20:00+08:00")
|
||||
weekend := &db.TaskSchedule{Enabled: true, ScheduleType: "weekly", TimezoneMode: "beijing", Weekdays: []int{6, 7}, StartTime: "00:00:00", EndTime: "00:00:00", CreatedAt: old, UpdatedAt: old}
|
||||
for _, at := range []string{"2026-10-17T00:00:00+08:00", "2026-10-18T00:00:00+08:00", "2026-10-18T23:59:59+08:00"} {
|
||||
w := evaluateRuntimeScheduleWindow(weekend, calendarTestTime(at), boot)
|
||||
if !w.active {
|
||||
t.Fatalf("weekend unexpectedly inactive at %s: %+v", at, w)
|
||||
}
|
||||
}
|
||||
weekday := &db.TaskSchedule{Enabled: true, ScheduleType: "weekly", TimezoneMode: "beijing", Weekdays: []int{1, 2, 3, 4, 5}, StartTime: "00:00:00", EndTime: "09:00:00", CreatedAt: old, UpdatedAt: old}
|
||||
at := calendarTestTime("2026-10-19T00:00:00+08:00")
|
||||
if evaluateRuntimeScheduleWindow(weekend, at, boot).active || !evaluateRuntimeScheduleWindow(weekday, at, boot).active {
|
||||
t.Fatal("weekend-to-weekday boundary must keep the shared task union open")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeScheduleUsesBeijingWindowAcrossTimezones(t *testing.T) {
|
||||
s := &db.TaskSchedule{Enabled: true, ScheduleType: "weekly", TimezoneMode: "beijing", Weekdays: []int{5}, StartTime: "18:00:00", EndTime: "00:00:00", CreatedAt: calendarTestTime("2026-10-15T12:00:00+08:00")}
|
||||
w := evaluateRuntimeScheduleWindow(s, calendarTestTime("2026-10-16T06:00:05-04:00"), calendarTestTime("2026-10-15T07:36:05-04:00"))
|
||||
if !w.active || w.key != "active:2026-10-16T18:00" {
|
||||
t.Fatalf("unexpected timezone result: %+v", w)
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ type TaskDTO struct {
|
||||
ID string `json:"id"`
|
||||
ExplorationID int64 `json:"exploration_id"`
|
||||
Name string `json:"name"` // 可选任务名称;空=未命名
|
||||
Remark string `json:"remark"`
|
||||
CategoryID *int64 `json:"category_id,omitempty"`
|
||||
CategoryName string `json:"category_name,omitempty"`
|
||||
Pinned bool `json:"pinned"`
|
||||
@@ -115,6 +116,7 @@ func taskDTO(t *Task, status string) TaskDTO {
|
||||
ID: t.ID,
|
||||
ExplorationID: t.ExpID,
|
||||
Name: lifecycle.Name,
|
||||
Remark: lifecycle.Remark,
|
||||
CategoryID: lifecycle.CategoryID,
|
||||
CategoryName: lifecycle.CategoryName,
|
||||
Pinned: lifecycle.PinnedAt > 0,
|
||||
|
||||
@@ -474,6 +474,10 @@ func (s *Server) interceptSetJudgeConfig(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 400, "incomplete_script_action 必须是 ask 或 model")
|
||||
return
|
||||
}
|
||||
if err := req.ValidateRetry(); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.m.interceptor.SetJudgeConfig(req); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func TestJudgeConfigIncompleteScriptDefaultAndOverride(t *testing.T) {
|
||||
@@ -20,7 +25,7 @@ func TestJudgeConfigIncompleteScriptDefaultAndOverride(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = pg.Close() })
|
||||
keys := []string{"llm_judge_enabled", "llm_judge_profile_id", "llm_judge_prompt", "llm_judge_timeout_seconds", "llm_judge_fail_action", "llm_judge_ask_timeout_seconds", "llm_judge_ask_timeout_action", "llm_judge_incomplete_script_action"}
|
||||
keys := []string{"llm_judge_enabled", "llm_judge_profile_id", "llm_judge_prompt", "llm_judge_timeout_seconds", "llm_judge_retry_count", "llm_judge_retry_interval_ms", "llm_judge_fail_action", "llm_judge_ask_timeout_seconds", "llm_judge_ask_timeout_action", "llm_judge_incomplete_script_action"}
|
||||
for _, key := range keys {
|
||||
value, exists, err := pg.GetSetting(key)
|
||||
if err != nil {
|
||||
@@ -47,14 +52,80 @@ func TestJudgeConfigIncompleteScriptDefaultAndOverride(t *testing.T) {
|
||||
{`,"incomplete_script_action":"model"`, "model", 200},
|
||||
{`,"incomplete_script_action":"invalid"`, "model", 400},
|
||||
} {
|
||||
req := httptest.NewRequest("PUT", "/api/intercept/judge-config", strings.NewReader(`{"fail_action":"allow","ask_timeout_action":"deny"`+tc.option+`}`))
|
||||
req := httptest.NewRequest("PUT", "/api/intercept/judge-config", strings.NewReader(`{"fail_action":"allow","ask_timeout_action":"deny","retry_count":2,"retry_interval_ms":17`+tc.option+`}`))
|
||||
w := httptest.NewRecorder()
|
||||
s.interceptSetJudgeConfig(w, req)
|
||||
if w.Code != tc.code {
|
||||
t.Fatalf("option=%s status=%d body=%s", tc.option, w.Code, w.Body.String())
|
||||
}
|
||||
if cfg := s.m.interceptor.GetJudgeConfig(); cfg.RetryCount != 2 || cfg.RetryIntervalMS != 17 {
|
||||
t.Fatalf("retry configuration not persisted: %+v", cfg)
|
||||
}
|
||||
if got := s.m.interceptor.GetJudgeConfig().IncompleteScriptAction; got != tc.want {
|
||||
t.Fatalf("option=%s action=%s want=%s", tc.option, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestJudgeConfigRejectsInvalidRetryBeforeSaving(t *testing.T) {
|
||||
// No manager is needed: invalid input must be rejected before database writes.
|
||||
s := &Server{}
|
||||
for _, fields := range []string{
|
||||
`"retry_count":-1`, `"retry_count":21`, `"retry_count":1.5`,
|
||||
`"retry_interval_ms":-1`, `"retry_interval_ms":3600001`, `"retry_interval_ms":1.5`,
|
||||
} {
|
||||
t.Run(fields, func(t *testing.T) {
|
||||
req := httptest.NewRequest("PUT", "/api/intercept/judge", strings.NewReader(`{"fail_action":"allow","ask_timeout_action":"deny",`+fields+`}`))
|
||||
w := httptest.NewRecorder()
|
||||
s.interceptSetJudgeConfig(w, req)
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var judgeConfigSQLiteNow sync.Once
|
||||
|
||||
func TestJudgeConfigRetryRoundTrip(t *testing.T) {
|
||||
// Exercise production settings SQL without requiring an external PG service.
|
||||
judgeConfigSQLiteNow.Do(func() {
|
||||
sqlite.MustRegisterDeterministicScalarFunction("now", 0, func(*sqlite.FunctionContext, []driver.Value) (driver.Value, error) {
|
||||
return "2026-01-01 00:00:00", nil
|
||||
})
|
||||
})
|
||||
sqldb, err := sql.Open("sqlite", ":memory:")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sqldb.Close() })
|
||||
if _, err := sqldb.Exec(`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT, updated_at TEXT)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pg := &db.DB{DB: sqldb}
|
||||
s := &Server{m: &Manager{pg: pg, interceptor: intercept.New(pg)}}
|
||||
for _, tc := range []struct{ count, interval int }{{2, 17}, {20, 3600000}, {0, 0}} {
|
||||
cfg := s.m.interceptor.GetJudgeConfig()
|
||||
cfg.RetryCount, cfg.RetryIntervalMS = tc.count, tc.interval
|
||||
body, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
s.interceptSetJudgeConfig(w, httptest.NewRequest("PUT", "/api/intercept/judge", strings.NewReader(string(body))))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
// Construct a fresh interceptor to prove persistence, rather than cache reuse.
|
||||
s.m.interceptor = intercept.New(pg)
|
||||
w = httptest.NewRecorder()
|
||||
s.interceptGetJudgeConfig(w, httptest.NewRequest("GET", "/api/intercept/judge", nil))
|
||||
var got intercept.JudgeConfig
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.RetryCount != tc.count || got.RetryIntervalMS != tc.interval {
|
||||
t.Fatalf("saved=%+v got=%+v", cfg, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ import (
|
||||
type Task struct {
|
||||
ID string `json:"id"`
|
||||
ExpID int64 `json:"exploration_id"`
|
||||
Remark string `json:"remark"`
|
||||
Name string `json:"name"` // 可选任务名称;空=未命名
|
||||
CategoryID *int64 `json:"category_id,omitempty"`
|
||||
CategoryName string `json:"category_name,omitempty"`
|
||||
@@ -79,6 +80,7 @@ type Task struct {
|
||||
// directly after the task has been published by Manager.
|
||||
type taskLifecycleState struct {
|
||||
Name string
|
||||
Remark string
|
||||
PinnedAt int64
|
||||
Status string
|
||||
Paused bool
|
||||
@@ -106,6 +108,7 @@ func (t *Task) lifecycleSnapshot() taskLifecycleState {
|
||||
func (t *Task) lifecycleSnapshotLocked() taskLifecycleState {
|
||||
return taskLifecycleState{
|
||||
Name: t.Name,
|
||||
Remark: t.Remark,
|
||||
PinnedAt: t.PinnedAt,
|
||||
Status: t.Status,
|
||||
Paused: t.Paused,
|
||||
@@ -130,6 +133,7 @@ func (t *Task) updateLifecycle(update func(*taskLifecycleState)) {
|
||||
state := t.lifecycleSnapshotLocked()
|
||||
update(&state)
|
||||
t.Name = state.Name
|
||||
t.Remark = state.Remark
|
||||
t.PinnedAt = state.PinnedAt
|
||||
t.Status = state.Status
|
||||
t.Paused = state.Paused
|
||||
@@ -832,6 +836,7 @@ func taskFromPG(pt *pgdb.Task, store *pgdb.ExplorationStore, ic *intercept.Inter
|
||||
return &Task{
|
||||
ID: strconv.FormatInt(pt.ID, 10), ExpID: pt.ExplorationID,
|
||||
Name: pt.Name,
|
||||
Remark: pt.Remark,
|
||||
CategoryID: cloneInt64Ptr(pt.CategoryID), CategoryName: pt.CategoryName,
|
||||
PinnedAt: unixOrZero(pt.PinnedAt),
|
||||
Description: pt.Description, Goal: pt.Goal, CreatedAt: pt.CreatedAt.Unix(), Paused: pt.Paused, Queued: pt.Queued,
|
||||
@@ -871,6 +876,7 @@ func (m *Manager) UpdateTaskMetadata(taskID string, patch pgdb.TaskPatch) (*Task
|
||||
}
|
||||
task.updateLifecycle(func(state *taskLifecycleState) {
|
||||
state.Name = updated.Name
|
||||
state.Remark = updated.Remark
|
||||
state.PinnedAt = unixOrZero(updated.PinnedAt)
|
||||
})
|
||||
return task, nil
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
const maxRemarkRunes = 2000
|
||||
|
||||
func normalizeRemark(value string) (string, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if utf8.RuneCountInString(value) > maxRemarkRunes {
|
||||
return "", fmt.Errorf("备注最多 %d 个字符", maxRemarkRunes)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (s *Server) updateScheduleMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := parseScheduleID(r)
|
||||
if err != nil || id <= 0 {
|
||||
writeErr(w, 400, "计划编号无效")
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxTaskMetadataRequestSize)
|
||||
var request struct {
|
||||
Name *string `json:"name"`
|
||||
Remark *string `json:"remark"`
|
||||
}
|
||||
if err := decode(r, &request); err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
writeErr(w, 413, "请求正文过大")
|
||||
} else {
|
||||
writeErr(w, 400, err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
if request.Name == nil && request.Remark == nil {
|
||||
writeErr(w, 400, "需要提供 name 或 remark")
|
||||
return
|
||||
}
|
||||
if request.Name != nil {
|
||||
name := strings.TrimSpace(*request.Name)
|
||||
if name == "" || utf8.RuneCountInString(name) > maxTaskNameRunes {
|
||||
writeErr(w, 400, fmt.Sprintf("计划名称须为 1 至 %d 个字符", maxTaskNameRunes))
|
||||
return
|
||||
}
|
||||
request.Name = &name
|
||||
}
|
||||
if request.Remark != nil {
|
||||
remark, err := normalizeRemark(*request.Remark)
|
||||
if err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
request.Remark = &remark
|
||||
}
|
||||
item, err := s.m.pg.UpdateTaskScheduleMetadata(id, db.TaskSchedulePatch{Name: request.Name, Remark: request.Remark})
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if item == nil {
|
||||
writeErr(w, 404, "计划不存在")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, item)
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func TestRemarksRoundTripPreservesExecutionState(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
task, err := m.CreateTask("remark test description", "original goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskID, _ := strconv.ParseInt(task.ID, 10, 64)
|
||||
defer func() { _ = m.pg.DeleteTask(taskID) }()
|
||||
scheduleInput := db.TaskScheduleInput{Name: "remark schedule", Enabled: false, ScheduleType: "once", RunDate: "2099-01-01", StartTime: "09:00", TaskIDs: []int64{taskID}}
|
||||
schedule, err := m.pg.CreateTaskSchedule(scheduleInput)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = m.pg.DeleteTaskSchedule(schedule.ID) }()
|
||||
if _, err := m.pg.Exec(`UPDATE task_schedules SET status='completed',last_window_key='preserve-window',last_error='preserve-error',last_transition_at=now() WHERE id=$1`, schedule.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original, err := m.pg.GetTaskSchedule(schedule.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
originalLifecycle := task.lifecycleSnapshot()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
|
||||
token, err := signJWT(s.jwtKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := s.Handler()
|
||||
request := func(path, body string, authenticated bool) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPatch, path, strings.NewReader(body))
|
||||
if authenticated {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
taskPath := "/api/tasks/" + task.ID
|
||||
schedulePath := fmt.Sprintf("/api/schedules/%d/remark", schedule.ID)
|
||||
for _, path := range []string{taskPath, schedulePath} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
for _, remark := range []string{" 中文备注 📝\n第二行 <script>alert(1)</script> ", strings.Repeat("📝", maxRemarkRunes), ""} {
|
||||
body, _ := json.Marshal(map[string]string{"remark": remark})
|
||||
rec := request(path, string(body), true)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("save: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var response struct {
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := strings.TrimSpace(remark)
|
||||
if response.Remark != expected {
|
||||
t.Fatal("response remark mismatch")
|
||||
}
|
||||
if path == taskPath {
|
||||
persisted, err := m.pg.GetTask(taskID)
|
||||
if err != nil || persisted.Remark != expected {
|
||||
t.Fatalf("persisted task: %+v %v", persisted, err)
|
||||
}
|
||||
listed, err := m.pg.ListTasks()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := false
|
||||
for _, item := range listed {
|
||||
if item.ID == taskID {
|
||||
found = item.Remark == expected
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("task list lost remark")
|
||||
}
|
||||
dto := taskDTO(task, s.resolvedTaskStatus(task))
|
||||
if dto.Remark != expected || dto.Goal != "original goal" || dto.Description != "remark test description" {
|
||||
t.Fatal("task DTO lost remark or changed goal")
|
||||
}
|
||||
state := task.lifecycleSnapshot()
|
||||
if state.Status != originalLifecycle.Status || state.Paused != originalLifecycle.Paused || state.Queued != originalLifecycle.Queued {
|
||||
t.Fatal("remark changed task lifecycle")
|
||||
}
|
||||
} else {
|
||||
persisted, err := m.pg.GetTaskSchedule(schedule.ID)
|
||||
if err != nil || persisted.Remark != expected {
|
||||
t.Fatalf("persisted schedule: %+v %v", persisted, err)
|
||||
}
|
||||
if persisted.Status != original.Status || persisted.Enabled != original.Enabled || persisted.LastWindowKey != original.LastWindowKey || persisted.LastError != original.LastError || !persisted.LastTransitionAt.Equal(*original.LastTransitionAt) || len(persisted.TaskIDs) != 1 || persisted.TaskIDs[0] != taskID {
|
||||
t.Fatal("remark changed calendar state or bindings")
|
||||
}
|
||||
listed, err := m.pg.ListTaskSchedules()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := false
|
||||
for _, item := range listed {
|
||||
if item.ID == schedule.ID {
|
||||
found = item.Remark == expected
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("schedule list lost remark")
|
||||
}
|
||||
}
|
||||
}
|
||||
cases := []struct {
|
||||
body string
|
||||
authenticated bool
|
||||
status int
|
||||
}{
|
||||
{`{}`, true, 400}, {`{"remark":null}`, true, 400}, {`{"remark":123}`, true, 400}, {`{`, true, 400},
|
||||
{`{"remark":"` + strings.Repeat("文", maxRemarkRunes+1) + `"}`, true, 400},
|
||||
{`{"remark":"` + strings.Repeat("x", maxTaskMetadataRequestSize) + `"}`, true, 413},
|
||||
{`{"remark":"denied"}`, false, 401},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
rec := request(path, tc.body, tc.authenticated)
|
||||
if rec.Code != tc.status {
|
||||
t.Fatalf("validation status=%d want=%d body=%s", rec.Code, tc.status, rec.Body.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// A normal rename/pin patch must preserve a previously saved remark.
|
||||
note := "保留的任务备注"
|
||||
if _, err := m.UpdateTaskMetadata(task.ID, db.TaskPatch{Remark: ¬e}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := request(taskPath, `{"name":"新名称","pinned":true}`, true)
|
||||
if rec.Code != 200 || !bytes.Contains(rec.Body.Bytes(), []byte(note)) {
|
||||
t.Fatalf("rename lost remark: %s", rec.Body.String())
|
||||
}
|
||||
note = "保留的计划备注"
|
||||
if _, err := m.pg.UpdateTaskScheduleRemark(schedule.ID, note); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
metadataPath := fmt.Sprintf("/api/schedules/%d/metadata", schedule.ID)
|
||||
rec = request(metadataPath, `{"name":" 行内改名 "}`, true)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("schedule rename: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
renamed, err := m.pg.GetTaskSchedule(schedule.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if renamed.Name != "行内改名" || renamed.Remark != note || renamed.Status != original.Status || renamed.Enabled != original.Enabled || renamed.LastWindowKey != original.LastWindowKey || renamed.LastError != original.LastError || !renamed.LastTransitionAt.Equal(*original.LastTransitionAt) || len(renamed.TaskIDs) != 1 || renamed.TaskIDs[0] != taskID {
|
||||
t.Fatalf("rename changed calendar state or metadata: %+v", renamed)
|
||||
}
|
||||
for _, body := range []string{`{}`, `{"name":null}`, `{"name":" "}`, `{"name":123}`, `{"name":"` + strings.Repeat("文", maxTaskNameRunes+1) + `"}`, `{"name":"must not apply","remark":"` + strings.Repeat("文", maxRemarkRunes+1) + `"}`} {
|
||||
if rec := request(metadataPath, body, true); rec.Code != 400 {
|
||||
t.Fatalf("invalid rename: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
unchanged, err := m.pg.GetTaskSchedule(schedule.ID)
|
||||
if err != nil || unchanged.Name != "行内改名" || unchanged.Remark != note {
|
||||
t.Fatalf("invalid patch partially changed metadata: %+v %v", unchanged, err)
|
||||
}
|
||||
if rec := request(metadataPath, `{"name":"denied"}`, false); rec.Code != 401 {
|
||||
t.Fatalf("rename auth: %d", rec.Code)
|
||||
}
|
||||
scheduleInput.Name = "新计划名称"
|
||||
updated, err := m.pg.UpdateTaskSchedule(schedule.ID, scheduleInput)
|
||||
if err != nil || updated.Remark != note {
|
||||
t.Fatalf("schedule edit lost remark: %+v %v", updated, err)
|
||||
}
|
||||
for _, path := range []string{"/api/tasks/9223372036854775807", "/api/schedules/9223372036854775807/remark"} {
|
||||
if rec := request(path, `{"remark":"missing"}`, true); rec.Code != 404 {
|
||||
t.Fatalf("missing record: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package server
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestProfileRequestLimiterSurvivesCacheInvalidation(t *testing.T) {
|
||||
s := &Server{}
|
||||
limiter := s.requestLimiterForProfile(1)
|
||||
if limiter == s.requestLimiterForProfile(2) || limiter == s.requestLimiterForProfile(0) {
|
||||
t.Fatal("different profiles must have independent quotas")
|
||||
}
|
||||
s.invalidateProfileAgents()
|
||||
if got := s.requestLimiterForProfile(1); got != limiter {
|
||||
t.Fatal("clearing providers reset the profile's rate limiter")
|
||||
}
|
||||
}
|
||||
+42
-15
@@ -103,6 +103,9 @@ type Server struct {
|
||||
provCacheMu sync.Mutex
|
||||
provByProfile map[int64]*provEntry
|
||||
provCacheGen uint64
|
||||
// Quota histories survive provider/agent cache invalidation. Key 0 belongs
|
||||
// to the non-persisted global config; persisted profiles use their DB IDs.
|
||||
requestLimiters map[int64]*agent.RequestLimiter
|
||||
|
||||
// llmHealth is the process-wide circuit-breaker state for LLM failover (轮询).
|
||||
// It deliberately lives OUTSIDE the provider caches: rebuilding the chain
|
||||
@@ -446,7 +449,7 @@ func (s *Server) applyLLM(cfg agent.Config) error {
|
||||
}
|
||||
if prov == nil {
|
||||
var err error
|
||||
prov, err = cfg.NewProvider()
|
||||
prov, err = cfg.NewProviderWithLimiter(s.requestLimiterForProfile(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -581,31 +584,51 @@ func (s *Server) providerForProfile(id int64) (llm.Provider, agent.Config, bool)
|
||||
if !ok {
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
prov, err := cfg.NewProvider()
|
||||
if err != nil {
|
||||
log.Printf("[engine] build provider for LLM profile %d failed: %v", id, err)
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
// Wrap with recorder, tagged with this profile's name.
|
||||
if p, _ := s.m.pg.ProfileByID(id); p != nil {
|
||||
prov = llmrec.Wrap(prov, s.m.PG(), cfg.Model, p.Name, cfg.ThinkingType, cfg.ReasoningEffort, s.m.LLMRecordEnabled)
|
||||
prov = bindSideProvider(prov, cfg, id, p.Name)
|
||||
}
|
||||
profile, _ := s.m.pg.ProfileByID(id)
|
||||
s.provCacheMu.Lock()
|
||||
if generation != s.provCacheGen {
|
||||
s.provCacheMu.Unlock()
|
||||
return s.providerForProfile(id)
|
||||
}
|
||||
if e := s.provByProfile[id]; e != nil { // lost the race → keep the winner
|
||||
prov, cfg = e.prov, e.cfg
|
||||
} else {
|
||||
s.provByProfile[id] = &provEntry{prov: prov, cfg: cfg}
|
||||
log.Printf("[engine] built provider for LLM profile %d (%s / %s)", id, cfg.Provider(), cfg.Model)
|
||||
s.provCacheMu.Unlock()
|
||||
return e.prov, e.cfg, true
|
||||
}
|
||||
// Building the HTTP client does not perform network I/O. Keep this step
|
||||
// under the generation lock so a stale build cannot overwrite the retained
|
||||
// limiter's settings after a newer configuration has already been installed.
|
||||
prov, err := cfg.NewProviderWithLimiter(s.requestLimiterForProfileLocked(id))
|
||||
if err != nil {
|
||||
s.provCacheMu.Unlock()
|
||||
log.Printf("[engine] build provider for LLM profile %d failed: %v", id, err)
|
||||
return nil, agent.Config{}, false
|
||||
}
|
||||
if profile != nil {
|
||||
prov = llmrec.Wrap(prov, s.m.PG(), cfg.Model, profile.Name, cfg.ThinkingType, cfg.ReasoningEffort, s.m.LLMRecordEnabled)
|
||||
prov = bindSideProvider(prov, cfg, id, profile.Name)
|
||||
}
|
||||
s.provByProfile[id] = &provEntry{prov: prov, cfg: cfg}
|
||||
log.Printf("[engine] built provider for LLM profile %d (%s / %s)", id, cfg.Provider(), cfg.Model)
|
||||
s.provCacheMu.Unlock()
|
||||
return prov, cfg, true
|
||||
}
|
||||
|
||||
func (s *Server) requestLimiterForProfile(id int64) *agent.RequestLimiter {
|
||||
s.provCacheMu.Lock()
|
||||
defer s.provCacheMu.Unlock()
|
||||
return s.requestLimiterForProfileLocked(id)
|
||||
}
|
||||
|
||||
func (s *Server) requestLimiterForProfileLocked(id int64) *agent.RequestLimiter {
|
||||
if s.requestLimiters == nil {
|
||||
s.requestLimiters = make(map[int64]*agent.RequestLimiter)
|
||||
}
|
||||
if s.requestLimiters[id] == nil {
|
||||
s.requestLimiters[id] = &agent.RequestLimiter{}
|
||||
}
|
||||
return s.requestLimiters[id]
|
||||
}
|
||||
|
||||
// chatAgentForProfile returns a ChatAgent built from a specific LLM profile, cached
|
||||
// per profile id. Returns nil if the profile is missing or has no API key.
|
||||
func (s *Server) chatAgentForProfile(id int64) *agent.ChatAgent {
|
||||
@@ -681,6 +704,8 @@ func (s *Server) Handler() http.Handler {
|
||||
|
||||
// 页面一键更新。走的是默认的 JWT 鉴权(auth.go 只放行 /api/auth/* 和
|
||||
// /api/health),所以这几个改动程序自身的接口天然需要登录。
|
||||
mux.HandleFunc("GET /api/update/settings", s.getUpdateSettings)
|
||||
mux.HandleFunc("PUT /api/update/settings", s.putUpdateSettings)
|
||||
mux.HandleFunc("GET /api/update/check", s.updateCheck)
|
||||
mux.HandleFunc("POST /api/update/apply", s.updateApply)
|
||||
mux.HandleFunc("POST /api/update/rollback", s.updateRollback)
|
||||
@@ -692,6 +717,8 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("POST /api/schedules", s.createSchedule)
|
||||
mux.HandleFunc("GET /api/schedules/{id}", s.getSchedule)
|
||||
mux.HandleFunc("PATCH /api/schedules/{id}", s.updateSchedule)
|
||||
mux.HandleFunc("PATCH /api/schedules/{id}/remark", s.updateScheduleMetadata)
|
||||
mux.HandleFunc("PATCH /api/schedules/{id}/metadata", s.updateScheduleMetadata)
|
||||
mux.HandleFunc("DELETE /api/schedules/{id}", s.deleteSchedule)
|
||||
mux.HandleFunc("POST /api/schedules/{id}/pause", s.pauseSchedule)
|
||||
mux.HandleFunc("POST /api/schedules/{id}/resume", s.resumeSchedule)
|
||||
|
||||
@@ -1530,10 +1530,11 @@ func skillRelPath(file string) (string, string) {
|
||||
if strings.HasPrefix(file, "/") || strings.Contains(file, "//") {
|
||||
return "", "invalid path: must be relative with no empty segments"
|
||||
}
|
||||
// 4. Normalize and final safety re-check after Clean.
|
||||
// filepath.Clean removes redundant separators and resolves single dots.
|
||||
clean := filepath.Clean(file)
|
||||
if clean == "." || filepath.IsAbs(clean) || strings.HasPrefix(clean, "..") {
|
||||
// 4. Normalize as a URL/API path, not as a host filesystem path. API paths
|
||||
// always use '/', including when ARTEX runs on Windows. Filesystem calls
|
||||
// below accept this canonical form through filepath.Join.
|
||||
clean := path.Clean(file)
|
||||
if clean == "." || path.IsAbs(clean) || strings.HasPrefix(clean, "..") {
|
||||
return "", "invalid path"
|
||||
}
|
||||
return clean, ""
|
||||
@@ -1554,6 +1555,10 @@ func walkSkillFiles(root string) ([]string, error) {
|
||||
if relErr != nil || rel == "." {
|
||||
return nil
|
||||
}
|
||||
// The file list is an HTTP API contract consumed by a frontend that splits
|
||||
// paths on '/'. filepath.Rel uses '\\' on Windows, so normalize before the
|
||||
// value leaves the backend.
|
||||
rel = filepath.ToSlash(rel)
|
||||
if d.IsDir() {
|
||||
entries = append(entries, rel+"/")
|
||||
} else {
|
||||
|
||||
@@ -64,6 +64,33 @@ func TestSkillRelPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkSkillFilesUsesSlashSeparatedAPIPaths(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(root, "scripts", "helpers"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "scripts", "helpers", "run.py"), []byte("pass\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
entries, err := walkSkillFiles(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"scripts/", "scripts/helpers/", "scripts/helpers/run.py"}
|
||||
if len(entries) != len(want) {
|
||||
t.Fatalf("walkSkillFiles() = %q, want %q", entries, want)
|
||||
}
|
||||
for i := range want {
|
||||
if entries[i] != want[i] {
|
||||
t.Errorf("walkSkillFiles()[%d] = %q, want %q", i, entries[i], want[i])
|
||||
}
|
||||
if strings.Contains(entries[i], `\`) {
|
||||
t.Errorf("walkSkillFiles()[%d] contains a Windows separator: %q", i, entries[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type nopWriteCloser struct{ io.Writer }
|
||||
|
||||
func (nopWriteCloser) Close() error { return nil }
|
||||
|
||||
+13
-3
@@ -26,6 +26,7 @@ func (s *Server) updateTaskMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxTaskMetadataRequestSize)
|
||||
var request struct {
|
||||
Name *string `json:"name"`
|
||||
Remark *string `json:"remark"`
|
||||
Pinned *bool `json:"pinned"`
|
||||
}
|
||||
if err := decode(r, &request); err != nil {
|
||||
@@ -37,8 +38,8 @@ func (s *Server) updateTaskMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
return
|
||||
}
|
||||
if request.Name == nil && request.Pinned == nil {
|
||||
writeErr(w, http.StatusBadRequest, "至少需要提供 name 或 pinned")
|
||||
if request.Name == nil && request.Pinned == nil && request.Remark == nil {
|
||||
writeErr(w, http.StatusBadRequest, "至少需要提供 name、pinned 或 remark")
|
||||
return
|
||||
}
|
||||
if request.Name != nil {
|
||||
@@ -53,7 +54,16 @@ func (s *Server) updateTaskMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
request.Name = &name
|
||||
}
|
||||
task, err := s.m.UpdateTaskMetadata(taskID, db.TaskPatch{Name: request.Name, Pinned: request.Pinned})
|
||||
|
||||
if request.Remark != nil {
|
||||
remark, err := normalizeRemark(*request.Remark)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
request.Remark = &remark
|
||||
}
|
||||
task, err := s.m.UpdateTaskMetadata(taskID, db.TaskPatch{Name: request.Name, Pinned: request.Pinned, Remark: request.Remark})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
|
||||
+23
-11
@@ -57,10 +57,11 @@ func bootUpdateState() selfupdate.State {
|
||||
// 每 IP 每小时 60 次——不缓存的话,多开几个标签页或刷几次页面就把配额耗光了,
|
||||
// 之后真想更新时反而查不动。用户显式点"检查更新"时可以 force 绕过缓存。
|
||||
type releaseCache struct {
|
||||
mu sync.Mutex
|
||||
rel *selfupdate.Release
|
||||
err error
|
||||
at time.Time
|
||||
mu sync.Mutex
|
||||
rel *selfupdate.Release
|
||||
err error
|
||||
at time.Time
|
||||
network string
|
||||
// fetch 是取数函数,仅为测试留的注入点;为 nil 时走真正的 GitHub 查询。
|
||||
fetch func(context.Context, *http.Client) (*selfupdate.Release, error)
|
||||
}
|
||||
@@ -80,11 +81,11 @@ var relCache = &releaseCache{}
|
||||
//
|
||||
// 取数期间一直持有锁:并发请求会排队等同一次查询的结果,而不是各自去打 GitHub
|
||||
// (页面刚加载时多个标签页同时来查,正是最容易触发限流的时刻)。
|
||||
func (c *releaseCache) get(ctx context.Context, client *http.Client, force bool) (*selfupdate.Release, error) {
|
||||
func (c *releaseCache) get(ctx context.Context, client *http.Client, force bool, network string) (*selfupdate.Release, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if !force {
|
||||
if !force && c.network == network {
|
||||
ttl := releaseTTL
|
||||
if c.err != nil {
|
||||
ttl = releaseErrTTL
|
||||
@@ -106,7 +107,7 @@ func (c *releaseCache) get(ctx context.Context, client *http.Client, force bool)
|
||||
if err != nil && ctx.Err() != nil && errors.Is(ctx.Err(), context.Canceled) {
|
||||
return c.rel, err
|
||||
}
|
||||
c.rel, c.err, c.at = rel, err, time.Now()
|
||||
c.rel, c.err, c.at, c.network = rel, err, time.Now(), network
|
||||
return rel, err
|
||||
}
|
||||
|
||||
@@ -227,8 +228,13 @@ func (s *Server) updateCheck(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// 顶栏提示走缓存(默认);用户点"检查更新"时带 force=1 强制回源。
|
||||
force := r.URL.Query().Get("force") != ""
|
||||
client := selfupdate.NewClient(s.m.GlobalProxy())
|
||||
rel, err := relCache.get(r.Context(), client, force)
|
||||
client, network, err := s.updateClient()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
defer client.CloseIdleConnections()
|
||||
rel, err := relCache.get(r.Context(), client, force, network)
|
||||
if err != nil {
|
||||
out["error"] = err.Error()
|
||||
writeJSON(w, 200, out)
|
||||
@@ -271,8 +277,13 @@ func (s *Server) updateApply(w http.ResponseWriter, r *http.Request) {
|
||||
current := BuildVersion
|
||||
|
||||
// 走缓存:确保装上的就是用户在界面上看到并确认的那个版本。
|
||||
client := selfupdate.NewClient(s.m.GlobalProxy())
|
||||
rel, err := relCache.get(r.Context(), client, false)
|
||||
client, network, err := s.updateClient()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
defer client.CloseIdleConnections()
|
||||
rel, err := relCache.get(r.Context(), client, false, network)
|
||||
if err != nil {
|
||||
writeErr(w, 502, err.Error())
|
||||
return
|
||||
@@ -294,6 +305,7 @@ func (s *Server) updateApply(w http.ResponseWriter, r *http.Request) {
|
||||
go func() {
|
||||
// 刻意用 s.ctx 而不是请求的 ctx:HTTP 响应一返回请求就结束了,
|
||||
// 挂在它上面下载会立刻被取消。
|
||||
defer client.CloseIdleConnections()
|
||||
err := selfupdate.Stage(s.ctx, client, rel, current, func(ph selfupdate.Phase, pct int, msg string) {
|
||||
updHub.publish(ph, pct, msg)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/selfupdate"
|
||||
)
|
||||
|
||||
const updateSettingsKey = "update.network"
|
||||
|
||||
type updateSettings struct {
|
||||
Proxy string `json:"proxy"`
|
||||
}
|
||||
|
||||
func (cfg *updateSettings) validate() error {
|
||||
cfg.Proxy = strings.TrimSpace(cfg.Proxy)
|
||||
if _, err := selfupdate.ParseProxy(cfg.Proxy); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) loadUpdateSettings() (updateSettings, error) {
|
||||
cfg := updateSettings{}
|
||||
raw, ok, err := s.m.pg.GetSetting(updateSettingsKey)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("读取更新网络设置失败: %w", err)
|
||||
}
|
||||
if ok {
|
||||
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
|
||||
return cfg, fmt.Errorf("更新网络设置格式无效")
|
||||
}
|
||||
}
|
||||
if err := cfg.validate(); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (s *Server) getUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
cfg, err := s.loadUpdateSettings()
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, cfg)
|
||||
}
|
||||
|
||||
func (s *Server) putUpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||
var cfg updateSettings
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8192)).Decode(&cfg); err != nil {
|
||||
writeErr(w, 400, "更新网络设置格式无效")
|
||||
return
|
||||
}
|
||||
if err := cfg.validate(); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
raw, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.m.pg.SetSettingContext(r.Context(), updateSettingsKey, string(raw)); err != nil {
|
||||
writeErr(w, 500, "保存更新网络设置失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, cfg)
|
||||
}
|
||||
|
||||
// Capture one effective proxy for both release discovery and all asset downloads.
|
||||
// A different proxy bypasses cached success/error results from the previous route.
|
||||
func (s *Server) updateClient() (*http.Client, string, error) {
|
||||
cfg, err := s.loadUpdateSettings()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
client, err := selfupdate.NewClient(cfg.Proxy)
|
||||
return client, cfg.Proxy, err
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUpdateSettingsHTTPPersistence(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
old, existed, err := m.pg.GetSetting(updateSettingsKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if existed {
|
||||
m.pg.SetSetting(updateSettingsKey, old)
|
||||
} else {
|
||||
m.pg.Exec("DELETE FROM settings WHERE key=$1", updateSettingsKey)
|
||||
}
|
||||
}()
|
||||
m.pg.Exec("DELETE FROM settings WHERE key=$1", updateSettingsKey)
|
||||
dir := t.TempDir()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
s := New(ctx, m, dir, dir, dir)
|
||||
token, err := signJWT(s.jwtKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := s.Handler()
|
||||
request := func(method, body string, authenticated bool) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, "/api/update/settings", bytes.NewBufferString(body))
|
||||
if authenticated {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
return res
|
||||
}
|
||||
for _, method := range []string{"GET", "PUT"} {
|
||||
if r := request(method, `{}`, false); r.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthenticated %s: %d", method, r.Code)
|
||||
}
|
||||
}
|
||||
if cfg, err := s.loadUpdateSettings(); err != nil || cfg.Proxy != "" {
|
||||
t.Fatalf("default: %+v %v", cfg, err)
|
||||
}
|
||||
for _, body := range []string{`{"proxy":"127.0.0.1:7897"}`, `{"proxy":"http://proxy:65536"}`, `{`} {
|
||||
if r := request("PUT", body, true); r.Code != 400 {
|
||||
t.Fatalf("invalid setting accepted: %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.globalProxy = "http://127.0.0.1:1"
|
||||
m.mu.Unlock()
|
||||
originalGlobal := m.GlobalProxy()
|
||||
for _, proxy := range []string{" http://127.0.0.1:7897 ", ""} {
|
||||
body, _ := json.Marshal(updateSettings{Proxy: proxy})
|
||||
if r := request("PUT", string(body), true); r.Code != 200 {
|
||||
t.Fatalf("save: %d %s", r.Code, r.Body.String())
|
||||
}
|
||||
// Read through a fresh Server to prove the setting comes from the DB.
|
||||
fresh := &Server{m: m}
|
||||
cfg, err := fresh.loadUpdateSettings()
|
||||
if err != nil || cfg.Proxy != strings.TrimSpace(proxy) {
|
||||
t.Fatalf("reload: %+v %v", cfg, err)
|
||||
}
|
||||
r := request("GET", "", true)
|
||||
if r.Code != 200 {
|
||||
t.Fatalf("GET settings: %d", r.Code)
|
||||
}
|
||||
want := cfg
|
||||
var got updateSettings
|
||||
if err := json.Unmarshal(r.Body.Bytes(), &got); err != nil || got != want {
|
||||
t.Fatalf("GET: %+v %v", got, err)
|
||||
}
|
||||
client, effective, err := fresh.updateClient()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.CloseIdleConnections()
|
||||
if proxy != "" && effective != "http://127.0.0.1:7897" {
|
||||
t.Fatalf("proxy not normalized: %q", effective)
|
||||
}
|
||||
if proxy == "" && client.Transport.(*http.Transport).Proxy != nil {
|
||||
t.Fatal("direct inherited proxy")
|
||||
}
|
||||
if m.GlobalProxy() != originalGlobal {
|
||||
t.Fatal("update setting changed global proxy")
|
||||
}
|
||||
}
|
||||
}
|
||||
+54
-11
@@ -26,7 +26,7 @@ func TestReleaseCacheServesFromCache(t *testing.T) {
|
||||
})
|
||||
|
||||
for range 5 {
|
||||
rel, err := c.get(t.Context(), nil, false)
|
||||
rel, err := c.get(t.Context(), nil, false, "")
|
||||
if err != nil {
|
||||
t.Fatalf("get: %v", err)
|
||||
}
|
||||
@@ -46,11 +46,11 @@ func TestReleaseCacheForceBypasses(t *testing.T) {
|
||||
return &selfupdate.Release{TagName: "v0.3.8"}, nil
|
||||
})
|
||||
|
||||
if _, err := c.get(t.Context(), nil, false); err != nil {
|
||||
if _, err := c.get(t.Context(), nil, false, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 用户点「检查更新」必须拿到实时结果,否则刚发布的版本要等缓存过期才看得见。
|
||||
if _, err := c.get(t.Context(), nil, true); err != nil {
|
||||
if _, err := c.get(t.Context(), nil, true, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 2 {
|
||||
@@ -65,12 +65,12 @@ func TestReleaseCacheExpiresAfterTTL(t *testing.T) {
|
||||
return &selfupdate.Release{TagName: "v0.3.8"}, nil
|
||||
})
|
||||
|
||||
if _, err := c.get(t.Context(), nil, false); err != nil {
|
||||
if _, err := c.get(t.Context(), nil, false, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 把落库时间往前拨到刚过期,模拟 TTL 到点。
|
||||
c.at = time.Now().Add(-releaseTTL - time.Second)
|
||||
if _, err := c.get(t.Context(), nil, false); err != nil {
|
||||
if _, err := c.get(t.Context(), nil, false, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 2 {
|
||||
@@ -85,11 +85,11 @@ func TestReleaseCacheUsesShorterTTLForErrors(t *testing.T) {
|
||||
return nil, errors.New("github 不可达")
|
||||
})
|
||||
|
||||
if _, err := c.get(t.Context(), nil, false); err == nil {
|
||||
if _, err := c.get(t.Context(), nil, false, ""); err == nil {
|
||||
t.Fatal("期望返回错误")
|
||||
}
|
||||
// 失败结果也要缓存一会儿,否则 GitHub 不可达时每次页面加载都白等一次超时。
|
||||
if _, err := c.get(t.Context(), nil, false); err == nil {
|
||||
if _, err := c.get(t.Context(), nil, false, ""); err == nil {
|
||||
t.Fatal("期望返回错误")
|
||||
}
|
||||
if calls != 1 {
|
||||
@@ -101,7 +101,7 @@ func TestReleaseCacheUsesShorterTTLForErrors(t *testing.T) {
|
||||
t.Fatalf("错误 TTL(%v) 必须短于成功 TTL(%v)", releaseErrTTL, releaseTTL)
|
||||
}
|
||||
c.at = time.Now().Add(-releaseErrTTL - time.Second)
|
||||
if _, err := c.get(t.Context(), nil, false); err == nil {
|
||||
if _, err := c.get(t.Context(), nil, false, ""); err == nil {
|
||||
t.Fatal("期望返回错误")
|
||||
}
|
||||
if calls != 2 {
|
||||
@@ -114,7 +114,7 @@ func TestReleaseCacheDoesNotPoisonOnCallerCancel(t *testing.T) {
|
||||
c := newTestCache(func(ctx context.Context, _ *http.Client) (*selfupdate.Release, error) {
|
||||
return good, nil
|
||||
})
|
||||
if _, err := c.get(t.Context(), nil, false); err != nil {
|
||||
if _, err := c.get(t.Context(), nil, false, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ func TestReleaseCacheDoesNotPoisonOnCallerCancel(t *testing.T) {
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := c.get(ctx, nil, false); err == nil {
|
||||
if _, err := c.get(ctx, nil, false, ""); err == nil {
|
||||
t.Fatal("调用方已取消时应把错误透传给它")
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ func TestReleaseCacheDoesNotPoisonOnCallerCancel(t *testing.T) {
|
||||
c.fetch = func(context.Context, *http.Client) (*selfupdate.Release, error) {
|
||||
return good, nil
|
||||
}
|
||||
rel, err := c.get(t.Context(), nil, false)
|
||||
rel, err := c.get(t.Context(), nil, false, "")
|
||||
if err != nil {
|
||||
t.Fatalf("取消之后的正常请求不应报错: %v", err)
|
||||
}
|
||||
@@ -153,3 +153,46 @@ func TestReleaseCacheDoesNotPoisonOnCallerCancel(t *testing.T) {
|
||||
t.Fatalf("应拿到正常结果,得到 %+v", rel)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseCacheChangesWithNetwork(t *testing.T) {
|
||||
calls := 0
|
||||
c := newTestCache(func(context.Context, *http.Client) (*selfupdate.Release, error) {
|
||||
calls++
|
||||
if calls == 1 {
|
||||
return nil, errors.New("direct unavailable")
|
||||
}
|
||||
return &selfupdate.Release{TagName: "v0.3.21"}, nil
|
||||
})
|
||||
if _, err := c.get(t.Context(), nil, false, ""); err == nil {
|
||||
t.Fatal("expected direct error")
|
||||
}
|
||||
if _, err := c.get(t.Context(), nil, false, "http://localhost:7897"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.get(t.Context(), nil, false, "http://localhost:7897"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 2 {
|
||||
t.Fatalf("same proxy should reuse cache; calls=%d", calls)
|
||||
}
|
||||
if _, err := c.get(t.Context(), nil, false, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 3 {
|
||||
t.Fatalf("switching back to direct must refetch; calls=%d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateSettingsValidation(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
proxy string
|
||||
valid bool
|
||||
}{
|
||||
{"", true}, {" http://127.0.0.1:7897 ", true}, {"localhost:7897", false},
|
||||
} {
|
||||
cfg := updateSettings{Proxy: tc.proxy}
|
||||
if err := cfg.validate(); (err == nil) != tc.valid {
|
||||
t.Errorf("validation: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { DateSelect } from "@/components/date-select";
|
||||
import { RemarkEditor, ScheduleNameEditor } from "@/components/remark-editor";
|
||||
import { TimeSelect } from "@/components/time-select";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -702,7 +703,7 @@ export default function SchedulesPage() {
|
||||
</Card>
|
||||
) : (
|
||||
<div className="overflow-x-auto rounded-lg border bg-card">
|
||||
<Table>
|
||||
<Table className="**:data-[slot='table-cell']:px-4 **:data-[slot='table-head']:px-4">
|
||||
<TableHeader className="bg-muted/40">
|
||||
<TableRow>
|
||||
<TableHead className="w-12">
|
||||
@@ -712,7 +713,9 @@ export default function SchedulesPage() {
|
||||
onCheckedChange={(checked) => toggleAllVisible(checked === true)}
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead className="font-mono">ID</TableHead>
|
||||
<TableHead className="min-w-44">计划名称</TableHead>
|
||||
<TableHead>备注</TableHead>
|
||||
<TableHead className="w-28">时间线</TableHead>
|
||||
<TableHead className="min-w-48">运行周期</TableHead>
|
||||
<TableHead className="min-w-40">开始时间</TableHead>
|
||||
@@ -726,7 +729,7 @@ export default function SchedulesPage() {
|
||||
<TableBody>
|
||||
{visibleItems.map((item) => (
|
||||
<React.Fragment key={item.id}>
|
||||
<TableRow>
|
||||
<TableRow className="group">
|
||||
<TableCell className="w-12">
|
||||
<Checkbox
|
||||
aria-label={`选择计划 ${item.name}`}
|
||||
@@ -735,8 +738,29 @@ export default function SchedulesPage() {
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="font-medium">{item.name}</div>
|
||||
<div className="text-muted-foreground text-xs">计划 #{item.id}</div>
|
||||
<code className="bg-muted rounded px-1.5 py-0.5 font-mono text-xs">{item.id}</code>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">
|
||||
<ScheduleNameEditor
|
||||
value={item.name}
|
||||
label={`计划 #${item.id}`}
|
||||
onSave={async (name) => {
|
||||
const updated = await api.renameSchedule(item.id, name);
|
||||
setItems((current) => current.map((entry) => entry.id === item.id ? { ...entry, name: updated.name } : entry));
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<RemarkEditor
|
||||
value={item.remark}
|
||||
label={`计划 #${item.id} ${item.name}`}
|
||||
onSave={async (remark) => {
|
||||
const updated = await api.updateScheduleRemark(item.id, remark);
|
||||
setItems((current) =>
|
||||
current.map((entry) => entry.id === item.id ? { ...entry, remark: updated.remark } : entry),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button size="sm" variant="outline" onClick={() => void toggleTimeline(item.id)}>
|
||||
@@ -844,7 +868,7 @@ export default function SchedulesPage() {
|
||||
</TableRow>
|
||||
{expandedId === item.id ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={10} className="bg-muted/10 p-3">
|
||||
<TableCell colSpan={12} className="bg-muted/10 p-3">
|
||||
<ScheduleTimeline schedule={timelineById[item.id]} loading={timelineLoadingId === item.id} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
@@ -46,6 +46,7 @@ import { toast } from "sonner";
|
||||
|
||||
import { AssetInterceptRulesEditor } from "@/components/asset-intercept-rules-editor";
|
||||
import { DateSelect } from "@/components/date-select";
|
||||
import { RemarkEditor } from "@/components/remark-editor";
|
||||
import { StatusBadge } from "@/components/status-badge";
|
||||
import { TablePagination } from "@/components/table-pagination";
|
||||
import { TaskLLMProfileChain } from "@/components/task-llm-profile-chain";
|
||||
@@ -566,6 +567,18 @@ export default function TasksPage() {
|
||||
[load],
|
||||
);
|
||||
|
||||
const updateTaskRemark = React.useCallback(
|
||||
async (task: Task, remark: string) => {
|
||||
const updated = await api.updateTask(task.id, { remark });
|
||||
setTasks((current) =>
|
||||
current.map((entry) => entry.id === task.id ? { ...entry, remark: updated.remark } : entry),
|
||||
);
|
||||
lastRef.current = "";
|
||||
load();
|
||||
},
|
||||
[load],
|
||||
);
|
||||
|
||||
const renameTask = React.useCallback(
|
||||
async (task: Task, name: string) => {
|
||||
try {
|
||||
@@ -942,6 +955,7 @@ export default function TasksPage() {
|
||||
onSort={sortTasksBy}
|
||||
/>
|
||||
<TableHead>名称</TableHead>
|
||||
<TableHead>备注</TableHead>
|
||||
<TableHead>描述</TableHead>
|
||||
<TableHead>目标</TableHead>
|
||||
<SortableTaskHead
|
||||
@@ -989,6 +1003,7 @@ export default function TasksPage() {
|
||||
onDelete={deleteTask}
|
||||
onControl={controlTask}
|
||||
onRename={renameTask}
|
||||
onRemark={updateTaskRemark}
|
||||
onTogglePinned={toggleTaskPinned}
|
||||
onArchive={queueTaskArchive}
|
||||
selected={selectedIds.has(task.id)}
|
||||
@@ -1164,6 +1179,7 @@ const TaskRow = React.memo(function TaskRow({
|
||||
onDelete,
|
||||
onControl,
|
||||
onRename,
|
||||
onRemark,
|
||||
onTogglePinned,
|
||||
onArchive,
|
||||
selected,
|
||||
@@ -1174,6 +1190,7 @@ const TaskRow = React.memo(function TaskRow({
|
||||
onDelete: (id: string, options: DeleteTaskOptions) => Promise<void>;
|
||||
onControl: (id: string, action: "pause" | "resume") => Promise<void>;
|
||||
onRename: (task: Task, name: string) => Promise<void>;
|
||||
onRemark: (task: Task, remark: string) => Promise<void>;
|
||||
onTogglePinned: (task: Task) => Promise<void>;
|
||||
onArchive: (task: Task) => Promise<void>;
|
||||
selected: boolean;
|
||||
@@ -1198,6 +1215,9 @@ const TaskRow = React.memo(function TaskRow({
|
||||
{taskIsPinned(task) && <PinIcon className="text-primary size-4 shrink-0" aria-label="已置顶" />}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<RemarkEditor value={task.remark} label={`任务 #${task.id}`} onSave={(remark) => onRemark(task, remark)} />
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground max-w-40">
|
||||
<Link
|
||||
href={`/function/tasks/detail?id=${encodeURIComponent(task.id)}`}
|
||||
@@ -1222,7 +1242,8 @@ const TaskRow = React.memo(function TaskRow({
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-xs tabular-nums">
|
||||
{(() => {
|
||||
const f = task.distinct_findings ?? task.findings;
|
||||
// Keep report severity counts visible while a merged folder awaits its own assessment.
|
||||
const f = task.findings ?? task.distinct_findings;
|
||||
const total = f ? f.critical + f.high + f.medium + f.low : 0;
|
||||
if (!f || (total === 0 && !task.distinct_findings?.total))
|
||||
return <span className="text-muted-foreground">0</span>;
|
||||
@@ -1230,7 +1251,7 @@ const TaskRow = React.memo(function TaskRow({
|
||||
return (
|
||||
<span
|
||||
className="font-medium whitespace-nowrap"
|
||||
title={`独立漏洞:严重 / 高 / 中 / 低;上报 ${task.distinct_findings?.reports ?? total} 条;待评估 ${task.distinct_findings?.unassessed ?? 0} 个`}
|
||||
title={`${task.findings ? "原始上报" : "独立漏洞"}:严重 / 高 / 中 / 低;上报 ${task.distinct_findings?.reports ?? total} 条;待评估 ${task.distinct_findings?.unassessed ?? 0} 个`}
|
||||
>
|
||||
{seg(f.critical, "text-rose-600 dark:text-rose-400")}
|
||||
<span className="text-muted-foreground">/</span>
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Field as FormField, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
@@ -200,6 +201,8 @@ const defaultJudge = (): JudgeConfig => ({
|
||||
profile_id: 0,
|
||||
prompt: "",
|
||||
timeout_seconds: 15,
|
||||
retry_count: 0,
|
||||
retry_interval_ms: 1000,
|
||||
fail_action: "allow",
|
||||
ask_timeout_seconds: 300,
|
||||
ask_timeout_action: "deny",
|
||||
@@ -207,7 +210,7 @@ const defaultJudge = (): JudgeConfig => ({
|
||||
});
|
||||
|
||||
function JudgeCard() {
|
||||
const [cfg, setCfg] = React.useState<JudgeConfig>(defaultJudge());
|
||||
const [cfg, setCfg] = React.useState<JudgeConfig>(defaultJudge);
|
||||
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
@@ -337,7 +340,7 @@ function JudgeCard() {
|
||||
<div className="grid gap-4 lg:grid-cols-5">
|
||||
{/* 左:提示词编辑器(直接展开,主区域) */}
|
||||
<Card className="lg:col-span-3">
|
||||
<CardContent className="flex h-full flex-col gap-2 p-4">
|
||||
<CardContent className="flex min-h-0 flex-1 flex-col gap-2 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium">审批提示词</p>
|
||||
@@ -348,7 +351,7 @@ function JudgeCard() {
|
||||
</Button>
|
||||
</div>
|
||||
<Textarea
|
||||
className="min-h-[22rem] flex-1 resize-none font-mono text-xs leading-relaxed"
|
||||
className="field-sizing-fixed min-h-[22rem] max-h-[none] flex-1 resize-none font-mono text-xs leading-relaxed"
|
||||
value={cfg.prompt}
|
||||
onChange={(e) => patch({ prompt: e.target.value })}
|
||||
placeholder="留空使用内置模板"
|
||||
@@ -376,7 +379,7 @@ function JudgeCard() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="模型判定超时(秒)">
|
||||
<Field label="每次模型判定超时(秒)">
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
@@ -387,7 +390,48 @@ function JudgeCard() {
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="模型失败时(出错 / 超时 / 无法解析)">
|
||||
<FieldGroup>
|
||||
<FormField>
|
||||
<FieldLabel htmlFor="judge-retry-count">失败重试次数</FieldLabel>
|
||||
<Input
|
||||
id="judge-retry-count"
|
||||
type="number"
|
||||
min={0}
|
||||
max={20}
|
||||
step={1}
|
||||
value={cfg.retry_count}
|
||||
onChange={(e) => {
|
||||
const n = Number(e.target.value);
|
||||
if (Number.isInteger(n) && n >= 0 && n <= 20) patch({ retry_count: n });
|
||||
}}
|
||||
aria-describedby="judge-retry-count-hint"
|
||||
/>
|
||||
<FieldDescription id="judge-retry-count-hint">
|
||||
首次审批失败后额外重试 0–20 次,0 表示不重试。出错、超时或裁决无法解析时重试;正常放行、转人工或拦截后立即结束。
|
||||
</FieldDescription>
|
||||
</FormField>
|
||||
<FormField data-disabled={cfg.retry_count === 0}>
|
||||
<FieldLabel htmlFor="judge-retry-interval">重试间隔(毫秒)</FieldLabel>
|
||||
<Input
|
||||
id="judge-retry-interval"
|
||||
type="number"
|
||||
min={0}
|
||||
max={3600000}
|
||||
step={1}
|
||||
value={cfg.retry_interval_ms}
|
||||
disabled={cfg.retry_count === 0}
|
||||
onChange={(e) => {
|
||||
const n = Number(e.target.value);
|
||||
if (Number.isInteger(n) && n >= 0 && n <= 3600000) patch({ retry_interval_ms: n });
|
||||
}}
|
||||
aria-describedby="judge-retry-interval-hint"
|
||||
/>
|
||||
<FieldDescription id="judge-retry-interval-hint">
|
||||
默认 1000 毫秒,0 表示立即重试。每次审批均有独立超时,全部尝试失败后执行下方失败策略。模型配置中的建连和空响应重试仍在每次审批内生效。
|
||||
</FieldDescription>
|
||||
</FormField>
|
||||
</FieldGroup>
|
||||
<Field label="模型失败时(重试耗尽后)">
|
||||
<Select value={cfg.fail_action} onValueChange={(v) => patch({ fail_action: v as JudgeConfig["fail_action"] })}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
|
||||
@@ -15,9 +15,11 @@ import { toast } from "sonner";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { api, openSSE } from "@/lib/api";
|
||||
import type { UpdateCheck, UpdateProgress } from "@/lib/types";
|
||||
import type { UpdateCheck, UpdateProgress, UpdateSettings } from "@/lib/types";
|
||||
|
||||
/** 等待新版本上线的最长时间。一次升级要经过三次进程启动(暂存 → 换装 → 新版),
|
||||
* 每次都是秒级,三分钟足够覆盖慢磁盘和 Docker 容器重建。 */
|
||||
@@ -45,6 +47,32 @@ export function UpdateCard() {
|
||||
const [restarting, setRestarting] = React.useState(false);
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
|
||||
const [network, setNetwork] = React.useState<UpdateSettings | null>(null);
|
||||
const [savedNetwork, setSavedNetwork] = React.useState<UpdateSettings | null>(null);
|
||||
const [savingNetwork, setSavingNetwork] = React.useState(false);
|
||||
const [networkError, setNetworkError] = React.useState("");
|
||||
const streamRef = React.useRef<ReturnType<typeof openSSE> | null>(null);
|
||||
const networkDirty = network?.proxy !== savedNetwork?.proxy;
|
||||
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
api
|
||||
.getUpdateSettings()
|
||||
.then((settings) => {
|
||||
if (!active) return;
|
||||
setNetwork(settings);
|
||||
setSavedNetwork(settings);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (active) setNetworkError("读取更新网络设置失败:" + (e as Error).message);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => () => streamRef.current?.close(), []);
|
||||
|
||||
// quiet 同时决定要不要绕过后端缓存:进页面时的自动检查用缓存(顶栏刚查过),
|
||||
// 用户手动点「检查更新」则强制回源,否则刚发布的版本要等缓存过期才看得到。
|
||||
const check = React.useCallback((quiet = false) => {
|
||||
@@ -69,6 +97,25 @@ export function UpdateCard() {
|
||||
check(true);
|
||||
}, [check]);
|
||||
|
||||
const saveNetwork = async () => {
|
||||
if (!network) return;
|
||||
setSavingNetwork(true);
|
||||
setNetworkError("");
|
||||
try {
|
||||
const settings = await api.saveUpdateSettings({
|
||||
proxy: network.proxy,
|
||||
});
|
||||
setNetwork(settings);
|
||||
setSavedNetwork(settings);
|
||||
toast.success("更新网络设置已保存");
|
||||
check();
|
||||
} catch (e) {
|
||||
setNetworkError((e as Error).message);
|
||||
} finally {
|
||||
setSavingNetwork(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 轮询 /api/health 直到版本号变化。
|
||||
//
|
||||
// 判据必须是"版本变了"而不是"能连上了":换装过程中旧版本会短暂地重新起来一次
|
||||
@@ -94,12 +141,14 @@ export function UpdateCard() {
|
||||
}
|
||||
}
|
||||
setRestarting(false);
|
||||
setBusy(false);
|
||||
toast.error("等待服务重启超时。请检查后端日志,或确认 artex 是通过 start.sh / start.bat 启动的。");
|
||||
}, []);
|
||||
|
||||
// 订阅更新进度。SSE 不走 Next 的 /api 重写(那层会缓冲,事件推不出来)。
|
||||
const openStream = React.useCallback(
|
||||
(fromVersion: string) => {
|
||||
streamRef.current?.close();
|
||||
const es = openSSE("/api/update/stream");
|
||||
es.onmessage = (ev) => {
|
||||
let p: UpdateProgress;
|
||||
@@ -120,10 +169,11 @@ export function UpdateCard() {
|
||||
void waitForNewVersion(fromVersion);
|
||||
}
|
||||
};
|
||||
streamRef.current = es;
|
||||
es.onerror = () => {
|
||||
// 进程退出时 SSE 必然断开。如果已经进入等待重启,这属于正常现象,
|
||||
// 交给 /api/health 轮询继续判定即可。
|
||||
es.close();
|
||||
// EventSource 自动重连,恢复服务端保存的当前进度。
|
||||
};
|
||||
return es;
|
||||
},
|
||||
@@ -145,13 +195,16 @@ export function UpdateCard() {
|
||||
|
||||
setBusy(true);
|
||||
setProgress({ phase: "downloading", percent: 0, message: "准备中…" });
|
||||
const es = openStream(from);
|
||||
api.applyUpdate().catch((e) => {
|
||||
es.close();
|
||||
setBusy(false);
|
||||
setProgress(null);
|
||||
toast.error("启动更新失败:" + (e as Error).message);
|
||||
});
|
||||
api
|
||||
.applyUpdate()
|
||||
.then(() => {
|
||||
openStream(from);
|
||||
})
|
||||
.catch((e) => {
|
||||
setBusy(false);
|
||||
setProgress(null);
|
||||
toast.error("启动更新失败:" + (e as Error).message);
|
||||
});
|
||||
};
|
||||
|
||||
const doRollback = () => {
|
||||
@@ -193,7 +246,47 @@ export function UpdateCard() {
|
||||
</CardTitle>
|
||||
<CardDescription>从 GitHub 检查并安装新版本。更新会重启程序,正在运行的任务会被中断。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!networkError} data-disabled={busy || restarting || savingNetwork || !network}>
|
||||
<FieldLabel htmlFor="update-proxy" className="text-sm font-normal text-muted-foreground">
|
||||
更新代理(可选)
|
||||
</FieldLabel>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="update-proxy"
|
||||
autoComplete="off"
|
||||
placeholder="http://host:port 或 socks5://host:port(留空=直连)"
|
||||
value={network?.proxy ?? ""}
|
||||
disabled={busy || restarting || savingNetwork || !network}
|
||||
aria-invalid={!!networkError}
|
||||
onChange={(e) =>
|
||||
network &&
|
||||
setNetwork({
|
||||
proxy: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => void saveNetwork()}
|
||||
disabled={!network || savingNetwork || checking || busy || restarting}
|
||||
>
|
||||
{savingNetwork ? "保存中…" : "保存"}
|
||||
</Button>
|
||||
</div>
|
||||
<FieldDescription className="text-xs">
|
||||
独立出口代理,仅用于检查版本和下载更新,支持 HTTP / HTTPS / SOCKS5。留空保存后直连;不影响任务、网络搜索或
|
||||
LLM 的代理。
|
||||
</FieldDescription>
|
||||
{networkDirty && <p className="text-xs text-muted-foreground">修改尚未保存,保存后将自动检查更新。</p>}
|
||||
{networkError && (
|
||||
<p role="alert" className="text-xs text-destructive">
|
||||
{networkError}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="text-muted-foreground">当前版本</span>
|
||||
<Badge variant="secondary" className="font-mono">
|
||||
@@ -238,7 +331,7 @@ export function UpdateCard() {
|
||||
<p className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 p-2 text-xs text-destructive">
|
||||
<TriangleAlertIcon className="mt-0.5 size-3.5 shrink-0" />
|
||||
无法连接 GitHub:{info.error}
|
||||
{" "}可在上方配置全局代理后重试。
|
||||
{" "}可配置更新代理或切换为直连后重试。
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -274,6 +367,12 @@ export function UpdateCard() {
|
||||
</p>
|
||||
)}
|
||||
|
||||
{progress?.phase === "failed" && (
|
||||
<p role="alert" className="text-xs text-destructive">
|
||||
更新失败:{progress.error || progress.message}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{showProgress && (
|
||||
<div className="space-y-1.5">
|
||||
<Progress value={pct} className={downloading ? undefined : "animate-pulse"} />
|
||||
@@ -284,14 +383,29 @@ export function UpdateCard() {
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => check(false)} disabled={checking || busy || restarting}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => check(false)}
|
||||
disabled={checking || busy || restarting || networkDirty || savingNetwork || !network}
|
||||
>
|
||||
<RefreshCwIcon className={checking ? "size-4 animate-spin" : "size-4"} />
|
||||
检查更新
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={doUpdate}
|
||||
disabled={busy || restarting || !info?.has_update || info?.asset_available === false}
|
||||
disabled={
|
||||
checking ||
|
||||
networkDirty ||
|
||||
savingNetwork ||
|
||||
!network ||
|
||||
busy ||
|
||||
restarting ||
|
||||
!!info?.error ||
|
||||
!info?.has_update ||
|
||||
info?.asset_available === false
|
||||
}
|
||||
>
|
||||
<DownloadIcon className="size-4" />
|
||||
{info?.has_update ? `更新到 ${info.latest}` : "立即更新"}
|
||||
|
||||
@@ -111,6 +111,40 @@ function HighlightedBody({ body, format }: { body: string; format: BodyFormat })
|
||||
return body;
|
||||
}
|
||||
|
||||
// Empty grid rows have no text, so native selection copying drops their newlines.
|
||||
// Map the selected DOM boundaries back to the raw packet instead.
|
||||
function selectedPacketText(container: HTMLElement, value: string, lines: string[]): string | null {
|
||||
const selection = window.getSelection();
|
||||
if (!selection || selection.isCollapsed || selection.rangeCount !== 1) return null;
|
||||
const range = selection.getRangeAt(0);
|
||||
if (!container.contains(range.startContainer) || !container.contains(range.endContainer)) return null;
|
||||
|
||||
let start: number | null = null;
|
||||
let end: number | null = null;
|
||||
let offset = 0;
|
||||
container.querySelectorAll("[data-line] code").forEach((code, index) => {
|
||||
if (range.intersectsNode(code)) {
|
||||
const selected = document.createRange();
|
||||
selected.selectNodeContents(code);
|
||||
if (range.compareBoundaryPoints(Range.START_TO_START, selected) > 0) {
|
||||
selected.setStart(range.startContainer, range.startOffset);
|
||||
}
|
||||
if (range.compareBoundaryPoints(Range.END_TO_END, selected) < 0) {
|
||||
selected.setEnd(range.endContainer, range.endOffset);
|
||||
}
|
||||
const prefix = document.createRange();
|
||||
prefix.selectNodeContents(code);
|
||||
prefix.setEnd(selected.startContainer, selected.startOffset);
|
||||
start ??= offset + prefix.toString().length;
|
||||
prefix.setEnd(selected.endContainer, selected.endOffset);
|
||||
end = offset + prefix.toString().length;
|
||||
}
|
||||
const lineEnd = offset + lines[index].length;
|
||||
offset = lineEnd + (value[lineEnd] === "\r" ? 2 : 1);
|
||||
});
|
||||
return start !== null && end !== null ? value.slice(start, end) : null;
|
||||
}
|
||||
|
||||
export function HttpCodeBlock({ raw }: { raw: string }) {
|
||||
const [wrapLines, setWrapLines] = React.useState(true);
|
||||
const [copied, setCopied] = React.useState(false);
|
||||
@@ -183,6 +217,12 @@ export function HttpCodeBlock({ raw }: { raw: string }) {
|
||||
aria-readonly="true"
|
||||
tabIndex={0}
|
||||
className="max-h-[calc(100vh-15rem)] min-w-0 overflow-auto bg-background py-3 font-mono text-xs outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
|
||||
onCopy={(event) => {
|
||||
const text = selectedPacketText(event.currentTarget, value, lines);
|
||||
if (text === null) return;
|
||||
event.preventDefault();
|
||||
event.clipboardData.setData("text/plain", text);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "a") return;
|
||||
event.preventDefault();
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { PencilIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type EditorProps = {
|
||||
value?: string;
|
||||
label: string;
|
||||
onSave: (value: string) => Promise<void>;
|
||||
};
|
||||
|
||||
export function RemarkEditor(props: EditorProps) {
|
||||
return <InlineTextEditor {...props} multiline fieldName="备注" maxCharacters={2000} emptyLabel="添加备注" />;
|
||||
}
|
||||
|
||||
export function ScheduleNameEditor(props: EditorProps) {
|
||||
return <InlineTextEditor {...props} multiline={false} fieldName="名称" maxCharacters={200} emptyLabel="未命名" />;
|
||||
}
|
||||
|
||||
function InlineTextEditor({
|
||||
value = "",
|
||||
label,
|
||||
onSave,
|
||||
multiline,
|
||||
fieldName,
|
||||
maxCharacters,
|
||||
emptyLabel,
|
||||
}: EditorProps & { multiline: boolean; fieldName: string; maxCharacters: number; emptyLabel: string }) {
|
||||
const [editing, setEditing] = React.useState(false);
|
||||
const [draft, setDraft] = React.useState(value);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [error, setError] = React.useState("");
|
||||
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||
const textareaRef = React.useRef<HTMLTextAreaElement>(null);
|
||||
const cancelOnBlurRef = React.useRef(false);
|
||||
const savingRef = React.useRef(false);
|
||||
const errorID = React.useId();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!editing) setDraft(value);
|
||||
}, [editing, value]);
|
||||
|
||||
function refocus() {
|
||||
requestAnimationFrame(() => (multiline ? textareaRef.current : inputRef.current)?.focus());
|
||||
}
|
||||
|
||||
async function finishEditing() {
|
||||
if (savingRef.current) return;
|
||||
if (cancelOnBlurRef.current) {
|
||||
cancelOnBlurRef.current = false;
|
||||
setDraft(value);
|
||||
setError("");
|
||||
setEditing(false);
|
||||
return;
|
||||
}
|
||||
const next = draft.trim();
|
||||
if (next === value.trim()) {
|
||||
setEditing(false);
|
||||
return;
|
||||
}
|
||||
if (!multiline && next.length === 0) {
|
||||
setError("名称不能为空");
|
||||
refocus();
|
||||
return;
|
||||
}
|
||||
if (Array.from(next).length > maxCharacters) {
|
||||
setError(`${fieldName}最多 ${maxCharacters} 个字符`);
|
||||
refocus();
|
||||
return;
|
||||
}
|
||||
savingRef.current = true;
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSave(next);
|
||||
toast.success(`${fieldName}已保存`);
|
||||
setEditing(false);
|
||||
} catch (cause) {
|
||||
setError(`${fieldName}保存失败:${(cause as Error).message}`);
|
||||
refocus();
|
||||
} finally {
|
||||
savingRef.current = false;
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (editing) {
|
||||
const inputProps = {
|
||||
value: draft,
|
||||
autoFocus: true,
|
||||
disabled: saving,
|
||||
"aria-busy": saving,
|
||||
"aria-label": `${label}${fieldName}`,
|
||||
"aria-invalid": error.length > 0,
|
||||
"aria-describedby": error ? errorID : undefined,
|
||||
title: multiline ? "Enter 保存,Shift+Enter 换行,Esc 取消;留空可清除备注" : "Enter 或失焦保存,Esc 取消",
|
||||
onFocus: (event: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => event.currentTarget.select(),
|
||||
onChange: (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
setDraft(event.target.value);
|
||||
setError("");
|
||||
},
|
||||
onBlur: () => void finishEditing(),
|
||||
onKeyDown: (event: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
if (event.nativeEvent.isComposing) return;
|
||||
if (event.key === "Enter" && (!multiline || !event.shiftKey)) {
|
||||
event.preventDefault();
|
||||
event.currentTarget.blur();
|
||||
} else if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
cancelOnBlurRef.current = true;
|
||||
event.currentTarget.blur();
|
||||
}
|
||||
},
|
||||
};
|
||||
return (
|
||||
<div className={cn("flex min-w-0 flex-col gap-1 font-medium", multiline && "w-32 min-w-28 sm:w-48")}>
|
||||
{multiline ? (
|
||||
<Textarea
|
||||
{...inputProps}
|
||||
ref={textareaRef}
|
||||
rows={1}
|
||||
className="max-h-40 min-h-7 resize-none px-2 py-1 [overflow-wrap:anywhere]"
|
||||
/>
|
||||
) : (
|
||||
<Input {...inputProps} ref={inputRef} className="h-7 min-w-28 max-w-48 px-2 font-medium" />
|
||||
)}
|
||||
{error ? (
|
||||
<p id={errorID} role="alert" className="whitespace-normal text-destructive text-xs">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const startEditing = () => {
|
||||
setDraft(value);
|
||||
setError("");
|
||||
setEditing(true);
|
||||
};
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group/inline-editor flex min-w-0 items-center gap-1 font-medium",
|
||||
multiline ? "w-32 sm:w-48" : "max-w-xs",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="min-w-0 truncate rounded-sm text-left hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
aria-label={`${label}${fieldName},点击编辑`}
|
||||
title={value.length > 0 ? value : `点击编辑${fieldName}`}
|
||||
onClick={startEditing}
|
||||
>
|
||||
{value.length > 0 ? (
|
||||
<span className="block truncate">{value}</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground">{emptyLabel}</span>
|
||||
)}
|
||||
</button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="shrink-0 opacity-100 transition-opacity [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-focus-within:opacity-100 [@media(hover:hover)]:group-hover:opacity-100 [@media(hover:hover)]:group-focus-within/inline-editor:opacity-100 [@media(hover:hover)]:group-hover/inline-editor:opacity-100"
|
||||
aria-label={`编辑${label}的${fieldName}`}
|
||||
title={`编辑${fieldName}`}
|
||||
onClick={startEditing}
|
||||
>
|
||||
<PencilIcon />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+6
-1
@@ -106,6 +106,7 @@ import type {
|
||||
TrafficHost,
|
||||
TrafficResp,
|
||||
UpdateCheck,
|
||||
UpdateSettings,
|
||||
UsageStats,
|
||||
WorkspaceFile,
|
||||
WorkspaceListing,
|
||||
@@ -325,6 +326,8 @@ export const api = {
|
||||
schedule: input.schedule ? schedulePayload(input.schedule) : undefined,
|
||||
}),
|
||||
schedules: () => get<{ schedules: TaskSchedule[] }>("/schedules").then((r) => arr(r.schedules)),
|
||||
renameSchedule: (id: number, name: string) => patch<TaskSchedule>(`/schedules/${id}/metadata`, { name }),
|
||||
updateScheduleRemark: (id: number, remark: string) => patch<TaskSchedule>(`/schedules/${id}/remark`, { remark }),
|
||||
schedule: (id: number) => get<TaskSchedule>(`/schedules/${id}`),
|
||||
createSchedule: (input: ScheduleInput) => post<TaskSchedule>("/schedules", schedulePayload(input)),
|
||||
updateSchedule: (id: number, input: ScheduleInput) => patch<TaskSchedule>(`/schedules/${id}`, schedulePayload(input)),
|
||||
@@ -334,7 +337,7 @@ export const api = {
|
||||
runScheduleNow: (id: number) =>
|
||||
post<{ ok: boolean; started: number; errors?: string[] }>(`/schedules/${id}/run-now`, {}),
|
||||
taskCategories: () => get<{ categories: TaskCategory[] }>("/task-categories").then((r) => arr(r.categories)),
|
||||
updateTask: (id: string, input: { name?: string; pinned?: boolean }) => patch<Task>(`/tasks/${id}`, input),
|
||||
updateTask: (id: string, input: { name?: string; pinned?: boolean; remark?: string }) => patch<Task>(`/tasks/${id}`, input),
|
||||
renameTask: (id: string, name: string) => patch<Task>(`/tasks/${id}`, { name }),
|
||||
pinTask: (id: string, pinned: boolean) => patch<Task>(`/tasks/${id}`, { pinned }),
|
||||
createTaskCategory: (name: string) => post<TaskCategory>("/task-categories", { name }),
|
||||
@@ -1410,6 +1413,8 @@ export const api = {
|
||||
// 后端对 GitHub 的查询结果有 30 分钟缓存(未认证的 GitHub API 是 60 次/小时/IP,
|
||||
// 顶栏每次整页加载都会查一次,不缓存会很快耗光配额)。force=true 强制回源,
|
||||
// 留给用户显式点「检查更新」时用。
|
||||
getUpdateSettings: () => get<UpdateSettings>("/update/settings"),
|
||||
saveUpdateSettings: (settings: UpdateSettings) => put<UpdateSettings>("/update/settings", settings),
|
||||
checkUpdate: (force = false) => get<UpdateCheck>(`/update/check${force ? "?force=1" : ""}`),
|
||||
// 202 即返回,实际下载在后台跑,进度走 /api/update/stream。
|
||||
applyUpdate: () => post<{ ok: boolean; target: string }>(`/update/apply`),
|
||||
|
||||
@@ -1357,6 +1357,7 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
const task = mockTasks.find((item) => item.id === seg[1]);
|
||||
if (!task) throw new Error("任务不存在");
|
||||
if (typeof b.name === "string") task.name = b.name.trim();
|
||||
if (typeof b.remark === "string") task.remark = b.remark.trim();
|
||||
if (typeof b.pinned === "boolean") {
|
||||
task.pinned = b.pinned;
|
||||
task.pinned_at = b.pinned ? (task.pinned_at ?? new Date().toISOString()) : null;
|
||||
@@ -2511,6 +2512,8 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
profile_id: 0,
|
||||
prompt: "",
|
||||
timeout_seconds: 15,
|
||||
retry_count: 0,
|
||||
retry_interval_ms: 1000,
|
||||
fail_action: "allow",
|
||||
ask_timeout_seconds: 300,
|
||||
ask_timeout_action: "deny",
|
||||
|
||||
@@ -7,6 +7,7 @@ export type EngineMode = "exploring" | "paused" | "stalled" | "idle";
|
||||
export interface Task {
|
||||
distinct_findings?: FindingDistinctStats;
|
||||
id: string;
|
||||
remark?: string;
|
||||
name?: string; // 可选任务名称;空/缺省=未命名,展示时回退到描述
|
||||
category_id?: number;
|
||||
category_name?: string;
|
||||
@@ -718,6 +719,7 @@ export interface AgentTrigger {
|
||||
export interface TaskSchedule {
|
||||
id: number;
|
||||
name: string;
|
||||
remark?: string;
|
||||
enabled: boolean;
|
||||
timezone_mode: "beijing" | "system";
|
||||
timezone?: string;
|
||||
@@ -1361,7 +1363,9 @@ export interface JudgeConfig {
|
||||
enabled: boolean;
|
||||
profile_id: number; // 0 = 跟随激活/默认配置
|
||||
prompt: string; // 判定提示词;GET 未设置时后端回填内置模板全文
|
||||
timeout_seconds: number; // 模型调用超时
|
||||
timeout_seconds: number; // 每次模型审批调用的超时
|
||||
retry_count: number; // 审批失败后的额外重试次数,0 = 不重试
|
||||
retry_interval_ms: number; // 审批重试间隔(毫秒),0 = 立即重试
|
||||
fail_action: "allow" | "ask" | "deny"; // 模型出错/超时/不可解析时的回退
|
||||
ask_timeout_seconds: number; // 模型判 ask 转人工后的审批等待超时
|
||||
ask_timeout_action: "allow" | "deny"; // 审批超时后的默认动作
|
||||
@@ -1611,6 +1615,10 @@ export interface FindingTrafficDetail {
|
||||
response: EvidenceBodyPreview;
|
||||
}
|
||||
|
||||
export interface UpdateSettings {
|
||||
proxy: string;
|
||||
}
|
||||
|
||||
/** GET /api/update/check —— 当前版本与 GitHub 最新正式版的比较结果。 */
|
||||
export interface UpdateCheck {
|
||||
/** 当前运行的版本;开发构建为 "dev" 或 git describe 的带后缀形式。 */
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "https://openapi.vercel.sh/vercel.json",
|
||||
"framework": "nextjs",
|
||||
"installCommand": "npm ci",
|
||||
"buildCommand": "npm run build",
|
||||
"git": {
|
||||
"deploymentEnabled": false
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user