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 |
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 发布在线更新
|
||||
|
||||
|
||||
+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
|
||||
}
|
||||
|
||||
+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,
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -704,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)
|
||||
@@ -715,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)}`}
|
||||
|
||||
@@ -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}` : "立即更新"}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
@@ -1613,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