提交记录修改.github/workflows/go.yml+7 −1看文件
修改.github/workflows/www.yml+59 −7看文件
修改CHANGELOG.md+3 −1看文件
修改CONTRIBUTING.md+10 −2看文件
修改Makefile+3 −5看文件
修改README.am.md+3 −3看文件
修改README.ar.md+3 −3看文件
修改README.be.md+3 −3看文件
修改README.es.md+3 −3看文件
修改README.fa.md+3 −3看文件
修改README.fr.md+3 −3看文件
修改README.ko.md+3 −3看文件
修改README.md+3 −3看文件
修改README.my.md+3 −3看文件
修改README.prs.md+3 −3看文件
修改README.ps.md+3 −3看文件
修改README.ru.md+3 −3看文件
修改README.so.md+3 −3看文件
修改README.ti.md+3 −3看文件
修改README.zh-TW.md+3 −3看文件
修改RELEASING.md+1 −1看文件
修改VERSION+1 −1看文件
修改agent-vm.setup.sh+11 −3看文件
修改assets.go+6 −0看文件
修改cmd/cage/main.go+55 −4看文件
修改desktop/Cage.swift+103 −17看文件
新增desktop/UpdateInstaller.swift+183 −0看文件
新增desktop/Updates.swift+480 −0看文件
新增desktop/UpdatesTests.swift+136 −0看文件
修改docs/BACKLOG.md+4 −2看文件
修改docs/README.md+1 −0看文件
修改docs/design/managed-proxy.md+4 −0看文件
修改docs/design/network-checks.md+3 −1看文件
修改docs/design/workbench.md+40 −2看文件
修改docs/getting-started.md+18 −2看文件
修改docs/public-releases.md+4 −4看文件
新增docs/releases/0.1.0-alpha.1.md+36 −0看文件
修改docs/releasing.md+17 −2看文件
修改docs/troubleshooting.md+1 −1看文件
新增internal/appupdate/update.go+411 −0看文件
新增internal/appupdate/update_test.go+131 −0看文件
修改internal/cage/browser-agent.mjs+55 −66看文件
新增internal/cage/browser-audit.mjs+93 −0看文件
新增internal/cage/browser-audit.test.mjs+91 −0看文件
新增internal/cage/browser-downloads.mjs+188 −0看文件
新增internal/cage/browser-downloads.test.mjs+79 −0看文件
新增internal/cage/editor-migrate.py+67 −0看文件
新增internal/cage/editor-migrate.test.py+33 −0看文件
修改internal/cage/guest-services.sh+25 −0看文件
修改internal/cage/guest-start.sh+5 −3看文件
新增internal/cage/guest-tools.sh+49 −0看文件
修改internal/cage/guest.go+86 −2看文件
新增internal/cage/guest_versions_test.go+81 −0看文件
修改internal/cage/novnc-patch.py+96 −10看文件
修改internal/cage/save-download.py+149 −35看文件
新增internal/cage/save-download.test.py+95 −0看文件
新增internal/cage/tool-versions.env+8 −0看文件
修改internal/cli/setup.go+2 −1看文件
修改internal/managedproxy/store.go+12 −2看文件
修改internal/managedproxy/store_test.go+84 −0看文件
新增internal/version/identity.go+28 −0看文件
修改internal/version/version.go+12 −3看文件
新增internal/workbench/browser_recovery_test.go+44 −0看文件
新增internal/workbench/browser_text_test.go+49 −0看文件
新增internal/workbench/control_legacy.go+66 −0看文件
新增internal/workbench/control_lifecycle.go+109 −0看文件
新增internal/workbench/control_lifecycle_test.go+148 −0看文件
修改internal/workbench/desktop.go+305 −51看文件
新增internal/workbench/environment_versions.go+210 −0看文件
新增internal/workbench/environment_versions_test.go+147 −0看文件
新增internal/workbench/favorites.go+152 −0看文件
新增internal/workbench/favorites_test.go+105 −0看文件
新增internal/workbench/network_intent.go+65 −0看文件
新增internal/workbench/network_intent_test.go+177 −0看文件
修改internal/workbench/projects_test.go+6 −4看文件
修改internal/workbench/proxy.go+29 −14看文件
修改internal/workbench/proxy_interface.go+1 −1看文件
新增internal/workbench/proxy_pause_test.go+168 −0看文件
修改internal/workbench/proxy_test.go+1 −1看文件
修改internal/workbench/runtime.go+43 −13看文件
修改internal/workbench/safety.go+18 −9看文件
修改internal/workbench/server.go+77 −26看文件
新增scripts/browser-audit-smoke.mjs+175 −0看文件
新增scripts/browser-controls-smoke.mjs+153 −0看文件
修改scripts/build-app.sh+48 −6看文件
新增scripts/check-version.mjs+13 −0看文件
新增scripts/cleanup-apps.mjs+89 −0看文件
新增scripts/cleanup-apps.test.mjs+89 −0看文件
新增scripts/control-upgrade-smoke.mjs+52 −0看文件
修改scripts/package-macos.sh+1 −0看文件
新增scripts/test-app-updates.sh+8 −0看文件
新增scripts/verify-macos-release.sh+36 −0看文件
修改ui/package-lock.json+2 −2看文件
修改ui/package.json+1 −1看文件
新增ui/scripts/browser-chrome-smoke.mjs+348 −0看文件
新增ui/scripts/packaged-startup-smoke.mjs+42 −0看文件
新增ui/scripts/recovery-ui-smoke.mjs+103 −0看文件
新增ui/scripts/remote-input-smoke.mjs+316 −0看文件
新增ui/scripts/remote-visibility-smoke.mjs+102 −0看文件
新增ui/scripts/rfb-wire-fixture.mjs+92 −0看文件
修改ui/scripts/workbench-fixture.mjs+17 −5看文件
新增ui/src/app-updates.jsx+115 −0看文件
新增ui/src/browser-downloads.jsx+51 −0看文件
新增ui/src/browser-favorites.jsx+474 −0看文件
新增ui/src/environment-versions.jsx+53 −0看文件
新增ui/src/logo.png看文件 修改ui/src/main.jsx+114 −11看文件
新增ui/src/network-latency.jsx+78 −0看文件
修改ui/src/remote-input.js+70 −5看文件
修改ui/src/remote-input.test.mjs+104 −3看文件
修改ui/src/settings.jsx+2 −0看文件
修改ui/src/style.css+152 −8看文件
修改ui/src/views.jsx+19 −5看文件
新增ui/src/window-visibility.js+17 −0看文件
修改ui/src/workspace-sidebar.jsx+10 −5看文件
修改ui/src/workspace-tabs.jsx+232 −6看文件
修改ui/vendor/novnc/README.cage.md+1 −1看文件
删除www/.openai/hosting.json+0 −6
修改www/README.md+13 −5看文件
修改www/astro.config.mjs+2 −1看文件
修改www/package-lock.json+4 −101看文件
修改www/package.json+3 −9看文件
删除www/public/apple-touch-icon.png 删除www/public/favicon.png 删除www/public/favicon.svg+0 −5
新增www/public/first-run.jpg看文件 删除www/public/first-run.png 删除www/public/og.png 修改www/public/robots.txt+1 −1看文件
删除www/public/workbench.png 删除www/scripts/build-favicon.mjs+0 −29
删除www/scripts/build-og.mjs+0 −82
新增www/scripts/check-site.mjs+31 −0看文件
新增www/scripts/sync-release.mjs+113 −0看文件
新增www/scripts/sync-release.test.mjs+32 −0看文件
删除www/src/components/Architecture.astro+0 −479
新增www/src/components/CageHome.astro+62 −0看文件
删除www/src/components/CodeBlock.astro+0 −215
删除www/src/components/Contribute.astro+0 −219
删除www/src/components/Credits.astro+0 −156
删除www/src/components/DocGroups.astro+0 −104
删除www/src/components/Docs.astro+0 −27
删除www/src/components/Footer.astro+0 −101
删除www/src/components/Heading.astro+0 −109
删除www/src/components/Hero.astro+0 −331
删除www/src/components/Install.astro+0 −179
删除www/src/components/InstallTabs.astro+0 −171
删除www/src/components/Landing.astro+0 −28
删除www/src/components/Nav.astro+0 −325
删除www/src/components/Reference.astro+0 −251
删除www/src/components/Threat.astro+0 −133
删除www/src/components/Usage.astro+0 −125
新增www/src/data/release.json+5 −0看文件
新增www/src/i18n/cage.ts+72 −0看文件
删除www/src/i18n/en.ts+0 −848
删除www/src/i18n/fr.ts+0 −845
删除www/src/i18n/index.ts+0 −38
新增www/src/i18n/languages.ts+94 −0看文件
删除www/src/layouts/Base.astro+0 −116
删除www/src/lib/french-typography.ts+0 −44
删除www/src/lib/inline.ts+0 −30
删除www/src/lib/shell-highlight.ts+0 −138
删除www/src/lib/slug.ts+0 −12
修改www/src/pages/404.astro+1 −1看文件
新增www/src/pages/[locale]/index.astro+9 −0看文件
删除www/src/pages/fr/index.astro+0 −3
修改www/src/pages/index.astro+2 −53看文件
修改www/src/styles/cage.css+75 −0看文件
删除www/src/styles/global.css+0 −408
| @@ -25,18 +25,24 @@ jobs: | ||
| 25 | 25 | cache: npm |
| 26 | 26 | cache-dependency-path: ui/package-lock.json |
| 27 | 27 | - uses: astral-sh/[email protected] |
| 28 | 新增: - name: Application version consistency | |
| 29 | 新增: run: node scripts/check-version.mjs | |
| 28 | 30 | - name: Build the actual macOS application |
| 29 | 31 | run: bash scripts/build-app.sh |
| 30 | 32 | - name: Workbench checks |
| 31 | 33 | run: | |
| 32 | 34 | npm run --prefix ui lint |
| 33 | 35 | npm test --prefix ui |
| 34 | 删除: node --test internal/cage/clipboard.test.cjs | |
| 36 | 新增: node --test internal/cage/clipboard.test.cjs internal/cage/browser-audit.test.mjs internal/cage/browser-downloads.test.mjs | |
| 37 | 新增: uv run internal/cage/save-download.test.py | |
| 38 | 新增: uv run internal/cage/editor-migrate.test.py | |
| 35 | 39 | - name: Go tests and vet |
| 36 | 40 | run: | |
| 37 | 41 | make test-go |
| 38 | 42 | go test -race ./internal/cage ./internal/managedproxy ./internal/workbench |
| 39 | 43 | go vet ./cmd/cage ./internal/cage ./internal/managedproxy ./internal/workbench |
| 44 | 新增: - name: Native application updater | |
| 45 | 新增: run: bash scripts/test-app-updates.sh | |
| 40 | 46 | - name: Patched networking and shared files |
| 41 | 47 | run: | |
| 42 | 48 | go test github.com/containers/gvisor-tap-vsock/pkg/services/dns github.com/lima-vm/lima/v2/pkg/hostagent/dns github.com/lima-vm/lima/v2/pkg/networks/usernet github.com/lima-vm/sshocker/pkg/reversesshfs |
| @@ -1,19 +1,52 @@ | ||
| 1 | 删除:name: Website checks | |
| 1 | 新增:name: Website and public releases | |
| 2 | 2 | on: |
| 3 | 3 | push: |
| 4 | 删除: paths: ['www/**', '.github/workflows/www.yml'] | |
| 4 | 新增: branches: [main] | |
| 5 | 新增: paths: ['www/**', 'assets/**', 'README*.md', 'scripts/verify-macos-release.sh', '.github/workflows/www.yml'] | |
| 5 | 6 | pull_request: |
| 6 | 删除: paths: ['www/**', '.github/workflows/www.yml'] | |
| 7 | 新增: paths: ['www/**', 'assets/**', 'README*.md', 'scripts/verify-macos-release.sh', '.github/workflows/www.yml'] | |
| 8 | 新增: release: | |
| 9 | 新增: types: [published, edited] | |
| 7 | 10 | workflow_dispatch: |
| 11 | 新增: inputs: | |
| 12 | 新增: release_tag: | |
| 13 | 新增: description: 'Optional public release tag to download and verify before deployment' | |
| 14 | 新增: required: false | |
| 15 | 新增: type: string | |
| 8 | 16 | permissions: |
| 9 | 17 | contents: read |
| 18 | 新增:concurrency: | |
| 19 | 新增: group: website-${{ github.ref }} | |
| 20 | 新增: cancel-in-progress: false | |
| 10 | 21 | jobs: |
| 22 | 新增: verify-release: | |
| 23 | 新增: if: (github.event_name == 'release' && !github.event.release.draft) || (github.event_name == 'workflow_dispatch' && inputs.release_tag != '') | |
| 24 | 新增: runs-on: macos-15 | |
| 25 | 新增: timeout-minutes: 15 | |
| 26 | 新增: steps: | |
| 27 | 新增: # Tags can predate this workflow. The verification tools live on main. | |
| 28 | 新增: - uses: actions/checkout@v4 | |
| 29 | 新增: with: | |
| 30 | 新增: ref: main | |
| 31 | 新增: persist-credentials: false | |
| 32 | 新增: - uses: actions/setup-node@v4 | |
| 33 | 新增: with: | |
| 34 | 新增: node-version: 24 | |
| 35 | 新增: - name: Download public assets and verify SHA-256 | |
| 36 | 新增: env: | |
| 37 | 新增: RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag }} | |
| 38 | 新增: run: node www/scripts/sync-release.mjs --tag "$RELEASE_TAG" --output "$RUNNER_TEMP/release.json" --archive-directory "$RUNNER_TEMP/release" | |
| 39 | 新增: - name: Verify the shipped macOS application | |
| 40 | 新增: run: bash scripts/verify-macos-release.sh "$RUNNER_TEMP/release" | |
| 11 | 41 | build: |
| 42 | 新增: needs: verify-release | |
| 43 | 新增: if: always() && !cancelled() && (needs.verify-release.result == 'success' || needs.verify-release.result == 'skipped') | |
| 12 | 44 | runs-on: ubuntu-latest |
| 13 | 45 | timeout-minutes: 15 |
| 14 | 46 | steps: |
| 15 | 47 | - uses: actions/checkout@v4 |
| 16 | 48 | with: |
| 49 | 新增: ref: ${{ github.event_name == 'release' && 'main' || github.ref }} | |
| 17 | 50 | persist-credentials: false |
| 18 | 51 | - uses: actions/setup-node@v4 |
| 19 | 52 | with: |
| @@ -21,11 +54,30 @@ jobs: | ||
| 21 | 54 | cache: npm |
| 22 | 55 | cache-dependency-path: www/package-lock.json |
| 23 | 56 | - run: npm ci --prefix www |
| 57 | 新增: - run: node --test www/scripts/sync-release.test.mjs | |
| 58 | 新增: - name: Resolve the public download version | |
| 59 | 新增: run: node www/scripts/sync-release.mjs | |
| 24 | 60 | - run: npm run --prefix www check |
| 25 | 61 | - run: npm run --prefix www build |
| 26 | 删除: - uses: actions/upload-artifact@v4 | |
| 62 | 新增: - run: node www/scripts/check-site.mjs | |
| 63 | 新增: - uses: actions/upload-pages-artifact@v4 | |
| 27 | 64 | with: |
| 28 | 删除: name: cage-website | |
| 29 | 65 | path: www/dist |
| 30 | 删除:# Publication is separate from CI while the project is private. | |
| 31 | 删除:# GitHub Pages must not silently expose a private preview. | |
| 66 | 新增: deploy: | |
| 67 | 新增: needs: build | |
| 68 | 新增: if: always() && needs.build.result == 'success' && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.event_name == 'release') | |
| 69 | 新增: runs-on: ubuntu-latest | |
| 70 | 新增: timeout-minutes: 10 | |
| 71 | 新增: concurrency: | |
| 72 | 新增: group: github-pages | |
| 73 | 新增: cancel-in-progress: false | |
| 74 | 新增: permissions: | |
| 75 | 新增: pages: write | |
| 76 | 新增: id-token: write | |
| 77 | 新增: environment: | |
| 78 | 新增: name: github-pages | |
| 79 | 新增: url: ${{ steps.deployment.outputs.page_url }} | |
| 80 | 新增: steps: | |
| 81 | 新增: - name: Deploy GitHub Pages | |
| 82 | 新增: id: deployment | |
| 83 | 新增: uses: actions/deploy-pages@v4 | |
| @@ -1,4 +1,6 @@ | ||
| 1 | 删除:# Changelog | |
| 1 | 新增:# Upstream agent-vm changelog | |
| 2 | 新增: | |
| 3 | 新增:The entries below retain the upstream agent-vm version history. Cage release notes and validation scope are published in [Cage Releases](https://github.com/Lee-xeo/Claude-Cage/releases); Cage uses its own `VERSION` and macOS packaging workflow. These upstream version numbers and platform artifacts do not describe Cage desktop releases. | |
| 2 | 4 | |
| 3 | 5 | ## 0.3.1 |
| 4 | 6 | |
| @@ -14,6 +14,8 @@ bash scripts/build-app.sh | ||
| 14 | 14 | |
| 15 | 15 | 构建会下载并校验固定版本的 Mihomo,构建前端和嵌入式客机组件,再生成 `_output/Cage.app`。未指定签名身份的本地开发构建使用 ad-hoc 签名;不能将其视为可通过 Gatekeeper 的正式发行包。 |
| 16 | 16 | |
| 17 | 新增:需要保留日常 App 时,指定独立输出且不使用 `--install`:`CAGE_BUILD_OUTPUT="$PWD/_output/validation/Cage.app" bash scripts/build-app.sh`。输出必须是绝对 `.app` 路径;此模式不清理其他副本。目标 App 或控制程序仍在运行时,构建会拒绝覆盖。开发构建也不能用于验证正式签名包的自动安装成功路径。 | |
| 18 | 新增: | |
| 17 | 19 | 安装到当前用户的 Applications 目录: |
| 18 | 20 | |
| 19 | 21 | ```sh |
| @@ -46,7 +48,9 @@ bash scripts/build-app.sh --install | ||
| 46 | 48 | npm ci --prefix ui |
| 47 | 49 | npm run --prefix ui lint |
| 48 | 50 | npm test --prefix ui |
| 49 | 删除:node --test internal/cage/clipboard.test.cjs | |
| 51 | 新增:node --test internal/cage/clipboard.test.cjs internal/cage/browser-audit.test.mjs internal/cage/browser-downloads.test.mjs | |
| 52 | 新增:uv run internal/cage/save-download.test.py | |
| 53 | 新增:uv run internal/cage/editor-migrate.test.py | |
| 50 | 54 | go test -race ./internal/workbench ./internal/cage ./internal/managedproxy |
| 51 | 55 | go test ./internal/... ./cmd/... |
| 52 | 56 | ``` |
| @@ -59,6 +63,10 @@ go test github.com/containers/gvisor-tap-vsock/pkg/services/dns \ | ||
| 59 | 63 | github.com/lima-vm/lima/v2/pkg/networks/usernet |
| 60 | 64 | ``` |
| 61 | 65 | |
| 66 | 新增:修改浏览器启动或控制逻辑时,在 Linux 客机的独立 X 显示中运行 `DISPLAY=:183 node scripts/browser-controls-smoke.mjs`。该检查使用临时配置和真实控制器,验证人工浏览标记、标签与导航、重启后的页面及 Cookie 恢复,并检查未认证请求和跨来源请求仍被拒绝。 | |
| 67 | 新增: | |
| 68 | 新增:修改更新或恢复界面时,运行 `node ui/scripts/recovery-ui-smoke.mjs`;修改画面可见性时,运行 `node ui/scripts/remote-visibility-smoke.mjs`。两者需要可用的 Playwright 和已启动的前端开发服务,可通过 `CAGE_UI_URL` 指定地址;测试使用隔离接口,后者还使用真实 RFB 握手与帧验证停止和恢复,不连接日常 VM。修改原生更新流程时运行 `bash scripts/test-app-updates.sh`,正式签名、公证及真实安装仍须单独验收。组件清单、固定工具安装器和网络续租回归已包含在上述 Go 包测试中,无需重复执行一套独立命令。 | |
| 69 | 新增: | |
| 62 | 70 | 修改上游源码时,保持 `patches/` 与 `third_party/` 一致,并按 `patches/README.md` 核对同步方式。UI 改动需要在实际 App 中验证状态、失败恢复和关键交互;编译通过不能证明登录、联网或用户操作已成功。 |
| 63 | 71 | |
| 64 | 72 | 建议使用独立测试配置和非敏感测试项目,避免将开发验证写入日常环境。启动前的 Git 保护检查属于主机状态:单独指定 Cage 配置目录不会隔离全局 Git 设置,测试修改路径时应使用隔离的测试用户目录。应用必须先解释影响,用户明确确认后才将 `safe.bareRepository` 设置为 `explicit`,并在复检通过后启动环境;读取状态不得修改 Git 配置。真实网络验证应区分代理连通、环境放行、浏览器访问、Claude 授权与模型请求,不能互相替代。 |
| @@ -67,7 +75,7 @@ go test github.com/containers/gvisor-tap-vsock/pkg/services/dns \ | ||
| 67 | 75 | |
| 68 | 76 | 配置与状态默认在 `~/.claude-cage/`。`CLAUDE_CAGE_CONFIG` 可以指向另一份私有配置,其父目录拥有独立状态。配置文件权限为 `0600`;不要把该目录作为共享项目或提交到 Git。 |
| 69 | 77 | |
| 70 | 删除:`environment.json` 固定记录环境的 VM 目录,`projects.json` 保存明确打开的共享目录,`workbench.json` 保存当前项目与偏好。选择项目不会改变 VM 身份。浏览器配置在客机的 `/home/cage-browser/profile`,Claude Code 的固定安装版本见 `agent-vm.setup.sh`。 | |
| 78 | 新增:`environment.json` 固定记录环境的 VM 目录,`projects.json` 保存明确打开的共享目录,`workbench.json` 保存当前项目与偏好。选择项目不会改变 VM 身份。浏览器配置在客机的 `/home/cage-browser/profile`,受管工具的最低版本与包摘要见 `internal/cage/tool-versions.env`。替换 App、同步组件和升级工具是不同操作,契约见[工作台设计](docs/design/workbench.md#持久环境的组件与工具版本)。 | |
| 71 | 79 | |
| 72 | 80 | ```sh |
| 73 | 81 | bash scripts/fetch-proxy-core.sh |
| @@ -12,11 +12,9 @@ | ||
| 12 | 12 | GO ?= go |
| 13 | 13 | GOOS ?= $(shell $(GO) env GOOS) |
| 14 | 14 | GOARCH ?= $(shell $(GO) env GOARCH) |
| 15 | 删除:# The tag when HEAD has one, else the next release's: a build after 0.3.0 is | |
| 16 | 删除:# 0.3.1-dev, not 0.3.0-N after the last tag (version --min). | |
| 17 | 删除:NEXT_VERSION := 0.3.1 | |
| 18 | 删除:VERSION ?= $(shell t=$$(git describe --tags --match 'v[0-9]*' --exact-match --dirty=.m 2>/dev/null) && echo "$$t" | sed 's/^v//' || \ | |
| 19 | 删除: echo "$(NEXT_VERSION)-dev.$$(git rev-parse --short HEAD 2>/dev/null || echo unknown)") | |
| 15 | 新增:# Cage's VERSION file owns the default. Upstream release tooling can still | |
| 16 | 新增:# supply VERSION explicitly when building a historical agent-vm tag. | |
| 17 | 新增:VERSION ?= $(shell tr -d '\r\n' < VERSION) | |
| 20 | 18 | LIMA_VERSION := $(shell awk '$$1 == "lima" { print $$4 }' third_party/SOURCES) |
| 21 | 19 | |
| 22 | 20 | ifeq ($(GOARCH),amd64) |
| @@ -25,7 +25,7 @@ Claude Cage የሊኑክስ ተርሚናልን፣ አሳሽ እና ፋይል አ | ||
| 25 | 25 | |
| 26 | 26 | **የ Cage ዋና በይነገጽ** |
| 27 | 27 | |
| 28 | 删除:! [አልፋ 2 የስራ ቤንች እና ተርሚናል ሄሎ-ካጅ ማሳያ ፕሮጄክትን ያሳያል](www/public/workbench.jpg) | |
| 28 | 新增:! [Cage የስራ ቤንች እና ተርሚናል ሄሎ-ካጅ ማሳያ ፕሮጄክትን ያሳያል](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## በ Cage ምን ማድረግ ይችላሉ |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage የሊኑክስ ተርሚናልን፣ አሳሽ እና ፋይል አ | ||
| 54 | 54 | |
| 55 | 55 | ጫኚው የስራ ቤንች እና የኔትወርክ ፕሮክሲ ኮርን ያካትታል። ዕለታዊ አጠቃቀም Go፣ Node.js፣ Docker ወይም Clash መጫን አያስፈልገውም። መጀመሪያ ማስጀመር የሊኑክስን ምስል እና የግንባታ መሳሪያዎችን ለማውረድ አሁንም የበይነመረብ ግንኙነት ይፈልጋል። Cage የኔትወርክ ተኪ አገልግሎትም ሆነ የClaude መለያ አይሰጥም። |
| 56 | 56 | |
| 57 | 删除:የአሁኑ ስሪት፡ `0.2.0-alpha.2`. የምንጭ ኮድ፣ ድር ጣቢያ እና የተለቀቁት ይፋዊ ናቸው። ለጫኚ ፊርማ፣ አፕል ኖተራይዜሽን እና የማረጋገጫ ወሰን የእያንዳንዱን ልቀት ማስታወሻ ይመልከቱ። ንጹህ ማሽን መጫን፣ macOS 14 ን በሚያሄዱ አካላዊ Macs ላይ ተኳሃኝነት፣ የእውነተኛ Claude መለያ ፈቃድ እና የሞዴል ጥያቄዎች አሁንም ሙሉ ማረጋገጫ ያስፈልጋቸዋል። | |
| 57 | 新增:የአሁኑ ስሪት፡ `0.1.0-alpha.1`. የምንጭ ኮድ፣ ድር ጣቢያ እና የተለቀቁት ይፋዊ ናቸው። ለጫኚ ፊርማ፣ አፕል ኖተራይዜሽን እና የማረጋገጫ ወሰን የእያንዳንዱን ልቀት ማስታወሻ ይመልከቱ። ንጹህ ማሽን መጫን፣ macOS 14 ን በሚያሄዱ አካላዊ Macs ላይ ተኳሃኝነት፣ የእውነተኛ Claude መለያ ፈቃድ እና የሞዴል ጥያቄዎች አሁንም ሙሉ ማረጋገጫ ያስፈልጋቸዋል። | |
| 58 | 58 | |
| 59 | 删除:የውስጠ-መተግበሪያ ማሻሻያ ድጋፍ ያላቸው ስሪቶች ከታች በስተግራ ጥግ ላይ ያለውን የዝማኔ ቁጥጥር ያሳያሉ። ዝማኔ ሲገኝ፣ የታች ቀስት መሣሪያ ጫፉ 'አውርድ ዝመናን' ያነባል። እሱን ጠቅ ማድረግ ያውርዳል፣ ያረጋግጣል፣ ይጭናል እና መተግበሪያውን እንደገና ያስጀምራል። አስቀምጥ እና መጀመሪያ ስራዎችን ማስኬድ አቁም. በተመረጠው የአውታረ መረብ ተኪ በኩል ማውረድን ያዘምናል፣ ወደ ቀጥታ ግንኙነት ምንም መመለስ የለም። በራስ ሰር መጫን ከተመሳሳይ አታሚ ፊርማ እና የአፕል ማረጋገጫ ያስፈልገዋል። አልፋ 1 ተጠቃሚዎች መጀመሪያ አልፋ 2ን በእጅ መጫን አለባቸው። ተከታይ ስሪቶች የውስጠ-መተግበሪያ ዝማኔዎችን መጠቀም ይችላሉ። ለዝርዝር መረጃ ይመልከቱ [ያሻሽሉ እና ያራግፉ](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:የውስጠ-መተግበሪያ ማሻሻያ ድጋፍ ያላቸው ስሪቶች ከታች በስተግራ ጥግ ላይ ያለውን የዝማኔ ቁጥጥር ያሳያሉ። ዝማኔ ሲገኝ፣ የታች ቀስት መሣሪያ ጫፉ 'አውርድ ዝመናን' ያነባል። እሱን ጠቅ ማድረግ ያውርዳል፣ ያረጋግጣል፣ ይጭናል እና መተግበሪያውን እንደገና ያስጀምራል። አስቀምጥ እና መጀመሪያ ስራዎችን ማስኬድ አቁም. በተመረጠው የአውታረ መረብ ተኪ በኩል ማውረድን ያዘምናል፣ ወደ ቀጥታ ግንኙነት ምንም መመለስ የለም። በራስ ሰር መጫን ከተመሳሳይ አታሚ ፊርማ እና የአፕል ማረጋገጫ ያስፈልገዋል። ተከታይ ስሪቶች የውስጠ-መተግበሪያ ዝማኔዎችን መጠቀም ይችላሉ። ለዝርዝር መረጃ ይመልከቱ [ያሻሽሉ እና ያራግፉ](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## በሶስት ደረጃዎች ይጀምሩ |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage عبارة عن جهاز Linux افتراضي خفيف الوزن ي | ||
| 25 | 25 | |
| 26 | 26 | **الواجهة الرئيسية للقفص:** |
| 27 | 27 | |
| 28 | 删除:! [منضدة العمل والمحطة الطرفية لـ Alpha 2 تعرض المشروع التجريبي لـ hello-cage](www/public/workbench.jpg) | |
| 28 | 新增:! [منضدة العمل والمحطة الطرفية لـ Cage تعرض المشروع التجريبي لـ hello-cage](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## ما يمكنك فعله مع كيج |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage عبارة عن جهاز Linux افتراضي خفيف الوزن ي | ||
| 54 | 54 | |
| 55 | 55 | يشتمل برنامج التثبيت على منضدة العمل ونواة وكيل الشبكة. لا يتطلب الاستخدام اليومي تثبيت Go أو Node.js أو Docker أو Clash. لا يزال الإطلاق الأول يتطلب اتصالاً بالإنترنت لتنزيل صورة Linux وأدوات التطوير. لا يوفر Cage خدمة وكيل الشبكة ولا حساب Claude. |
| 56 | 56 | |
| 57 | 删除:الإصدار الحالي: `0.2.0-alpha.2`. كود المصدر والموقع الإلكتروني والإصدارات عامة. راجع ملاحظات كل إصدار لتوقيع المثبت وتوثيق Apple ونطاق التحقق من الصحة. لا يزال التثبيت النظيف للجهاز، والتوافق على أجهزة Mac الفعلية التي تعمل بنظام macOS 14، والترخيص الحقيقي لحساب Claude، وطلبات النماذج تتطلب التحقق الكامل من الصحة. | |
| 57 | 新增:الإصدار الحالي: `0.1.0-alpha.1`. كود المصدر والموقع الإلكتروني والإصدارات عامة. راجع ملاحظات كل إصدار لتوقيع المثبت وتوثيق Apple ونطاق التحقق من الصحة. لا يزال التثبيت النظيف للجهاز، والتوافق على أجهزة Mac الفعلية التي تعمل بنظام macOS 14، والترخيص الحقيقي لحساب Claude، وطلبات النماذج تتطلب التحقق الكامل من الصحة. | |
| 58 | 58 | |
| 59 | 删除:تُظهر الإصدارات التي تدعم التحديث داخل التطبيق عنصر تحكم في التحديث في الزاوية السفلية اليسرى. عندما يتوفر تحديث، يقرأ تلميح الأداة المتجه للأسفل "تنزيل التحديث". يؤدي النقر فوقه إلى تنزيل التطبيق والتحقق منه وتثبيته وإعادة تشغيله. حفظ وإيقاف تشغيل المهام أولاً. يتم تنزيل التحديثات من خلال وكيل الشبكة المحدد، دون الرجوع إلى الاتصال المباشر. يتطلب التثبيت التلقائي توقيعًا من نفس الناشر وتحققًا من Apple. يجب على مستخدمي Alpha 1 أولاً تثبيت Alpha 2 يدويًا؛ يمكن للإصدارات اللاحقة استخدام التحديثات داخل التطبيق. لمزيد من التفاصيل، انظر [ترقية وإلغاء التثبيت](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:تُظهر الإصدارات التي تدعم التحديث داخل التطبيق عنصر تحكم في التحديث في الزاوية السفلية اليسرى. عندما يتوفر تحديث، يقرأ تلميح الأداة المتجه للأسفل "تنزيل التحديث". يؤدي النقر فوقه إلى تنزيل التطبيق والتحقق منه وتثبيته وإعادة تشغيله. حفظ وإيقاف تشغيل المهام أولاً. يتم تنزيل التحديثات من خلال وكيل الشبكة المحدد، دون الرجوع إلى الاتصال المباشر. يتطلب التثبيت التلقائي توقيعًا من نفس الناشر وتحققًا من Apple. يمكن للإصدارات اللاحقة استخدام التحديثات داخل التطبيق. لمزيد من التفاصيل، انظر [ترقية وإلغاء التثبيت](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## ابدأ في ثلاث خطوات |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage - гэта лёгкая віртуальная машына Linux, | ||
| 25 | 25 | |
| 26 | 26 | **Асноўны інтэрфейс Cage:** |
| 27 | 27 | |
| 28 | 删除:! [Варштат і тэрмінал Alpha 2, якія паказваюць дэма-праект Hello-Cage](www/public/workbench.jpg) | |
| 28 | 新增:! [Варштат і тэрмінал Cage, якія паказваюць дэма-праект Hello-Cage](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## Што ты можаш зрабіць з Cageам |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage - гэта лёгкая віртуальная машына Linux, | ||
| 54 | 54 | |
| 55 | 55 | Праграма ўстаноўкі ўключае варштат і ядро сеткавага проксі. Штодзённае выкарыстанне не патрабуе ўстаноўкі Go, Node.js, Docker або Clash. Для першага запуску па-ранейшаму патрабуецца падключэнне да Інтэрнэту для загрузкі вобраза Linux і інструментаў распрацоўкі. Cage не забяспечвае ні паслугу сеткавага проксі, ні ўліковы запіс Claude. |
| 56 | 56 | |
| 57 | 删除:Актуальная версія: `0.2.0-alpha.2`. Зыходны код, вэб-сайт і выпускі з'яўляюцца агульнадаступнымі. Звярніцеся да заўваг да кожнага выпуску для подпісу ўсталёўшчыка, натарыяльнага засведчання Apple і аб'ёму праверкі. Усталяванне на чыстай машыне, сумяшчальнасць на фізічных Mac пад кіраваннем macOS 14, аўтарызацыя рэальнага ўліковага запісу Claude і запыты мадэляў па-ранейшаму патрабуюць поўнай праверкі. | |
| 57 | 新增:Актуальная версія: `0.1.0-alpha.1`. Зыходны код, вэб-сайт і выпускі з'яўляюцца агульнадаступнымі. Звярніцеся да заўваг да кожнага выпуску для подпісу ўсталёўшчыка, натарыяльнага засведчання Apple і аб'ёму праверкі. Усталяванне на чыстай машыне, сумяшчальнасць на фізічных Mac пад кіраваннем macOS 14, аўтарызацыя рэальнага ўліковага запісу Claude і запыты мадэляў па-ранейшаму патрабуюць поўнай праверкі. | |
| 58 | 58 | |
| 59 | 删除:Версіі з падтрымкай абнаўленняў у праграме паказваюць элемент кіравання абнаўленнямі ў левым ніжнім куце. Калі абнаўленне даступна, падказка са стрэлкай уніз абвяшчае «Спампаваць абнаўленне». Пстрыкнуўшы па ім, праграма спампоўваецца, правяраецца, усталёўваецца і перазапускаецца. Спачатку захавайце і спыніце запушчаныя задачы. Абнаўленні спампоўваюцца праз абраны сеткавы проксі без вяртання да прамога злучэння. Аўтаматычная ўстаноўка патрабуе подпісу таго ж выдаўца і праверкі Apple. Карыстальнікі Alpha 1 павінны спачатку ўсталяваць Alpha 2 уручную; наступныя версіі могуць выкарыстоўваць абнаўленні ў дадатку. Падрабязней гл [Абнавіць і выдаліць](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:Версіі з падтрымкай абнаўленняў у праграме паказваюць элемент кіравання абнаўленнямі ў левым ніжнім куце. Калі абнаўленне даступна, падказка са стрэлкай уніз абвяшчае «Спампаваць абнаўленне». Пстрыкнуўшы па ім, праграма спампоўваецца, правяраецца, усталёўваецца і перазапускаецца. Спачатку захавайце і спыніце запушчаныя задачы. Абнаўленні спампоўваюцца праз абраны сеткавы проксі без вяртання да прамога злучэння. Аўтаматычная ўстаноўка патрабуе подпісу таго ж выдаўца і праверкі Apple. Наступныя версіі могуць выкарыстоўваць абнаўленні ў дадатку. Падрабязней гл [Абнавіць і выдаліць](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## Пачніце ў тры этапы |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage es una máquina virtual Linux liviana que combina una terminal Linux | ||
| 25 | 25 | |
| 26 | 26 | **Interfaz principal de Cage:** |
| 27 | 27 | |
| 28 | 删除:! [Banco de trabajo y terminal Alpha 2 que muestra el proyecto de demostración hello-cage](www/public/workbench.jpg) | |
| 28 | 新增:! [Banco de trabajo y terminal Cage que muestra el proyecto de demostración hello-cage](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## ¿Qué puedes hacer con la jaula? |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ La versión inicial admite **Apple Silicon Macs (chips de la serie M), con macOS | ||
| 54 | 54 | |
| 55 | 55 | El instalador incluye el banco de trabajo y el núcleo del proxy de red. El uso diario no requiere instalar Go, Node.js, Docker o Clash. El primer lanzamiento aún requiere una conexión a Internet para descargar la imagen de Linux y las herramientas de desarrollo. Cage no proporciona un servicio de proxy de red ni una cuenta Claude. |
| 56 | 56 | |
| 57 | 删除:Versión actual: `0.2.0-alpha.2`. El código fuente, el sitio web y los lanzamientos son públicos. Consulte las notas de cada versión para conocer la firma del instalador, la certificación notarial de Apple y el alcance de la validación. La instalación en máquina limpia, la compatibilidad con Mac físicos que ejecutan macOS 14, la autorización de cuentas reales de Claude y las solicitudes de modelos aún requieren una validación completa. | |
| 57 | 新增:Versión actual: `0.1.0-alpha.1`. El código fuente, el sitio web y los lanzamientos son públicos. Consulte las notas de cada versión para conocer la firma del instalador, la certificación notarial de Apple y el alcance de la validación. La instalación en máquina limpia, la compatibilidad con Mac físicos que ejecutan macOS 14, la autorización de cuentas reales de Claude y las solicitudes de modelos aún requieren una validación completa. | |
| 58 | 58 | |
| 59 | 删除:Las versiones con soporte de actualización en la aplicación muestran un control de actualización en la esquina inferior izquierda. Cuando hay una actualización disponible, la información sobre herramientas de la flecha hacia abajo dice "Descargar actualización". Al hacer clic en él, se descarga, verifica, instala y reinicia la aplicación. Guarde y detenga la ejecución de tareas primero. Las actualizaciones se descargan a través del proxy de red seleccionado, sin recurrir a una conexión directa. La instalación automática requiere una firma del mismo editor y verificación de Apple. Los usuarios de Alpha 1 primero deben instalar Alpha 2 manualmente; Las versiones posteriores pueden utilizar actualizaciones dentro de la aplicación. Para más detalles, consulte [Actualizar y desinstalar](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:Las versiones con soporte de actualización en la aplicación muestran un control de actualización en la esquina inferior izquierda. Cuando hay una actualización disponible, la información sobre herramientas de la flecha hacia abajo dice "Descargar actualización". Al hacer clic en él, se descarga, verifica, instala y reinicia la aplicación. Guarde y detenga la ejecución de tareas primero. Las actualizaciones se descargan a través del proxy de red seleccionado, sin recurrir a una conexión directa. La instalación automática requiere una firma del mismo editor y verificación de Apple. Las versiones posteriores pueden utilizar actualizaciones dentro de la aplicación. Para más detalles, consulte [Actualizar y desinstalar](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## Comience en tres pasos |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage یک ماشین مجازی لینوکس سبک وزن است که ت | ||
| 25 | 25 | |
| 26 | 26 | **رابط اصلی Cage:** |
| 27 | 27 | |
| 28 | 删除:! [میز کار و پایانه آلفا 2 که پروژه آزمایشی hello-cage را نشان می دهد](www/public/workbench.jpg) | |
| 28 | 新增:! [میز کار و پایانه Cage که پروژه آزمایشی hello-cage را نشان می دهد](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## کاری که می توانید با Cage انجام دهید |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage یک ماشین مجازی لینوکس سبک وزن است که ت | ||
| 54 | 54 | |
| 55 | 55 | نصب کننده شامل میز کار و هسته پروکسی شبکه است. استفاده روزانه نیازی به نصب Go، Node.js، Docker یا Clash ندارد. اولین راهاندازی همچنان به اتصال اینترنت برای دانلود تصویر لینوکس و ابزارهای توسعه نیاز دارد. Cage نه سرویس پروکسی شبکه و نه حساب Claude ارائه می دهد. |
| 56 | 56 | |
| 57 | 删除:نسخه فعلی: `0.2.0-alpha.2`. کد منبع، وبسایت و نسخهها عمومی هستند. به یادداشتهای هر نسخه برای امضای نصبکننده، تأیید اسناد رسمی اپل و دامنه اعتبارسنجی مراجعه کنید. نصب ماشین تمیز، سازگاری در مک های فیزیکی دارای سیستم عامل macOS 14، مجوز واقعی حساب Claude، و درخواست های مدل هنوز به تأیید کامل نیاز دارند. | |
| 57 | 新增:نسخه فعلی: `0.1.0-alpha.1`. کد منبع، وبسایت و نسخهها عمومی هستند. به یادداشتهای هر نسخه برای امضای نصبکننده، تأیید اسناد رسمی اپل و دامنه اعتبارسنجی مراجعه کنید. نصب ماشین تمیز، سازگاری در مک های فیزیکی دارای سیستم عامل macOS 14، مجوز واقعی حساب Claude، و درخواست های مدل هنوز به تأیید کامل نیاز دارند. | |
| 58 | 58 | |
| 59 | 删除:نسخههایی که از بهروزرسانی درونبرنامه پشتیبانی میکنند، کنترل بهروزرسانی را در گوشه پایین سمت چپ نشان میدهند. وقتی یک بهروزرسانی در دسترس است، راهنمای ابزار فلش رو به پایین «دانلود بهروزرسانی» را میخواند. با کلیک بر روی آن برنامه دانلود، تأیید، نصب و راه اندازی مجدد می شود. ابتدا وظایف در حال اجرا را ذخیره و متوقف کنید. بهروزرسانیها از طریق پراکسی شبکه انتخاب شده، بدون بازگشت به اتصال مستقیم، دانلود میشوند. نصب خودکار به امضای همان ناشر و تأیید اپل نیاز دارد. کاربران آلفا 1 ابتدا باید آلفا 2 را به صورت دستی نصب کنند. نسخه های بعدی می توانند از به روز رسانی های درون برنامه ای استفاده کنند. برای جزئیات، نگاه کنید [ارتقا و حذف نصب کنید](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:نسخههایی که از بهروزرسانی درونبرنامه پشتیبانی میکنند، کنترل بهروزرسانی را در گوشه پایین سمت چپ نشان میدهند. وقتی یک بهروزرسانی در دسترس است، راهنمای ابزار فلش رو به پایین «دانلود بهروزرسانی» را میخواند. با کلیک بر روی آن برنامه دانلود، تأیید، نصب و راه اندازی مجدد می شود. ابتدا وظایف در حال اجرا را ذخیره و متوقف کنید. بهروزرسانیها از طریق پراکسی شبکه انتخاب شده، بدون بازگشت به اتصال مستقیم، دانلود میشوند. نصب خودکار به امضای همان ناشر و تأیید اپل نیاز دارد. نسخه های بعدی می توانند از به روز رسانی های درون برنامه ای استفاده کنند. برای جزئیات، نگاه کنید [ارتقا و حذف نصب کنید](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## در سه مرحله شروع کنید |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage est une machine virtuelle Linux légère qui combine un terminal Lin | ||
| 25 | 25 | |
| 26 | 26 | **L'interface principale de Cage :** |
| 27 | 27 | |
| 28 | 删除:! [Établi et terminal Alpha 2 montrant le projet de démonstration hello-cage](www/public/workbench.jpg) | |
| 28 | 新增:! [Établi et terminal Cage montrant le projet de démonstration hello-cage](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## Ce que vous pouvez faire avec Cage |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ La version initiale prend en charge **Mac Apple Silicon (puces de la série M), | ||
| 54 | 54 | |
| 55 | 55 | Le programme d'installation comprend le workbench et le noyau du proxy réseau. Une utilisation quotidienne ne nécessite pas l'installation de Go, Node.js, Docker ou Clash. Le premier lancement nécessite toujours une connexion Internet pour télécharger l’image Linux et les outils de développement. Cage ne fournit ni service proxy réseau ni compte Claude. |
| 56 | 56 | |
| 57 | 删除:Version actuelle : `0.2.0-alpha.2`. Le code source, le site Web et les versions sont publics. Reportez-vous aux notes de chaque version pour la signature du programme d'installation, la notarisation Apple et la portée de la validation. L'installation sur une machine propre, la compatibilité sur les Mac physiques exécutant macOS 14, l'autorisation réelle du compte Claude et les demandes de modèle nécessitent toujours une validation complète. | |
| 57 | 新增:Version actuelle : `0.1.0-alpha.1`. Le code source, le site Web et les versions sont publics. Reportez-vous aux notes de chaque version pour la signature du programme d'installation, la notarisation Apple et la portée de la validation. L'installation sur une machine propre, la compatibilité sur les Mac physiques exécutant macOS 14, l'autorisation réelle du compte Claude et les demandes de modèle nécessitent toujours une validation complète. | |
| 58 | 58 | |
| 59 | 删除:Les versions avec prise en charge des mises à jour intégrées à l'application affichent un contrôle de mise à jour dans le coin inférieur gauche. Lorsqu'une mise à jour est disponible, l'info-bulle de la flèche vers le bas indique « Télécharger la mise à jour ». En cliquant dessus, vous téléchargez, vérifiez, installez et redémarrez l'application. Enregistrez et arrêtez d'abord les tâches en cours d'exécution. Les mises à jour sont téléchargées via le proxy réseau sélectionné, sans recours à une connexion directe. L'installation automatique nécessite une signature du même éditeur et une vérification Apple. Les utilisateurs d'Alpha 1 doivent d'abord installer Alpha 2 manuellement ; les versions ultérieures peuvent utiliser des mises à jour intégrées à l'application. Pour plus de détails, voir [Mettre à niveau et désinstaller](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:Les versions avec prise en charge des mises à jour intégrées à l'application affichent un contrôle de mise à jour dans le coin inférieur gauche. Lorsqu'une mise à jour est disponible, l'info-bulle de la flèche vers le bas indique « Télécharger la mise à jour ». En cliquant dessus, vous téléchargez, vérifiez, installez et redémarrez l'application. Enregistrez et arrêtez d'abord les tâches en cours d'exécution. Les mises à jour sont téléchargées via le proxy réseau sélectionné, sans recours à une connexion directe. L'installation automatique nécessite une signature du même éditeur et une vérification Apple. Les versions ultérieures peuvent utiliser des mises à jour intégrées à l'application. Pour plus de détails, voir [Mettre à niveau et désinstaller](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## Commencez en trois étapes |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage는 Linux 터미널, 브라우저 및 파일 편집기를 단일 데 | ||
| 25 | 25 | |
| 26 | 26 | **Cage의 기본 인터페이스:** |
| 27 | 27 | |
| 28 | 删除:! [hello-cage 데모 프로젝트를 보여주는 Alpha 2 워크벤치 및 터미널](www/public/workbench.jpg) | |
| 28 | 新增:! [hello-cage 데모 프로젝트를 보여주는 Cage 워크벤치 및 터미널](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## 케이지로 할 수 있는 일 |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage는 Linux 터미널, 브라우저 및 파일 편집기를 단일 데 | ||
| 54 | 54 | |
| 55 | 55 | 설치 프로그램에는 워크벤치와 네트워크 프록시 코어가 포함되어 있습니다. 일상적인 사용에는 Go, Node.js, Docker 또는 Clash를 설치할 필요가 없습니다. 처음 실행 시에는 Linux 이미지와 개발 도구를 다운로드하기 위해 인터넷 연결이 필요합니다. Cage는 네트워크 프록시 서비스나 Claude 계정을 제공하지 않습니다. |
| 56 | 56 | |
| 57 | 删除:현재 버전: `0.2.0-alpha.2`. 소스 코드, 웹사이트, 릴리스는 공개되어 있습니다. 설치 프로그램 서명, Apple 공증 및 검증 범위에 대해서는 각 릴리스의 노트를 참조하세요. 클린 머신 설치, macOS 14를 실행하는 실제 Mac에서의 호환성, 실제 Claude 계정 인증 및 모델 요청에는 여전히 완전한 검증이 필요합니다. | |
| 57 | 新增:현재 버전: `0.1.0-alpha.1`. 소스 코드, 웹사이트, 릴리스는 공개되어 있습니다. 설치 프로그램 서명, Apple 공증 및 검증 범위에 대해서는 각 릴리스의 노트를 참조하세요. 클린 머신 설치, macOS 14를 실행하는 실제 Mac에서의 호환성, 실제 Claude 계정 인증 및 모델 요청에는 여전히 완전한 검증이 필요합니다. | |
| 58 | 58 | |
| 59 | 删除:인앱 업데이트를 지원하는 버전은 왼쪽 하단에 업데이트 컨트롤이 표시됩니다. 업데이트를 사용할 수 있으면 아래쪽 화살표 도구 설명에 '업데이트 다운로드'가 표시됩니다. 이를 클릭하면 애플리케이션이 다운로드, 확인, 설치 및 다시 시작됩니다. 먼저 실행 중인 작업을 저장하고 중지하세요. 업데이트는 직접 연결을 사용하지 않고 선택한 네트워크 프록시를 통해 다운로드됩니다. 자동 설치에는 동일한 게시자의 서명과 Apple 확인이 필요합니다. Alpha 1 사용자는 먼저 Alpha 2를 수동으로 설치해야 합니다. 후속 버전에서는 인앱 업데이트를 사용할 수 있습니다. 자세한 내용은 다음을 참조하세요. [업그레이드 및 제거](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:인앱 업데이트를 지원하는 버전은 왼쪽 하단에 업데이트 컨트롤이 표시됩니다. 업데이트를 사용할 수 있으면 아래쪽 화살표 도구 설명에 '업데이트 다운로드'가 표시됩니다. 이를 클릭하면 애플리케이션이 다운로드, 확인, 설치 및 다시 시작됩니다. 먼저 실행 중인 작업을 저장하고 중지하세요. 업데이트는 직접 연결을 사용하지 않고 선택한 네트워크 프록시를 통해 다운로드됩니다. 자동 설치에는 동일한 게시자의 서명과 Apple 확인이 필요합니다. 후속 버전에서는 인앱 업데이트를 사용할 수 있습니다. 자세한 내용은 다음을 참조하세요. [업그레이드 및 제거](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## 3단계로 시작하세요 |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage 是一个轻量 Linux 虚拟机,把 Linux 终端、浏览器和文 | ||
| 25 | 25 | |
| 26 | 26 | **Cage 运行主界面:** |
| 27 | 27 | |
| 28 | 删除: | |
| 28 | 新增: | |
| 29 | 29 | |
| 30 | 30 | ## 你可以用它做什么 |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage 是一个轻量 Linux 虚拟机,把 Linux 终端、浏览器和文 | ||
| 54 | 54 | |
| 55 | 55 | 安装包随附工作台和代理核心,日常使用无需安装 Go、Node.js、Docker 或 Clash。首次启动仍需联网下载 Linux 镜像与开发工具;Cage 不提供代理服务或 Claude 账户。 |
| 56 | 56 | |
| 57 | 删除:当前版本为 `0.2.0-alpha.2`。源码、主页与发行物公开;安装包的签名、公证和验收范围以对应 Release 说明为准。干净机器安装、macOS 14 实机兼容性、真实 Claude 授权与模型请求仍需完整验收。 | |
| 57 | 新增:当前版本为 `0.1.0-alpha.1`。源码、主页与发行物公开;安装包的签名、公证和验收范围以对应 Release 说明为准。干净机器安装、macOS 14 实机兼容性、真实 Claude 授权与模型请求仍需完整验收。 | |
| 58 | 58 | |
| 59 | 删除:支持应用内更新的版本会在左下角显示更新入口:有新版时,向下箭头的悬浮提示为“下载更新”,点击后下载、校验、安装并重启;有运行任务时先确认保存并停止。更新经所选代理下载,无直连回退。自动安装要求同一发布者签名且通过 Apple 验证;Alpha 1 用户需要先手动安装 Alpha 2,后续版本可通过应用内更新。具体条件见[升级与卸载](docs/getting-started.md#升级与卸载)。 | |
| 59 | 新增:支持应用内更新的版本会在左下角显示更新入口:有新版时,向下箭头的悬浮提示为“下载更新”,点击后下载、校验、安装并重启;有运行任务时先确认保存并停止。更新经所选代理下载,无直连回退。自动安装要求同一发布者签名且通过 Apple 验证;后续版本可通过应用内更新。具体条件见[升级与卸载](docs/getting-started.md#升级与卸载)。 | |
| 60 | 60 | |
| 61 | 61 | ## 三步开始 |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage သည် desktop အပလီကေးရှင်းတစ်ခ | ||
| 25 | 25 | |
| 26 | 26 | **Cage ၏ အဓိက အင်တာဖေ့စ်** |
| 27 | 27 | |
| 28 | 删除:! [Alpha 2 workbench နှင့် terminal သည် hello-cage demo ပရောဂျက်ကို ပြသထားသည်။](www/public/workbench.jpg) | |
| 28 | 新增:! [Cage workbench နှင့် terminal သည် hello-cage demo ပရောဂျက်ကို ပြသထားသည်။](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## Cage နဲ့ သင်ဘာလုပ်နိုင်လဲ။ |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage သည် desktop အပလီကေးရှင်းတစ်ခ | ||
| 54 | 54 | |
| 55 | 55 | ထည့်သွင်းသူတွင် workbench နှင့် network proxy core ပါဝင်သည်။ နေ့စဉ်အသုံးပြုမှုသည် Go၊ Node.js၊ Docker သို့မဟုတ် Clash ကို ထည့်သွင်းရန် မလိုအပ်ပါ။ Linux ရုပ်ပုံနှင့် ဖွံ့ဖြိုးတိုးတက်ရေးကိရိယာများကို ဒေါင်းလုဒ်လုပ်ရန် ပထမဦးစွာ လွှင့်တင်ရန် အင်တာနက်ချိတ်ဆက်မှု လိုအပ်နေသေးသည်။ Cage သည် ကွန်ရက် ပရောက်စီ ဝန်ဆောင်မှု သို့မဟုတ် Claude အကောင့်ကို မပေးပေ။ |
| 56 | 56 | |
| 57 | 删除:လက်ရှိဗားရှင်း- `0.2.0-alpha.2`. အရင်းအမြစ်ကုဒ်၊ ဝဘ်ဆိုက်နှင့် ထုတ်ဝေမှုများကို အများသူငှာဖြစ်သည်။ တပ်ဆင်သူလက်မှတ်ထိုးခြင်းအတွက် ထုတ်ဝေမှုတစ်ခုစီ၏ မှတ်စုများ၊ Apple notarization နှင့် တရားဝင်မှုအတိုင်းအတာကို ကိုးကားပါ။ စက်သန့်ရှင်းမှု တပ်ဆင်မှု၊ macOS 14 အသုံးပြုသည့် ရုပ်ပိုင်းဆိုင်ရာ Mac များတွင် လိုက်ဖက်ညီမှု၊ အစစ်အမှန် Claude အကောင့်ခွင့်ပြုချက်နှင့် မော်ဒယ်တောင်းဆိုမှုများသည် အပြည့်အဝ တရားဝင်မှု လိုအပ်နေသေးသည်။ | |
| 57 | 新增:လက်ရှိဗားရှင်း- `0.1.0-alpha.1`. အရင်းအမြစ်ကုဒ်၊ ဝဘ်ဆိုက်နှင့် ထုတ်ဝေမှုများကို အများသူငှာဖြစ်သည်။ တပ်ဆင်သူလက်မှတ်ထိုးခြင်းအတွက် ထုတ်ဝေမှုတစ်ခုစီ၏ မှတ်စုများ၊ Apple notarization နှင့် တရားဝင်မှုအတိုင်းအတာကို ကိုးကားပါ။ စက်သန့်ရှင်းမှု တပ်ဆင်မှု၊ macOS 14 အသုံးပြုသည့် ရုပ်ပိုင်းဆိုင်ရာ Mac များတွင် လိုက်ဖက်ညီမှု၊ အစစ်အမှန် Claude အကောင့်ခွင့်ပြုချက်နှင့် မော်ဒယ်တောင်းဆိုမှုများသည် အပြည့်အဝ တရားဝင်မှု လိုအပ်နေသေးသည်။ | |
| 58 | 58 | |
| 59 | 删除:အက်ပ်အတွင်း အပ်ဒိတ်ပံ့ပိုးမှုပါရှိသော ဗားရှင်းများသည် ဘယ်ဘက်အောက်ခြေထောင့်တွင် အပ်ဒိတ်ထိန်းချုပ်မှုကို ပြသသည်။ အပ်ဒိတ်တစ်ခုရလာသောအခါ၊ အောက်မြှားကိရိယာအကြံပြုချက်သည် 'ဒေါင်းလုဒ်အပ်ဒိတ်' ကိုဖတ်သည်။ ၎င်းကိုနှိပ်ခြင်းဖြင့် ဒေါင်းလုဒ်လုပ်ခြင်း၊ အတည်ပြုခြင်း၊ ထည့်သွင်းခြင်းနှင့် အက်ပ်လီကေးရှင်းကို ပြန်လည်စတင်ပါ။ အလုပ်များကို ဦးစွာသိမ်းပြီး ရပ်လိုက်ပါ။ တိုက်ရိုက်ချိတ်ဆက်မှုသို့ နောက်ပြန်မဆုတ်ဘဲ ရွေးချယ်ထားသော ကွန်ရက်ပရောက်စီမှတစ်ဆင့် ဒေါင်းလုဒ်လုပ်ခြင်းကို အပ်ဒိတ်လုပ်ပါ။ အလိုအလျောက်ထည့်သွင်းခြင်းတွင် တူညီသောထုတ်ဝေသူနှင့် Apple အတည်ပြုခြင်းမှ လက်မှတ်လိုအပ်သည်။ Alpha 1 အသုံးပြုသူများသည် ပထမဆုံး Alpha 2 ကို ကိုယ်တိုင်ထည့်သွင်းရပါမည်။ နောက်ဆက်တွဲဗားရှင်းများသည် အက်ပ်အတွင်း အပ်ဒိတ်များကို သုံးနိုင်သည်။ အသေးစိတ်ကို ကြည့်ပါ။ [အဆင့်မြှင့်ပြီး ဖြုတ်လိုက်ပါ။](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:အက်ပ်အတွင်း အပ်ဒိတ်ပံ့ပိုးမှုပါရှိသော ဗားရှင်းများသည် ဘယ်ဘက်အောက်ခြေထောင့်တွင် အပ်ဒိတ်ထိန်းချုပ်မှုကို ပြသသည်။ အပ်ဒိတ်တစ်ခုရလာသောအခါ၊ အောက်မြှားကိရိယာအကြံပြုချက်သည် 'ဒေါင်းလုဒ်အပ်ဒိတ်' ကိုဖတ်သည်။ ၎င်းကိုနှိပ်ခြင်းဖြင့် ဒေါင်းလုဒ်လုပ်ခြင်း၊ အတည်ပြုခြင်း၊ ထည့်သွင်းခြင်းနှင့် အက်ပ်လီကေးရှင်းကို ပြန်လည်စတင်ပါ။ အလုပ်များကို ဦးစွာသိမ်းပြီး ရပ်လိုက်ပါ။ တိုက်ရိုက်ချိတ်ဆက်မှုသို့ နောက်ပြန်မဆုတ်ဘဲ ရွေးချယ်ထားသော ကွန်ရက်ပရောက်စီမှတစ်ဆင့် ဒေါင်းလုဒ်လုပ်ခြင်းကို အပ်ဒိတ်လုပ်ပါ။ အလိုအလျောက်ထည့်သွင်းခြင်းတွင် တူညီသောထုတ်ဝေသူနှင့် Apple အတည်ပြုခြင်းမှ လက်မှတ်လိုအပ်သည်။ နောက်ဆက်တွဲဗားရှင်းများသည် အက်ပ်အတွင်း အပ်ဒိတ်များကို သုံးနိုင်သည်။ အသေးစိတ်ကို ကြည့်ပါ။ [အဆင့်မြှင့်ပြီး ဖြုတ်လိုက်ပါ။](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## အဆင့်သုံးဆင့်ဖြင့် စတင်လိုက်ပါ။ |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage یک ماشین مجازی لینوکس سبک وزن است که ت | ||
| 25 | 25 | |
| 26 | 26 | **رابط اصلی Cage:** |
| 27 | 27 | |
| 28 | 删除:! [میز کار و پایانه آلفا 2 که پروژه آزمایشی hello-cage را نشان می دهد](www/public/workbench.jpg) | |
| 28 | 新增:! [میز کار و پایانه Cage که پروژه آزمایشی hello-cage را نشان می دهد](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## کاری که می توانید با Cage انجام دهید |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage یک ماشین مجازی لینوکس سبک وزن است که ت | ||
| 54 | 54 | |
| 55 | 55 | نصب کننده شامل میز کار و هسته پروکسی شبکه است. استفاده روزانه نیازی به نصب Go، Node.js، Docker یا Clash ندارد. اولین راهاندازی همچنان به اتصال اینترنت برای دانلود تصویر لینوکس و ابزارهای توسعه نیاز دارد. Cage نه سرویس پروکسی شبکه و نه حساب Claude ارائه می دهد. |
| 56 | 56 | |
| 57 | 删除:نسخه فعلی: `0.2.0-alpha.2`. کد منبع، وبسایت و نسخهها عمومی هستند. به یادداشتهای هر نسخه برای امضای نصبکننده، تأیید اسناد رسمی اپل و دامنه اعتبارسنجی مراجعه کنید. نصب ماشین تمیز، سازگاری در مک های فیزیکی دارای سیستم عامل macOS 14، مجوز واقعی حساب Claude، و درخواست های مدل هنوز به تأیید کامل نیاز دارند. | |
| 57 | 新增:نسخه فعلی: `0.1.0-alpha.1`. کد منبع، وبسایت و نسخهها عمومی هستند. به یادداشتهای هر نسخه برای امضای نصبکننده، تأیید اسناد رسمی اپل و دامنه اعتبارسنجی مراجعه کنید. نصب ماشین تمیز، سازگاری در مک های فیزیکی دارای سیستم عامل macOS 14، مجوز واقعی حساب Claude، و درخواست های مدل هنوز به تأیید کامل نیاز دارند. | |
| 58 | 58 | |
| 59 | 删除:نسخههایی که از بهروزرسانی درونبرنامه پشتیبانی میکنند، کنترل بهروزرسانی را در گوشه پایین سمت چپ نشان میدهند. وقتی یک بهروزرسانی در دسترس است، راهنمای ابزار فلش رو به پایین «دانلود بهروزرسانی» را میخواند. با کلیک بر روی آن برنامه دانلود، تأیید، نصب و راه اندازی مجدد می شود. ابتدا وظایف در حال اجرا را ذخیره و متوقف کنید. بهروزرسانیها از طریق پراکسی شبکه انتخاب شده، بدون بازگشت به اتصال مستقیم، دانلود میشوند. نصب خودکار به امضای همان ناشر و تأیید اپل نیاز دارد. کاربران آلفا 1 ابتدا باید آلفا 2 را به صورت دستی نصب کنند. نسخه های بعدی می توانند از به روز رسانی های درون برنامه ای استفاده کنند. برای جزئیات، نگاه کنید [ارتقا و حذف نصب کنید](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:نسخههایی که از بهروزرسانی درونبرنامه پشتیبانی میکنند، کنترل بهروزرسانی را در گوشه پایین سمت چپ نشان میدهند. وقتی یک بهروزرسانی در دسترس است، راهنمای ابزار فلش رو به پایین «دانلود بهروزرسانی» را میخواند. با کلیک بر روی آن برنامه دانلود، تأیید، نصب و راه اندازی مجدد می شود. ابتدا وظایف در حال اجرا را ذخیره و متوقف کنید. بهروزرسانیها از طریق پراکسی شبکه انتخاب شده، بدون بازگشت به اتصال مستقیم، دانلود میشوند. نصب خودکار به امضای همان ناشر و تأیید اپل نیاز دارد. نسخه های بعدی می توانند از به روز رسانی های درون برنامه ای استفاده کنند. برای جزئیات، نگاه کنید [ارتقا و حذف نصب کنید](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## در سه مرحله شروع کنید |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ | ||
| 25 | 25 | |
| 26 | 26 | **د Cage اصلي انٹرفیس:** |
| 27 | 27 | |
| 28 | 删除:! [د الفا 2 ورک بینچ او ترمینل د هیلو Cage ډیمو پروژه ښیې](www/public/workbench.jpg) | |
| 28 | 新增:! [د Cage ورک بینچ او ترمینل د هیلو Cage ډیمو پروژه ښیې](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## تاسو د Cage سره څه کولی شئ |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ | ||
| 54 | 54 | |
| 55 | 55 | انسټالر کې ورک بینچ او د شبکې پراکسي کور شامل دي. ورځنی استعمال د Go، Node.js، Docker، یا Clash نصبولو ته اړتیا نلري. لومړی لانچ لاهم د لینکس عکس او پراختیا وسیلو ډاونلوډ کولو لپاره انټرنیټ پیوستون ته اړتیا لري. Cage نه د شبکې پراکسي خدمت وړاندې کوي او نه د کلاډ حساب. |
| 56 | 56 | |
| 57 | 删除:اوسنۍ نسخه: `0.2.0-alpha.2`. د سرچینې کوډ، ویب پاڼه، او خپرونه عامه دي. د انسټالر لاسلیک کولو، د ایپل نوټاریزیشن، او د اعتبار ساحه لپاره د هرې خوشې کولو یادښتونو ته مراجعه وکړئ. د کلین ماشین نصب کول، د macOS 14 چلولو فزیکي ماکونو کې مطابقت، د ریښتیني کلاډ حساب واک، او د ماډل غوښتنې لاهم بشپړ تایید ته اړتیا لري. | |
| 57 | 新增:اوسنۍ نسخه: `0.1.0-alpha.1`. د سرچینې کوډ، ویب پاڼه، او خپرونه عامه دي. د انسټالر لاسلیک کولو، د ایپل نوټاریزیشن، او د اعتبار ساحه لپاره د هرې خوشې کولو یادښتونو ته مراجعه وکړئ. د کلین ماشین نصب کول، د macOS 14 چلولو فزیکي ماکونو کې مطابقت، د ریښتیني کلاډ حساب واک، او د ماډل غوښتنې لاهم بشپړ تایید ته اړتیا لري. | |
| 58 | 58 | |
| 59 | 删除:د ایپ اپډیټ ملاتړ سره نسخې په لاندې کیڼ کونج کې د تازه کنټرول ښیې. کله چې یو تازه معلومات شتون ولري، د ښکته تیر ټوپ ټایپ 'د ډاونلوډ تازه کول' لوستل کیږي. په دې کلیک کولو سره اپلیکیشن ډاونلوډ، تایید، نصب او بیا پیل کوي. لومړی د چلولو دندې خوندي کړئ او ودروئ. تازه معلومات د ټاکل شوي شبکې پراکسي له لارې ډاونلوډ کیږي ، پرته له مستقیم اړیکې سره. اتوماتیک نصب د ورته خپرونکي لاسلیک او د ایپل تصدیق ته اړتیا لري. د الفا 1 کاروونکي باید لومړی الفا 2 په لاسي ډول نصب کړي؛ ورپسې نسخې کولی شي په اپلیکیشن کې تازه معلومات وکاروي. د جزیاتو لپاره، وګورئ [اپ گریڈ او غیر نصب کړئ](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:د ایپ اپډیټ ملاتړ سره نسخې په لاندې کیڼ کونج کې د تازه کنټرول ښیې. کله چې یو تازه معلومات شتون ولري، د ښکته تیر ټوپ ټایپ 'د ډاونلوډ تازه کول' لوستل کیږي. په دې کلیک کولو سره اپلیکیشن ډاونلوډ، تایید، نصب او بیا پیل کوي. لومړی د چلولو دندې خوندي کړئ او ودروئ. تازه معلومات د ټاکل شوي شبکې پراکسي له لارې ډاونلوډ کیږي ، پرته له مستقیم اړیکې سره. اتوماتیک نصب د ورته خپرونکي لاسلیک او د ایپل تصدیق ته اړتیا لري. ورپسې نسخې کولی شي په اپلیکیشن کې تازه معلومات وکاروي. د جزیاتو لپاره، وګورئ [اپ گریڈ او غیر نصب کړئ](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## په دریو مرحلو کې پیل کړئ |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage — это легкая виртуальная машина Linux, | ||
| 25 | 25 | |
| 26 | 26 | **Основной интерфейс Cage:** |
| 27 | 27 | |
| 28 | 删除:! [Рабочая среда и терминал Alpha 2, демонстрирующие демонстрационный проект hello-cage](www/public/workbench.jpg) | |
| 28 | 新增:! [Рабочая среда и терминал Cage, демонстрирующие демонстрационный проект hello-cage](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## Что можно сделать с Cageем |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage — это легкая виртуальная машина Linux, | ||
| 54 | 54 | |
| 55 | 55 | Установщик включает в себя рабочую среду и ядро сетевого прокси. Ежедневное использование не требует установки Go, Node.js, Docker или Clash. При первом запуске по-прежнему требуется подключение к Интернету для загрузки образа Linux и инструментов разработки. Cage не предоставляет ни услуги сетевого прокси, ни учетную запись Claude. |
| 56 | 56 | |
| 57 | 删除:Текущая версия: `0.2.0-alpha.2`. Исходный код, веб-сайт и релизы являются общедоступными. Подробную информацию о подписании установщика, нотариальном заверении Apple и объеме проверки см. в примечаниях к каждому выпуску. Установка на чистом компьютере, совместимость с физическими компьютерами Mac под управлением macOS 14, авторизация реальной учетной записи Claude и запросы моделей по-прежнему требуют полной проверки. | |
| 57 | 新增:Текущая версия: `0.1.0-alpha.1`. Исходный код, веб-сайт и релизы являются общедоступными. Подробную информацию о подписании установщика, нотариальном заверении Apple и объеме проверки см. в примечаниях к каждому выпуску. Установка на чистом компьютере, совместимость с физическими компьютерами Mac под управлением macOS 14, авторизация реальной учетной записи Claude и запросы моделей по-прежнему требуют полной проверки. | |
| 58 | 58 | |
| 59 | 删除:В версиях с поддержкой обновления внутри приложения в левом нижнем углу отображается элемент управления обновлением. Когда обновление доступно, всплывающая подсказка со стрелкой вниз гласит: «Загрузить обновление». Нажатие на нее загружает, проверяет, устанавливает и перезапускает приложение. Сначала сохраните и остановите выполнение задач. Обновления загружаются через выбранный сетевой прокси-сервер без возврата к прямому соединению. Для автоматической установки требуется подпись того же издателя и проверка Apple. Пользователи Alpha 1 должны сначала установить Alpha 2 вручную; последующие версии могут использовать обновления внутри приложения. Подробности см. [Обновить и удалить](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:В версиях с поддержкой обновления внутри приложения в левом нижнем углу отображается элемент управления обновлением. Когда обновление доступно, всплывающая подсказка со стрелкой вниз гласит: «Загрузить обновление». Нажатие на нее загружает, проверяет, устанавливает и перезапускает приложение. Сначала сохраните и остановите выполнение задач. Обновления загружаются через выбранный сетевой прокси-сервер без возврата к прямому соединению. Для автоматической установки требуется подпись того же издателя и проверка Apple. Последующие версии могут использовать обновления внутри приложения. Подробности см. [Обновить и удалить](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## Начните работу в три шага |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage waa mashiin macmal ah oo Linux ah oo fudud kaas oo isku dara termina | ||
| 25 | 25 | |
| 26 | 26 | **Interface ugu weyn ee Cage:** |
| 27 | 27 | |
| 28 | 删除:! [Kursiga shaqada ee Alpha 2 iyo terminal muujinaya mashruuca demo-qafiska](www/public/workbench.jpg) | |
| 28 | 新增:! [Kursiga shaqada ee Cage iyo terminal muujinaya mashruuca demo-qafiska](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## Maxaad ku samayn kartaa Cage |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Siideynta hore waa ay taageertaa **Apple Silicon Macs (M-series chips), oo ku sh | ||
| 54 | 54 | |
| 55 | 55 | Rakibahu waxa ka mid ah bench-ka shaqada iyo xudunta wakiilka network. Isticmaalka maalinlaha ah uma baahna rakibida Go, Node.js, Docker, ama Clash. Daahfurka ugu horreeya wuxuu weli u baahan yahay isku xirka internetka si loo soo dejiyo sawirka Linux iyo aaladaha horumarinta. Cage ma bixiso adeeg wakiil shabakad ama akoon Claude. |
| 56 | 56 | |
| 57 | 删除:Nooca hadda: `0.2.0-alpha.2`. Koodhka isha, mareegaha, iyo sii daynta waa dadwayne. Tixraac qoraalada sii daynta kasta ee saxeexa rakibaha, notarization Apple, iyo baaxadda ansixinta. Ku rakibida mashiinka nadiifka ah, waafaqid ku saabsan Macs-ka jireed ee ku shaqeeya macOS 14, oggolaanshaha koontada Claude dhabta ah, iyo codsiyada moodeelka ayaa wali u baahan ansaxinta buuxda. | |
| 57 | 新增:Nooca hadda: `0.1.0-alpha.1`. Koodhka isha, mareegaha, iyo sii daynta waa dadwayne. Tixraac qoraalada sii daynta kasta ee saxeexa rakibaha, notarization Apple, iyo baaxadda ansixinta. Ku rakibida mashiinka nadiifka ah, waafaqid ku saabsan Macs-ka jireed ee ku shaqeeya macOS 14, oggolaanshaha koontada Claude dhabta ah, iyo codsiyada moodeelka ayaa wali u baahan ansaxinta buuxda. | |
| 58 | 58 | |
| 59 | 删除:Noocyada leh taageerada cusboonaysiinta app-ku waxay muujinayaan xakamaynta cusboonaysiinta ee geeska bidix ee hoose. Marka cusboonaysiinta la heli karo, aaladda fallaadha hoose waxay akhridaa 'Download update'. Markaad gujiso waxay soo dejisaa, xaqiijisaa, rakibtaa, oo dib u bilawdaa arjiga. Keydi oo jooji socodsiinta hawlaha marka hore. Cusboonaysiinta soo dejinta iyada oo loo marayo wakiilka shabakadda ee la xushay, iyada oo aan dib loogu laaban xiriir toos ah. Rakibaadda tooska ah waxay u baahan tahay saxeex isla daabacaha iyo xaqiijinta Apple. Isticmaalayaasha Alpha 1 waa inay marka hore gacanta ku rakibaan Alpha 2; Noocyada soo socda waxay isticmaali karaan cusbooneysiinta app-ka. Faahfaahinta, eeg [Kor u qaad oo ka saar](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:Noocyada leh taageerada cusboonaysiinta app-ku waxay muujinayaan xakamaynta cusboonaysiinta ee geeska bidix ee hoose. Marka cusboonaysiinta la heli karo, aaladda fallaadha hoose waxay akhridaa 'Download update'. Markaad gujiso waxay soo dejisaa, xaqiijisaa, rakibtaa, oo dib u bilawdaa arjiga. Keydi oo jooji socodsiinta hawlaha marka hore. Cusboonaysiinta soo dejinta iyada oo loo marayo wakiilka shabakadda ee la xushay, iyada oo aan dib loogu laaban xiriir toos ah. Rakibaadda tooska ah waxay u baahan tahay saxeex isla daabacaha iyo xaqiijinta Apple. Noocyada soo socda waxay isticmaali karaan cusbooneysiinta app-ka. Faahfaahinta, eeg [Kor u qaad oo ka saar](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## Ku bilow saddex tallaabo |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ | ||
| 25 | 25 | |
| 26 | 26 | **ቀንዲ መተሓላለፊ Cage፤** |
| 27 | 27 | |
| 28 | 删除:! [ኣልፋ 2 ወርክቤንችን ተርሚናልን ንሄሎ-Cage ዲሞ ፕሮጀክት ዘርኢ](www/public/workbench.jpg) | |
| 28 | 新增:! [Cage ወርክቤንችን ተርሚናልን ንሄሎ-Cage ዲሞ ፕሮጀክት ዘርኢ](www/public/workbench.jpg) | |
| 29 | 29 | |
| 30 | 30 | ## ብCage እንታይ ክትገብር ትኽእል |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ | ||
| 54 | 54 | |
| 55 | 55 | እቲ መተካእታ ንወርክቤንችን ኔትወርክ ፕሮክሲ ኮርን የጠቓልል። መዓልታዊ ኣጠቓቕማ Go, Node.js, Docker, ወይ Clash ምትካል ኣየድልዮን እዩ። መጀመርታ ምጅማር ሕጂ ውን ናይ ሊኑክስ ምስልን መሳርሒታት ምዕባለን ንምውራድ ናይ ኢንተርነት ምትእስሳር የድሊ። Cage ናይ መርበብ ፕሮክሲ ኣገልግሎት ይኹን ናይ Claude ኣካውንት ኣይህብን እዩ። |
| 56 | 56 | |
| 57 | 删除:ናይ ሕጂ ስሪት፤ `0.2.0-alpha.2`. እቲ ምንጪ ኮድ፡ መርበብ ሓበሬታን ምውጻእን ንህዝቢ ዝቐርብ እዩ። ንመተካእታ ምፍራም፣ ኣፕል ኖታራይዜሽንን ስፍሓት ምጽዳቕን ዝምልከት ናይ ነፍሲ ወከፍ ምውጻእ መዘኻኸሪታት ተወከስ። ጽሩይ-ማሽን ምትካል፡ ኣብ macOS 14 ዝሰርሓ ፊዚካዊ ማክስ ምትእስሳር፡ ሓቀኛ ክላውድ ኣካውንት ፍቓድ፡ ከምኡ’ውን ናይ ሞዴል ሕቶታት ሕጂ’ውን ምሉእ ምጽዳቕ የድልዮም። | |
| 57 | 新增:ናይ ሕጂ ስሪት፤ `0.1.0-alpha.1`. እቲ ምንጪ ኮድ፡ መርበብ ሓበሬታን ምውጻእን ንህዝቢ ዝቐርብ እዩ። ንመተካእታ ምፍራም፣ ኣፕል ኖታራይዜሽንን ስፍሓት ምጽዳቕን ዝምልከት ናይ ነፍሲ ወከፍ ምውጻእ መዘኻኸሪታት ተወከስ። ጽሩይ-ማሽን ምትካል፡ ኣብ macOS 14 ዝሰርሓ ፊዚካዊ ማክስ ምትእስሳር፡ ሓቀኛ ክላውድ ኣካውንት ፍቓድ፡ ከምኡ’ውን ናይ ሞዴል ሕቶታት ሕጂ’ውን ምሉእ ምጽዳቕ የድልዮም። | |
| 58 | 58 | |
| 59 | 删除:ኣብ ውሽጢ መተግበሪ ናይ ምዕባለ ደገፍ ዘለዎም ስሪት ኣብ ታሕተዋይ ጸጋማይ ኩርናዕ ናይ ምዕባለ ምቁጽጻር የርእዩ። ሓደ ምዕባለ ምስ ዝህሉ፡ እቲ ኣብ ታሕቲ ዘሎ ፍላጻ ዝሕብር መሳርሒ ‘Download update’ ዝብል ይንበብ። ንዕኡ ጠዊቕካ ነቲ መተግበሪ የውርድ፣ የረጋግጽ፣ ይተክልን ዳግማይ ይጅምሮን። መጀመርታ ስራሕካ ዓቅብ፣ ድሕሪኡ ዝሰርሑ ዕማማት ኣቋርጽ። እዋናዊ ሓበሬታታት ብመንገዲ እቲ ዝተመርጸ መርበብ ፕሮክሲ ይወርድ፣ ናብ ቀጥታዊ ምትእስሳር ዝኾነ ምምላስ የብሉን። ኣውቶማቲክ ምትካል ካብ ተመሳሳሊ ኣሕታሚ ፌርማን ምርግጋጽ ኣፕልን የድሊ። ተጠቀምቲ ኣልፋ 1 መጀመርያ ኣልፋ 2 ብኢዶም ክጭብጥዎ ኣለዎም፤ ስዒቦም ዝመጹ ስሪታት ኣብ ውሽጢ ኣፕ ዝግበር ምዕባለታት ክጥቀሙ ይኽእሉ። ንዝርዝር ሓበሬታ ርአ [ምዕባይን ምእላይን።](docs/getting-started.md#升级与卸载). | |
| 59 | 新增:ኣብ ውሽጢ መተግበሪ ናይ ምዕባለ ደገፍ ዘለዎም ስሪት ኣብ ታሕተዋይ ጸጋማይ ኩርናዕ ናይ ምዕባለ ምቁጽጻር የርእዩ። ሓደ ምዕባለ ምስ ዝህሉ፡ እቲ ኣብ ታሕቲ ዘሎ ፍላጻ ዝሕብር መሳርሒ ‘Download update’ ዝብል ይንበብ። ንዕኡ ጠዊቕካ ነቲ መተግበሪ የውርድ፣ የረጋግጽ፣ ይተክልን ዳግማይ ይጅምሮን። መጀመርታ ስራሕካ ዓቅብ፣ ድሕሪኡ ዝሰርሑ ዕማማት ኣቋርጽ። እዋናዊ ሓበሬታታት ብመንገዲ እቲ ዝተመርጸ መርበብ ፕሮክሲ ይወርድ፣ ናብ ቀጥታዊ ምትእስሳር ዝኾነ ምምላስ የብሉን። ኣውቶማቲክ ምትካል ካብ ተመሳሳሊ ኣሕታሚ ፌርማን ምርግጋጽ ኣፕልን የድሊ። ስዒቦም ዝመጹ ስሪታት ኣብ ውሽጢ ኣፕ ዝግበር ምዕባለታት ክጥቀሙ ይኽእሉ። ንዝርዝር ሓበሬታ ርአ [ምዕባይን ምእላይን።](docs/getting-started.md#升级与卸载). | |
| 60 | 60 | |
| 61 | 61 | ## ብሰለስተ ስጉምትታት ጀምር |
| 62 | 62 | |
| @@ -25,7 +25,7 @@ Claude Cage 是一個輕量 Linux 虛擬機器,把 Linux 終端、瀏覽器和 | ||
| 25 | 25 | |
| 26 | 26 | **Cage 執行主介面:** |
| 27 | 27 | |
| 28 | 删除: | |
| 28 | 新增: | |
| 29 | 29 | |
| 30 | 30 | ## 你可以用它做什麼 |
| 31 | 31 | |
| @@ -54,9 +54,9 @@ Claude Cage 是一個輕量 Linux 虛擬機器,把 Linux 終端、瀏覽器和 | ||
| 54 | 54 | |
| 55 | 55 | 安裝包隨附工作臺和代理核心,日常使用無需安裝 Go、Node.js、Docker 或 Clash。首次啟動仍需聯網下載 Linux 映象與開發工具;Cage 不提供代理服務或 Claude 賬戶。 |
| 56 | 56 | |
| 57 | 删除:當前版本為 `0.2.0-alpha.2`。原始碼、主頁與發行物公開;安裝包的簽名、公證和驗收範圍以對應 Release 說明為準。乾淨機器安裝、macOS 14 實機相容性、真實 Claude 授權與模型請求仍需完整驗收。 | |
| 57 | 新增:當前版本為 `0.1.0-alpha.1`。原始碼、主頁與發行物公開;安裝包的簽名、公證和驗收範圍以對應 Release 說明為準。乾淨機器安裝、macOS 14 實機相容性、真實 Claude 授權與模型請求仍需完整驗收。 | |
| 58 | 58 | |
| 59 | 删除:支援應用內更新的版本會在左下角顯示更新入口:有新版時,向下箭頭的懸浮提示為“下載更新”,點選後下載、校驗、安裝並重啟;有執行任務時先確認儲存並停止。更新經所選代理下載,無直連回退。自動安裝要求同一發布者簽名且透過 Apple 驗證;Alpha 1 使用者需要先手動安裝 Alpha 2,後續版本可透過應用內更新。具體條件見[升級與解除安裝](docs/getting-started.md#升级与卸载)。 | |
| 59 | 新增:支援應用內更新的版本會在左下角顯示更新入口:有新版時,向下箭頭的懸浮提示為“下載更新”,點選後下載、校驗、安裝並重啟;有執行任務時先確認儲存並停止。更新經所選代理下載,無直連回退。自動安裝要求同一發布者簽名且透過 Apple 驗證;後續版本可透過應用內更新。具體條件見[升級與解除安裝](docs/getting-started.md#升级与卸载)。 | |
| 60 | 60 | |
| 61 | 61 | ## 三步開始 |
| 62 | 62 | |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | # Releasing agent-vm |
| 2 | 2 | |
| 3 | 3 | This is the retained upstream release procedure. For Claude Cage, use |
| 4 | 删除:[the macOS release guide](docs/releasing.md) and `scripts/package-macos.sh`. | |
| 4 | 新增:[the macOS release guide](docs/releasing.md), [public distribution and Pages deployment](docs/public-releases.md), and `scripts/package-macos.sh`. | |
| 5 | 5 | The upstream Homebrew/Nix/multi-platform artifacts are not Cage releases. |
| 6 | 6 | |
| 7 | 7 | `release.sh` checks a commit, tags it, builds a tarball per platform from the tag, publishes them |
| @@ -1 +1 @@ | ||
| 1 | 删除:0.2.0-alpha.1 | |
| 1 | 新增:0.1.0-alpha.1 | |
| @@ -180,7 +180,11 @@ echo '[ -f "$HOME/.agent-vm.env" ] && { set -a; . "$HOME/.agent-vm.env"; set +a; | ||
| 180 | 180 | # Always installed so users can `mise install ruby@latest`, etc., even when |
| 181 | 181 | # they've opted out of preinstalled Node. |
| 182 | 182 | echo "Installing mise..." |
| 183 | 删除:curl -fsSL https://mise.run | sh | |
| 183 | 新增:if [[ "${CLAUDE_CAGE:-}" == "1" ]]; then | |
| 184 | 新增: cage_install_tool mise | |
| 185 | 新增:else | |
| 186 | 新增: curl -fsSL https://mise.run | sh | |
| 187 | 新增:fi | |
| 184 | 188 | echo 'eval "$(~/.local/bin/mise activate zsh)"' >> ~/.zshenv |
| 185 | 189 | |
| 186 | 190 | if [[ "$INSTALL_DOCKER" == "1" ]]; then |
| @@ -244,7 +248,7 @@ if [[ "$INSTALL_CLAUDE" == "1" ]]; then | ||
| 244 | 248 | if [[ "${CLAUDE_CAGE:-}" == "1" ]]; then |
| 245 | 249 | # Official npm distribution; lock the first cage release to a known version. |
| 246 | 250 | # npm retries interrupted package transfers and verifies registry integrity. |
| 247 | 删除: npm install --prefix "$HOME/.local" --global @anthropic-ai/[email protected] | |
| 251 | 新增: cage_install_tool claude | |
| 248 | 252 | else |
| 249 | 253 | curl -fsSL https://claude.ai/install.sh | bash |
| 250 | 254 | fi |
| @@ -430,7 +434,11 @@ if [[ "$INSTALL_CODE_SERVER" == "1" ]]; then | ||
| 430 | 434 | # The editor of `agent-vm code` (internal/cli/code.go). No password here: every VM |
| 431 | 435 | # is a copy of this disk, so each one makes its own on first use. |
| 432 | 436 | echo "Installing code-server..." |
| 433 | 删除: curl -fsSL https://code-server.dev/install.sh | sh | |
| 437 | 新增: if [[ "${CLAUDE_CAGE:-}" == "1" ]]; then | |
| 438 | 新增: cage_install_tool code-server | |
| 439 | 新增: else | |
| 440 | 新增: curl -fsSL https://code-server.dev/install.sh | sh | |
| 441 | 新增: fi | |
| 434 | 442 | extensions=() |
| 435 | 443 | [[ "$INSTALL_CODE_CLAUDE" == "1" ]] && extensions+=(--install-extension anthropic.claude-code) |
| 436 | 444 | [[ "$INSTALL_CODE_OPENCODE" == "1" ]] && extensions+=(--install-extension sst-dev.opencode) |
| @@ -3,6 +3,12 @@ package agentvm | ||
| 3 | 3 | |
| 4 | 4 | import _ "embed" |
| 5 | 5 | |
| 6 | 新增:// CageVersion is the default version for source builds without linker flags. | |
| 7 | 新增:// Release builds may override internal/version.Version explicitly. | |
| 8 | 新增:// | |
| 9 | 新增://go:embed VERSION | |
| 10 | 新增:var CageVersion string | |
| 11 | 新增: | |
| 6 | 12 | // SetupScript provisions the base VM: `agent-vm setup` runs it in the guest, |
| 7 | 13 | // after the choices as export lines. |
| 8 | 14 | // |
| @@ -12,6 +12,7 @@ import ( | ||
| 12 | 12 | "strings" |
| 13 | 13 | "time" |
| 14 | 14 | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/appupdate" | |
| 15 | 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 16 | 17 | "github.com/sylvinus/agent-vm/internal/cli" |
| 17 | 18 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| @@ -69,6 +70,9 @@ func run() int { | ||
| 69 | 70 | if err != nil { |
| 70 | 71 | return fail(err) |
| 71 | 72 | } |
| 73 | 新增: if args[0] == "app-update" { | |
| 74 | 新增: return appupdate.Run(path, args[1:], os.Stdout) | |
| 75 | 新增: } | |
| 72 | 76 | if args[0] == "serve" { |
| 73 | 77 | if err := workbench.Serve(path); err != nil { |
| 74 | 78 | return fail(err) |
| @@ -76,22 +80,69 @@ func run() int { | ||
| 76 | 80 | return 0 |
| 77 | 81 | } |
| 78 | 82 | if args[0] == "desktop" { |
| 79 | 删除: address, err := workbench.Desktop(path) | |
| 83 | 新增: options := workbench.DesktopOptions{} | |
| 84 | 新增: returnJSON := false | |
| 85 | 新增: for _, argument := range args[1:] { | |
| 86 | 新增: switch argument { | |
| 87 | 新增: case "--json": | |
| 88 | 新增: returnJSON = true | |
| 89 | 新增: case "--complete-update": | |
| 90 | 新增: options.CompleteUpdate = true | |
| 91 | 新增: case "--existing": | |
| 92 | 新增: options.UseExisting = true | |
| 93 | 新增: default: | |
| 94 | 新增: return fail(fmt.Errorf("unknown desktop option: %s", argument)) | |
| 95 | 新增: } | |
| 96 | 新增: } | |
| 97 | 新增: entry, err := workbench.Desktop(path, options) | |
| 80 | 98 | if err != nil { |
| 99 | 新增: if returnJSON { | |
| 100 | 新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) | |
| 101 | 新增: return 1 | |
| 102 | 新增: } | |
| 81 | 103 | return fail(err) |
| 82 | 104 | } |
| 83 | 105 | // Native launchers consume this on a pipe, never in a shared log. |
| 84 | 删除: returnJSON := len(args) > 1 && args[1] == "--json" | |
| 85 | 106 | if returnJSON { |
| 86 | 删除: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"url": address}) | |
| 107 | 新增: _ = json.NewEncoder(os.Stdout).Encode(entry) | |
| 87 | 108 | } else { |
| 88 | 删除: if err := openWorkbench(address); err != nil { | |
| 109 | 新增: if entry.URL == "" { | |
| 110 | 新增: return fail(fmt.Errorf("%s", entry.Message)) | |
| 111 | 新增: } | |
| 112 | 新增: if err := openWorkbench(entry.URL); err != nil { | |
| 89 | 113 | return fail(err) |
| 90 | 114 | } |
| 91 | 115 | fmt.Println("Cage workbench opened.") |
| 92 | 116 | } |
| 93 | 117 | return 0 |
| 94 | 118 | } |
| 119 | 新增: if args[0] == "prepare-update" { | |
| 120 | 新增: stop, returnJSON := false, false | |
| 121 | 新增: for _, argument := range args[1:] { | |
| 122 | 新增: switch argument { | |
| 123 | 新增: case "--stop": | |
| 124 | 新增: stop = true | |
| 125 | 新增: case "--json": | |
| 126 | 新增: returnJSON = true | |
| 127 | 新增: default: | |
| 128 | 新增: return fail(fmt.Errorf("unknown prepare-update option: %s", argument)) | |
| 129 | 新增: } | |
| 130 | 新增: } | |
| 131 | 新增: result, err := workbench.PrepareUpdate(path, stop) | |
| 132 | 新增: if err != nil { | |
| 133 | 新增: if returnJSON { | |
| 134 | 新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) | |
| 135 | 新增: return 1 | |
| 136 | 新增: } | |
| 137 | 新增: return fail(err) | |
| 138 | 新增: } | |
| 139 | 新增: if returnJSON { | |
| 140 | 新增: _ = json.NewEncoder(os.Stdout).Encode(result) | |
| 141 | 新增: } else if result.Status != "prepared" { | |
| 142 | 新增: return fail(fmt.Errorf("%s", result.Message)) | |
| 143 | 新增: } | |
| 144 | 新增: return 0 | |
| 145 | 新增: } | |
| 95 | 146 | if args[0] == "init" { |
| 96 | 147 | if err = os.MkdirAll(filepath.Dir(path), 0700); err != nil { |
| 97 | 148 | return fail(err) |
| @@ -10,6 +10,17 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 10 | 10 | private var loading: NSTextField! |
| 11 | 11 | private var retry: NSButton! |
| 12 | 12 | private var backdrop: NSVisualEffectView! |
| 13 | 新增: private var completeUpdateButton: NSButton! | |
| 14 | 新增: private var existingEnvironmentButton: NSButton! | |
| 15 | 新增: private var completeUpdateMenu: NSMenuItem! | |
| 16 | 新增: private var controllerNeedsUpdate = false | |
| 17 | 新增: private var appUpdater: CageAppUpdater! | |
| 18 | 新增: | |
| 19 | 新增: private struct DesktopEntry { | |
| 20 | 新增: let status: String | |
| 21 | 新增: let url: URL? | |
| 22 | 新增: let message: String | |
| 23 | 新增: } | |
| 13 | 24 | |
| 14 | 25 | static func main() { |
| 15 | 26 | let app = NSApplication.shared |
| @@ -63,8 +74,32 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 63 | 74 | retry.translatesAutoresizingMaskIntoConstraints = false |
| 64 | 75 | retry.isHidden = true |
| 65 | 76 | content.addSubview(retry) |
| 77 | 新增: completeUpdateButton = NSButton(title: "保存后停止环境并完成更新", target: self, action: #selector(completePendingUpdate)) | |
| 78 | 新增: completeUpdateButton.bezelStyle = .rounded | |
| 79 | 新增: completeUpdateButton.translatesAutoresizingMaskIntoConstraints = false | |
| 80 | 新增: completeUpdateButton.isHidden = true | |
| 81 | 新增: content.addSubview(completeUpdateButton) | |
| 82 | 新增: existingEnvironmentButton = NSButton(title: "打开现有环境保存文件", target: self, action: #selector(openExistingEnvironment)) | |
| 83 | 新增: existingEnvironmentButton.bezelStyle = .rounded | |
| 84 | 新增: existingEnvironmentButton.translatesAutoresizingMaskIntoConstraints = false | |
| 85 | 新增: existingEnvironmentButton.isHidden = true | |
| 86 | 新增: content.addSubview(existingEnvironmentButton) | |
| 66 | 87 | NSLayoutConstraint.activate([loading.centerXAnchor.constraint(equalTo: content.centerXAnchor), loading.centerYAnchor.constraint(equalTo: content.centerYAnchor, constant: -16), loading.widthAnchor.constraint(lessThanOrEqualToConstant: 600), retry.centerXAnchor.constraint(equalTo: content.centerXAnchor), retry.topAnchor.constraint(equalTo: loading.bottomAnchor, constant: 20)]) |
| 88 | 新增: NSLayoutConstraint.activate([existingEnvironmentButton.centerXAnchor.constraint(equalTo: content.centerXAnchor), existingEnvironmentButton.topAnchor.constraint(equalTo: retry.bottomAnchor, constant: 10), completeUpdateButton.centerXAnchor.constraint(equalTo: content.centerXAnchor), completeUpdateButton.topAnchor.constraint(equalTo: existingEnvironmentButton.bottomAnchor, constant: 10)]) | |
| 67 | 89 | applyAppearance(appearance) |
| 90 | 新增: appUpdater = CageAppUpdater(bundleURL: Bundle.main.bundleURL, onChange: { [weak self] state in | |
| 91 | 新增: guard let data = try? JSONSerialization.data(withJSONObject: state), let json = String(data: data, encoding: .utf8) else { return } | |
| 92 | 新增: self?.webView.evaluateJavaScript("window.dispatchEvent(new CustomEvent('cage-app-update',{detail:\(json)}));", completionHandler: nil) | |
| 93 | 新增: }, confirmStop: { [weak self] completion in | |
| 94 | 新增: guard let self else { completion(false); return } | |
| 95 | 新增: let alert = NSAlert() | |
| 96 | 新增: alert.messageText = "更新已下载,保存并停止环境后安装重启" | |
| 97 | 新增: alert.informativeText = "请先保存编辑器中的文件并结束正在运行的工作。继续后 Cage 会停止环境、安装已验证的更新并重新启动。" | |
| 98 | 新增: alert.addButton(withTitle: "已保存,停止并安装") | |
| 99 | 新增: alert.addButton(withTitle: "稍后安装") | |
| 100 | 新增: self.window.makeKeyAndOrderFront(nil) | |
| 101 | 新增: alert.beginSheetModal(for: self.window) { completion($0 == .alertFirstButtonReturn) } | |
| 102 | 新增: }, quit: { [weak self] in self?.allowQuit = true; NSApp.terminate(nil) }, reconnect: { [weak self] in self?.bootstrap() }) | |
| 68 | 103 | window.makeKeyAndOrderFront(nil) |
| 69 | 104 | NSApp.activate(ignoringOtherApps: true) |
| 70 | 105 | bootstrap() |
| @@ -76,6 +111,9 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 76 | 111 | let appMenu = NSMenu(title: "Cage") |
| 77 | 112 | appItem.submenu = appMenu |
| 78 | 113 | appMenu.addItem(withTitle: "关于 Cage", action: #selector(about), keyEquivalent: "") |
| 114 | 新增: appMenu.addItem(withTitle: "检查应用更新…", action: #selector(checkApplicationUpdate), keyEquivalent: "") | |
| 115 | 新增: completeUpdateMenu = appMenu.addItem(withTitle: "完成待安装更新…", action: #selector(completePendingUpdate), keyEquivalent: "") | |
| 116 | 新增: completeUpdateMenu.isHidden = true | |
| 79 | 117 | appMenu.addItem(.separator()) |
| 80 | 118 | appMenu.addItem(withTitle: "设置…", action: #selector(settings), keyEquivalent: ",") |
| 81 | 119 | appMenu.addItem(.separator()) |
| @@ -123,7 +161,8 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 123 | 161 | } |
| 124 | 162 | @objc private func about() { |
| 125 | 163 | let version = Bundle.main.object(forInfoDictionaryKey: "CageVersion") as? String ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "开发版本" |
| 126 | 删除: NSApp.orderFrontStandardAboutPanel(options: [.applicationName:"Cage", .applicationVersion:version, .credits:NSAttributedString(string:"本机隔离编码工作区\n基于 agent-vm、Lima、Chromium、noVNC 与 xterm.js")]) | |
| 164 | 新增: let status = controllerNeedsUpdate ? "\n当前连接旧后台;更新尚未完成。" : "" | |
| 165 | 新增: NSApp.orderFrontStandardAboutPanel(options: [.applicationName:"Cage", .applicationVersion:version, .credits:NSAttributedString(string:"本机隔离编码工作区\n基于 agent-vm、Lima、Chromium、noVNC 与 xterm.js" + status)]) | |
| 127 | 166 | } |
| 128 | 167 | @objc private func settings() { action("settings") } |
| 129 | 168 | @objc private func openProject() { action("openProject") } |
| @@ -132,32 +171,56 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 132 | 171 | @objc private func closeTab() { action("closeTab") } |
| 133 | 172 | @objc private func closeWindow() { window.close() } |
| 134 | 173 | @objc private func requestQuit() { NSApp.terminate(nil) } |
| 174 | 新增: @objc private func checkApplicationUpdate() { _ = appUpdater?.handle("check") } | |
| 135 | 175 | @objc private func retryConnection() { bootstrap() } |
| 176 | 新增: @objc private func openExistingEnvironment() { bootstrap(options: ["--existing"]) } | |
| 177 | 新增: @objc private func completePendingUpdate() { | |
| 178 | 新增: let alert = NSAlert() | |
| 179 | 新增: alert.messageText = "保存文件后完成更新" | |
| 180 | 新增: alert.informativeText = "这会停止现有环境和终端任务,再切换到新版后台。项目文件和登录状态会保留。请先保存编辑器中的修改。" | |
| 181 | 新增: alert.addButton(withTitle: "已保存,停止并更新") | |
| 182 | 新增: alert.addButton(withTitle: "继续当前工作") | |
| 183 | 新增: alert.beginSheetModal(for: window) { response in | |
| 184 | 新增: if response == .alertFirstButtonReturn { self.bootstrap(options: ["--complete-update"]) } | |
| 185 | 新增: } | |
| 186 | 新增: } | |
| 136 | 187 | private func action(_ name: String) { webView.evaluateJavaScript("window.cageNativeAction?.('\(name)')", completionHandler: nil) } |
| 137 | 删除: private func requestEntry(_ completion: @escaping (Result<URL, Error>) -> Void) { | |
| 188 | 新增: private func requestEntry(options: [String] = [], _ completion: @escaping (Result<DesktopEntry, Error>) -> Void) { | |
| 138 | 189 | guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else { |
| 139 | 190 | completion(.failure(NSError(domain: "Cage", code: 1))); return |
| 140 | 191 | } |
| 141 | 192 | DispatchQueue.global(qos: .userInitiated).async { |
| 142 | 删除: let process = Process(); process.executableURL = executable; process.arguments = ["desktop", "--json"] | |
| 193 | 新增: let process = Process(); process.executableURL = executable; process.arguments = ["desktop", "--json"] + options | |
| 143 | 194 | let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice |
| 144 | 195 | do { |
| 145 | 196 | try process.run() |
| 146 | 197 | let data = output.fileHandleForReading.readDataToEndOfFile() |
| 147 | 198 | process.waitUntilExit() |
| 148 | 删除: let result = try JSONSerialization.jsonObject(with: data) as? [String:String] | |
| 149 | 删除: guard process.terminationStatus == 0, let raw = result?["url"], let url = URL(string: raw), url.scheme == "http", url.host == "localhost", url.port != nil, url.fragment?.isEmpty == false else { throw NSError(domain:"Cage", code:1) } | |
| 150 | 删除: DispatchQueue.main.async { completion(.success(url)) } | |
| 199 | 新增: let result = try JSONSerialization.jsonObject(with: data) as? [String:Any] | |
| 200 | 新增: let message = result?["message"] as? String ?? "工作台未能启动,请重试连接。" | |
| 201 | 新增: guard process.terminationStatus == 0, let status = result?["status"] as? String else { throw NSError(domain:"Cage", code:1, userInfo:[NSLocalizedDescriptionKey:message]) } | |
| 202 | 新增: if status == "upgrade_pending" { | |
| 203 | 新增: DispatchQueue.main.async { completion(.success(DesktopEntry(status:status, url:nil, message:message))) } | |
| 204 | 新增: return | |
| 205 | 新增: } | |
| 206 | 新增: guard let raw = result?["url"] as? String, let url = URL(string: raw), url.scheme == "http", url.host == "localhost", url.port != nil, url.fragment?.isEmpty == false else { throw NSError(domain:"Cage", code:1, userInfo:[NSLocalizedDescriptionKey:message]) } | |
| 207 | 新增: DispatchQueue.main.async { completion(.success(DesktopEntry(status:status, url:url, message:""))) } | |
| 151 | 208 | } catch { DispatchQueue.main.async { completion(.failure(error)) } } |
| 152 | 209 | } |
| 153 | 210 | } |
| 154 | 删除: private func bootstrap() { | |
| 155 | 删除: loading.stringValue = "正在启动 Cage 工作台…" | |
| 211 | 新增: private func bootstrap(options: [String] = []) { | |
| 212 | 新增: loading.stringValue = options.contains("--complete-update") ? "正在停止环境并切换到新版后台…" : "正在启动 Cage 工作台…" | |
| 156 | 213 | loading.isHidden = false; retry.isHidden = true; webView.isHidden = true |
| 157 | 删除: requestEntry { result in | |
| 214 | 新增: completeUpdateButton.isHidden = true; existingEnvironmentButton.isHidden = true | |
| 215 | 新增: requestEntry(options: options) { result in | |
| 158 | 216 | switch result { |
| 159 | 删除: case .success(let url): self.expectedPort = url.port!; self.webView.load(URLRequest(url: url)) | |
| 160 | 删除: case .failure: self.showError("工作台未能启动。请重试;详细信息位于 ~/.claude-cage/control.log。") | |
| 217 | 新增: case .success(let entry): | |
| 218 | 新增: self.controllerNeedsUpdate = entry.status != "ready" | |
| 219 | 新增: self.completeUpdateMenu.isHidden = !self.controllerNeedsUpdate | |
| 220 | 新增: self.window.title = self.controllerNeedsUpdate ? "Cage(更新待完成)" : "Cage" | |
| 221 | 新增: if let url = entry.url { self.expectedPort = url.port!; self.webView.load(URLRequest(url: url)) } | |
| 222 | 新增: else { self.showError(entry.message); self.completeUpdateButton.isHidden = false; self.existingEnvironmentButton.isHidden = false } | |
| 223 | 新增: case .failure(let error): self.showError(error.localizedDescription) | |
| 161 | 224 | } |
| 162 | 225 | } |
| 163 | 226 | } |
| @@ -173,7 +236,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 173 | 236 | window.backgroundColor = NSColor(srgbRed: Double((hex >> 16) & 255)/255, green: Double((hex >> 8) & 255)/255, blue: Double(hex & 255)/255, alpha: 1) |
| 174 | 237 | loading.textColor = .labelColor |
| 175 | 238 | } |
| 176 | 删除: func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loading.isHidden = true; retry.isHidden = true; webView.isHidden = false; window.makeFirstResponder(webView) } | |
| 239 | 新增: func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loading.isHidden = true; retry.isHidden = true; completeUpdateButton.isHidden = true; existingEnvironmentButton.isHidden = true; webView.isHidden = false; window.makeFirstResponder(webView); publishWindowVisibility() } | |
| 177 | 240 | func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { showError("无法连接工作台。后台任务不会因此自动结束。") } |
| 178 | 241 | func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { bootstrap() } |
| 179 | 242 | func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { |
| @@ -184,6 +247,13 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 184 | 247 | let origin = message.frameInfo.securityOrigin |
| 185 | 248 | guard message.frameInfo.isMainFrame, origin.protocol == "http", origin.host == "localhost", origin.port == expectedPort, let body = message.body as? [String:Any], let action = body["action"] as? String else { replyHandler(nil,"请求来源无效"); return } |
| 186 | 249 | switch action { |
| 250 | 新增: case "workbenchReady": | |
| 251 | 新增: guard !controllerNeedsUpdate else { replyHandler(nil,"后台版本尚未同步,更新未完成"); return } | |
| 252 | 新增: appUpdater?.markLaunchReady() | |
| 253 | 新增: replyHandler(true,nil) | |
| 254 | 新增: case "appUpdate": | |
| 255 | 新增: guard let operation = body["operation"] as? String, ["status", "check", "install", "cancel"].contains(operation) else { replyHandler(nil,"更新操作无效"); return } | |
| 256 | 新增: replyHandler(appUpdater.handle(operation),nil) | |
| 187 | 257 | case "appearance": |
| 188 | 258 | guard let mode = body["mode"] as? String, ["system", "light", "dark"].contains(mode), let background = body["background"] as? String, background.range(of: "^#[0-9a-fA-F]{6}$", options: .regularExpression) != nil else { replyHandler(nil,"外观参数无效"); return } |
| 189 | 259 | let value: [String:Any] = ["mode":mode,"background":background,"translucent":body["translucent"] as? Bool ?? false] |
| @@ -198,9 +268,11 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 198 | 268 | let panel = NSOpenPanel(); panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true; panel.allowsMultipleSelection = false; panel.prompt = "共享此项目"; panel.message = "仅此文件夹会与 Cage 共享。请选择具体项目。" |
| 199 | 269 | panel.beginSheetModal(for:window) { response in replyHandler(response == .OK ? panel.url?.path : "",nil) } |
| 200 | 270 | case "refreshSession": |
| 201 | 删除: requestEntry { result in | |
| 271 | 新增: requestEntry(options: controllerNeedsUpdate ? ["--existing"] : []) { result in | |
| 202 | 272 | switch result { |
| 203 | 删除: case .success(let url): replyHandler(["url":url.absoluteString],nil) | |
| 273 | 新增: case .success(let entry): | |
| 274 | 新增: if let url = entry.url { replyHandler(["url":url.absoluteString],nil) } | |
| 275 | 新增: else { replyHandler(nil,entry.message) } | |
| 204 | 276 | case .failure: replyHandler(nil,"工作台会话恢复失败,请重新连接后重试。") |
| 205 | 277 | } |
| 206 | 278 | } |
| @@ -211,11 +283,25 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 211 | 283 | } |
| 212 | 284 | func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = NSAlert(); alert.messageText = message; alert.beginSheetModal(for:window){_ in completionHandler()} } |
| 213 | 285 | func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alert = NSAlert(); alert.messageText = message; alert.addButton(withTitle:"确定"); alert.addButton(withTitle:"取消"); alert.beginSheetModal(for:window){completionHandler($0 == .alertFirstButtonReturn)} } |
| 214 | 删除: func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { window.makeKeyAndOrderFront(nil); return true } | |
| 286 | 新增: private func publishWindowVisibility(forceHidden: Bool = false) { | |
| 287 | 新增: guard window != nil, webView != nil else { return } | |
| 288 | 新增: let visible = !forceHidden && window.isVisible && !window.isMiniaturized && window.occlusionState.contains(.visible) | |
| 289 | 新增: webView.evaluateJavaScript("window.cageWindowVisible = \(visible ? "true" : "false"); window.dispatchEvent(new Event('cage-window-visibility'));", completionHandler: nil) | |
| 290 | 新增: } | |
| 291 | 新增: func windowDidChangeOcclusionState(_ notification: Notification) { publishWindowVisibility() } | |
| 292 | 新增: func windowDidMiniaturize(_ notification: Notification) { publishWindowVisibility() } | |
| 293 | 新增: func windowDidDeminiaturize(_ notification: Notification) { publishWindowVisibility() } | |
| 294 | 新增: func windowWillClose(_ notification: Notification) { publishWindowVisibility(forceHidden: true) } | |
| 295 | 新增: func applicationDidHide(_ notification: Notification) { publishWindowVisibility(forceHidden: true) } | |
| 296 | 新增: func applicationDidUnhide(_ notification: Notification) { publishWindowVisibility() } | |
| 297 | 新增: func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { window.makeKeyAndOrderFront(nil); publishWindowVisibility(); return true } | |
| 215 | 298 | func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false } |
| 299 | 新增: func applicationWillTerminate(_ notification: Notification) { appUpdater?.cancelForTermination() } | |
| 216 | 300 | func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { |
| 217 | 删除: if allowQuit { return .terminateNow } | |
| 218 | 删除: if webView.isHidden { return .terminateNow } | |
| 301 | 新增: if allowQuit || webView.isHidden || appUpdater?.awaitingInitialWorkbench == true { | |
| 302 | 新增: if appUpdater?.prepareForTermination({ NSApp.reply(toApplicationShouldTerminate: true) }) == true { return .terminateLater } | |
| 303 | 新增: return .terminateNow | |
| 304 | 新增: } | |
| 219 | 305 | window.makeKeyAndOrderFront(nil); action("quit"); return .terminateCancel |
| 220 | 306 | } |
| 221 | 307 | } |
| @@ -0,0 +1,183 @@ | ||
| 1 | 新增:import Cocoa | |
| 2 | 新增:import Darwin | |
| 3 | 新增: | |
| 4 | 新增:@main | |
| 5 | 新增:final class CageUpdateInstaller: NSObject, NSApplicationDelegate { | |
| 6 | 新增: private var plan: CageUpdatePlan! | |
| 7 | 新增: private var parent: NSRunningApplication! | |
| 8 | 新增: private var manager = FileManager.default | |
| 9 | 新增: private var didReplace = false | |
| 10 | 新增: private var originalVersion = "" | |
| 11 | 新增: | |
| 12 | 新增: static func main() { | |
| 13 | 新增: let app = NSApplication.shared | |
| 14 | 新增: let delegate = CageUpdateInstaller(); app.delegate = delegate | |
| 15 | 新增: app.setActivationPolicy(.accessory) | |
| 16 | 新增: withExtendedLifetime(delegate) { app.run() } | |
| 17 | 新增: } | |
| 18 | 新增: func applicationDidFinishLaunching(_ notification: Notification) { | |
| 19 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 20 | 新增: do { | |
| 21 | 新增: try self.readPlan() | |
| 22 | 新增: let directory = URL(fileURLWithPath: self.plan.target).deletingLastPathComponent() | |
| 23 | 新增: DispatchQueue.main.async { | |
| 24 | 新增: if FileManager.default.isWritableFile(atPath: directory.path) { self.prepare() } | |
| 25 | 新增: else { | |
| 26 | 新增: NSWorkspace.shared.requestAuthorization(to: .replaceFile) { authorization, _ in | |
| 27 | 新增: DispatchQueue.main.async { | |
| 28 | 新增: guard let authorization else { self.finishBeforeCommit("未获得安装权限,原应用已保留"); return } | |
| 29 | 新增: self.manager = FileManager(authorization: authorization) | |
| 30 | 新增: self.prepare() | |
| 31 | 新增: } | |
| 32 | 新增: } | |
| 33 | 新增: } | |
| 34 | 新增: } | |
| 35 | 新增: } catch { self.finishBeforeCommit(error.localizedDescription) } | |
| 36 | 新增: } | |
| 37 | 新增: } | |
| 38 | 新增: private func readPlan() throws { | |
| 39 | 新增: guard CommandLine.arguments.count == 2 else { throw CageUpdateError("安装任务无效") } | |
| 40 | 新增: let location = URL(fileURLWithPath: CommandLine.arguments[1]).resolvingSymlinksInPath() | |
| 41 | 新增: let directory = location.deletingLastPathComponent() | |
| 42 | 新增: let attributes = try FileManager.default.attributesOfItem(atPath: directory.path) | |
| 43 | 新增: guard (attributes[.ownerAccountID] as? NSNumber)?.uint32Value == getuid(), | |
| 44 | 新增: ((attributes[.posixPermissions] as? NSNumber)?.intValue ?? 0) & 0o077 == 0 else { throw CageUpdateError("安装任务目录权限无效") } | |
| 45 | 新增: let data = try Data(contentsOf: location) | |
| 46 | 新增: guard data.count <= 16384 else { throw CageUpdateError("安装任务过大") } | |
| 47 | 新增: plan = try JSONDecoder().decode(CageUpdatePlan.self, from: data) | |
| 48 | 新增: guard plan.parentPID == getppid(), let running = NSRunningApplication(processIdentifier: plan.parentPID), | |
| 49 | 新增: running.bundleURL?.resolvingSymlinksInPath().path == plan.target else { throw CageUpdateError("安装任务不属于当前 Cage 应用") } | |
| 50 | 新增: parent = running | |
| 51 | 新增: let selfURL = URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath() | |
| 52 | 新增: let ownTeam = try CageUpdateFiles.signingInfo(selfURL, bundle: false) | |
| 53 | 新增: guard ownTeam == plan.team, | |
| 54 | 新增: URL(fileURLWithPath: plan.candidate).resolvingSymlinksInPath().path == directory.appendingPathComponent("Cage.app").path, | |
| 55 | 新增: plan.backup == directory.appendingPathComponent("previous.app").path, | |
| 56 | 新增: plan.resultPath == directory.deletingLastPathComponent().appendingPathComponent("last-result.json").path, | |
| 57 | 新增: selfURL.deletingLastPathComponent() == directory else { throw CageUpdateError("安装任务路径或签名不匹配") } | |
| 58 | 新增: let target = URL(fileURLWithPath: plan.target) | |
| 59 | 新增: guard target == target.resolvingSymlinksInPath(), target.pathExtension == "app", !target.path.hasPrefix("/Volumes/") else { throw CageUpdateError("安装位置不支持自动更新") } | |
| 60 | 新增: _ = try CageUpdateFiles.signingInfo(target, bundle: true, expectedTeam: ownTeam) | |
| 61 | 新增: try CageUpdateFiles.verifyApp(URL(fileURLWithPath: plan.candidate), version: plan.version, team: ownTeam) | |
| 62 | 新增: let info = try PropertyListSerialization.propertyList(from: Data(contentsOf: target.appendingPathComponent("Contents/Info.plist")), format: nil) as? [String: Any] | |
| 63 | 新增: guard let current = info?["CageVersion"] as? String, CageUpdateVersion.isNewer(plan.version, than: current) else { throw CageUpdateError("更新版本必须高于当前安装版本") } | |
| 64 | 新增: originalVersion = current | |
| 65 | 新增: } | |
| 66 | 新增: private func prepare() { | |
| 67 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 68 | 新增: do { | |
| 69 | 新增: let backup = URL(fileURLWithPath: self.plan.backup) | |
| 70 | 新增: if FileManager.default.fileExists(atPath: backup.path) { try FileManager.default.removeItem(at: backup) } | |
| 71 | 新增: try FileManager.default.copyItem(at: URL(fileURLWithPath: self.plan.target), to: backup) | |
| 72 | 新增: _ = try CageUpdateFiles.signingInfo(backup, bundle: true, expectedTeam: self.plan.team) | |
| 73 | 新增: self.send(["status": "ready"]) | |
| 74 | 新增: let command = FileHandle.standardInput.readDataToEndOfFile() | |
| 75 | 新增: guard command == Data("COMMIT\n".utf8) else { self.exitHelper(); return } | |
| 76 | 新增: let deadline = Date().addingTimeInterval(90) | |
| 77 | 新增: while !self.parent.isTerminated && Date() < deadline { Thread.sleep(forTimeInterval: 0.1) } | |
| 78 | 新增: guard self.parent.isTerminated else { throw CageUpdateError("Cage 尚未退出,更新未安装") } | |
| 79 | 新增: try self.replace() | |
| 80 | 新增: DispatchQueue.main.async { self.openInstalled() } | |
| 81 | 新增: } catch { | |
| 82 | 新增: if self.parent?.isTerminated == true { self.recover(error.localizedDescription) } | |
| 83 | 新增: else { self.finishBeforeCommit(error.localizedDescription) } | |
| 84 | 新增: } | |
| 85 | 新增: } | |
| 86 | 新增: } | |
| 87 | 新增: private func replace() throws { | |
| 88 | 新增: let target = URL(fileURLWithPath: plan.target) | |
| 89 | 新增: let candidate = URL(fileURLWithPath: plan.candidate) | |
| 90 | 新增: _ = try CageUpdateFiles.signingInfo(target, bundle: true, expectedTeam: plan.team) | |
| 91 | 新增: try CageUpdateFiles.verifyApp(candidate, version: plan.version, team: plan.team) | |
| 92 | 新增: try CageUpdateFiles.replaceAndVerify(target: target, candidate: candidate, backup: URL(fileURLWithPath: plan.backup), manager: manager, onReplace: { self.didReplace = true }) { | |
| 93 | 新增: try CageUpdateFiles.verifyApp($0, version: plan.version, team: plan.team) | |
| 94 | 新增: } | |
| 95 | 新增: } | |
| 96 | 新增: private func openInstalled() { | |
| 97 | 新增: let configuration = NSWorkspace.OpenConfiguration() | |
| 98 | 新增: configuration.activates = true | |
| 99 | 新增: configuration.createsNewApplicationInstance = true | |
| 100 | 新增: let token = UUID().uuidString | |
| 101 | 新增: var environment = inheritedProfile(); environment["CAGE_UPDATE_CONFIRMATION"] = token | |
| 102 | 新增: configuration.environment = environment | |
| 103 | 新增: NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: plan.target), configuration: configuration) { app, error in | |
| 104 | 新增: guard error == nil, let app else { self.recover("新版本未能启动,正在恢复原应用"); return } | |
| 105 | 新增: let acknowledgement = URL(fileURLWithPath: self.plan.resultPath).deletingLastPathComponent().appendingPathComponent("launch-\(token).json") | |
| 106 | 新增: DispatchQueue.global(qos: .utility).async { | |
| 107 | 新增: let deadline = Date().addingTimeInterval(45) | |
| 108 | 新增: while !app.isTerminated && Date() < deadline { | |
| 109 | 新增: if let data = try? Data(contentsOf: acknowledgement), data.count < 1024, | |
| 110 | 新增: let value = try? JSONSerialization.jsonObject(with: data) as? [String: String], value["version"] == self.plan.version { | |
| 111 | 新增: try? FileManager.default.removeItem(at: acknowledgement) | |
| 112 | 新增: self.record(success: true, message: "Cage 已更新至 \(self.plan.version)") | |
| 113 | 新增: self.cleanSuccessfulTask(); self.exitHelper(); return | |
| 114 | 新增: } | |
| 115 | 新增: Thread.sleep(forTimeInterval: 0.2) | |
| 116 | 新增: } | |
| 117 | 新增: DispatchQueue.main.async { _ = app.terminate() } | |
| 118 | 新增: let terminationDeadline = Date().addingTimeInterval(10) | |
| 119 | 新增: while !app.isTerminated && Date() < terminationDeadline { Thread.sleep(forTimeInterval: 0.1) } | |
| 120 | 新增: if app.isTerminated { self.recover("新版本工作台未能就绪,正在恢复原应用") } | |
| 121 | 新增: else { | |
| 122 | 新增: self.record(success: false, message: "新版本未确认就绪,请退出 Cage 后重试;原应用备份已保留") | |
| 123 | 新增: self.exitHelper() | |
| 124 | 新增: } | |
| 125 | 新增: } | |
| 126 | 新增: } | |
| 127 | 新增: } | |
| 128 | 新增: private func inheritedProfile() -> [String: String] { | |
| 129 | 新增: if let path = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"] { return ["CLAUDE_CAGE_CONFIG": path] } | |
| 130 | 新增: return [:] | |
| 131 | 新增: } | |
| 132 | 新增: private func recover(_ reason: String) { | |
| 133 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 134 | 新增: var message = reason | |
| 135 | 新增: var canOpen = false | |
| 136 | 新增: let target = URL(fileURLWithPath: self.plan.target), backup = URL(fileURLWithPath: self.plan.backup) | |
| 137 | 新增: do { | |
| 138 | 新增: let originalIntact = (try? CageUpdateFiles.verifyApp(target, version: self.originalVersion, team: self.plan.team, gatekeeper: false)) != nil | |
| 139 | 新增: if self.didReplace || !originalIntact { | |
| 140 | 新增: try CageUpdateFiles.verifyApp(backup, version: self.originalVersion, team: self.plan.team, gatekeeper: false) | |
| 141 | 新增: // A failed target may contain invalid executables. Use only | |
| 142 | 新增: // the verified original controller to release the backend. | |
| 143 | 新增: let control = backup.appendingPathComponent("Contents/Resources/cage") | |
| 144 | 新增: let handoffData = try CageUpdateFiles.run(control.path, ["prepare-update", "--json"], timeout: 90) | |
| 145 | 新增: guard let handoff = try JSONSerialization.jsonObject(with: handoffData) as? [String: Any], handoff["status"] as? String == "prepared" else { | |
| 146 | 新增: throw CageUpdateError("新版本后台尚未安全退出,原应用备份已保留") | |
| 147 | 新增: } | |
| 148 | 新增: if !originalIntact { try CageUpdateFiles.restore(backup: backup, target: target, manager: self.manager) } | |
| 149 | 新增: try CageUpdateFiles.verifyApp(target, version: self.originalVersion, team: self.plan.team, gatekeeper: false) | |
| 150 | 新增: message += "。已恢复原应用,可稍后重试" | |
| 151 | 新增: } else { message += "。原应用已保留" } | |
| 152 | 新增: canOpen = true | |
| 153 | 新增: } catch { message += "。自动恢复未完成,未启动未经验证的应用。备份位置:\(backup.path)" } | |
| 154 | 新增: self.record(success: false, message: message) | |
| 155 | 新增: DispatchQueue.main.async { | |
| 156 | 新增: guard canOpen else { | |
| 157 | 新增: let alert = NSAlert(); alert.messageText = "Cage 更新与自动恢复未完成"; alert.informativeText = message; alert.runModal() | |
| 158 | 新增: self.exitHelper(); return | |
| 159 | 新增: } | |
| 160 | 新增: let configuration = NSWorkspace.OpenConfiguration(); configuration.activates = true; configuration.createsNewApplicationInstance = true; configuration.environment = self.inheritedProfile() | |
| 161 | 新增: NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: self.plan.target), configuration: configuration) { app, _ in | |
| 162 | 新增: if app == nil { | |
| 163 | 新增: let alert = NSAlert(); alert.messageText = "Cage 更新未完成"; alert.informativeText = message; alert.runModal() | |
| 164 | 新增: } | |
| 165 | 新增: self.exitHelper() | |
| 166 | 新增: } | |
| 167 | 新增: } | |
| 168 | 新增: } | |
| 169 | 新增: } | |
| 170 | 新增: private func record(success: Bool, message: String) { | |
| 171 | 新增: guard let data = try? JSONSerialization.data(withJSONObject: ["success": success, "message": message, "version": plan.version]) else { return } | |
| 172 | 新增: try? CageUpdateFiles.write(data, to: URL(fileURLWithPath: plan.resultPath)) | |
| 173 | 新增: } | |
| 174 | 新增: private func cleanSuccessfulTask() { | |
| 175 | 新增: let directory = URL(fileURLWithPath: plan.backup).deletingLastPathComponent() | |
| 176 | 新增: try? FileManager.default.removeItem(at: directory) | |
| 177 | 新增: } | |
| 178 | 新增: private func finishBeforeCommit(_ message: String) { send(["status": "error", "message": message]); exitHelper() } | |
| 179 | 新增: private func send(_ value: [String: Any]) { | |
| 180 | 新增: if var data = try? JSONSerialization.data(withJSONObject: value) { data.append(10); try? FileHandle.standardOutput.write(contentsOf: data) } | |
| 181 | 新增: } | |
| 182 | 新增: private func exitHelper() { DispatchQueue.main.async { NSApp.terminate(nil) } } | |
| 183 | 新增:} | |
| @@ -0,0 +1,480 @@ | ||
| 1 | 新增:import Cocoa | |
| 2 | 新增:import CryptoKit | |
| 3 | 新增:import Security | |
| 4 | 新增:import Darwin | |
| 5 | 新增: | |
| 6 | 新增:let cageUpdateBundleID = "io.github.lee-xeo.claude-cage" | |
| 7 | 新增: | |
| 8 | 新增:final class CageUpdateValidation { | |
| 9 | 新增: private let lock = NSLock() | |
| 10 | 新增: private let completion = DispatchGroup() | |
| 11 | 新增: private var cancelled = false | |
| 12 | 新增: private var process: Process? | |
| 13 | 新增: | |
| 14 | 新增: init() { completion.enter() } | |
| 15 | 新增: func checkCancellation() throws { | |
| 16 | 新增: lock.lock(); defer { lock.unlock() } | |
| 17 | 新增: if cancelled { throw CageUpdateError("更新验证已取消") } | |
| 18 | 新增: } | |
| 19 | 新增: func start(_ value: Process) throws { | |
| 20 | 新增: lock.lock(); defer { lock.unlock() } | |
| 21 | 新增: if cancelled { throw CageUpdateError("更新验证已取消") } | |
| 22 | 新增: try value.run() | |
| 23 | 新增: process = value | |
| 24 | 新增: } | |
| 25 | 新增: func released(_ value: Process) { | |
| 26 | 新增: lock.lock(); defer { lock.unlock() } | |
| 27 | 新增: if process === value { process = nil } | |
| 28 | 新增: } | |
| 29 | 新增: func cancel() { | |
| 30 | 新增: lock.lock(); cancelled = true; let active = process; lock.unlock() | |
| 31 | 新增: if let active { CageUpdateFiles.stop(active) } | |
| 32 | 新增: } | |
| 33 | 新增: func finish() { completion.leave() } | |
| 34 | 新增: func wait() { completion.wait() } | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:struct CageUpdateError: LocalizedError { | |
| 38 | 新增: let message: String | |
| 39 | 新增: var errorDescription: String? { message } | |
| 40 | 新增: init(_ message: String) { self.message = message } | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:struct CageUpdatePlan: Codable { | |
| 44 | 新增: let version: String | |
| 45 | 新增: let team: String | |
| 46 | 新增: let target: String | |
| 47 | 新增: let candidate: String | |
| 48 | 新增: let backup: String | |
| 49 | 新增: let parentPID: Int32 | |
| 50 | 新增: let resultPath: String | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 53 | 新增:enum CageUpdateVersion { | |
| 54 | 新增: static func isNewer(_ candidate: String, than current: String) -> Bool { | |
| 55 | 新增: func parts(_ text: String) -> ([Int], [String])? { | |
| 56 | 新增: guard text.range(of: "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$", options: .regularExpression) != nil else { return nil } | |
| 57 | 新增: let sections = text.split(separator: "-", maxSplits: 1).map(String.init) | |
| 58 | 新增: let numbers = sections[0].split(separator: ".").compactMap { Int($0) } | |
| 59 | 新增: guard numbers.count == 3 else { return nil } | |
| 60 | 新增: let pre = sections.count == 2 ? sections[1].split(separator: ".").map(String.init) : [] | |
| 61 | 新增: if pre.contains(where: { $0.count > 1 && $0.first == "0" && $0.allSatisfy(\.isNumber) }) { return nil } | |
| 62 | 新增: return (numbers, pre) | |
| 63 | 新增: } | |
| 64 | 新增: guard let (a, ap) = parts(candidate), let (b, bp) = parts(current) else { return false } | |
| 65 | 新增: for i in 0..<3 where a[i] != b[i] { return a[i] > b[i] } | |
| 66 | 新增: if ap.isEmpty || bp.isEmpty { return ap.isEmpty && !bp.isEmpty } | |
| 67 | 新增: for i in 0..<min(ap.count, bp.count) where ap[i] != bp[i] { | |
| 68 | 新增: let x = ap[i], y = bp[i], xn = x.allSatisfy(\.isNumber), yn = y.allSatisfy(\.isNumber) | |
| 69 | 新增: if xn && yn { return x.count == y.count ? x > y : x.count > y.count } | |
| 70 | 新增: if xn != yn { return !xn } | |
| 71 | 新增: return x > y | |
| 72 | 新增: } | |
| 73 | 新增: return ap.count > bp.count | |
| 74 | 新增: } | |
| 75 | 新增:} | |
| 76 | 新增: | |
| 77 | 新增:enum CageUpdateFiles { | |
| 78 | 新增: static func restore(backup: URL, target: URL, manager: FileManager) throws { | |
| 79 | 新增: let copy = backup.deletingLastPathComponent().appendingPathComponent("restore-" + UUID().uuidString + ".app") | |
| 80 | 新增: try FileManager.default.copyItem(at: backup, to: copy) | |
| 81 | 新增: defer { try? FileManager.default.removeItem(at: copy) } | |
| 82 | 新增: if FileManager.default.fileExists(atPath: target.path) { | |
| 83 | 新增: _ = try manager.replaceItemAt(target, withItemAt: copy, backupItemName: nil, options: [.usingNewMetadataOnly]) | |
| 84 | 新增: } else { | |
| 85 | 新增: try manager.moveItem(at: copy, to: target) | |
| 86 | 新增: } | |
| 87 | 新增: } | |
| 88 | 新增: static func replaceAndVerify(target: URL, candidate: URL, backup: URL, manager: FileManager, onReplace: () -> Void = {}, restoreOriginal: (() throws -> Void)? = nil, verify: (URL) throws -> Void) throws { | |
| 89 | 新增: do { | |
| 90 | 新增: _ = try manager.replaceItemAt(target, withItemAt: candidate, backupItemName: nil, options: [.usingNewMetadataOnly]) | |
| 91 | 新增: onReplace() | |
| 92 | 新增: try verify(target) | |
| 93 | 新增: } catch { | |
| 94 | 新增: do { | |
| 95 | 新增: if let restoreOriginal { try restoreOriginal() } | |
| 96 | 新增: else { try restore(backup: backup, target: target, manager: manager) } | |
| 97 | 新增: } | |
| 98 | 新增: catch { throw CageUpdateError("安装与自动恢复均未完成,原应用备份已保留") } | |
| 99 | 新增: throw CageUpdateError("安装验证失败,已恢复原应用") | |
| 100 | 新增: } | |
| 101 | 新增: } | |
| 102 | 新增: static func privateDirectory(_ url: URL) throws { | |
| 103 | 新增: try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) | |
| 104 | 新增: let values = try url.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey]) | |
| 105 | 新增: guard values.isDirectory == true, values.isSymbolicLink != true else { throw CageUpdateError("更新目录无效") } | |
| 106 | 新增: try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: url.path) | |
| 107 | 新增: } | |
| 108 | 新增: static func write(_ data: Data, to url: URL) throws { | |
| 109 | 新增: try data.write(to: url, options: .atomic) | |
| 110 | 新增: try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) | |
| 111 | 新增: } | |
| 112 | 新增: static func digest(_ url: URL, validation: CageUpdateValidation? = nil) throws -> String { | |
| 113 | 新增: let file = try FileHandle(forReadingFrom: url) | |
| 114 | 新增: defer { try? file.close() } | |
| 115 | 新增: var hash = SHA256() | |
| 116 | 新增: while let data = try file.read(upToCount: 1024 * 1024), !data.isEmpty { try validation?.checkCancellation(); hash.update(data: data) } | |
| 117 | 新增: return hash.finalize().map { String(format: "%02x", $0) }.joined() | |
| 118 | 新增: } | |
| 119 | 新增: static func stop(_ process: Process) { | |
| 120 | 新增: guard process.isRunning else { return } | |
| 121 | 新增: process.terminate() | |
| 122 | 新增: DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 2) { | |
| 123 | 新增: if process.isRunning { Darwin.kill(process.processIdentifier, SIGKILL) } | |
| 124 | 新增: } | |
| 125 | 新增: } | |
| 126 | 新增: static func run(_ executable: String, _ arguments: [String], timeout: TimeInterval = 90, validation: CageUpdateValidation? = nil) throws -> Data { | |
| 127 | 新增: let process = Process() | |
| 128 | 新增: process.executableURL = URL(fileURLWithPath: executable) | |
| 129 | 新增: process.arguments = arguments | |
| 130 | 新增: let pipe = Pipe(); process.standardOutput = pipe; process.standardError = pipe | |
| 131 | 新增: let expiration = DispatchWorkItem { stop(process) } | |
| 132 | 新增: if let validation { try validation.start(process) } else { try process.run() } | |
| 133 | 新增: defer { validation?.released(process) } | |
| 134 | 新增: DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + timeout, execute: expiration) | |
| 135 | 新增: let data = pipe.fileHandleForReading.readDataToEndOfFile() | |
| 136 | 新增: process.waitUntilExit(); expiration.cancel() | |
| 137 | 新增: try validation?.checkCancellation() | |
| 138 | 新增: guard process.terminationStatus == 0, data.count <= 1024 * 1024 else { throw CageUpdateError("本机更新验证未完成,请重试") } | |
| 139 | 新增: return data | |
| 140 | 新增: } | |
| 141 | 新增: static func signingInfo(_ url: URL, bundle: Bool, expectedTeam: String? = nil) throws -> String { | |
| 142 | 新增: var code: SecStaticCode? | |
| 143 | 新增: guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code else { throw CageUpdateError("无法读取应用签名") } | |
| 144 | 新增: var requirement: SecRequirement? | |
| 145 | 新增: let identity = bundle ? " and identifier \"\(cageUpdateBundleID)\"" : "" | |
| 146 | 新增: let team = expectedTeam.map { " and certificate leaf[subject.OU] = \"\($0)\"" } ?? "" | |
| 147 | 新增: let expression = "anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists\(identity)\(team)" | |
| 148 | 新增: guard SecRequirementCreateWithString(expression as CFString, [], &requirement) == errSecSuccess else { throw CageUpdateError("无法建立发布者签名要求") } | |
| 149 | 新增: let flags = SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckAllArchitectures | kSecCSCheckNestedCode) | |
| 150 | 新增: guard SecStaticCodeCheckValidity(code, flags, requirement) == errSecSuccess else { throw CageUpdateError("更新应用的 Apple 签名无效或发布者不匹配") } | |
| 151 | 新增: var information: CFDictionary? | |
| 152 | 新增: guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &information) == errSecSuccess, | |
| 153 | 新增: let info = information as? [String: Any], let actual = info[kSecCodeInfoTeamIdentifier as String] as? String, | |
| 154 | 新增: actual.range(of: "^[A-Z0-9]{10}$", options: .regularExpression) != nil else { throw CageUpdateError("当前开发构建没有可验证的发布者,无法自动安装更新") } | |
| 155 | 新增: if let expectedTeam, actual != expectedTeam { throw CageUpdateError("更新应用的发布者不匹配") } | |
| 156 | 新增: return actual | |
| 157 | 新增: } | |
| 158 | 新增: static func verifyApp(_ url: URL, version: String, team: String, gatekeeper: Bool = true, validation: CageUpdateValidation? = nil) throws { | |
| 159 | 新增: try validation?.checkCancellation() | |
| 160 | 新增: let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) | |
| 161 | 新增: guard values.isDirectory == true, values.isSymbolicLink != true, url.pathExtension == "app" else { throw CageUpdateError("更新包中缺少有效的 Cage.app") } | |
| 162 | 新增: let plist = url.appendingPathComponent("Contents/Info.plist") | |
| 163 | 新增: guard let info = try PropertyListSerialization.propertyList(from: Data(contentsOf: plist), format: nil) as? [String: Any], | |
| 164 | 新增: info["CFBundleIdentifier"] as? String == cageUpdateBundleID, | |
| 165 | 新增: info["CageVersion"] as? String == version, | |
| 166 | 新增: info["CFBundleExecutable"] as? String == "Cage" else { throw CageUpdateError("更新包的应用身份或版本不匹配") } | |
| 167 | 新增: if let minimum = info["LSMinimumSystemVersion"] as? String { | |
| 168 | 新增: let parts = minimum.split(separator: ".").compactMap { Int($0) } | |
| 169 | 新增: guard minimum.range(of: "^[0-9]+(\\.[0-9]+){0,2}$", options: .regularExpression) != nil, | |
| 170 | 新增: (1...3).contains(parts.count), ProcessInfo.processInfo.isOperatingSystemAtLeast(OperatingSystemVersion(majorVersion: parts[0], minorVersion: parts.count > 1 ? parts[1] : 0, patchVersion: parts.count > 2 ? parts[2] : 0)) else { throw CageUpdateError("此更新需要更高版本的 macOS") } | |
| 171 | 新增: } | |
| 172 | 新增: _ = try signingInfo(url, bundle: true, expectedTeam: team) | |
| 173 | 新增: _ = try run("/usr/bin/lipo", ["-verify_arch", "arm64", url.appendingPathComponent("Contents/MacOS/Cage").path], validation: validation) | |
| 174 | 新增: for name in ["cage", "mihomo", "CageUpdateInstaller"] { | |
| 175 | 新增: let nested = url.appendingPathComponent("Contents/Resources/\(name)") | |
| 176 | 新增: guard FileManager.default.fileExists(atPath: nested.path) else { throw CageUpdateError("更新包缺少必要的应用组件") } | |
| 177 | 新增: _ = try signingInfo(nested, bundle: false, expectedTeam: team) | |
| 178 | 新增: } | |
| 179 | 新增: if gatekeeper { _ = try run("/usr/sbin/spctl", ["--assess", "--type", "execute", "--verbose=2", url.path], validation: validation) } | |
| 180 | 新增: try validation?.checkCancellation() | |
| 181 | 新增: } | |
| 182 | 新增: static func validateTree(_ app: URL, validation: CageUpdateValidation? = nil) throws { | |
| 183 | 新增: let base = app.resolvingSymlinksInPath().path + "/" | |
| 184 | 新增: guard let items = FileManager.default.enumerator(at: app, includingPropertiesForKeys: [.isRegularFileKey, .fileSizeKey, .isSymbolicLinkKey], options: []) else { throw CageUpdateError("无法检查更新包内容") } | |
| 185 | 新增: var total: Int64 = 0 | |
| 186 | 新增: var count = 0 | |
| 187 | 新增: for case let entry as URL in items { | |
| 188 | 新增: try validation?.checkCancellation() | |
| 189 | 新增: count += 1 | |
| 190 | 新增: guard count <= 50000, entry.resolvingSymlinksInPath().path.hasPrefix(base) else { throw CageUpdateError("更新包包含越界文件或过多文件") } | |
| 191 | 新增: let values = try entry.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) | |
| 192 | 新增: if values.isRegularFile == true { total += Int64(values.fileSize ?? 0) } | |
| 193 | 新增: guard total <= 1024 * 1024 * 1024 else { throw CageUpdateError("解包后的应用超过 1 GiB") } | |
| 194 | 新增: } | |
| 195 | 新增: } | |
| 196 | 新增: static func withMountedImage<T>(archive: URL, directory: URL, validation: CageUpdateValidation? = nil, body: (URL) throws -> T) throws -> T { | |
| 197 | 新增: let mount = directory.appendingPathComponent("mount", isDirectory: true) | |
| 198 | 新增: try privateDirectory(mount) | |
| 199 | 新增: defer { | |
| 200 | 新增: if (try? run("/usr/bin/hdiutil", ["detach", mount.path], timeout: 30)) == nil { | |
| 201 | 新增: _ = try? run("/usr/bin/hdiutil", ["detach", "-force", mount.path], timeout: 30) | |
| 202 | 新增: } | |
| 203 | 新增: } | |
| 204 | 新增: _ = try run("/usr/bin/hdiutil", ["attach", "-readonly", "-nobrowse", "-noautoopen", "-mountpoint", mount.path, archive.path], validation: validation) | |
| 205 | 新增: try validation?.checkCancellation() | |
| 206 | 新增: return try body(mount) | |
| 207 | 新增: } | |
| 208 | 新增: static func extract(archive: URL, hash: String, version: String, team: String, directory: URL, validation: CageUpdateValidation? = nil) throws -> URL { | |
| 209 | 新增: guard try digest(archive, validation: validation) == hash else { throw CageUpdateError("安装包下载后发生变化,请重新下载") } | |
| 210 | 新增: return try withMountedImage(archive: archive, directory: directory, validation: validation) { mount in | |
| 211 | 新增: let source = mount.appendingPathComponent("Cage.app", isDirectory: true) | |
| 212 | 新增: try validateTree(source, validation: validation) | |
| 213 | 新增: try verifyApp(source, version: version, team: team, validation: validation) | |
| 214 | 新增: let target = directory.appendingPathComponent("Cage.app", isDirectory: true) | |
| 215 | 新增: _ = try run("/usr/bin/ditto", [source.path, target.path], validation: validation) | |
| 216 | 新增: try validateTree(target, validation: validation) | |
| 217 | 新增: try verifyApp(target, version: version, team: team, validation: validation) | |
| 218 | 新增: return target | |
| 219 | 新增: } | |
| 220 | 新增: } | |
| 221 | 新增:} | |
| 222 | 新增: | |
| 223 | 新增:/// Owns update state for one native window. All state transitions run on main. | |
| 224 | 新增:final class CageAppUpdater { | |
| 225 | 新增: private let bundleURL: URL | |
| 226 | 新增: private let root: URL | |
| 227 | 新增: private let onChange: ([String: Any]) -> Void | |
| 228 | 新增: private let confirmStop: (@escaping (Bool) -> Void) -> Void | |
| 229 | 新增: private let quit: () -> Void | |
| 230 | 新增: private let reconnect: () -> Void | |
| 231 | 新增: private var state: [String: Any] | |
| 232 | 新增: private var worker: Process? | |
| 233 | 新增: private var validationTask: CageUpdateValidation? | |
| 234 | 新增: private var installer: Process? | |
| 235 | 新增: private var installerInput: Pipe? | |
| 236 | 新增: private var prepared: (directory: URL, app: URL, version: String, team: String)? | |
| 237 | 新增: private var generation = 0 | |
| 238 | 新增: private var launchAcknowledged = false | |
| 239 | 新增: private var workbenchInitialized = false | |
| 240 | 新增: private var waitingForTermination = false | |
| 241 | 新增: private var installationCommitted = false | |
| 242 | 新增: | |
| 243 | 新增: init(bundleURL: URL, onChange: @escaping ([String: Any]) -> Void, confirmStop: @escaping (@escaping (Bool) -> Void) -> Void, quit: @escaping () -> Void, reconnect: @escaping () -> Void) { | |
| 244 | 新增: self.bundleURL = bundleURL.resolvingSymlinksInPath() | |
| 245 | 新增: self.onChange = onChange; self.confirmStop = confirmStop; self.quit = quit; self.reconnect = reconnect | |
| 246 | 新增: let path = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"] ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude-cage/config.json").path | |
| 247 | 新增: root = URL(fileURLWithPath: path).deletingLastPathComponent().appendingPathComponent("updates", isDirectory: true) | |
| 248 | 新增: let version = Bundle(url: bundleURL)?.object(forInfoDictionaryKey: "CageVersion") as? String ?? "开发版本" | |
| 249 | 新增: state = ["phase": "idle", "currentVersion": version, "message": ""] | |
| 250 | 新增: if let data = try? Data(contentsOf: root.appendingPathComponent("last-result.json")), data.count < 16384, | |
| 251 | 新增: let result = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { | |
| 252 | 新增: state["message"] = result["message"] as? String ?? "" | |
| 253 | 新增: if result["success"] as? Bool == false { state["phase"] = "failed"; state["retryable"] = true } | |
| 254 | 新增: } | |
| 255 | 新增: } | |
| 256 | 新增: func handle(_ operation: String) -> [String: Any] { | |
| 257 | 新增: let busy = ["checking", "downloading", "downloaded", "verifying", "installing"].contains(state["phase"] as? String ?? "") | |
| 258 | 新增: switch operation { | |
| 259 | 新增: case "status": break | |
| 260 | 新增: case "check": if !busy && worker == nil && validationTask == nil && installer == nil && prepared == nil { startDownload(checkOnly: true) } | |
| 261 | 新增: case "install": | |
| 262 | 新增: if !busy && worker == nil && validationTask == nil && installer == nil { if prepared != nil { beginInstallation() } else { startDownload(checkOnly: false) } } | |
| 263 | 新增: case "cancel": | |
| 264 | 新增: if installer == nil && state["phase"] as? String != "installing" { generation += 1; if let worker { CageUpdateFiles.stop(worker) }; validationTask?.cancel(); change(["phase": prepared == nil ? "available" : "ready", "message": "更新已暂停,可稍后继续", "retryable": true]) } | |
| 265 | 新增: default: break | |
| 266 | 新增: } | |
| 267 | 新增: return state | |
| 268 | 新增: } | |
| 269 | 新增: func cancelForTermination() { | |
| 270 | 新增: generation += 1 | |
| 271 | 新增: if let worker { CageUpdateFiles.stop(worker) } | |
| 272 | 新增: validationTask?.cancel() | |
| 273 | 新增: try? installerInput?.fileHandleForWriting.close() | |
| 274 | 新增: if !installationCommitted, let installer { CageUpdateFiles.stop(installer) } | |
| 275 | 新增: } | |
| 276 | 新增: func prepareForTermination(_ completion: @escaping () -> Void) -> Bool { | |
| 277 | 新增: if installationCommitted { return false } | |
| 278 | 新增: if waitingForTermination { return true } | |
| 279 | 新增: let download = worker, validation = validationTask, helper = installer | |
| 280 | 新增: let directory = prepared?.directory | |
| 281 | 新增: cancelForTermination() | |
| 282 | 新增: guard download != nil || validation != nil || helper != nil || directory != nil else { return false } | |
| 283 | 新增: waitingForTermination = true | |
| 284 | 新增: change(["message": "正在取消更新并清理临时文件…"]) | |
| 285 | 新增: DispatchQueue.global(qos: .utility).async { | |
| 286 | 新增: download?.waitUntilExit() | |
| 287 | 新增: validation?.wait() | |
| 288 | 新增: helper?.waitUntilExit() | |
| 289 | 新增: if let directory { try? FileManager.default.removeItem(at: directory) } | |
| 290 | 新增: DispatchQueue.main.async { self.waitingForTermination = false; completion() } | |
| 291 | 新增: } | |
| 292 | 新增: return true | |
| 293 | 新增: } | |
| 294 | 新增: var awaitingInitialWorkbench: Bool { | |
| 295 | 新增: guard let token = ProcessInfo.processInfo.environment["CAGE_UPDATE_CONFIRMATION"], UUID(uuidString: token) != nil else { return false } | |
| 296 | 新增: return !workbenchInitialized | |
| 297 | 新增: } | |
| 298 | 新增: func markLaunchReady() { | |
| 299 | 新增: workbenchInitialized = true | |
| 300 | 新增: guard !launchAcknowledged, let token = ProcessInfo.processInfo.environment["CAGE_UPDATE_CONFIRMATION"], UUID(uuidString: token) != nil, | |
| 301 | 新增: let data = try? JSONSerialization.data(withJSONObject: ["version": state["currentVersion"] as? String ?? ""]) else { return } | |
| 302 | 新增: do { | |
| 303 | 新增: try CageUpdateFiles.privateDirectory(root) | |
| 304 | 新增: try CageUpdateFiles.write(data, to: root.appendingPathComponent("launch-\(token).json")) | |
| 305 | 新增: launchAcknowledged = true | |
| 306 | 新增: change(["phase": "current", "message": "Cage 已更新至 \(state["currentVersion"] as? String ?? "")"]) | |
| 307 | 新增: } catch { failure("更新已安装,但启动确认未能保存") } | |
| 308 | 新增: } | |
| 309 | 新增: private func change(_ values: [String: Any]) { | |
| 310 | 新增: if values["phase"] as? String == "current" { state.removeValue(forKey: "latestVersion") } | |
| 311 | 新增: for (key, value) in values { state[key] = value } | |
| 312 | 新增: onChange(state) | |
| 313 | 新增: } | |
| 314 | 新增: private func failure(_ message: String) { change(["phase": "failed", "message": message, "retryable": true]) } | |
| 315 | 新增: private var cage: URL { bundleURL.appendingPathComponent("Contents/Resources/cage") } | |
| 316 | 新增: private func startDownload(checkOnly: Bool) { | |
| 317 | 新增: generation += 1; let operation = generation | |
| 318 | 新增: change(["phase": "checking", "message": "正在通过所选代理检查更新", "receivedBytes": 0, "totalBytes": 0, "retryable": false]) | |
| 319 | 新增: let process = Process(); process.executableURL = cage; process.arguments = ["app-update", checkOnly ? "check" : "download"] | |
| 320 | 新增: let pipe = Pipe(); process.standardOutput = pipe; process.standardError = FileHandle.nullDevice | |
| 321 | 新增: worker = process | |
| 322 | 新增: do { try process.run() } catch { worker = nil; failure("无法启动更新检查,请确认应用组件完整"); return } | |
| 323 | 新增: DispatchQueue.global(qos: .utility).async { | |
| 324 | 新增: var pending = Data(); var last: [String: Any]? | |
| 325 | 新增: while true { | |
| 326 | 新增: let chunk = pipe.fileHandleForReading.availableData | |
| 327 | 新增: if chunk.isEmpty { break } | |
| 328 | 新增: pending.append(chunk) | |
| 329 | 新增: if pending.count > 65536 { process.terminate(); break } | |
| 330 | 新增: while let end = pending.firstIndex(of: 10) { | |
| 331 | 新增: let line = pending.prefix(upTo: end); pending.removeSubrange(...end) | |
| 332 | 新增: guard let value = try? JSONSerialization.jsonObject(with: line) as? [String: Any] else { continue } | |
| 333 | 新增: last = value | |
| 334 | 新增: var visible = value; visible.removeValue(forKey: "archivePath"); visible.removeValue(forKey: "sha256") | |
| 335 | 新增: DispatchQueue.main.async { if self.generation == operation { self.change(visible) } } | |
| 336 | 新增: } | |
| 337 | 新增: } | |
| 338 | 新增: process.waitUntilExit() | |
| 339 | 新增: let result = last | |
| 340 | 新增: DispatchQueue.main.async { | |
| 341 | 新增: if self.worker === process { self.worker = nil } | |
| 342 | 新增: guard self.generation == operation else { return } | |
| 343 | 新增: if process.terminationStatus != 0 { | |
| 344 | 新增: self.failure(result?["message"] as? String ?? "更新请求未完成,请重试") | |
| 345 | 新增: } else if !checkOnly, let result, result["phase"] as? String == "downloaded" { | |
| 346 | 新增: self.verifyDownload(result, operation: operation) | |
| 347 | 新增: } | |
| 348 | 新增: } | |
| 349 | 新增: } | |
| 350 | 新增: } | |
| 351 | 新增: private func verifyDownload(_ result: [String: Any], operation: Int) { | |
| 352 | 新增: guard let path = result["archivePath"] as? String, let hash = result["sha256"] as? String, | |
| 353 | 新增: let version = result["latestVersion"] as? String, hash.range(of: "^[0-9a-f]{64}$", options: .regularExpression) != nil else { failure("下载进程返回了无效安装包"); return } | |
| 354 | 新增: let archive = URL(fileURLWithPath: path).resolvingSymlinksInPath() | |
| 355 | 新增: guard archive.path.hasPrefix(root.resolvingSymlinksInPath().path + "/download-"), archive.lastPathComponent == "Cage.dmg" else { failure("安装包路径不属于本次私有下载"); return } | |
| 356 | 新增: change(["phase": "verifying", "message": "正在验证 Apple 签名和应用内容", "retryable": false]) | |
| 357 | 新增: let task = CageUpdateValidation() | |
| 358 | 新增: validationTask = task | |
| 359 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 360 | 新增: defer { | |
| 361 | 新增: task.finish() | |
| 362 | 新增: DispatchQueue.main.async { if self.validationTask === task { self.validationTask = nil } } | |
| 363 | 新增: } | |
| 364 | 新增: let directory = self.root.appendingPathComponent("verified-" + UUID().uuidString, isDirectory: true) | |
| 365 | 新增: do { | |
| 366 | 新增: try task.checkCancellation() | |
| 367 | 新增: let team = try CageUpdateFiles.signingInfo(self.bundleURL, bundle: true) | |
| 368 | 新增: try CageUpdateFiles.privateDirectory(directory) | |
| 369 | 新增: let app = try CageUpdateFiles.extract(archive: archive, hash: hash, version: version, team: team, directory: directory, validation: task) | |
| 370 | 新增: try task.checkCancellation() | |
| 371 | 新增: try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) | |
| 372 | 新增: DispatchQueue.main.async { | |
| 373 | 新增: if self.generation != operation { try? FileManager.default.removeItem(at: directory); return } | |
| 374 | 新增: self.prepared = (directory, app, version, team) | |
| 375 | 新增: self.change(["phase": "ready", "message": "更新已下载并验证", "retryable": true]) | |
| 376 | 新增: self.beginInstallation() | |
| 377 | 新增: } | |
| 378 | 新增: } catch { | |
| 379 | 新增: try? FileManager.default.removeItem(at: directory) | |
| 380 | 新增: try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) | |
| 381 | 新增: DispatchQueue.main.async { if self.generation == operation { self.failure(error.localizedDescription) } } | |
| 382 | 新增: } | |
| 383 | 新增: } | |
| 384 | 新增: } | |
| 385 | 新增: private func beginInstallation() { | |
| 386 | 新增: guard let prepared, installer == nil else { return } | |
| 387 | 新增: change(["phase": "installing", "message": "正在准备安装更新", "retryable": false]) | |
| 388 | 新增: let operation = generation | |
| 389 | 新增: let task = CageUpdateValidation() | |
| 390 | 新增: validationTask = task | |
| 391 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 392 | 新增: defer { | |
| 393 | 新增: task.finish() | |
| 394 | 新增: DispatchQueue.main.async { if self.validationTask === task { self.validationTask = nil } } | |
| 395 | 新增: } | |
| 396 | 新增: do { | |
| 397 | 新增: guard !self.bundleURL.path.hasPrefix("/Volumes/"), self.bundleURL.pathExtension == "app" else { throw CageUpdateError("请先将 Cage 安装到应用程序目录,再自动更新") } | |
| 398 | 新增: try CageUpdateFiles.verifyApp(prepared.app, version: prepared.version, team: prepared.team, validation: task) | |
| 399 | 新增: let helper = prepared.directory.appendingPathComponent("CageUpdateInstaller") | |
| 400 | 新增: let originalHelper = self.bundleURL.appendingPathComponent("Contents/Resources/CageUpdateInstaller") | |
| 401 | 新增: try? FileManager.default.removeItem(at: helper) | |
| 402 | 新增: try FileManager.default.copyItem(at: originalHelper, to: helper) | |
| 403 | 新增: _ = try CageUpdateFiles.signingInfo(helper, bundle: false, expectedTeam: prepared.team) | |
| 404 | 新增: let plan = CageUpdatePlan(version: prepared.version, team: prepared.team, target: self.bundleURL.path, candidate: prepared.app.path, | |
| 405 | 新增: backup: prepared.directory.appendingPathComponent("previous.app").path, parentPID: ProcessInfo.processInfo.processIdentifier, resultPath: self.root.appendingPathComponent("last-result.json").path) | |
| 406 | 新增: let planURL = prepared.directory.appendingPathComponent("install.json") | |
| 407 | 新增: try CageUpdateFiles.write(JSONEncoder().encode(plan), to: planURL) | |
| 408 | 新增: try task.checkCancellation() | |
| 409 | 新增: DispatchQueue.main.async { if self.generation == operation { self.launchInstaller(helper: helper, plan: planURL) } } | |
| 410 | 新增: } catch { DispatchQueue.main.async { if self.generation == operation { self.failure(error.localizedDescription) } } } | |
| 411 | 新增: } | |
| 412 | 新增: } | |
| 413 | 新增: private func launchInstaller(helper: URL, plan: URL) { | |
| 414 | 新增: let process = Process(); process.executableURL = helper; process.arguments = [plan.path] | |
| 415 | 新增: let input = Pipe(), output = Pipe(); process.standardInput = input; process.standardOutput = output; process.standardError = FileHandle.nullDevice | |
| 416 | 新增: installer = process; installerInput = input | |
| 417 | 新增: do { try process.run() } catch { installer = nil; installerInput = nil; failure("无法启动安全安装程序"); return } | |
| 418 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 419 | 新增: var data = Data() | |
| 420 | 新增: while data.count < 16384 { | |
| 421 | 新增: let byte = output.fileHandleForReading.readData(ofLength: 1) | |
| 422 | 新增: if byte.isEmpty || byte == Data([10]) { break } | |
| 423 | 新增: data.append(byte) | |
| 424 | 新增: } | |
| 425 | 新增: let response = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] | |
| 426 | 新增: DispatchQueue.main.async { | |
| 427 | 新增: guard self.installer === process, !self.waitingForTermination else { return } | |
| 428 | 新增: if response?["status"] as? String == "ready" { self.prepareEnvironment(stop: false) } | |
| 429 | 新增: else { self.abortInstaller(); self.failure(response?["message"] as? String ?? "安全安装准备失败,原应用已保留") } | |
| 430 | 新增: } | |
| 431 | 新增: } | |
| 432 | 新增: } | |
| 433 | 新增: private func abortInstaller() { | |
| 434 | 新增: try? installerInput?.fileHandleForWriting.close() | |
| 435 | 新增: installerInput = nil | |
| 436 | 新增: if let helper = installer { | |
| 437 | 新增: CageUpdateFiles.stop(helper) | |
| 438 | 新增: DispatchQueue.global(qos: .utility).async { | |
| 439 | 新增: helper.waitUntilExit() | |
| 440 | 新增: DispatchQueue.main.async { if self.installer === helper { self.installer = nil } } | |
| 441 | 新增: } | |
| 442 | 新增: } | |
| 443 | 新增: } | |
| 444 | 新增: private func prepareEnvironment(stop: Bool) { | |
| 445 | 新增: change(["phase": "installing", "message": stop ? "正在停止环境,准备安装" : "正在检查环境是否可安全更新"]) | |
| 446 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 447 | 新增: do { | |
| 448 | 新增: let arguments = ["prepare-update"] + (stop ? ["--stop"] : []) + ["--json"] | |
| 449 | 新增: let process = Process(); process.executableURL = self.cage; process.arguments = arguments | |
| 450 | 新增: let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice | |
| 451 | 新增: try process.run() | |
| 452 | 新增: let expiration = DispatchWorkItem { if process.isRunning { process.terminate() } } | |
| 453 | 新增: DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 180, execute: expiration) | |
| 454 | 新增: let data = output.fileHandleForReading.readDataToEndOfFile(); process.waitUntilExit(); expiration.cancel() | |
| 455 | 新增: guard data.count <= 16384, let result = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw CageUpdateError("无法确认环境已停止") } | |
| 456 | 新增: DispatchQueue.main.async { | |
| 457 | 新增: guard !self.waitingForTermination else { return } | |
| 458 | 新增: switch result["status"] as? String { | |
| 459 | 新增: case "prepared" where process.terminationStatus == 0: | |
| 460 | 新增: guard self.installer?.isRunning == true else { self.failure("安装程序已退出,原应用已保留"); self.reconnect(); return } | |
| 461 | 新增: do { | |
| 462 | 新增: try self.installerInput?.fileHandleForWriting.write(contentsOf: Data("COMMIT\n".utf8)) | |
| 463 | 新增: try self.installerInput?.fileHandleForWriting.close() | |
| 464 | 新增: self.installationCommitted = true | |
| 465 | 新增: self.change(["phase": "installing", "message": "正在安装并重启 Cage"]) | |
| 466 | 新增: self.quit() | |
| 467 | 新增: } catch { self.abortInstaller(); self.failure("无法开始安装,原应用已保留"); self.reconnect() } | |
| 468 | 新增: case "stop_required" where !stop: | |
| 469 | 新增: self.confirmStop { confirmed in | |
| 470 | 新增: if confirmed { self.prepareEnvironment(stop: true) } | |
| 471 | 新增: else { self.abortInstaller(); self.change(["phase": "ready", "message": "更新已下载,保存工作后可继续安装", "retryable": true]) } | |
| 472 | 新增: } | |
| 473 | 新增: default: | |
| 474 | 新增: self.abortInstaller(); self.failure(result["message"] as? String ?? "环境未能安全停止,更新未安装") | |
| 475 | 新增: } | |
| 476 | 新增: } | |
| 477 | 新增: } catch { DispatchQueue.main.async { self.abortInstaller(); self.failure(error.localizedDescription) } } | |
| 478 | 新增: } | |
| 479 | 新增: } | |
| 480 | 新增:} | |
| @@ -0,0 +1,136 @@ | ||
| 1 | 新增:import Cocoa | |
| 2 | 新增: | |
| 3 | 新增:@main | |
| 4 | 新增:enum UpdatesTests { | |
| 5 | 新增: static func expect(_ condition: @autoclosure () -> Bool, _ message: String) throws { | |
| 6 | 新增: if !condition() { throw CageUpdateError("TEST FAILED: " + message) } | |
| 7 | 新增: } | |
| 8 | 新增: static func rejects(_ message: String, _ body: () throws -> Void) throws { | |
| 9 | 新增: var rejected = false | |
| 10 | 新增: do { try body() } catch { rejected = true } | |
| 11 | 新增: try expect(rejected, message) | |
| 12 | 新增: } | |
| 13 | 新增: static func main() throws { | |
| 14 | 新增: try expect(CageUpdateVersion.isNewer("0.2.0-alpha.10", than: "0.2.0-alpha.9"), "numeric prerelease ordering") | |
| 15 | 新增: try expect(CageUpdateVersion.isNewer("0.2.0", than: "0.2.0-alpha.10"), "stable promotion") | |
| 16 | 新增: for invalid in ["0.2.0-alpha.01", "../0.3.0", "1.0", "1.0.0/../../"] { | |
| 17 | 新增: try expect(!CageUpdateVersion.isNewer(invalid, than: "0.1.0"), "invalid version rejected") | |
| 18 | 新增: } | |
| 19 | 新增: try expect(!CageUpdateVersion.isNewer("0.2.0", than: "0.2.0"), "same version rejected") | |
| 20 | 新增: try expect(!CageUpdateVersion.isNewer("0.1.0", than: "0.2.0"), "downgrade rejected") | |
| 21 | 新增: | |
| 22 | 新增: let root = FileManager.default.temporaryDirectory.appendingPathComponent("cage-updates-test-" + UUID().uuidString) | |
| 23 | 新增: try CageUpdateFiles.privateDirectory(root) | |
| 24 | 新增: defer { try? FileManager.default.removeItem(at: root) } | |
| 25 | 新增: let hashFile = root.appendingPathComponent("content") | |
| 26 | 新增: try CageUpdateFiles.write(Data("abc".utf8), to: hashFile) | |
| 27 | 新增: let hash = try CageUpdateFiles.digest(hashFile) | |
| 28 | 新增: try expect(hash == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "stream digest") | |
| 29 | 新增: let permissions = try FileManager.default.attributesOfItem(atPath: hashFile.path) | |
| 30 | 新增: try expect((permissions[.posixPermissions] as? NSNumber)?.intValue == 0o600, "private file mode") | |
| 31 | 新增: let escaped = root.appendingPathComponent("escaped.app") | |
| 32 | 新增: try CageUpdateFiles.privateDirectory(escaped) | |
| 33 | 新增: try FileManager.default.createSymbolicLink(at: escaped.appendingPathComponent("outside"), withDestinationURL: hashFile) | |
| 34 | 新增: try rejects("app symlink escape") { try CageUpdateFiles.validateTree(escaped) } | |
| 35 | 新增: | |
| 36 | 新增: let old = root.appendingPathComponent("Cage.app"), next = root.appendingPathComponent("next.app"), backup = root.appendingPathComponent("backup.app") | |
| 37 | 新增: for location in [old, next, backup] { try CageUpdateFiles.privateDirectory(location) } | |
| 38 | 新增: try Data("old".utf8).write(to: old.appendingPathComponent("marker")) | |
| 39 | 新增: try Data("old".utf8).write(to: backup.appendingPathComponent("marker")) | |
| 40 | 新增: try Data("new".utf8).write(to: next.appendingPathComponent("marker")) | |
| 41 | 新增: try CageUpdateFiles.replaceAndVerify(target: old, candidate: next, backup: backup, manager: .default) { | |
| 42 | 新增: let marker = try String(contentsOf: $0.appendingPathComponent("marker"), encoding: .utf8) | |
| 43 | 新增: try expect(marker == "new", "new content reaches final install path") | |
| 44 | 新增: } | |
| 45 | 新增: try CageUpdateFiles.restore(backup: backup, target: old, manager: .default) | |
| 46 | 新增: let restored = try String(contentsOf: old.appendingPathComponent("marker"), encoding: .utf8) | |
| 47 | 新增: try expect(restored == "old", "launch failure can restore original") | |
| 48 | 新增: try CageUpdateFiles.privateDirectory(next) | |
| 49 | 新增: try Data("invalid".utf8).write(to: next.appendingPathComponent("marker")) | |
| 50 | 新增: try rejects("post-install validation must roll back") { | |
| 51 | 新增: try CageUpdateFiles.replaceAndVerify(target: old, candidate: next, backup: backup, manager: .default) { _ in throw CageUpdateError("verification failed") } | |
| 52 | 新增: } | |
| 53 | 新增: let rollback = try String(contentsOf: old.appendingPathComponent("marker"), encoding: .utf8) | |
| 54 | 新增: try expect(rollback == "old", "failed validation leaves original installed") | |
| 55 | 新增: try CageUpdateFiles.privateDirectory(next) | |
| 56 | 新增: try Data("invalid-after-replace".utf8).write(to: next.appendingPathComponent("marker")) | |
| 57 | 新增: var replaced = false | |
| 58 | 新增: try rejects("post-install and rollback failure must remain a changed transaction") { | |
| 59 | 新增: try CageUpdateFiles.replaceAndVerify(target: old, candidate: next, backup: backup, manager: .default, | |
| 60 | 新增: onReplace: { replaced = true }, restoreOriginal: { throw CageUpdateError("injected restore I/O failure") }) { _ in | |
| 61 | 新增: throw CageUpdateError("injected validation failure") | |
| 62 | 新增: } | |
| 63 | 新增: } | |
| 64 | 新增: try expect(replaced, "replacement must be recorded before validation or rollback can fail") | |
| 65 | 新增: let failedTarget = try String(contentsOf: old.appendingPathComponent("marker"), encoding: .utf8) | |
| 66 | 新增: let retainedBackup = try String(contentsOf: backup.appendingPathComponent("marker"), encoding: .utf8) | |
| 67 | 新增: try expect(failedTarget == "invalid-after-replace" && retainedBackup == "old", "double failure must retain the original backup and report the changed target") | |
| 68 | 新增: try CageUpdateFiles.restore(backup: backup, target: old, manager: .default) | |
| 69 | 新增: try rejects("unsigned application refused") { _ = try CageUpdateFiles.signingInfo(old, bundle: true) } | |
| 70 | 新增: | |
| 71 | 新增: // A real child that ignores SIGTERM must not keep cancellation pending. | |
| 72 | 新增: let running = root.appendingPathComponent("validation-running") | |
| 73 | 新增: let task = CageUpdateValidation() | |
| 74 | 新增: DispatchQueue.global().async { | |
| 75 | 新增: defer { task.finish() } | |
| 76 | 新增: _ = try? CageUpdateFiles.run("/bin/sh", ["-c", "trap '' TERM; touch \"$1\"; exec /bin/sleep 30", "validation", running.path], validation: task) | |
| 77 | 新增: } | |
| 78 | 新增: let startedDeadline = Date().addingTimeInterval(5) | |
| 79 | 新增: while !FileManager.default.fileExists(atPath: running.path) && Date() < startedDeadline { Thread.sleep(forTimeInterval: 0.01) } | |
| 80 | 新增: try expect(FileManager.default.fileExists(atPath: running.path), "real validation child started") | |
| 81 | 新增: let cancelledAt = Date() | |
| 82 | 新增: task.cancel(); task.wait() | |
| 83 | 新增: try expect(Date().timeIntervalSince(cancelledAt) < 5, "unresponsive verification process is killed and joined") | |
| 84 | 新增: | |
| 85 | 新增: // Mount only this test's own tiny image. Cancellation inside the real | |
| 86 | 新增: // mount scope must still execute hdiutil detach before completion. | |
| 87 | 新增: let contents = root.appendingPathComponent("image-source") | |
| 88 | 新增: try CageUpdateFiles.privateDirectory(contents) | |
| 89 | 新增: try Data("fixture".utf8).write(to: contents.appendingPathComponent("marker")) | |
| 90 | 新增: let archive = root.appendingPathComponent("fixture.dmg") | |
| 91 | 新增: _ = try CageUpdateFiles.run("/usr/bin/hdiutil", ["create", "-size", "20m", "-fs", "HFS+", "-volname", "CageUpdateQA", "-srcfolder", contents.path, archive.path]) | |
| 92 | 新增: let mountTask = CageUpdateValidation() | |
| 93 | 新增: try rejects("cancelled mounted verification") { | |
| 94 | 新增: try CageUpdateFiles.withMountedImage(archive: archive, directory: root.appendingPathComponent("verification"), validation: mountTask) { mount in | |
| 95 | 新增: try expect(FileManager.default.fileExists(atPath: mount.appendingPathComponent("marker").path), "test image mounted") | |
| 96 | 新增: mountTask.cancel() | |
| 97 | 新增: try mountTask.checkCancellation() | |
| 98 | 新增: } | |
| 99 | 新增: } | |
| 100 | 新增: mountTask.finish(); mountTask.wait() | |
| 101 | 新增: let mounts = try CageUpdateFiles.run("/usr/bin/hdiutil", ["info", "-plist"]) | |
| 102 | 新增: let info = try PropertyListSerialization.propertyList(from: mounts, format: nil) as? [String: Any] | |
| 103 | 新增: let images = info?["images"] as? [[String: Any]] ?? [] | |
| 104 | 新增: try expect(!images.contains(where: { $0["image-path"] as? String == archive.path }), "cancellation detached its own image") | |
| 105 | 新增: | |
| 106 | 新增: // A just-installed instance can be rolled back natively until the | |
| 107 | 新增: // trusted workbench explicitly confirms its API initialization. | |
| 108 | 新增: let savedEnvironment = ProcessInfo.processInfo.environment | |
| 109 | 新增: let confirmation = UUID().uuidString | |
| 110 | 新增: setenv("CAGE_UPDATE_CONFIRMATION", confirmation, 1) | |
| 111 | 新增: setenv("CLAUDE_CAGE_CONFIG", root.appendingPathComponent("profile/config.json").path, 1) | |
| 112 | 新增: defer { | |
| 113 | 新增: for key in ["CAGE_UPDATE_CONFIRMATION", "CLAUDE_CAGE_CONFIG"] { | |
| 114 | 新增: if let value = savedEnvironment[key] { setenv(key, value, 1) } else { unsetenv(key) } | |
| 115 | 新增: } | |
| 116 | 新增: } | |
| 117 | 新增: let updater = CageAppUpdater(bundleURL: old, onChange: { _ in }, confirmStop: { $0(false) }, quit: {}, reconnect: {}) | |
| 118 | 新增: try expect(updater.awaitingInitialWorkbench, "newly installed uninitialized window permits native rollback termination") | |
| 119 | 新增: updater.markLaunchReady() | |
| 120 | 新增: try expect(!updater.awaitingInitialWorkbench, "initialized workbench keeps ordinary quit confirmation") | |
| 121 | 新增: try expect(FileManager.default.fileExists(atPath: root.appendingPathComponent("profile/updates/launch-\(confirmation).json").path), "explicit workbench readiness writes installer acknowledgement") | |
| 122 | 新增: | |
| 123 | 新增: if CommandLine.arguments.count == 2 { | |
| 124 | 新增: let signed = URL(fileURLWithPath: CommandLine.arguments[1]) | |
| 125 | 新增: let team = try CageUpdateFiles.signingInfo(signed, bundle: true) | |
| 126 | 新增: try rejects("different publisher refused") { _ = try CageUpdateFiles.signingInfo(signed, bundle: true, expectedTeam: "AAAAAAAAAA") } | |
| 127 | 新增: let tampered = root.appendingPathComponent("tampered.app") | |
| 128 | 新增: try FileManager.default.copyItem(at: signed, to: tampered) | |
| 129 | 新增: let plist = tampered.appendingPathComponent("Contents/Info.plist") | |
| 130 | 新增: try Data("tampered".utf8).write(to: plist) | |
| 131 | 新增: try rejects("real signature tampering refused") { _ = try CageUpdateFiles.signingInfo(tampered, bundle: true, expectedTeam: team) } | |
| 132 | 新增: print("PASS: real Developer ID signature, wrong publisher, and tampered App checks") | |
| 133 | 新增: } | |
| 134 | 新增: print("PASS: versions, private files, containment, replacement/double-failure rollback, process cancellation, and temporary image cleanup") | |
| 135 | 新增: } | |
| 136 | 新增:} | |
| @@ -1,6 +1,8 @@ | ||
| 1 | 删除:# Backlog | |
| 1 | 新增:# Upstream agent-vm backlog | |
| 2 | 2 | |
| 3 | 删除:Known gaps and ideas, not on the website. | |
| 3 | 新增:This file retains upstream ideas and their original status. It is historical reference, not the Cage roadmap or a statement of current platform support. Cage desktop targets Apple Silicon macOS; current usage and development entry points are in the [Cage documentation index](README.md). | |
| 4 | 新增: | |
| 5 | 新增:Known upstream gaps and ideas follow. | |
| 4 | 6 | |
| 5 | 7 | ## Windows, natively |
| 6 | 8 | |
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | | 安装、配置代理、打开第一个项目 | [开始使用](getting-started.md) | |
| 10 | 10 | | 查看快捷键、文件保存、关闭与退出行为 | [日常使用](getting-started.md#日常使用) | |
| 11 | 11 | | 升级应用、更新环境工具或卸载 | [升级与卸载](getting-started.md#升级与卸载) | |
| 12 | 新增:| 查看首个内测版本的能力与验收范围 | [0.1.0-alpha.1 发行说明](releases/0.1.0-alpha.1.md) | | |
| 12 | 13 | | 排查下载、启动、联网与授权问题 | [常见问题与恢复](troubleshooting.md) | |
| 13 | 14 | | 报告隔离或凭据安全问题 | [安全报告](../SECURITY.md) | |
| 14 | 15 | |
| @@ -20,6 +20,8 @@ | ||
| 20 | 20 | |
| 21 | 21 | 订阅支持含 `proxies` 或 `payload` 的 Clash/Mihomo YAML,也接受含内联节点的完整配置。只含远程 provider 的配置、Base64 列表和各类分享链接暂不支持,需提供节点订阅地址或先导出 YAML。支持 HTTP、SOCKS5、SS、SSR、VMess、VLESS、Trojan、Hysteria、Hysteria2、TUIC、AnyTLS;具体字段仍须由固定版本核心校验。代理链必须引用同一来源内的具体节点,选择分组和 DIRECT 链路会被拒绝。 |
| 22 | 22 | |
| 23 | 新增:每份导入内容最多 8 MiB,全部来源保存后的 JSON 总量最多 32 MiB。累计超限时拒绝保存并保留原文件,用户仍可查看或删除已有来源。 | |
| 24 | 新增: | |
| 23 | 25 | 默认手动选择固定节点,与现有出口 IP 变化规则协作。自动测速可以提供建议;自动切换和负载均衡涉及出口变化,需单独设计准入流程,首版不静默启用。 |
| 24 | 26 | |
| 25 | 27 | ## 流量与模块职责 |
| @@ -70,6 +72,8 @@ Cage 业务 DNS 继续通过选定节点发送,不回退主机解析器。订 | ||
| 70 | 72 | |
| 71 | 73 | 节点和订阅更新由同一控制服务串行应用,避免并发更新覆盖用户刚选的节点。应用前保存可恢复配置并验证候选内容;失败保留原版本。 |
| 72 | 74 | |
| 75 | 新增:自动订阅更新和物理网卡恢复会保留用户手动暂停外网的状态。人工代理操作可以按现有流程重新检查并恢复联网;如果用户在下载订阅或应用核心期间再次暂停,较新的暂停优先,操作完成后仍保持离线。 | |
| 76 | 新增: | |
| 73 | 77 | 生效切换先关闭现有联网授权并断开旧业务连接,再应用新节点、检查核心实际选择,最后重新执行准入。代理配置的 `proxy_revision` 随切换和核心重启更新,纳入配置指纹。VM 外门槛只允许在其余配置相同的条件下更新该版本,同时撤销旧报告和连接;地址、DNS、语言等变化仍需重启 VM。界面分别显示尚未配置、尚未应用、代理已停止、待启动环境、正在检查和外网未放行;只有当前节点已应用、核心读回匹配且 VM 放行仍有效时才显示已联网。 |
| 74 | 78 | |
| 75 | 79 | 手动切换不能悄悄改写已绑定的静态 IP 或地区基准。新节点不符合用户保存的出口规则时保持离线,引导用户另选节点或明确修改规则。 |
| @@ -42,7 +42,7 @@ VM 外出站控制由 hostagent 持有。新实例默认关闭外网,guest 内 | ||
| 42 | 42 | - 运行时策略检查确认当前加载的地址族、协议和私网访问规则。 |
| 43 | 43 | - 客机探针尝试访问公网及宿主管理端口,并与 VM 外网络层的拒绝记录核对。UDP 超时本身不作为通过依据。 |
| 44 | 44 | - 共享文件使用临时文件完成双向往返;宿主私有目录使用无敏感内容的探针验证不可读,同时检查挂载范围。 |
| 45 | 删除:- 浏览器通过隐藏、临时的诊断页面读回 Chromium 的时区、语言和平台,避免读取账号页面或改变可见标签的焦点。 | |
| 45 | 新增:- 浏览器通过隐藏、临时的诊断页面读回 Chromium 的时区、语言和平台,避免读取账号页面或改变可见标签的焦点。检测完成或失败后,先等待隐藏页面关闭,再销毁其临时浏览环境;页面关闭失败时保留该环境并从用户标签中排除,避免销毁仍被引用的环境导致整个浏览器崩溃。 | |
| 46 | 46 | - 故障演练只在检测专用连接中注入代理不可用,验证终端、浏览器和 DNS 的失败路径,不停止用户的代理进程。 |
| 47 | 47 | |
| 48 | 48 | 这些证据支持列明的采样和策略结论,不能代替完整虚拟化逃逸审计,也不能判定账号资格或预测封禁。 |
| @@ -55,6 +55,8 @@ VM 外出站控制由 hostagent 持有。新实例默认关闭外网,guest 内 | ||
| 55 | 55 | |
| 56 | 56 | 暂停不进入普通任务队列,会立即取消检查和后台监测,再关闭出站。放行和续期与暂停串行核对,已撤销的检查不能重新放行。停止环境可取消正在启动或检查的任务;被取消任务的完成消息不会覆盖停止结果。工作台为启动任务记录私有停止标记,分离运行的 hostagent 在初始化前及运行中读取该标记,避免取消后的后台启动继续拉起 VM。标记绑定单个任务,不影响下一次启动。 |
| 57 | 57 | |
| 58 | 新增:人工暂停意图和暂停序号保存在私有 `network-intent.json`,控制服务启动监测前恢复;后台重启、订阅定期刷新和网卡恢复不会解除暂停。记录缺失时无法判断旧配置的暂停意图,因此默认关闭,等待用户明确恢复;损坏或无法读取时同样保持关闭并提示原因。启动、重检、恢复或应用环境配置,以及手动应用代理配置,可请求恢复;恢复必须先成功保存,且不能覆盖请求提交之后发生的暂停。暂停保存失败仍会撤销当前放行并报错,恢复保存失败也保持关闭。 | |
| 59 | 新增: | |
| 58 | 60 | ## 外部服务与隐私 |
| 59 | 61 | |
| 60 | 62 | 固定出口查询使用 [ipify 的公开接口](https://www.ipify.org/)。地区信息查询使用 [ipwho.is 的指定 IP 查询接口](https://ipwhois.io/documentation),查询地址与实际测到的出口绑定。同一 IP 的位置缓存一小时,最多保存 64 条,以减少查询和配额占用;该服务公开的免费额度为每出口每天 1,000 次,超限或不可用时不能把缺失定位判为处于允许范围。 |
| @@ -35,9 +35,15 @@ VM 身份固定保存在主机私有的 `environment.json`;最后打开的项 | ||
| 35 | 35 | |
| 36 | 36 | 标签支持重命名、置顶、拖动排序和关闭。浏览器标签通过右键或 Shift+F10 打开操作菜单,终端通过行末菜单管理。重命名只改变显示名称;置顶标签排列在各自列表前方,拖动调整同一列表内部的顺序。名称、置顶与顺序保存在本地。⌘1–9 与 ⌘⇧[ / ] 按当前列表的显示顺序切换:浏览器中切换顶部网页,终端中切换同目录的终端。关闭当前网页后激活相邻浏览器页。刷新后重新连接仍存活的终端与浏览器,已结束的进程不因标签恢复而重新启动。 |
| 37 | 37 | |
| 38 | 新增:浏览器标签栏与新建按钮垂直居中,标签总宽度随内容区调整,不显示横向滚动条。空间充足时标签最大宽度为 220px;拥挤时当前标签优先保留标题空间,其他标签平分剩余宽度。极窄标签保留可点击位置和悬停标题,右侧搜索入口可按名称或网址查找所有页面。指针拖动时标签跟随移动,相邻标签实时让位;松手保存顺序,Esc 或指针取消恢复原顺序。置顶和普通标签分别在各自分组内排序。 | |
| 39 | 新增: | |
| 40 | 新增:地址栏右侧星标与 ⌘D 打开当前网页的收藏编辑框,收藏夹按钮与 ⌘⇧O 打开收藏面板。收藏支持名称、HTTP(S) 地址、单层收藏夹分组、搜索、移动和删除;删除收藏夹将其中的收藏移至未分类。打开收藏通过现有浏览器新建页接口进入 VM,不在主机执行收藏网址。文件编辑器与内部浏览器页面不提供收藏。 | |
| 41 | 新增: | |
| 42 | 新增:收藏由主机控制服务保存在当前配置目录的私有 `favorites.json`,权限为 `0600`;所有项目共用,应用和控制服务重启后保留,不与 Chromium 或外部浏览器同步。`GET /api/favorites` 返回 `items` 与 `folders`;`POST /api/favorites` 通过 `save`、`delete`、`save_folder`、`delete_folder` 操作单条记录,沿用工作台认证与来源校验。修改在专用互斥锁下读取最新文件并原子写入,避免并发新增覆盖其他窗口的收藏。保存失败保留编辑输入,读取失败不覆盖原文件。收藏操作不更改 VM、网络或共享目录状态。 | |
| 43 | 新增: | |
| 38 | 44 | ## 设置页 |
| 39 | 45 | |
| 40 | 删除:设置占据完整窗口,左侧分类为通用、外观、网络与代理、IP 变化规则、时区与语言、环境与恢复;右侧显示表单,底部固定保存区。离开未保存的表单需要确认,保存失败保留输入。返回工作台保持选中的标签与终端、浏览器连接。 | |
| 46 | 新增:设置占据完整窗口,左侧分类为通用、外观、网络与代理、IP 变化规则、时区与语言、环境与恢复;右侧显示表单,底部固定保存区。离开未保存的表单需要确认,保存失败保留输入。返回工作台保留选中的标签与终端,并恢复可见浏览器画面的连接。 | |
| 41 | 47 | |
| 42 | 48 | 通用页提供浏览器默认网站,缺省为 `https://www.bing.com/`。该偏好保存在 `workbench.json` 的 `browser_home_url`,只接受不含认证信息的 HTTP(S) 网址;保存同步至客机浏览器,无需重启 VM 或终端。工作台新建网页、浏览器最后一页关闭后的补充页使用这个地址;连接时将恢复的空白页和 Chromium 内置新标签页转到该地址,已有普通网页继续保留。 |
| 43 | 49 | |
| @@ -51,18 +57,22 @@ VM 身份固定保存在主机私有的 `environment.json`;最后打开的项 | ||
| 51 | 57 | |
| 52 | 58 | 外观由控制服务独立保存至 appearance.json,前端自动提交,修改失败保留输入并允许重试。读取、保存和本机 Codex 导入分别通过 GET /api/appearance、POST /api/appearance、GET /api/appearance/codex 完成,沿用工作台认证。外观操作不走环境配置应用流程,不重启 VM 或终端;本机导入只复制当前偏好,不创建持续文件监听。 |
| 53 | 59 | |
| 54 | 删除:按钮按下即时反馈,项目列表在 180ms 内展开,设置页在 160ms 内进入;减少动态效果模式下直接显示最终状态。终端与远程画面在切换设置或返回工作台时保持挂载,避免重建连接。 | |
| 60 | 新增:按钮按下即时反馈,项目列表在 180ms 内展开,设置页在 160ms 内进入;减少动态效果模式下直接显示最终状态。工作台终端保持连接。浏览器画面不可见时关闭显示连接,重新可见时重连;浏览器进程、页面、下载和登录状态继续保留。原生窗口隐藏、最小化或关闭也会暂停显示连接,单纯失去键盘焦点不触发暂停。 | |
| 55 | 61 | |
| 56 | 62 | 主要验证视口为 1280×850 与原生最小窗口的内容区 820×558。更窄页面可收起侧栏;设置表单独立滚动,保存操作持续可见。环境连接正常且外网放行仍有效时,品牌区、工作台和状态栏显示绿色带对钩盾牌,并提供状态文字。连接中断、检查中、网络关闭或放行过期时撤销绿色标记;VM 运行但浏览器连接未就绪时显示恢复入口。 |
| 57 | 63 | |
| 58 | 64 | 界面保留实际网络状态、项目路径和失败原因,日志与详细检查按需打开。 |
| 59 | 65 | |
| 66 | 新增:底部状态栏显示当前代理节点到 `www.gstatic.com/generate_204` 的 HTTP 延迟,单位为毫秒。环境运行且没有配置任务时立即检测,之后每 30 秒更新;点击延迟可重新检测。节点或配置版本变化后丢弃旧读数,停止或控制连接中断时显示“延迟 —”,检测失败显示“延迟不可用”。测速沿用内置核心的节点检测接口,不启动代理、不改变节点和外网放行状态;延迟成功不代表环境已获准联网。 | |
| 67 | 新增: | |
| 60 | 68 | ## 模块职责 |
| 61 | 69 | |
| 62 | 70 | 主机控制服务管理配置、VM 生命周期、会话与只通向该配置唯一 VM 的连接。前端只调用这个服务。终端在 VM 的 SSH 会话中执行;浏览器控制器和 Chromium 在 VM 内运行。编辑器页面也通过 VM 浏览器呈现,避免将来自 guest 的任意网页脚本作为主机控制页面加载。 |
| 63 | 71 | |
| 64 | 72 | 应用窗口是本机工作台的容器,不是执行外部网站的主机浏览器。外部地址统一交给 VM 浏览器;所有网页与编码进程的网络仍由现有 VM 外代理出口接管。 |
| 65 | 73 | |
| 74 | 新增:Chromium 通过继承的私有调试管道接受标签与导航命令,不开放 CDP 端口。网页由用户手工操作,启动时关闭 Blink 的 `AutomationControlled` 标记,避免仅因工作台控制管道而向网页报告自动化模式。浏览器服务停止时,先由控制器通知 Chromium 保存标签和配置后退出,再清理剩余子进程。此设置保留浏览器控制与登录态,不保证第三方网站的人机验证一定通过。 | |
| 75 | 新增: | |
| 66 | 76 | ## 验收重点 |
| 67 | 77 | |
| 68 | 78 | 1. 从应用启动到可操作,无需查终端找端口或复制访问密码。 |
| @@ -81,3 +91,31 @@ VM 身份固定保存在主机私有的 `environment.json`;最后打开的项 | ||
| 81 | 91 | 自动时区查询通过已选代理完成。应用配置前验证,随后停止环境、保存前一份配置并重启;探测失败保留原配置。运行中不会因定期位置探测自动重启。用户选择恢复配置时,同样明确提示终端中断,并启动恢复后的环境。按键偏好单独保存,不重启环境。 |
| 82 | 92 | |
| 83 | 93 | 共享下载先存入 guest 私有目录,完成后以编码用户权限统一写入 Cage 环境默认工作区的 Downloads。同名文件不覆盖,路径与符号链接受到检查。终端通过专用 SSH 连接进入 guest,禁用本机转义、本机命令、代理转发及宿主环境继承。工作台刷新可以连接仍在运行的会话;控制服务或 VM 重启后的旧终端不能复原。 |
| 94 | 新增: | |
| 95 | 新增:下载列表区分下载中、保存中、已保存、失败和已取消。只有完整文件在共享目录中发布后才显示已保存;写入失败保留客机源文件,可在修复空间或共享连接后重试。状态原子保存在浏览器私有目录,控制器恢复后只对已完整下载且源文件仍在的项目提供保存重试;下载被中断时需要从原网页重新下载。列表保留最近 50 条结束记录,最多同时处理 50 个未结束下载,保存过程串行执行。成功保存后清理对应客机源文件;清理失败显示提示,已保存文件保持可用。 | |
| 96 | 新增: | |
| 97 | 新增:编辑器由独立系统服务监督,进程异常退出时自动重新启动。工作台的编辑器恢复操作只重启该服务并重新加载项目页面,保留 VM、浏览器和工作台终端。迁移旧版编辑器时,先核对用户、安装目录、Cage 私有配置和监听参数;无法确认身份的进程不自动停止。 | |
| 98 | 新增: | |
| 99 | 新增:## 更新与后台接管 | |
| 100 | 新增: | |
| 101 | 新增:左下角更新入口在发现新版时显示向下箭头,悬浮提示“下载更新”。点击后通过所选受管代理下载 Release 安装包并核验摘要、应用身份、同一 Developer ID Team 签名和 Apple 验证结果,随后安装并重启;代理失败无直连回退。有运行环境时,原生确认框要求用户先保存并停止。安装或新工作台启动失败时尝试恢复旧 App,无法恢复时保留备份和失败信息。ad-hoc 构建不进入自动安装流程。 | |
| 102 | 新增: | |
| 103 | 新增:更新源为公开 GitHub Releases 接口,不需要 GitHub 凭据,也不读取浏览器登录会话。访问失败时显示原因;草稿、附件缺失或非公开发行物不能作为可用更新。首次安装使用公开 DMG,后续版本由应用内更新器检查和下载。 | |
| 104 | 新增: | |
| 105 | 新增:应用启动通过私有启动密钥核对正在运行的控制服务。身份包含完整版本、当前可执行文件的 SHA-256 和控制协议号;文件摘要在进程启动时固定,同版本号的不同构建也能区分。相同构建复用后台;不同构建只有在没有运行环境、作业和存活终端时才自动接管。接管期间拒绝新任务,停止独立代理并优雅退出控制服务,然后由新程序取得同一配置的控制锁。 | |
| 106 | 新增: | |
| 107 | 新增:已有工作时,原生窗口显示“更新待完成”,可明确打开现有环境保存文件,也可在保存后选择停止环境并完成更新。连接旧后台时,窗口标题和关于窗口持续标明更新未完成,不能只用新 App 的版本号代表全部运行组件。 | |
| 108 | 新增: | |
| 109 | 新增:不支持版本握手的旧控制服务需要一次明确的停止与迁移操作。启动器使用认证会话提交停止,确认同一任务成功、环境停止和终端关闭,再核对进程所属用户、可执行文件、完整启动参数、工作目录、监听端口和启动时间后发送退出信号。身份变化、停止失败或退出超时都会中止更新,不发送强制杀死信号。此兼容操作仅支持 macOS,普通启动不会执行。 | |
| 110 | 新增: | |
| 111 | 新增:安装器共用 `cage prepare-update --json`:空闲后台退出后返回 `prepared`,仍需保存停止时返回 `stop_required`;用户确认后调用 `prepare-update --stop --json` 完成停止与退出。失败以非零退出码和 `error` 状态返回。该入口不启动新后台;安装器替换应用并重新打开后,由常规启动入口接管。 | |
| 112 | 新增: | |
| 113 | 新增:## 持久环境的组件与工具版本 | |
| 114 | 新增: | |
| 115 | 新增:应用与 Linux 磁盘分别升级。Cage 的浏览器控制器、显示服务、编辑器服务和下载辅助程序以嵌入资源的统一摘要标识;只有完整启动脚本成功后,才向客机写入 root 所有的组件清单。工作台连接时读取该清单,缺失、协议不兼容或摘要不符都会显示需要更新,不能仅因健康检查成功就把旧组件标为就绪。 | |
| 116 | 新增: | |
| 117 | 新增:“更新环境组件”在现有 VM 中重新应用幂等脚本,重启浏览器与编辑器相关服务,保留磁盘、项目、账户和工作台独立终端。操作前需要保存浏览器和编辑器中的修改;编辑器内的集成终端可能结束。脚本失败时清单保持无效,用户可查看任务结果并重试。已有运行依赖完整时,组件更新可在暂停外网时执行;用户的暂停状态继续保留。 | |
| 118 | 新增: | |
| 119 | 新增:“更新环境工具”是单独的显式操作,需要组件已经同步且外网处于有效放行状态。Chromium 使用 Debian 软件源的更新,code-server、mise 和 Claude 使用随 App 固定的最低版本;当前版本更高时保留现有版本。初次安装与后续升级共用固定安装器,下载包核验摘要后才安装。工具更新不重建磁盘,完成后重新启动相关服务并核对组件状态。更新期间继续运行原有网络检查与短期续租;人工暂停、停止或配置变化仍会阻止联网。 | |
| 120 | 新增: | |
| 121 | 新增:`GET /api/environment/versions` 只在用户查看环境设置时读取工具版本,不加入周期状态查询。返回控制服务实际构建、组件的 `current` / `required`、后端判定的 `update_required`、工具实际与最低版本,以及 `tools_update_allowed`。组件与工具更新分别通过 `POST /api/environment/update`、`POST /api/environment/tools` 提交到现有作业队列。应用原生版本来自 App 的版本信息,不能用旧控制服务的版本代替。 | |
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | |
| 15 | 15 | ## 1. 安装应用 |
| 16 | 16 | |
| 17 | 删除:从 [GitHub Releases](https://github.com/Lee-xeo/Claude-Cage/releases) 的发布条目下载 Apple Silicon `.dmg`。仓库处于私有测试阶段时,需要使用获授权的 GitHub 账户登录才能查看。 | |
| 17 | 新增:从[项目主页](https://lee-xeo.github.io/Claude-Cage/)或 [GitHub Releases](https://github.com/Lee-xeo/Claude-Cage/releases) 的公开发布条目下载 Apple Silicon `.dmg`,无需获得仓库访问授权。 | |
| 18 | 18 | |
| 19 | 19 | 打开 `.dmg`,将 Cage 拖入 Applications(应用程序),然后从“应用程序”打开 Cage。无需先安装开发工具或 Clash。签名、公证和平台验证情况以该安装包的 Release 说明为准。如果系统拒绝打开,先按[安装问题](troubleshooting.md#下载或安装受阻)核对版本与来源。 |
| 20 | 20 | |
| @@ -74,6 +74,10 @@ claude | ||
| 74 | 74 | |
| 75 | 75 | 浏览器独立于项目,网页和文件编辑器使用顶部标签页;切换项目不会关闭或迁移网页。终端通过行末菜单管理,浏览器标签可通过右键或 Shift+F10 打开菜单,支持重命名、置顶和关闭。拖动可调整同一列表内的顺序,刷新后保留。⌘1–9 切换当前浏览器的页面或当前目录的终端。 |
| 76 | 76 | |
| 77 | 新增:标签较多时会自动缩短,当前页面的标签保留更多标题空间。拖动时其他标签即时让位,松手保存顺序,Esc 取消;置顶标签在置顶分组内排序。右侧向下箭头可以搜索已打开的页面。 | |
| 78 | 新增: | |
| 79 | 新增:点击地址栏右侧的星标或按 ⌘D 收藏当前网页,可修改名称并选择或新建收藏夹。点击旁边的收藏夹按钮或按 ⌘⇧O,可搜索、打开和编辑收藏;编辑时可移动到其他收藏夹。删除收藏夹会把其中的网页移至“未分类”。收藏保存在本机当前 Cage 配置中,所有项目共用,重启后保留。 | |
| 80 | 新增: | |
| 77 | 81 | 浏览器下载统一写入 Cage 默认工作区的 `Downloads`,同名文件自动换名。新配置的默认工作区通常为 `~/.claude-cage-workspace/`;迁移配置可能保留已有位置。可以在默认工作区的文件编辑器中查看,不需要到代理私有目录查找下载文件。 |
| 78 | 82 | |
| 79 | 83 | ### 关闭、退出与再次打开 |
| @@ -88,6 +92,8 @@ claude | ||
| 88 | 92 | |
| 89 | 93 | 停止前先保存编辑器中的修改。再次打开 Cage 会使用同一环境,无需重新导入项目或重新创建虚拟磁盘。 |
| 90 | 94 | |
| 95 | 新增:切到终端、设置页,或隐藏、最小化窗口时,Cage 暂停浏览器画面的显示连接,保留浏览器页面、下载和后台任务。画面重新可见时自动连接;这项节省显示资源的行为不等于暂停浏览器或停止环境。 | |
| 96 | 新增: | |
| 91 | 97 | ### 按键与剪贴板 |
| 92 | 98 | |
| 93 | 99 | “设置 → 通用”可以选择按键习惯。Mac 模式将网页和编辑器的 `⌘F`、`⌘Z`、`⌘⇧Z` 等映射为 Linux 对应的 Ctrl 组合;本机地址栏与设置输入框保留 Mac 操作。终端的 `Ctrl+C` 中断命令,`⌘C` 复制选中文本。 |
| @@ -112,6 +118,8 @@ claude | ||
| 112 | 118 | |
| 113 | 119 | 点击底部网络状态可查看证据、重检或暂停外网。暂停会切断已有外部连接,终端和文件仍可离线使用。第三方 IP 信誉仅作提示,不单独决定联网;社区检查网站需要用户主动打开。 |
| 114 | 120 | |
| 121 | 新增:人工暂停会保存,关闭并重开后台后仍保持暂停,定期订阅刷新也不会自动恢复。旧配置没有暂停记录,或记录损坏时,Cage 默认保持外网关闭;确认后可通过启动环境、重新检测或手动应用网络配置恢复。若提示无法保存状态,当前外网仍会关闭,请解决配置写入问题后重试。 | |
| 122 | 新增: | |
| 115 | 123 | 后台约每 30 秒核对出口与环境配置,发现不符合规则时暂停外网。网络放行每次最多 90 秒,控制服务失联后到期关闭;完整报告最多有效 24 小时,过期需要重检。HTTP/SOCKS5 代理可能按连接分配不同出口,抽样检查不能证明每条连接使用相同 IP;固定出口仍需代理服务自身保证。 |
| 116 | 124 | |
| 117 | 125 | ## 网络与数据边界 |
| @@ -128,7 +136,15 @@ Cage 使用轻量 Linux 虚拟机,没有完整桌面。浏览器与编辑器 | ||
| 128 | 136 | |
| 129 | 137 | ## 升级与卸载 |
| 130 | 138 | |
| 131 | 删除:升级前保存文件,选择“停止环境并退出”,再用新安装包替换 Applications 中的 Cage。应用与用户数据分开存放,替换 App 会保留已有配置和虚拟磁盘;Alpha 版本之间的兼容性与特殊迁移步骤以 Release 说明为准。 | |
| 139 | 新增:首次安装请下载公开 Release 的 DMG。应用内更新用于后续版本升级。 | |
| 140 | 新增: | |
| 141 | 新增:应用内更新入口在左下角。有新版时,向下箭头悬浮显示“下载更新”;点击后自动下载、校验、安装并重启。有环境或任务运行时,下载校验完成后会弹出原生确认框,请保存文件再确认停止;暂不安装可保留下载结果,稍后继续。应用更新会结束工作台终端,保留项目、配置、虚拟磁盘和登录状态。安装或启动失败时会尝试恢复旧应用,并显示失败原因。 | |
| 142 | 新增: | |
| 143 | 新增:检查和下载使用已经应用并运行的所选代理,失败不会改用主机直连。自动安装要求当前 App 与新 App 使用相同发布者的 Developer ID 签名,且新包通过 Apple 验证;ad-hoc 开发构建不能自动安装。更新器使用公开的 GitHub Releases 接口,无需 GitHub 登录,也不读取浏览器会话。若提示更新源不可访问,先确认所选代理可用,再检查对应 Release 是否仍公开且附件完整;需要手动下载时使用同一公开 Release。实际安装、重启和恢复的验收范围以该版本说明为准。 | |
| 144 | 新增: | |
| 145 | 新增:手动替换 App 前,保存文件并选择“停止环境并退出”。新 App 会核对后台版本;若出现“更新待完成”,可先打开现有环境保存文件,再选择“保存后停止环境并完成更新”。Alpha 版本间的兼容性和特殊迁移要求以对应 Release 说明为准。 | |
| 146 | 新增: | |
| 147 | 新增:“设置 → 环境与恢复”分别提供环境组件与工具更新,并显示实际版本。组件更新会重启浏览器和编辑器,保留 VM、磁盘和工作台独立终端;编辑器内的集成终端可能结束,操作前需要保存内容。工具更新还要求外网已通过检查并获准联网,采用当前 App 指定的最低版本;人工暂停外网不会被更新操作解除。替换 App 不等于已经升级全部 Linux 工具。 | |
| 132 | 148 | |
| 133 | 149 | 卸载应用前也应先停止环境并退出,再将 Cage.app 移到废纸篓。删除 App 不会自动删除共享项目、默认工作区、代理配置或虚拟磁盘。需要清理这些数据时,先备份:私有状态默认在 `~/.claude-cage/`,默认工作区通常在 `~/.claude-cage-workspace/`,自行打开的项目仍在原目录。删除虚拟磁盘会丢失只存在于 Linux 环境中的文件和登录状态。 |
| 134 | 150 | |
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | |
| 17 | 17 | 发布或编辑 Release 会运行 `Website and public releases`:匿名下载附件,核对 SHA-256、应用版本、Developer ID 签名、公证票据与 Gatekeeper;通过后重建并部署主页。草稿不会进入公开下载列表。验收失败时,该轮主页部署停止,维护者应检查 Actions 日志并修正发行物。 |
| 18 | 18 | |
| 19 | 删除:版本标签对应的源码须包含发布工作流。`v0.2.0-alpha.1` 等早期标签没有该触发配置,编辑其 Release 不会自动运行新流程;需要复验时,使用下文带 `release_tag` 的手动命令。 | |
| 19 | 新增:版本标签对应的源码须包含发布工作流。需要复验时,使用下文带 `release_tag` 的手动命令。 | |
| 20 | 20 | |
| 21 | 21 | GitHub Release 一旦公开,应用内更新即可读到它,早于这项事后检查完成。因此,本地打包验收必须在发布草稿前通过,不能依赖 Actions 作为安装包公开前的审批门槛。CI 中若用默认 `GITHUB_TOKEN` 发布 Release,不会触发后续工作流,须另外显式调用网站工作流;手工网页发布或 `gh` 用户凭据发布会正常触发。 |
| 22 | 22 | |
| @@ -24,12 +24,12 @@ GitHub Release 一旦公开,应用内更新即可读到它,早于这项事 | ||
| 24 | 24 | |
| 25 | 25 | 支持应用内更新的客户端直接读取公开 Release,经所选受管代理下载,没有主机直连回退。正式客户端忽略预发行;预发行客户端可接收更新的预发行或正式版本。客户端仍独立核对摘要、应用身份、同一 Developer ID Team 和 Apple 验证结果。 |
| 26 | 26 | |
| 27 | 删除:`0.2.0-alpha.1` 不包含更新器,用户须手动下载安装 Alpha 2。Alpha 2 包含应用内更新器,后续版本可通过应用内入口升级。公开源校验与单元测试不能证明真实用户环境下的替换、重启和回滚已经验收;每次发布均须在 Release 中说明实际验证范围。 | |
| 27 | 新增:首个内测版本为 `0.1.0-alpha.1`,首次安装使用 DMG,后续版本可通过应用内入口升级。公开源校验与单元测试不能证明真实用户环境下的替换、重启和回滚已经验收;每次发布均须在 Release 中说明实际验证范围。 | |
| 28 | 28 | |
| 29 | 29 | 可在不安装、不启动 App 的情况下验证公开附件: |
| 30 | 30 | |
| 31 | 31 | ```sh |
| 32 | 删除:node www/scripts/sync-release.mjs --tag v0.2.0-alpha.1 \ | |
| 32 | 新增:node www/scripts/sync-release.mjs --tag v0.1.0-alpha.1 \ | |
| 33 | 33 | --output /tmp/cage-release-check/release.json \ |
| 34 | 34 | --archive-directory /tmp/cage-release-check/assets |
| 35 | 35 | bash scripts/verify-macos-release.sh /tmp/cage-release-check/assets |
| @@ -43,7 +43,7 @@ GitHub Pages 的发布源设为 GitHub Actions。`main` 的网站文件变更会 | ||
| 43 | 43 | gh workflow run www.yml --repo Lee-xeo/Claude-Cage --ref main |
| 44 | 44 | ``` |
| 45 | 45 | |
| 46 | 删除:需要同时重验某个公开安装包时,在命令后增加 `-f release_tag=v0.2.0-alpha.1`,替换为实际版本。 | |
| 46 | 新增:需要同时重验某个公开安装包时,在命令后增加 `-f release_tag=v0.1.0-alpha.1`,替换为实际版本。 | |
| 47 | 47 | |
| 48 | 48 | 主页构建从公开 Release 刷新下载链接,避免源码版本领先安装包时出现失效下载。图片、样式、404 返回链接与兼容重定向均使用 `/Claude-Cage/` 子路径。 |
| 49 | 49 | |
| @@ -0,0 +1,36 @@ | ||
| 1 | 新增:# Cage 0.1.0-alpha.1 | |
| 2 | 新增: | |
| 3 | 新增:这是 Cage 面向内测团队的首个版本,支持 Apple Silicon Mac 与 macOS 14 或更新版本。它把 Linux 终端、浏览器和文件编辑器放在同一个桌面工作区中,网络由 Cage 自己的受管代理接管。 | |
| 4 | 新增: | |
| 5 | 新增:## 安装与开始使用 | |
| 6 | 新增: | |
| 7 | 新增:发布后,从[本版本 Release](https://github.com/Lee-xeo/Claude-Cage/releases/tag/v0.1.0-alpha.1) 下载 `Cage-0.1.0-alpha.1-macos-arm64.dmg`,将 Cage 拖入 Applications,再从应用程序打开。配置自己的 Clash / Mihomo YAML 或订阅,选择节点后启动环境。首次启动会下载 Linux 镜像与开发工具。 | |
| 8 | 新增: | |
| 9 | 新增:代理服务和 Claude 账户或授权需要自行准备。打开演示或测试项目,在终端输入 `claude`,并在 Cage 浏览器中完成自己的账户授权。完整步骤见[开始使用](../getting-started.md)。 | |
| 10 | 新增: | |
| 11 | 新增:后续发布新版本时,可在应用内检查、下载、校验、安装并重启。下载经过所选受管代理,没有主机直连回退;新包须由同一 Apple 发布者签名并通过校验。有运行任务时,先保存并确认停止;应用替换保留项目、代理配置和虚拟磁盘。 | |
| 12 | 新增: | |
| 13 | 新增:## 本版能力 | |
| 14 | 新增: | |
| 15 | 新增:- 工作区集成项目与终端列表、浏览器标签、收藏和下载管理。 | |
| 16 | 新增:- 支持 Mac 快捷键、中文输入和文本剪贴板;窗口隐藏时停止浏览器画面传输,保留页面与任务。 | |
| 17 | 新增:- 网络与隔离检查控制外网放行;人工暂停可持久保存,订阅刷新和后台重启不会自动解除暂停。 | |
| 18 | 新增:- 编辑器可独立恢复;下载保存失败保留重试信息,同名文件不覆盖。 | |
| 19 | 新增:- 控制服务按版本和程序身份管理后台,环境设置可查看组件与工具版本。 | |
| 20 | 新增:- 主页与 README 共用产品内容和 15 种语言,默认中文,通过下拉框切换。 | |
| 21 | 新增: | |
| 22 | 新增:## 发布验收 | |
| 23 | 新增: | |
| 24 | 新增:本版本正在准备发行。新编号安装包的 Developer ID 签名、Apple 公证、票据附加、Gatekeeper 与实际安装入口须针对最终构建完成验收;结果将在正式发布时补齐,不能沿用其他构建的公证结果。 | |
| 25 | 新增: | |
| 26 | 新增:源码验证覆盖 Go 回归、相关竞态检查与 vet、前端 lint 与单元测试、浏览器和文件操作、更新器、第三方补丁与依赖许可。公开附件校验还需核对实际下载内容与 `SHA256SUMS`,版本与源码标签保持一致。 | |
| 27 | 新增: | |
| 28 | 新增:## 内测范围与限制 | |
| 29 | 新增: | |
| 30 | 新增:请先使用有备份的测试项目。共享目录的修改、删除会直接影响 Mac;同一环境中的项目共享账户、工具和文件系统。 | |
| 31 | 新增: | |
| 32 | 新增:以下仍需真实使用验收:全新实体 Mac 的镜像下载与完整安装、macOS 14 实机兼容性、真实 Claude 授权和模型请求,以及两个正式签名版本之间的原生自动替换、系统安装授权、重启与回滚整链路。单元测试与公证结果不代替这些验收。 | |
| 33 | 新增: | |
| 34 | 新增:网络检查反映当时配置与采样证据,无法保证账户不会受到平台限制。 | |
| 35 | 新增: | |
| 36 | 新增:[项目主页](https://lee-xeo.github.io/Claude-Cage/) · [文档导航](../README.md) · [问题反馈](https://github.com/Lee-xeo/Claude-Cage/issues) | |
| @@ -6,6 +6,8 @@ | ||
| 6 | 6 | |
| 7 | 7 | 需要 macOS、Xcode Command Line Tools、Go(版本见 `go.mod`)、Node.js 24、`uv`。`VERSION` 是 App、控制程序和安装包的版本来源。`CFBundleShortVersionString` 使用数字版本,关于窗口显示包含 Alpha 标记的完整版本。 |
| 8 | 8 | |
| 9 | 新增:每次发行都须对本次构建完成签名、公证和安装包验收。版本与通过范围以对应 Release 及其构建记录为准,其他版本的结果不能覆盖本次构建。 | |
| 10 | 新增: | |
| 9 | 11 | 对外分发还需要 Apple Developer ID Application 证书与配套私钥,以及已保存到钥匙串的 `notarytool` 凭据。证书、私钥和公证凭据只保存在钥匙串或 CI Secret 中,不写入源码或发布附件。按 [Apple 公证说明](https://developer.apple.com/documentation/security/customizing-the-notarization-workflow) 配置认证后,可先用 `xcrun notarytool history --keychain-profile <名称>` 验证。 |
| 10 | 12 | |
| 11 | 13 | ## 构建并验证 |
| @@ -15,6 +17,7 @@ | ||
| 15 | 17 | ```sh |
| 16 | 18 | export CAGE_SIGNING_IDENTITY='Developer ID Application: 你的名称 (TEAMID)' |
| 17 | 19 | export CAGE_NOTARY_PROFILE='你的公证凭据名称' |
| 20 | 新增:unset CAGE_BUILD_OUTPUT | |
| 18 | 21 | bash scripts/package-macos.sh |
| 19 | 22 | ``` |
| 20 | 23 | |
| @@ -31,6 +34,10 @@ bash scripts/package-macos.sh | ||
| 31 | 34 | |
| 32 | 35 | 只做本机开发时可运行 `bash scripts/build-app.sh`,未设置签名身份会使用 ad-hoc 签名。`--install` 可安装到 `~/Applications/Cage.app`,会替换该位置的旧版本。此构建方式不完成公证,不能作为已经通过 Gatekeeper 的下载包宣传。 |
| 33 | 36 | |
| 37 | 新增:构建先在临时目录验证新 App,再替换目标;目标中的 App 或控制程序仍在运行时,脚本拒绝覆盖。默认目标为 `_output/Cage.app`,并清理构建目录中的其他 Cage App。独立验证可将 `CAGE_BUILD_OUTPUT` 设为绝对 `.app` 路径且不使用 `--install`,此时不清理其他副本。正式打包使用默认目标,应先取消这个自定义变量。 | |
| 38 | 新增: | |
| 39 | 新增:使用 `--install` 时,安装副本先验证再替换到 `~/Applications/Cage.app`,随后清理构建目录及两个 Applications 目录中的其他 Cage App。清理按应用标识核对,跳过符号链接、其他软件,以及 App 或控制程序仍在运行的副本,不删除配置、虚拟磁盘、项目或历史 DMG。目标本身在构建前和替换前均检查是否运行。安装前须保存文件、停止环境并退出。发行打包成功时也会清理构建目录中的 App 副本。 | |
| 40 | 新增: | |
| 34 | 41 | ## Apple 返回等待或失败时 |
| 35 | 42 | |
| 36 | 43 | 公证结果文件保存提交 ID。超时后先查询原提交,不重复上传同一包: |
| @@ -46,8 +53,16 @@ DMG 提交已 Accepted 时,直接对原 DMG 执行 `xcrun stapler staple`、`x | ||
| 46 | 53 | |
| 47 | 54 | ## 发布与安装验收 |
| 48 | 55 | |
| 49 | 删除:推送前确认目标仓库仍为私有,检查提交内容不包含个人配置、节点凭据、登录链接和未脱敏截图。先推送源码提交及相应版本标签,再向 GitHub 预发行版上传 DMG、Mihomo 源码和校验文件;私有仓库附件仅对有权限的 GitHub 用户开放。 | |
| 56 | 新增:发行物通过公开的 GitHub Releases 分发。推送前检查提交内容不包含个人配置、节点凭据、登录链接和未脱敏截图;先推送源码提交及对应版本标签,再创建草稿、上传 DMG、Mihomo 源码与校验文件,附件完整后发布。公开源验证与主页自动部署见[公开发行与主页部署](public-releases.md)。 | |
| 50 | 57 | |
| 51 | 58 | 从实际 DMG 复制 App 后验证签名、票据与首次入口。用独立临时配置验证空状态,避免覆盖维护者正在使用的环境。每次发布说明分别列出已验证项和仍需真实用户操作的项目:干净 Mac 安装、首次镜像下载、代理配置、Claude 授权及模型请求、重启恢复、升级和卸载。单独通过公证不能替代这些产品验证。 |
| 52 | 59 | |
| 53 | 删除:更新版本前,用户应退出 Cage 并停止环境,再替换应用。应用配置、代理配置和虚拟磁盘位于用户数据目录,替换 App 保留这些内容;删除 App 也不会自动删除项目与虚拟磁盘。当前 Alpha 使用手动下载安装包升级。 | |
| 60 | 新增:应用内更新读取公开 Release 中与版本对应的 `Cage-<版本>-macos-arm64.dmg` 和 `SHA256SUMS`,通过所选受管代理获取,无直连回退。发布包及其中的控制程序、代理核心和更新安装器须由与当前 App 相同的 Developer ID Team 签名,并通过公证与 Gatekeeper 验证;ad-hoc 开发构建会被自动安装流程拒绝。公开下载源无需 GitHub 凭据;发布者仍须按每个版本分别验证下载、安装与重启,不能将附件公开可读等同于升级验收通过。 | |
| 61 | 新增: | |
| 62 | 新增:客户端下载校验后自动进入安装;存在运行环境时先取得用户保存停止的确认,再停止环境和控制服务、替换 App 并重启。版本接管与启动失败恢复见[工作台设计](design/workbench.md#更新与后台接管)。配置、代理和虚拟磁盘位于用户数据目录,替换或删除 App 不会自动删除这些数据;Linux 组件与工具另行升级。 | |
| 63 | 新增: | |
| 64 | 新增:## 客机工具版本与来源 | |
| 65 | 新增: | |
| 66 | 新增:`internal/cage/tool-versions.env` 保存 Cage 首装和受管升级使用的最低版本及平台摘要,`guest-tools.sh` 是共用安装器。code-server 固定为 [4.144.0 官方发行版](https://github.com/coder/code-server/releases/tag/v4.144.0),mise 固定为 [2026.10.25 官方发行版](https://github.com/jdx/mise/releases/tag/v2026.10.25);arm64 与 amd64 资产的 SHA-256 来自各项目 GitHub Release API 的资产 `digest` 字段。安装器下载指定版本并核对固定摘要,失败时不运行包安装。Claude Code 使用 npm 的固定版本 `2.1.314`,npm 校验注册表的包完整性。Chromium 从 Debian 的签名软件源更新,采用软件源维护的版本。 | |
| 67 | 新增: | |
| 68 | 新增:升级这些最低版本时,需要同时核对官方资产、更新摘要并验证现有持久环境,不能只改显示版本。受管升级保留较新的已安装版本,不清理用户配置,不重建 Linux 磁盘。组件脚本与工具包分别维护:组件摘要正确只证明 Cage 脚本匹配,不表示所有工具已升级或已完成漏洞审计。 | |
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | |
| 5 | 5 | ## 下载或安装受阻 |
| 6 | 6 | |
| 7 | 删除:**GitHub 显示 404,或看不到安装包。** 仓库处于私有测试阶段时,需要登录获授权的 GitHub 账户。Release 中的源码压缩包用于开发,安装应用应下载 `.dmg`。没有 `.dmg` 的条目尚不能按安装包路径使用。 | |
| 7 | 新增:**GitHub 显示 404,或看不到安装包。** 仓库与正式发布的附件公开可读,无需仓库授权。先从[项目主页](https://lee-xeo.github.io/Claude-Cage/)进入当前下载版本,检查网络与链接是否完整。Release 中的源码压缩包用于开发,安装应用应下载 `.dmg`;没有 `.dmg` 的条目不能按安装包使用。 | |
| 8 | 8 | |
| 9 | 9 | **Mac 提示应用损坏、无法验证或不支持。** 确认使用 Apple Silicon、macOS 14+,重新下载对应 Release 的完整安装包,并核对该 Release 的签名、公证说明和校验文件。保留系统提示的原文反馈问题;不要通过关闭 Gatekeeper 或删除隔离属性来掩盖发行问题。 |
| 10 | 10 | |
| @@ -0,0 +1,411 @@ | ||
| 1 | 新增:// Package appupdate downloads Cage releases through the selected managed egress. | |
| 2 | 新增:// Signature verification and application replacement belong to the native app. | |
| 3 | 新增:package appupdate | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "crypto/sha256" | |
| 8 | 新增: "encoding/hex" | |
| 9 | 新增: "encoding/json" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "fmt" | |
| 12 | 新增: "io" | |
| 13 | 新增: "net/http" | |
| 14 | 新增: "net/url" | |
| 15 | 新增: "os" | |
| 16 | 新增: "os/signal" | |
| 17 | 新增: "path/filepath" | |
| 18 | 新增: "strings" | |
| 19 | 新增: "syscall" | |
| 20 | 新增: "time" | |
| 21 | 新增: | |
| 22 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 23 | 新增: "github.com/sylvinus/agent-vm/internal/managedproxy" | |
| 24 | 新增: "github.com/sylvinus/agent-vm/internal/version" | |
| 25 | 新增: "golang.org/x/mod/semver" | |
| 26 | 新增:) | |
| 27 | 新增: | |
| 28 | 新增:const repository = "Lee-xeo/Claude-Cage" | |
| 29 | 新增:const releasesURL = "https://api.github.com/repos/" + repository + "/releases?per_page=100" | |
| 30 | 新增:const maxArchive = 512 << 20 | |
| 31 | 新增:const maxMetadata = 4 << 20 | |
| 32 | 新增: | |
| 33 | 新增:type asset struct { | |
| 34 | 新增: Name string `json:"name"` | |
| 35 | 新增: URL string `json:"browser_download_url"` | |
| 36 | 新增: Size int64 `json:"size"` | |
| 37 | 新增: Digest string `json:"digest"` | |
| 38 | 新增: State string `json:"state"` | |
| 39 | 新增:} | |
| 40 | 新增:type release struct { | |
| 41 | 新增: Tag string `json:"tag_name"` | |
| 42 | 新增: Draft bool `json:"draft"` | |
| 43 | 新增: Prerelease bool `json:"prerelease"` | |
| 44 | 新增: Assets []asset `json:"assets"` | |
| 45 | 新增:} | |
| 46 | 新增:type candidate struct { | |
| 47 | 新增: Version string `json:"version"` | |
| 48 | 新增: Archive asset `json:"archive"` | |
| 49 | 新增: Checksums asset `json:"checksums"` | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 52 | 新增:// State is one line of the native launcher's private update process protocol. | |
| 53 | 新增:// ArchivePath is returned only to the native launcher, never as a download URL. | |
| 54 | 新增:type State struct { | |
| 55 | 新增: Phase string `json:"phase"` | |
| 56 | 新增: CurrentVersion string `json:"currentVersion"` | |
| 57 | 新增: LatestVersion string `json:"latestVersion,omitempty"` | |
| 58 | 新增: ReceivedBytes int64 `json:"receivedBytes,omitempty"` | |
| 59 | 新增: TotalBytes int64 `json:"totalBytes,omitempty"` | |
| 60 | 新增: Message string `json:"message,omitempty"` | |
| 61 | 新增: Retryable bool `json:"retryable,omitempty"` | |
| 62 | 新增: ArchivePath string `json:"archivePath,omitempty"` | |
| 63 | 新增: SHA256 string `json:"sha256,omitempty"` | |
| 64 | 新增:} | |
| 65 | 新增: | |
| 66 | 新增:// Run only accepts fixed operations. URLs and destinations come from the | |
| 67 | 新增:// verified repository response and the current private profile. | |
| 68 | 新增:func Run(configPath string, args []string, output io.Writer) int { | |
| 69 | 新增: enc := json.NewEncoder(output) | |
| 70 | 新增: state := State{CurrentVersion: version.Version} | |
| 71 | 新增: emit := func() { _ = enc.Encode(state) } | |
| 72 | 新增: fail := func(err error) int { | |
| 73 | 新增: state.Phase, state.Message, state.Retryable = "failed", err.Error(), true | |
| 74 | 新增: emit() | |
| 75 | 新增: return 1 | |
| 76 | 新增: } | |
| 77 | 新增: if len(args) != 1 || (args[0] != "check" && args[0] != "download") { | |
| 78 | 新增: return fail(errors.New("更新操作无效")) | |
| 79 | 新增: } | |
| 80 | 新增: ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | |
| 81 | 新增: defer cancel() | |
| 82 | 新增: client, err := managedClient(ctx, configPath) | |
| 83 | 新增: if err != nil { | |
| 84 | 新增: return fail(err) | |
| 85 | 新增: } | |
| 86 | 新增: defer client.CloseIdleConnections() | |
| 87 | 新增: state.Phase, state.Message = "checking", "正在检查更新" | |
| 88 | 新增: emit() | |
| 89 | 新增: c, err := findRelease(ctx, client, version.Version) | |
| 90 | 新增: if err != nil { | |
| 91 | 新增: return fail(err) | |
| 92 | 新增: } | |
| 93 | 新增: if c == nil { | |
| 94 | 新增: state.Phase, state.Message = "current", "已是当前更新通道的最新版本" | |
| 95 | 新增: emit() | |
| 96 | 新增: return 0 | |
| 97 | 新增: } | |
| 98 | 新增: state.LatestVersion = c.Version | |
| 99 | 新增: if args[0] == "check" { | |
| 100 | 新增: state.Phase, state.Message = "available", "发现新版本,可下载更新" | |
| 101 | 新增: emit() | |
| 102 | 新增: return 0 | |
| 103 | 新增: } | |
| 104 | 新增: digest, err := releaseDigest(ctx, client, *c) | |
| 105 | 新增: if err != nil { | |
| 106 | 新增: return fail(err) | |
| 107 | 新增: } | |
| 108 | 新增: directory := filepath.Join(filepath.Dir(configPath), "updates") | |
| 109 | 新增: if err = os.MkdirAll(directory, 0700); err != nil { | |
| 110 | 新增: return fail(errors.New("无法创建私有更新目录")) | |
| 111 | 新增: } | |
| 112 | 新增: if st, e := os.Lstat(directory); e != nil || !st.IsDir() || st.Mode()&os.ModeSymlink != 0 { | |
| 113 | 新增: return fail(errors.New("更新目录必须是私有普通目录")) | |
| 114 | 新增: } | |
| 115 | 新增: if err = os.Chmod(directory, 0700); err != nil { | |
| 116 | 新增: return fail(errors.New("无法保护更新目录")) | |
| 117 | 新增: } | |
| 118 | 新增: job, err := os.MkdirTemp(directory, "download-") | |
| 119 | 新增: if err != nil { | |
| 120 | 新增: return fail(errors.New("无法创建更新下载任务")) | |
| 121 | 新增: } | |
| 122 | 新增: keep := false | |
| 123 | 新增: defer func() { | |
| 124 | 新增: if !keep { | |
| 125 | 新增: _ = os.RemoveAll(job) | |
| 126 | 新增: } | |
| 127 | 新增: }() | |
| 128 | 新增: archive := filepath.Join(job, "Cage.dmg") | |
| 129 | 新增: state.Phase, state.Message, state.TotalBytes = "downloading", "正在下载更新", c.Archive.Size | |
| 130 | 新增: emit() | |
| 131 | 新增: err = download(ctx, client, c.Archive, digest, archive, func(n int64) { | |
| 132 | 新增: state.ReceivedBytes = n | |
| 133 | 新增: emit() | |
| 134 | 新增: }) | |
| 135 | 新增: if err != nil { | |
| 136 | 新增: return fail(err) | |
| 137 | 新增: } | |
| 138 | 新增: keep = true | |
| 139 | 新增: state.Phase, state.Message, state.ArchivePath, state.SHA256 = "downloaded", "下载摘要已校验,正在验证应用", archive, digest | |
| 140 | 新增: emit() | |
| 141 | 新增: return 0 | |
| 142 | 新增:} | |
| 143 | 新增: | |
| 144 | 新增:func managedClient(ctx context.Context, configPath string) (*http.Client, error) { | |
| 145 | 新增: cfg, err := cage.Load(configPath) | |
| 146 | 新增: if err != nil { | |
| 147 | 新增: return nil, errors.New("请先配置并启动 Cage 的所选代理,再检查更新") | |
| 148 | 新增: } | |
| 149 | 新增: profile := filepath.Dir(configPath) | |
| 150 | 新增: p, err := managedproxy.Applied(profile, cfg.ProxyURL, cfg.ProxyRevision) | |
| 151 | 新增: if err != nil { | |
| 152 | 新增: return nil, errors.New("所选代理尚未应用,请在网络与代理中配置后重试") | |
| 153 | 新增: } | |
| 154 | 新增: if !managedproxy.Running(ctx, profile, p) { | |
| 155 | 新增: return nil, errors.New("所选代理未运行,请在网络与代理中启动后重试;更新不会改用主机直连") | |
| 156 | 新增: } | |
| 157 | 新增: egress, err := cage.NewEgress(cfg) | |
| 158 | 新增: if err != nil { | |
| 159 | 新增: return nil, errors.New("更新代理配置无效") | |
| 160 | 新增: } | |
| 161 | 新增: return &http.Client{ | |
| 162 | 新增: Transport: &http.Transport{Proxy: nil, DialContext: egress.DialContext, ForceAttemptHTTP2: true, TLSHandshakeTimeout: 15 * time.Second, ResponseHeaderTimeout: 30 * time.Second, IdleConnTimeout: 10 * time.Second}, | |
| 163 | 新增: Timeout: 20 * time.Minute, | |
| 164 | 新增: CheckRedirect: func(r *http.Request, via []*http.Request) error { | |
| 165 | 新增: if len(via) >= 5 || !allowedURL(r.URL, true) { | |
| 166 | 新增: return errors.New("更新下载重定向被拒绝") | |
| 167 | 新增: } | |
| 168 | 新增: return nil | |
| 169 | 新增: }, | |
| 170 | 新增: }, nil | |
| 171 | 新增:} | |
| 172 | 新增: | |
| 173 | 新增:func allowedURL(u *url.URL, redirect bool) bool { | |
| 174 | 新增: if u == nil || u.Scheme != "https" || u.User != nil || u.Fragment != "" || (u.Port() != "" && u.Port() != "443") { | |
| 175 | 新增: return false | |
| 176 | 新增: } | |
| 177 | 新增: switch u.Hostname() { | |
| 178 | 新增: case "api.github.com": | |
| 179 | 新增: return u.Path == "/repos/"+repository+"/releases" | |
| 180 | 新增: case "github.com": | |
| 181 | 新增: return strings.HasPrefix(u.Path, "/"+repository+"/releases/download/") && !strings.Contains(u.Path, "/../") | |
| 182 | 新增: case "release-assets.githubusercontent.com", "objects.githubusercontent.com": | |
| 183 | 新增: return redirect | |
| 184 | 新增: } | |
| 185 | 新增: return false | |
| 186 | 新增:} | |
| 187 | 新增: | |
| 188 | 新增:func request(ctx context.Context, client *http.Client, raw string) (*http.Response, error) { | |
| 189 | 新增: u, err := url.Parse(raw) | |
| 190 | 新增: if err != nil || !allowedURL(u, false) { | |
| 191 | 新增: return nil, errors.New("更新地址不属于 Cage 的受信发布源") | |
| 192 | 新增: } | |
| 193 | 新增: req, err := http.NewRequestWithContext(ctx, "GET", raw, nil) | |
| 194 | 新增: if err != nil { | |
| 195 | 新增: return nil, errors.New("更新请求无效") | |
| 196 | 新增: } | |
| 197 | 新增: req.Header.Set("User-Agent", "Cage-Updater/"+version.Version) | |
| 198 | 新增: req.Header.Set("Accept", "application/vnd.github+json") | |
| 199 | 新增: if u.Hostname() == "api.github.com" { | |
| 200 | 新增: req.Header.Set("X-GitHub-Api-Version", "2022-11-28") | |
| 201 | 新增: } | |
| 202 | 新增: resp, err := client.Do(req) | |
| 203 | 新增: if err != nil { | |
| 204 | 新增: if ctx.Err() != nil { | |
| 205 | 新增: return nil, errors.New("更新下载已取消") | |
| 206 | 新增: } | |
| 207 | 新增: return nil, errors.New("无法通过所选代理连接更新源,请检查网络后重试") | |
| 208 | 新增: } | |
| 209 | 新增: if resp.StatusCode != http.StatusOK { | |
| 210 | 新增: resp.Body.Close() | |
| 211 | 新增: switch resp.StatusCode { | |
| 212 | 新增: case 404: | |
| 213 | 新增: return nil, errors.New("更新源暂不可访问:仓库尚未公开或该发行包不可用") | |
| 214 | 新增: case 403, 429: | |
| 215 | 新增: return nil, errors.New("更新源请求受限,请稍后重试") | |
| 216 | 新增: default: | |
| 217 | 新增: return nil, fmt.Errorf("更新源返回 HTTP %d,请稍后重试", resp.StatusCode) | |
| 218 | 新增: } | |
| 219 | 新增: } | |
| 220 | 新增: return resp, nil | |
| 221 | 新增:} | |
| 222 | 新增: | |
| 223 | 新增:func limitedBody(resp *http.Response, limit int64) ([]byte, error) { | |
| 224 | 新增: defer resp.Body.Close() | |
| 225 | 新增: if resp.ContentLength > limit { | |
| 226 | 新增: return nil, errors.New("更新信息超过允许大小") | |
| 227 | 新增: } | |
| 228 | 新增: b, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) | |
| 229 | 新增: if err != nil || int64(len(b)) > limit { | |
| 230 | 新增: return nil, errors.New("更新信息下载中断或超过允许大小") | |
| 231 | 新增: } | |
| 232 | 新增: return b, nil | |
| 233 | 新增:} | |
| 234 | 新增: | |
| 235 | 新增:func findRelease(ctx context.Context, client *http.Client, current string) (*candidate, error) { | |
| 236 | 新增: resp, err := request(ctx, client, releasesURL) | |
| 237 | 新增: if err != nil { | |
| 238 | 新增: return nil, err | |
| 239 | 新增: } | |
| 240 | 新增: b, err := limitedBody(resp, maxMetadata) | |
| 241 | 新增: if err != nil { | |
| 242 | 新增: return nil, err | |
| 243 | 新增: } | |
| 244 | 新增: var releases []release | |
| 245 | 新增: if json.Unmarshal(b, &releases) != nil { | |
| 246 | 新增: return nil, errors.New("更新源返回了无效的版本信息") | |
| 247 | 新增: } | |
| 248 | 新增: return selectRelease(releases, current) | |
| 249 | 新增:} | |
| 250 | 新增: | |
| 251 | 新增:func selectRelease(releases []release, current string) (*candidate, error) { | |
| 252 | 新增: currentTag := "v" + current | |
| 253 | 新增: if !semver.IsValid(currentTag) || semver.Canonical(currentTag) != currentTag { | |
| 254 | 新增: return nil, errors.New("当前应用版本无效,无法安全比较更新") | |
| 255 | 新增: } | |
| 256 | 新增: var best *candidate | |
| 257 | 新增: for _, r := range releases { | |
| 258 | 新增: if r.Draft || !strings.HasPrefix(r.Tag, "v") || !semver.IsValid(r.Tag) || semver.Canonical(r.Tag) != r.Tag || semver.Compare(r.Tag, currentTag) <= 0 { | |
| 259 | 新增: continue | |
| 260 | 新增: } | |
| 261 | 新增: pre := r.Prerelease || semver.Prerelease(r.Tag) != "" | |
| 262 | 新增: if semver.Prerelease(currentTag) == "" && pre { | |
| 263 | 新增: continue | |
| 264 | 新增: } | |
| 265 | 新增: v := strings.TrimPrefix(r.Tag, "v") | |
| 266 | 新增: if best != nil && semver.Compare(r.Tag, "v"+best.Version) <= 0 { | |
| 267 | 新增: continue | |
| 268 | 新增: } | |
| 269 | 新增: c := candidate{Version: v} | |
| 270 | 新增: for _, a := range r.Assets { | |
| 271 | 新增: if a.State != "uploaded" { | |
| 272 | 新增: continue | |
| 273 | 新增: } | |
| 274 | 新增: if a.Name == "Cage-"+v+"-macos-arm64.dmg" && a.Size > 0 && a.Size <= maxArchive { | |
| 275 | 新增: c.Archive = a | |
| 276 | 新增: } | |
| 277 | 新增: if a.Name == "SHA256SUMS" && a.Size > 0 && a.Size <= 64<<10 { | |
| 278 | 新增: c.Checksums = a | |
| 279 | 新增: } | |
| 280 | 新增: } | |
| 281 | 新增: if c.Archive.URL == "" { | |
| 282 | 新增: continue | |
| 283 | 新增: } | |
| 284 | 新增: u, err := url.Parse(c.Archive.URL) | |
| 285 | 新增: if err != nil || !allowedURL(u, false) || u.Hostname() != "github.com" || !strings.HasPrefix(u.Path, "/"+repository+"/releases/download/"+r.Tag+"/") { | |
| 286 | 新增: continue | |
| 287 | 新增: } | |
| 288 | 新增: if c.Archive.Digest == "" && c.Checksums.URL == "" { | |
| 289 | 新增: continue | |
| 290 | 新增: } | |
| 291 | 新增: best = &c | |
| 292 | 新增: } | |
| 293 | 新增: return best, nil | |
| 294 | 新增:} | |
| 295 | 新增: | |
| 296 | 新增:func digestValue(raw string) (string, error) { | |
| 297 | 新增: if !strings.HasPrefix(raw, "sha256:") { | |
| 298 | 新增: return "", errors.New("发行包缺少有效的 SHA-256 摘要") | |
| 299 | 新增: } | |
| 300 | 新增: h := strings.TrimPrefix(raw, "sha256:") | |
| 301 | 新增: b, err := hex.DecodeString(h) | |
| 302 | 新增: if err != nil || len(b) != sha256.Size { | |
| 303 | 新增: return "", errors.New("发行包 SHA-256 摘要无效") | |
| 304 | 新增: } | |
| 305 | 新增: return strings.ToLower(h), nil | |
| 306 | 新增:} | |
| 307 | 新增: | |
| 308 | 新增:func releaseDigest(ctx context.Context, client *http.Client, c candidate) (string, error) { | |
| 309 | 新增: var hash string | |
| 310 | 新增: if c.Archive.Digest != "" { | |
| 311 | 新增: var err error | |
| 312 | 新增: hash, err = digestValue(c.Archive.Digest) | |
| 313 | 新增: if err != nil { | |
| 314 | 新增: return "", err | |
| 315 | 新增: } | |
| 316 | 新增: } | |
| 317 | 新增: if c.Checksums.URL == "" { | |
| 318 | 新增: return hash, nil | |
| 319 | 新增: } | |
| 320 | 新增: u, err := url.Parse(c.Checksums.URL) | |
| 321 | 新增: if err != nil || u.Hostname() != "github.com" || !strings.HasPrefix(u.Path, "/"+repository+"/releases/download/v"+c.Version+"/") { | |
| 322 | 新增: return "", errors.New("校验清单不属于同一发行版本") | |
| 323 | 新增: } | |
| 324 | 新增: resp, err := request(ctx, client, c.Checksums.URL) | |
| 325 | 新增: if err != nil { | |
| 326 | 新增: return "", err | |
| 327 | 新增: } | |
| 328 | 新增: b, err := limitedBody(resp, 64<<10) | |
| 329 | 新增: if err != nil { | |
| 330 | 新增: return "", err | |
| 331 | 新增: } | |
| 332 | 新增: found := "" | |
| 333 | 新增: for _, line := range strings.Split(string(b), "\n") { | |
| 334 | 新增: fields := strings.Fields(line) | |
| 335 | 新增: if len(fields) != 2 || strings.TrimPrefix(fields[1], "*") != c.Archive.Name { | |
| 336 | 新增: continue | |
| 337 | 新增: } | |
| 338 | 新增: h, err := digestValue("sha256:" + fields[0]) | |
| 339 | 新增: if err != nil || found != "" { | |
| 340 | 新增: return "", errors.New("发行包校验清单无效或重复") | |
| 341 | 新增: } | |
| 342 | 新增: found = h | |
| 343 | 新增: } | |
| 344 | 新增: if found == "" || (hash != "" && hash != found) { | |
| 345 | 新增: return "", errors.New("发行包与校验清单的 SHA-256 不一致") | |
| 346 | 新增: } | |
| 347 | 新增: return found, nil | |
| 348 | 新增:} | |
| 349 | 新增: | |
| 350 | 新增:func download(ctx context.Context, client *http.Client, a asset, digest, path string, progress func(int64)) error { | |
| 351 | 新增: if a.Size <= 0 || a.Size > maxArchive { | |
| 352 | 新增: return errors.New("发行包大小无效或超过 512 MiB") | |
| 353 | 新增: } | |
| 354 | 新增: if _, err := digestValue("sha256:" + digest); err != nil { | |
| 355 | 新增: return err | |
| 356 | 新增: } | |
| 357 | 新增: resp, err := request(ctx, client, a.URL) | |
| 358 | 新增: if err != nil { | |
| 359 | 新增: return err | |
| 360 | 新增: } | |
| 361 | 新增: defer resp.Body.Close() | |
| 362 | 新增: if resp.ContentLength > 0 && resp.ContentLength != a.Size { | |
| 363 | 新增: return errors.New("发行包大小与发布信息不一致") | |
| 364 | 新增: } | |
| 365 | 新增: f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) | |
| 366 | 新增: if err != nil { | |
| 367 | 新增: return errors.New("无法创建私有更新文件") | |
| 368 | 新增: } | |
| 369 | 新增: keep := false | |
| 370 | 新增: defer func() { | |
| 371 | 新增: f.Close() | |
| 372 | 新增: if !keep { | |
| 373 | 新增: os.Remove(path) | |
| 374 | 新增: } | |
| 375 | 新增: }() | |
| 376 | 新增: hash := sha256.New() | |
| 377 | 新增: w := &progressWriter{writer: io.MultiWriter(f, hash), notify: progress} | |
| 378 | 新增: n, err := io.Copy(w, io.LimitReader(resp.Body, a.Size+1)) | |
| 379 | 新增: if err != nil || n != a.Size { | |
| 380 | 新增: return errors.New("发行包下载中断或实际大小不匹配") | |
| 381 | 新增: } | |
| 382 | 新增: if hex.EncodeToString(hash.Sum(nil)) != digest { | |
| 383 | 新增: return errors.New("发行包 SHA-256 校验失败,请重新下载") | |
| 384 | 新增: } | |
| 385 | 新增: if err = f.Sync(); err != nil { | |
| 386 | 新增: return errors.New("无法保存更新文件") | |
| 387 | 新增: } | |
| 388 | 新增: if err = f.Close(); err != nil { | |
| 389 | 新增: return errors.New("无法保存更新文件") | |
| 390 | 新增: } | |
| 391 | 新增: keep = true | |
| 392 | 新增: progress(n) | |
| 393 | 新增: return nil | |
| 394 | 新增:} | |
| 395 | 新增: | |
| 396 | 新增:type progressWriter struct { | |
| 397 | 新增: writer io.Writer | |
| 398 | 新增: notify func(int64) | |
| 399 | 新增: total int64 | |
| 400 | 新增: last time.Time | |
| 401 | 新增:} | |
| 402 | 新增: | |
| 403 | 新增:func (w *progressWriter) Write(p []byte) (int, error) { | |
| 404 | 新增: n, err := w.writer.Write(p) | |
| 405 | 新增: w.total += int64(n) | |
| 406 | 新增: if time.Since(w.last) >= 250*time.Millisecond { | |
| 407 | 新增: w.last = time.Now() | |
| 408 | 新增: w.notify(w.total) | |
| 409 | 新增: } | |
| 410 | 新增: return n, err | |
| 411 | 新增:} | |
| @@ -0,0 +1,131 @@ | ||
| 1 | 新增:package appupdate | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/sha256" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "net/url" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "testing" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func fixtureRelease(v string, pre bool) release { | |
| 18 | 新增: return release{Tag: "v" + v, Prerelease: pre, Assets: []asset{{Name: "Cage-" + v + "-macos-arm64.dmg", URL: "https://github.com/" + repository + "/releases/download/v" + v + "/Cage-" + v + "-macos-arm64.dmg", Size: 3, Digest: "sha256:" + strings.Repeat("a", 64), State: "uploaded"}}} | |
| 19 | 新增:} | |
| 20 | 新增:func TestReleaseSelectionPreservesChannelsAndNumericPrereleases(t *testing.T) { | |
| 21 | 新增: rs := []release{fixtureRelease("0.2.0-alpha.9", true), fixtureRelease("0.2.0-alpha.10", true), fixtureRelease("0.1.0", false)} | |
| 22 | 新增: c, err := selectRelease(rs, "0.2.0-alpha.1") | |
| 23 | 新增: if err != nil || c == nil || c.Version != "0.2.0-alpha.10" { | |
| 24 | 新增: t.Fatalf("selected %#v: %v", c, err) | |
| 25 | 新增: } | |
| 26 | 新增: rs = append(rs, fixtureRelease("0.2.0", false), fixtureRelease("0.3.0-alpha.1", true)) | |
| 27 | 新增: c, err = selectRelease(rs, "0.1.0") | |
| 28 | 新增: if err != nil || c == nil || c.Version != "0.2.0" { | |
| 29 | 新增: t.Fatalf("stable channel %#v: %v", c, err) | |
| 30 | 新增: } | |
| 31 | 新增: if c, err = selectRelease(rs, "0.3.0"); err != nil || c != nil { | |
| 32 | 新增: t.Fatalf("downgrade: %#v %v", c, err) | |
| 33 | 新增: } | |
| 34 | 新增:} | |
| 35 | 新增:func TestRejectReleaseAssetOutsideRepositoryOrOversize(t *testing.T) { | |
| 36 | 新增: for _, mutate := range []func(*release){ | |
| 37 | 新增: func(r *release) { r.Assets[0].URL = "https://evil.example/Cage.dmg" }, | |
| 38 | 新增: func(r *release) { r.Assets[0].URL = "https://github.com/Other/App/releases/download/v0.2.0/Cage.dmg" }, | |
| 39 | 新增: func(r *release) { r.Assets[0].Size = maxArchive + 1 }, | |
| 40 | 新增: func(r *release) { r.Tag = "v../../malicious" }, | |
| 41 | 新增: func(r *release) { r.Draft = true }, | |
| 42 | 新增: func(r *release) { r.Assets[0].Digest = "" }, | |
| 43 | 新增: } { | |
| 44 | 新增: r := fixtureRelease("0.2.0", false) | |
| 45 | 新增: mutate(&r) | |
| 46 | 新增: if c, err := selectRelease([]release{r}, "0.1.0"); err != nil || c != nil { | |
| 47 | 新增: t.Fatalf("accepted %#v: %v", c, err) | |
| 48 | 新增: } | |
| 49 | 新增: } | |
| 50 | 新增:} | |
| 51 | 新增:func TestRedirectPolicyRejectsCredentialsAndHostLookalikes(t *testing.T) { | |
| 52 | 新增: for _, raw := range []string{"http://github.com/" + repository + "/releases/download/v1/a", "https://github.com.evil.example/a", "https://[email protected]/a", "https://github.com:8443/" + repository + "/releases/download/v1/a", "https://evil.githubusercontent.com/a", "https://release-assets.githubusercontent.com.evil.example/a", "file:///tmp/Cage.app"} { | |
| 53 | 新增: u, _ := url.Parse(raw) | |
| 54 | 新增: if allowedURL(u, true) { | |
| 55 | 新增: t.Fatal("accepted", raw) | |
| 56 | 新增: } | |
| 57 | 新增: } | |
| 58 | 新增: u, _ := url.Parse("https://release-assets.githubusercontent.com/github-production-release-asset/a?signature=private") | |
| 59 | 新增: if !allowedURL(u, true) || allowedURL(u, false) { | |
| 60 | 新增: t.Fatal("CDN must be accepted only after a trusted asset redirect") | |
| 61 | 新增: } | |
| 62 | 新增:} | |
| 63 | 新增: | |
| 64 | 新增:type roundTrip func(*http.Request) (*http.Response, error) | |
| 65 | 新增: | |
| 66 | 新增:func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } | |
| 67 | 新增:func responseClient(body string, status int) *http.Client { | |
| 68 | 新增: return &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) { | |
| 69 | 新增: return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), ContentLength: -1, Request: r}, nil | |
| 70 | 新增: })} | |
| 71 | 新增:} | |
| 72 | 新增:func TestDownloadVerifiesSizeDigestAndPrivateFile(t *testing.T) { | |
| 73 | 新增: content := "Cage archive" | |
| 74 | 新增: digest := fmt.Sprintf("%x", sha256.Sum256([]byte(content))) | |
| 75 | 新增: a := fixtureRelease("0.2.0", false).Assets[0] | |
| 76 | 新增: a.Size = int64(len(content)) | |
| 77 | 新增: for _, tc := range []struct { | |
| 78 | 新增: name, body, hash string | |
| 79 | 新增: ok bool | |
| 80 | 新增: }{{"valid", content, digest, true}, {"hash", content, strings.Repeat("a", 64), false}, {"oversize", content + "x", digest, false}, {"short", content[:3], digest, false}} { | |
| 81 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 82 | 新增: path := filepath.Join(t.TempDir(), "Cage.dmg") | |
| 83 | 新增: var received int64 | |
| 84 | 新增: err := download(context.Background(), responseClient(tc.body, 200), a, tc.hash, path, func(n int64) { received = n }) | |
| 85 | 新增: if tc.ok { | |
| 86 | 新增: b, e := os.ReadFile(path) | |
| 87 | 新增: if err != nil || e != nil || string(b) != content || received != a.Size { | |
| 88 | 新增: t.Fatalf("download %q %v %v %d", b, err, e, received) | |
| 89 | 新增: } | |
| 90 | 新增: st, _ := os.Stat(path) | |
| 91 | 新增: if st.Mode().Perm() != 0600 { | |
| 92 | 新增: t.Fatal("public file") | |
| 93 | 新增: } | |
| 94 | 新增: } else { | |
| 95 | 新增: if err == nil { | |
| 96 | 新增: t.Fatal("invalid download passed") | |
| 97 | 新增: } | |
| 98 | 新增: if _, e := os.Stat(path); !os.IsNotExist(e) { | |
| 99 | 新增: t.Fatal("invalid archive retained") | |
| 100 | 新增: } | |
| 101 | 新增: } | |
| 102 | 新增: }) | |
| 103 | 新增: } | |
| 104 | 新增:} | |
| 105 | 新增:func TestChecksumListMustAgreeAndBelongToSameRelease(t *testing.T) { | |
| 106 | 新增: r := fixtureRelease("0.2.0", false) | |
| 107 | 新增: a := r.Assets[0] | |
| 108 | 新增: c := candidate{Version: "0.2.0", Archive: a, Checksums: asset{Name: "SHA256SUMS", URL: "https://github.com/" + repository + "/releases/download/v0.2.0/SHA256SUMS"}} | |
| 109 | 新增: valid := strings.Repeat("a", 64) + " " + a.Name + "\n" | |
| 110 | 新增: if _, err := releaseDigest(context.Background(), responseClient(valid, 200), c); err != nil { | |
| 111 | 新增: t.Fatal(err) | |
| 112 | 新增: } | |
| 113 | 新增: for _, body := range []string{strings.Repeat("b", 64) + " " + a.Name, valid + valid, "invalid"} { | |
| 114 | 新增: if _, err := releaseDigest(context.Background(), responseClient(body, 200), c); err == nil { | |
| 115 | 新增: t.Fatal("invalid list passed") | |
| 116 | 新增: } | |
| 117 | 新增: } | |
| 118 | 新增: c.Checksums.URL = "https://github.com/" + repository + "/releases/download/v0.1.0/SHA256SUMS" | |
| 119 | 新增: if _, err := releaseDigest(context.Background(), responseClient(valid, 200), c); err == nil { | |
| 120 | 新增: t.Fatal("cross-version list passed") | |
| 121 | 新增: } | |
| 122 | 新增:} | |
| 123 | 新增:func TestPrivateReleaseAndMissingProxyDoNotReportCurrent(t *testing.T) { | |
| 124 | 新增: if _, err := findRelease(context.Background(), responseClient(`{"message":"Not Found"}`, 404), "0.1.0"); err == nil || !strings.Contains(err.Error(), "尚未公开") { | |
| 125 | 新增: t.Fatal(err) | |
| 126 | 新增: } | |
| 127 | 新增: var output bytes.Buffer | |
| 128 | 新增: if code := Run(filepath.Join(t.TempDir(), "config.json"), []string{"check"}, &output); code == 0 || strings.Contains(output.String(), `"phase":"current"`) { | |
| 129 | 新增: t.Fatal(code, output.String()) | |
| 130 | 新增: } | |
| 131 | 新增:} | |
| @@ -4,6 +4,8 @@ import { promisify } from "node:util"; | ||
| 4 | 4 | const runFile = promisify(execFile); |
| 5 | 5 | import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs"; |
| 6 | 6 | import http from "node:http"; |
| 7 | 新增:import { auditBrowser } from "./browser-audit.mjs"; | |
| 8 | 新增:import { DownloadManager } from "./browser-downloads.mjs"; | |
| 7 | 9 | import { timingSafeEqual } from "node:crypto"; |
| 8 | 10 | |
| 9 | 11 | const config = JSON.parse( |
| @@ -33,6 +35,9 @@ mkdirSync(downloadPath, { recursive: true }); | ||
| 33 | 35 | const flags = [ |
| 34 | 36 | "--user-data-dir=/home/cage-browser/profile", |
| 35 | 37 | "--remote-debugging-pipe", |
| 38 | 新增: // The pipe manages tabs for a human-operated browser. Keep it private while | |
| 39 | 新增: // preventing its presence alone from enabling Blink's automation marker. | |
| 40 | 新增: "--disable-blink-features=AutomationControlled", | |
| 36 | 41 | "--kiosk", |
| 37 | 42 | "--no-first-run", |
| 38 | 43 | "--restore-last-session", |
| @@ -57,8 +62,21 @@ const events = new Set(); | ||
| 57 | 62 | const auditContexts = new Set(); |
| 58 | 63 | const pending = new Map(), |
| 59 | 64 | targets = new Map(), |
| 60 | 删除: sessions = new Map(), | |
| 61 | 删除: downloads = new Map(); | |
| 65 | 新增: sessions = new Map(); | |
| 66 | 新增:const downloads = new DownloadManager({ | |
| 67 | 新增: directory: "/home/cage-browser", | |
| 68 | 新增: changed: () => broadcastState(), | |
| 69 | 新增: cancel: id => cdp("Browser.cancelDownload", { guid: id }), | |
| 70 | 新增: save: async (id, name) => { | |
| 71 | 新增: let output; | |
| 72 | 新增: try { | |
| 73 | 新增: output = (await runFile("/usr/bin/sudo", ["/usr/local/bin/cage-save-download", id, name], { maxBuffer: 16384 })).stdout; | |
| 74 | 新增: } catch (error) { | |
| 75 | 新增: output = error.stdout || '{"ok":false,"error":"下载保存未完成,请检查共享目录后重试。"}'; | |
| 76 | 新增: } | |
| 77 | 新增: return JSON.parse(output); | |
| 78 | 新增: }, | |
| 79 | 新增:}); | |
| 62 | 80 | function cdp(method, params = {}, sessionId, timeout = 4500) { |
| 63 | 81 | return new Promise((resolve, reject) => { |
| 64 | 82 | const id = ++sequence; |
| @@ -126,20 +144,8 @@ chrome.stdio[4].on("data", (chunk) => { | ||
| 126 | 144 | } |
| 127 | 145 | } |
| 128 | 146 | if (event.method === "Browser.downloadWillBegin") |
| 129 | 删除: downloads.set(p.guid, p.suggestedFilename); | |
| 130 | 删除: if ( | |
| 131 | 删除: event.method === "Browser.downloadProgress" && | |
| 132 | 删除: p.state === "completed" | |
| 133 | 删除: ) { | |
| 134 | 删除: const filename = downloads.get(p.guid); | |
| 135 | 删除: downloads.delete(p.guid); | |
| 136 | 删除: if (filename) | |
| 137 | 删除: spawn( | |
| 138 | 删除: "/usr/bin/sudo", | |
| 139 | 删除: ["/usr/local/bin/cage-save-download", p.guid, filename], | |
| 140 | 删除: { stdio: "ignore" }, | |
| 141 | 删除: ); | |
| 142 | 删除: } | |
| 147 | 新增: downloads.begin(p.guid, p.suggestedFilename); | |
| 148 | 新增: if (event.method === "Browser.downloadProgress") downloads.progress(p); | |
| 143 | 149 | } |
| 144 | 150 | }); |
| 145 | 151 | chrome.on("exit", () => { |
| @@ -198,13 +204,13 @@ async function newTab(url = homeURL) { | ||
| 198 | 204 | await activate(targetId, true); |
| 199 | 205 | return { id: targetId }; |
| 200 | 206 | } |
| 201 | 删除:async function editor(workspace = config.workspace) { | |
| 207 | 新增:async function editor(workspace = config.workspace, reload = false) { | |
| 202 | 208 | if (typeof workspace !== "string" || !workspace.startsWith("/")) throw new Error("Invalid workspace"); |
| 203 | 209 | const editorURL = `http://127.0.0.1:18080/?folder=${encodeURIComponent(workspace)}`; |
| 204 | 210 | const existing = [...targets.values()].find((t) => |
| 205 | 211 | t.url === editorURL, |
| 206 | 212 | ); |
| 207 | 删除: if (existing) { | |
| 213 | 新增: if (existing && !reload) { | |
| 208 | 214 | await activate(existing.targetId); |
| 209 | 215 | return { id: existing.targetId }; |
| 210 | 216 | } |
| @@ -213,6 +219,7 @@ async function editor(workspace = config.workspace) { | ||
| 213 | 219 | redirect: "manual", |
| 214 | 220 | headers: { "Content-Type": "application/x-www-form-urlencoded" }, |
| 215 | 221 | body: new URLSearchParams({ password: config.editorPassword }), |
| 222 | 新增: signal: AbortSignal.timeout(5000), | |
| 216 | 223 | }); |
| 217 | 224 | const cookies = response.headers.getSetCookie().map((raw) => { |
| 218 | 225 | const first = raw.split(";")[0], |
| @@ -228,8 +235,25 @@ async function editor(workspace = config.workspace) { | ||
| 228 | 235 | }); |
| 229 | 236 | if (!cookies.length) throw new Error("Editor authentication is unavailable"); |
| 230 | 237 | await cdp("Storage.setCookies", { cookies }); |
| 238 | 新增: if (existing) { | |
| 239 | 新增: await activate(existing.targetId); | |
| 240 | 新增: await cdp("Page.reload", {}, await session(existing.targetId)); | |
| 241 | 新增: return { id: existing.targetId }; | |
| 242 | 新增: } | |
| 231 | 243 | return newTab(editorURL); |
| 232 | 244 | } |
| 245 | 新增:async function restartEditor(workspace) { | |
| 246 | 新增: await runFile("/usr/bin/sudo", ["/usr/bin/systemctl", "restart", "cage-editor.service"], { timeout: 18000, maxBuffer: 4096 }); | |
| 247 | 新增: const deadline = Date.now() + 5000; | |
| 248 | 新增: while (Date.now() < deadline) { | |
| 249 | 新增: try { | |
| 250 | 新增: const response = await fetch("http://127.0.0.1:18080/healthz", { signal: AbortSignal.timeout(1000) }); | |
| 251 | 新增: if (response.ok) return editor(workspace || config.workspace, true); | |
| 252 | 新增: } catch {} | |
| 253 | 新增: await new Promise(resolve => setTimeout(resolve, 200)); | |
| 254 | 新增: } | |
| 255 | 新增: throw new Error("编辑器尚未恢复,请稍后重试。"); | |
| 256 | 新增:} | |
| 233 | 257 | async function tabState() { |
| 234 | 258 | const { targetInfos } = await cdp("Target.getTargets"); |
| 235 | 259 | for (const tab of targetInfos) |
| @@ -268,6 +292,7 @@ function displayTitle(tab) { | ||
| 268 | 292 | function publicState() { |
| 269 | 293 | return { |
| 270 | 294 | active: activeId, |
| 295 | 新增: downloads: downloads.snapshot(), | |
| 271 | 296 | tabs: [...targets.values()].map((t) => ({ |
| 272 | 297 | id: t.targetId, |
| 273 | 298 | title: displayTitle(t), |
| @@ -335,53 +360,6 @@ function mutate(fn) { | ||
| 335 | 360 | mutations = result.catch(() => {}); |
| 336 | 361 | return result; |
| 337 | 362 | } |
| 338 | 删除:// A hidden, disposable context avoids touching account tabs, browser cookies, | |
| 339 | 删除:// focus or the visible tab strip while reading Chromium's actual settings. | |
| 340 | 删除:async function auditBrowser(network, expectedTimezone) { | |
| 341 | 删除: const { browserContextId } = await cdp("Target.createBrowserContext", { disposeOnDetach: true }); | |
| 342 | 删除: auditContexts.add(browserContextId); | |
| 343 | 删除: try { | |
| 344 | 删除: const { targetId } = await cdp("Target.createTarget", { | |
| 345 | 删除: url: "about:blank", browserContextId, background: true, hidden: true, | |
| 346 | 删除: }); | |
| 347 | 删除: const { sessionId } = await cdp("Target.attachToTarget", { targetId, flatten: true }); | |
| 348 | 删除: if (network) { | |
| 349 | 删除: const navigation = await cdp("Page.navigate", { url: "http://198.18.0.254/" }, sessionId, 15000); | |
| 350 | 删除: if (navigation.errorText) throw new Error("诊断页面无法连接"); | |
| 351 | 删除: let loaded = false; | |
| 352 | 删除: const deadline = Date.now() + 3000; | |
| 353 | 删除: while (Date.now() < deadline) { | |
| 354 | 删除: try { | |
| 355 | 删除: const state = await cdp("Runtime.evaluate", { expression: "location.hostname === '198.18.0.254' && document.readyState === 'complete'", returnByValue: true }, sessionId, 500); | |
| 356 | 删除: if (state.result?.value === true) { loaded = true; break; } | |
| 357 | 删除: } catch { /* A navigation may replace the initial execution context. */ } | |
| 358 | 删除: await new Promise((resolve) => setTimeout(resolve, 25)); | |
| 359 | 删除: } | |
| 360 | 删除: if (!loaded) throw new Error("诊断页面尚未就绪"); | |
| 361 | 删除: } | |
| 362 | 删除: const expression = `(async () => { | |
| 363 | 删除: const result = {timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, | |
| 364 | 删除: expected_timezone: new Intl.DateTimeFormat('en', {timeZone:${JSON.stringify(expectedTimezone)}}).resolvedOptions().timeZone, | |
| 365 | 删除: language: navigator.language, languages: [...navigator.languages], platform: navigator.platform}; | |
| 366 | 删除: if (${network ? "true" : "false"}) { | |
| 367 | 删除: if (location.hostname !== '198.18.0.254') throw new Error('diagnostic navigation incomplete'); | |
| 368 | 删除: try { | |
| 369 | 删除: const response = await fetch('/egress', {cache:'no-store', credentials:'omit', signal:AbortSignal.timeout(14000)}); | |
| 370 | 删除: result.network = {status:response.status, ...await response.json()}; | |
| 371 | 删除: } catch { result.network = {status:0, error:'probe_unavailable'}; } | |
| 372 | 删除: } | |
| 373 | 删除: return result; | |
| 374 | 删除: })()`; | |
| 375 | 删除: const response = await cdp("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }, sessionId, 16000); | |
| 376 | 删除: if (response.exceptionDetails || !response.result?.value) throw new Error("浏览器诊断未完成"); | |
| 377 | 删除: return response.result.value; | |
| 378 | 删除: } finally { | |
| 379 | 删除: try { | |
| 380 | 删除: await cdp("Target.disposeBrowserContext", { browserContextId }); | |
| 381 | 删除: auditContexts.delete(browserContextId); | |
| 382 | 删除: } catch { /* Keep an unclosed diagnostic context out of the user tab list. */ } | |
| 383 | 删除: } | |
| 384 | 删除:} | |
| 385 | 363 | |
| 386 | 364 | const server = http.createServer(async (req, res) => { |
| 387 | 365 | res.setHeader("Cache-Control", "no-store"); |
| @@ -428,9 +406,13 @@ const server = http.createServer(async (req, res) => { | ||
| 428 | 406 | if (text.length > 65536) throw new Error("Request too large"); |
| 429 | 407 | } |
| 430 | 408 | const input = JSON.parse(text || "{}"); |
| 409 | 新增: if (req.url === "/download-retry") { | |
| 410 | 新增: res.end(JSON.stringify(downloads.retry(input.id))); | |
| 411 | 新增: return; | |
| 412 | 新增: } | |
| 431 | 413 | if (req.url === "/audit") { |
| 432 | 414 | if (typeof input.timezone !== "string" || input.timezone.length > 128) throw new Error("诊断时区无效"); |
| 433 | 删除: res.end(JSON.stringify(await auditBrowser(input.network === true, input.timezone))); | |
| 415 | 新增: res.end(JSON.stringify(await auditBrowser(cdp, auditContexts, input.network === true, input.timezone))); | |
| 434 | 416 | return; |
| 435 | 417 | } |
| 436 | 418 | const result = await mutate(async () => { |
| @@ -451,9 +433,16 @@ const server = http.createServer(async (req, res) => { | ||
| 451 | 433 | return resizeDisplay(input.width, input.height); |
| 452 | 434 | if (req.url === "/new") return newTab(input.url || undefined); |
| 453 | 435 | if (req.url === "/editor") return editor(input.workspace || config.workspace); |
| 436 | 新增: if (req.url === "/editor-restart") return restartEditor(input.workspace); | |
| 454 | 437 | const id = input.id || activeId; |
| 455 | 438 | if (!targets.has(id)) throw new Error("Tab no longer exists"); |
| 456 | 439 | switch (req.url) { |
| 440 | 新增: case "/insert-text": | |
| 441 | 新增: if (input.id !== activeId || typeof input.text !== "string" || | |
| 442 | 新增: !input.text || Buffer.byteLength(input.text, "utf8") > 8192) | |
| 443 | 新增: throw new Error("Input target or text is invalid"); | |
| 444 | 新增: await cdp("Input.insertText", { text: input.text }, await session(id)); | |
| 445 | 新增: break; | |
| 457 | 446 | case "/activate": |
| 458 | 447 | await activate(id); |
| 459 | 448 | break; |
| @@ -0,0 +1,93 @@ | ||
| 1 | 新增:// A hidden, disposable context avoids touching account tabs, browser cookies, | |
| 2 | 新增:// focus or the visible tab strip while reading Chromium's actual settings. | |
| 3 | 新增:export async function auditBrowser( | |
| 4 | 新增: cdp, | |
| 5 | 新增: auditContexts, | |
| 6 | 新增: network, | |
| 7 | 新增: expectedTimezone, | |
| 8 | 新增:) { | |
| 9 | 新增: const { browserContextId } = await cdp("Target.createBrowserContext", { | |
| 10 | 新增: disposeOnDetach: true, | |
| 11 | 新增: }); | |
| 12 | 新增: auditContexts.add(browserContextId); | |
| 13 | 新增: let targetId; | |
| 14 | 新增: try { | |
| 15 | 新增: ({ targetId } = await cdp("Target.createTarget", { | |
| 16 | 新增: url: "about:blank", | |
| 17 | 新增: browserContextId, | |
| 18 | 新增: background: true, | |
| 19 | 新增: hidden: true, | |
| 20 | 新增: })); | |
| 21 | 新增: const { sessionId } = await cdp("Target.attachToTarget", { | |
| 22 | 新增: targetId, | |
| 23 | 新增: flatten: true, | |
| 24 | 新增: }); | |
| 25 | 新增: if (network) { | |
| 26 | 新增: const navigation = await cdp( | |
| 27 | 新增: "Page.navigate", | |
| 28 | 新增: { url: "http://198.18.0.254/" }, | |
| 29 | 新增: sessionId, | |
| 30 | 新增: 15000, | |
| 31 | 新增: ); | |
| 32 | 新增: if (navigation.errorText) throw new Error("诊断页面无法连接"); | |
| 33 | 新增: let loaded = false; | |
| 34 | 新增: const deadline = Date.now() + 3000; | |
| 35 | 新增: while (Date.now() < deadline) { | |
| 36 | 新增: try { | |
| 37 | 新增: const state = await cdp( | |
| 38 | 新增: "Runtime.evaluate", | |
| 39 | 新增: { | |
| 40 | 新增: expression: | |
| 41 | 新增: "location.hostname === '198.18.0.254' && document.readyState === 'complete'", | |
| 42 | 新增: returnByValue: true, | |
| 43 | 新增: }, | |
| 44 | 新增: sessionId, | |
| 45 | 新增: 500, | |
| 46 | 新增: ); | |
| 47 | 新增: if (state.result?.value === true) { | |
| 48 | 新增: loaded = true; | |
| 49 | 新增: break; | |
| 50 | 新增: } | |
| 51 | 新增: } catch { | |
| 52 | 新增: /* A navigation may replace the initial execution context. */ | |
| 53 | 新增: } | |
| 54 | 新增: await new Promise((resolve) => setTimeout(resolve, 25)); | |
| 55 | 新增: } | |
| 56 | 新增: if (!loaded) throw new Error("诊断页面尚未就绪"); | |
| 57 | 新增: } | |
| 58 | 新增: const expression = `(async () => { | |
| 59 | 新增: const result = {timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, | |
| 60 | 新增: expected_timezone: new Intl.DateTimeFormat('en', {timeZone:${JSON.stringify(expectedTimezone)}}).resolvedOptions().timeZone, | |
| 61 | 新增: language: navigator.language, languages: [...navigator.languages], platform: navigator.platform}; | |
| 62 | 新增: if (${network ? "true" : "false"}) { | |
| 63 | 新增: if (location.hostname !== '198.18.0.254') throw new Error('diagnostic navigation incomplete'); | |
| 64 | 新增: try { | |
| 65 | 新增: const response = await fetch('/egress', {cache:'no-store', credentials:'omit', signal:AbortSignal.timeout(14000)}); | |
| 66 | 新增: result.network = {status:response.status, ...await response.json()}; | |
| 67 | 新增: } catch { result.network = {status:0, error:'probe_unavailable'}; } | |
| 68 | 新增: } | |
| 69 | 新增: return result; | |
| 70 | 新增: })()`; | |
| 71 | 新增: const response = await cdp( | |
| 72 | 新增: "Runtime.evaluate", | |
| 73 | 新增: { expression, awaitPromise: true, returnByValue: true }, | |
| 74 | 新增: sessionId, | |
| 75 | 新增: 16000, | |
| 76 | 新增: ); | |
| 77 | 新增: if (response.exceptionDetails || !response.result?.value) | |
| 78 | 新增: throw new Error("浏览器诊断未完成"); | |
| 79 | 新增: return response.result.value; | |
| 80 | 新增: } finally { | |
| 81 | 新增: try { | |
| 82 | 新增: // Hidden targets are owned by the CDP connection, not the context's tab | |
| 83 | 新增: // windows. Chromium 156 crashes after its 60s disposal timeout if a | |
| 84 | 新增: // hidden page still references the context. Close it before disposal. | |
| 85 | 新增: if (targetId) await cdp("Target.closeTarget", { targetId }); | |
| 86 | 新增: await cdp("Target.disposeBrowserContext", { browserContextId }); | |
| 87 | 新增: auditContexts.delete(browserContextId); | |
| 88 | 新增: } catch { | |
| 89 | 新增: // If closing the page fails, leave its context alive and excluded from | |
| 90 | 新增: // user tabs. Disposing it anyway would recreate the browser crash. | |
| 91 | 新增: } | |
| 92 | 新增: } | |
| 93 | 新增:} | |
| @@ -0,0 +1,91 @@ | ||
| 1 | 新增:import test from "node:test"; | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import { auditBrowser } from "./browser-audit.mjs"; | |
| 4 | 新增: | |
| 5 | 新增:function browser(failMethod) { | |
| 6 | 新增: const contexts = new Set(); | |
| 7 | 新增: const excluded = new Set(); | |
| 8 | 新增: const pages = new Map(); | |
| 9 | 新增: let unsafeDisposal = false; | |
| 10 | 新增: const observation = { timezone: "UTC", language: "en-US", platform: "Linux" }; | |
| 11 | 新增: const cdp = async (method, params) => { | |
| 12 | 新增: if (method === failMethod) throw new Error("injected failure"); | |
| 13 | 新增: switch (method) { | |
| 14 | 新增: case "Target.createBrowserContext": | |
| 15 | 新增: contexts.add("audit-context"); | |
| 16 | 新增: return { browserContextId: "audit-context" }; | |
| 17 | 新增: case "Target.createTarget": | |
| 18 | 新增: assert.equal(params.hidden, true); | |
| 19 | 新增: assert.ok(excluded.has(params.browserContextId)); | |
| 20 | 新增: pages.set("audit-page", params.browserContextId); | |
| 21 | 新增: return { targetId: "audit-page" }; | |
| 22 | 新增: case "Target.attachToTarget": | |
| 23 | 新增: return { sessionId: "audit-session" }; | |
| 24 | 新增: case "Runtime.evaluate": | |
| 25 | 新增: return { result: { value: observation } }; | |
| 26 | 新增: case "Target.closeTarget": | |
| 27 | 新增: // Disposal must await the close, not merely send both commands. | |
| 28 | 新增: await new Promise((resolve) => setImmediate(resolve)); | |
| 29 | 新增: pages.delete(params.targetId); | |
| 30 | 新增: return { success: true }; | |
| 31 | 新增: case "Target.disposeBrowserContext": | |
| 32 | 新增: if ([...pages.values()].includes(params.browserContextId)) { | |
| 33 | 新增: unsafeDisposal = true; | |
| 34 | 新增: throw new Error("live hidden page references this context"); | |
| 35 | 新增: } | |
| 36 | 新增: contexts.delete(params.browserContextId); | |
| 37 | 新增: return {}; | |
| 38 | 新增: default: | |
| 39 | 新增: throw new Error(`Unexpected command: ${method}`); | |
| 40 | 新增: } | |
| 41 | 新增: }; | |
| 42 | 新增: return { | |
| 43 | 新增: cdp, | |
| 44 | 新增: excluded, | |
| 45 | 新增: contexts, | |
| 46 | 新增: pages, | |
| 47 | 新增: observation, | |
| 48 | 新增: unsafe: () => unsafeDisposal, | |
| 49 | 新增: }; | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 52 | 新增:test("successful audits close their hidden pages before disposing contexts", async () => { | |
| 53 | 新增: const b = browser(); | |
| 54 | 新增: for (let i = 0; i < 3; i++) { | |
| 55 | 新增: assert.deepEqual( | |
| 56 | 新增: await auditBrowser(b.cdp, b.excluded, false, "UTC"), | |
| 57 | 新增: b.observation, | |
| 58 | 新增: ); | |
| 59 | 新增: assert.equal(b.unsafe(), false); | |
| 60 | 新增: assert.equal(b.pages.size, 0); | |
| 61 | 新增: assert.equal(b.contexts.size, 0); | |
| 62 | 新增: assert.equal(b.excluded.size, 0); | |
| 63 | 新增: } | |
| 64 | 新增:}); | |
| 65 | 新增: | |
| 66 | 新增:for (const method of [ | |
| 67 | 新增: "Target.createTarget", | |
| 68 | 新增: "Target.attachToTarget", | |
| 69 | 新增: "Runtime.evaluate", | |
| 70 | 新增:]) { | |
| 71 | 新增: test(`${method} failure still releases the audit resources safely`, async () => { | |
| 72 | 新增: const b = browser(method); | |
| 73 | 新增: await assert.rejects( | |
| 74 | 新增: auditBrowser(b.cdp, b.excluded, false, "UTC"), | |
| 75 | 新增: /injected failure/, | |
| 76 | 新增: ); | |
| 77 | 新增: assert.equal(b.unsafe(), false); | |
| 78 | 新增: assert.equal(b.pages.size, 0); | |
| 79 | 新增: assert.equal(b.contexts.size, 0); | |
| 80 | 新增: assert.equal(b.excluded.size, 0); | |
| 81 | 新增: }); | |
| 82 | 新增:} | |
| 83 | 新增: | |
| 84 | 新增:test("a failed page close preserves its context and keeps it out of user tabs", async () => { | |
| 85 | 新增: const b = browser("Target.closeTarget"); | |
| 86 | 新增: await auditBrowser(b.cdp, b.excluded, false, "UTC"); | |
| 87 | 新增: assert.equal(b.unsafe(), false); | |
| 88 | 新增: assert.equal(b.pages.size, 1); | |
| 89 | 新增: assert.equal(b.contexts.size, 1); | |
| 90 | 新增: assert.equal(b.excluded.size, 1); | |
| 91 | 新增:}); | |
| @@ -0,0 +1,188 @@ | ||
| 1 | 新增:import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; | |
| 2 | 新增:import { randomUUID } from "node:crypto"; | |
| 3 | 新增:import { basename, join } from "node:path"; | |
| 4 | 新增: | |
| 5 | 新增:const historyLimit = 50; | |
| 6 | 新增:const activeLimit = 50; | |
| 7 | 新增:const guidPattern = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i; | |
| 8 | 新增:const terminalStates = new Set(["saved", "failed", "canceled"]); | |
| 9 | 新增: | |
| 10 | 新增:export class DownloadManager { | |
| 11 | 新增: constructor({ directory, save, changed = () => {}, cancel = () => {} }) { | |
| 12 | 新增: this.directory = directory; | |
| 13 | 新增: this.manifest = join(directory, "download-state.json"); | |
| 14 | 新增: this.save = save; | |
| 15 | 新增: this.changed = changed; | |
| 16 | 新增: this.cancel = cancel; | |
| 17 | 新增: this.records = new Map(); | |
| 18 | 新增: this.queue = Promise.resolve(); | |
| 19 | 新增: this.lastProgress = 0; | |
| 20 | 新增: mkdirSync(join(directory, "Downloads"), { recursive: true }); | |
| 21 | 新增: this.restore(); | |
| 22 | 新增: } | |
| 23 | 新增: | |
| 24 | 新增: sourceExists(id) { | |
| 25 | 新增: try { | |
| 26 | 新增: return guidPattern.test(id) && lstatSync(join(this.directory, "Downloads", id)).isFile(); | |
| 27 | 新增: } catch { return false; } | |
| 28 | 新增: } | |
| 29 | 新增: | |
| 30 | 新增: restore() { | |
| 31 | 新增: try { | |
| 32 | 新增: if (!existsSync(this.manifest)) return; | |
| 33 | 新增: const fd = openSync(this.manifest, "r"); | |
| 34 | 新增: let data; | |
| 35 | 新增: try { | |
| 36 | 新增: const buffer = Buffer.alloc((1 << 20) + 1); | |
| 37 | 新增: let size = 0, n; | |
| 38 | 新增: while (size < buffer.length && (n = readSync(fd, buffer, size, buffer.length - size, null)) > 0) size += n; | |
| 39 | 新增: if (size > 1 << 20) throw new Error("Download manifest too large"); | |
| 40 | 新增: data = buffer.subarray(0, size); | |
| 41 | 新增: } finally { closeSync(fd); } | |
| 42 | 新增: const records = JSON.parse(data); | |
| 43 | 新增: if (!Array.isArray(records) || records.length > activeLimit + historyLimit) throw new Error("Invalid download manifest"); | |
| 44 | 新增: for (const item of records) { | |
| 45 | 新增: if (!guidPattern.test(item.id) || typeof item.name !== "string" || item.name.length > 1024 || basename(item.name) !== item.name) continue; | |
| 46 | 新增: const record = { id: item.id, name: item.name, state: item.state, | |
| 47 | 新增: receivedBytes: Number(item.receivedBytes) || 0, totalBytes: Number(item.totalBytes) || 0, | |
| 48 | 新增: updatedAt: item.updatedAt, sourceReady: item.sourceReady === true, | |
| 49 | 新增: ...(typeof item.path === "string" && item.path.length < 8192 ? { path: item.path } : {}), | |
| 50 | 新增: ...(typeof item.error === "string" ? { error: item.error.slice(0, 300) } : {}) }; | |
| 51 | 新增: if (record.state === "downloading") { | |
| 52 | 新增: record.state = "failed"; | |
| 53 | 新增: record.sourceReady = false; | |
| 54 | 新增: record.error = "下载被中断,请从原网页重新下载。"; | |
| 55 | 新增: } else if (record.state === "saving") { | |
| 56 | 新增: record.state = "failed"; | |
| 57 | 新增: record.error = "保存过程被中断。源文件仍在时可以重试;否则请检查 Downloads 中的文件。"; | |
| 58 | 新增: } | |
| 59 | 新增: if (!terminalStates.has(record.state)) continue; | |
| 60 | 新增: record.retryable = record.state === "failed" && record.sourceReady && this.sourceExists(record.id); | |
| 61 | 新增: this.records.set(record.id, record); | |
| 62 | 新增: } | |
| 63 | 新增: this.persist(); | |
| 64 | 新增: } catch { | |
| 65 | 新增: // Do not trust or expose arbitrary content from a damaged manifest. | |
| 66 | 新增: this.records.clear(); | |
| 67 | 新增: } | |
| 68 | 新增: } | |
| 69 | 新增: | |
| 70 | 新增: prune() { | |
| 71 | 新增: const finished = [...this.records.values()].filter(r => terminalStates.has(r.state)); | |
| 72 | 新增: for (const record of finished.slice(0, Math.max(0, finished.length - historyLimit))) this.records.delete(record.id); | |
| 73 | 新增: } | |
| 74 | 新增: | |
| 75 | 新增: persist() { | |
| 76 | 新增: this.prune(); | |
| 77 | 新增: const temporary = this.manifest + "." + randomUUID() + ".tmp"; | |
| 78 | 新增: let fd; | |
| 79 | 新增: try { | |
| 80 | 新增: fd = openSync(temporary, "wx", 0o600); | |
| 81 | 新增: writeFileSync(fd, JSON.stringify([...this.records.values()])); | |
| 82 | 新增: fsyncSync(fd); | |
| 83 | 新增: closeSync(fd); | |
| 84 | 新增: fd = undefined; | |
| 85 | 新增: renameSync(temporary, this.manifest); | |
| 86 | 新增: return true; | |
| 87 | 新增: } catch { | |
| 88 | 新增: if (fd !== undefined) closeSync(fd); | |
| 89 | 新增: try { unlinkSync(temporary); } catch {} | |
| 90 | 新增: return false; | |
| 91 | 新增: } | |
| 92 | 新增: } | |
| 93 | 新增: | |
| 94 | 新增: publish(record, persist = true) { | |
| 95 | 新增: record.updatedAt = new Date().toISOString(); | |
| 96 | 新增: const saved = !persist || this.persist(); | |
| 97 | 新增: if (!saved) { | |
| 98 | 新增: record.error = "无法保存下载记录,请检查客机可用空间。"; | |
| 99 | 新增: } | |
| 100 | 新增: this.changed(); | |
| 101 | 新增: return saved; | |
| 102 | 新增: } | |
| 103 | 新增: | |
| 104 | 新增: begin(id, name) { | |
| 105 | 新增: if (!guidPattern.test(id) || typeof name !== "string" || !name || name.length > 1024 || basename(name) !== name) return; | |
| 106 | 新增: const active = [...this.records.values()].filter(r => !terminalStates.has(r.state)).length; | |
| 107 | 新增: const record = { id, name, state: "downloading", receivedBytes: 0, totalBytes: 0, retryable: false, sourceReady: false }; | |
| 108 | 新增: if (active >= activeLimit) { | |
| 109 | 新增: record.state = "canceled"; | |
| 110 | 新增: record.error = "同时下载的文件过多,请等待部分下载完成后重试。"; | |
| 111 | 新增: void Promise.resolve(this.cancel(id)).catch(() => {}); | |
| 112 | 新增: } | |
| 113 | 新增: this.records.set(id, record); | |
| 114 | 新增: this.publish(record); | |
| 115 | 新增: } | |
| 116 | 新增: | |
| 117 | 新增: progress({ guid, state, receivedBytes, totalBytes }) { | |
| 118 | 新增: const record = this.records.get(guid); | |
| 119 | 新增: if (!record || record.state !== "downloading") return; | |
| 120 | 新增: record.receivedBytes = Number(receivedBytes) || 0; | |
| 121 | 新增: record.totalBytes = Number(totalBytes) || 0; | |
| 122 | 新增: if (state === "completed") { | |
| 123 | 新增: record.sourceReady = true; | |
| 124 | 新增: this.enqueue(record); | |
| 125 | 新增: } else if (state === "canceled") { | |
| 126 | 新增: record.state = "canceled"; | |
| 127 | 新增: record.error = "下载已取消,请从原网页重新下载。"; | |
| 128 | 新增: this.publish(record); | |
| 129 | 新增: } else if (Date.now() - this.lastProgress >= 500) { | |
| 130 | 新增: this.lastProgress = Date.now(); | |
| 131 | 新增: this.publish(record, false); | |
| 132 | 新增: } | |
| 133 | 新增: } | |
| 134 | 新增: | |
| 135 | 新增: retry(id) { | |
| 136 | 新增: const record = this.records.get(id); | |
| 137 | 新增: if (record?.state === "saving") return { ok: true }; | |
| 138 | 新增: if (!record || record.state !== "failed" || !record.sourceReady || !this.sourceExists(id)) { | |
| 139 | 新增: if (record) { | |
| 140 | 新增: record.retryable = false; | |
| 141 | 新增: record.error = "下载源文件已不可用,请从原网页重新下载。"; | |
| 142 | 新增: this.publish(record); | |
| 143 | 新增: } | |
| 144 | 新增: throw new Error("下载源文件已不可用,请从原网页重新下载。"); | |
| 145 | 新增: } | |
| 146 | 新增: this.enqueue(record); | |
| 147 | 新增: return { ok: true }; | |
| 148 | 新增: } | |
| 149 | 新增: | |
| 150 | 新增: enqueue(record) { | |
| 151 | 新增: if (!this.sourceExists(record.id)) { | |
| 152 | 新增: record.state = "failed"; | |
| 153 | 新增: record.retryable = false; | |
| 154 | 新增: record.error = "下载源文件不可用,请从原网页重新下载。"; | |
| 155 | 新增: this.publish(record); | |
| 156 | 新增: return; | |
| 157 | 新增: } | |
| 158 | 新增: record.state = "saving"; | |
| 159 | 新增: record.retryable = false; | |
| 160 | 新增: delete record.error; | |
| 161 | 新增: if (!this.publish(record)) { | |
| 162 | 新增: record.state = "failed"; | |
| 163 | 新增: record.retryable = true; | |
| 164 | 新增: this.changed(); | |
| 165 | 新增: return; | |
| 166 | 新增: } | |
| 167 | 新增: this.queue = this.queue.then(async () => { | |
| 168 | 新增: try { | |
| 169 | 新增: const result = await this.save(record.id, record.name); | |
| 170 | 新增: if (!result?.ok || typeof result.path !== "string") throw new Error(result?.error || "保存结果无效,请检查共享目录后重试。"); | |
| 171 | 新增: record.state = "saved"; | |
| 172 | 新增: record.path = result.path; | |
| 173 | 新增: record.name = result.name || record.name; | |
| 174 | 新增: record.receivedBytes = result.bytes ?? record.receivedBytes; | |
| 175 | 新增: if (result.warning) record.error = result.warning; | |
| 176 | 新增: } catch (error) { | |
| 177 | 新增: record.state = "failed"; | |
| 178 | 新增: record.error = String(error.message || "保存失败,请检查共享目录后重试。").slice(0, 300); | |
| 179 | 新增: record.retryable = this.sourceExists(record.id); | |
| 180 | 新增: } | |
| 181 | 新增: this.publish(record); | |
| 182 | 新增: }); | |
| 183 | 新增: } | |
| 184 | 新增: | |
| 185 | 新增: snapshot() { | |
| 186 | 新增: return [...this.records.values()].reverse().map(({ sourceReady, ...record }) => record); | |
| 187 | 新增: } | |
| 188 | 新增:} | |
| @@ -0,0 +1,79 @@ | ||
| 1 | 新增:import { test } from "node:test"; | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import { randomUUID } from "node:crypto"; | |
| 4 | 新增:import { mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs"; | |
| 5 | 新增:import { tmpdir } from "node:os"; | |
| 6 | 新增:import { join } from "node:path"; | |
| 7 | 新增:import { DownloadManager } from "./browser-downloads.mjs"; | |
| 8 | 新增: | |
| 9 | 新增:function fixture(t, save) { | |
| 10 | 新增: const directory = mkdtempSync(join(tmpdir(), "cage-download-test-")); | |
| 11 | 新增: t.after(() => rmSync(directory, { recursive: true, force: true })); | |
| 12 | 新增: const options = { directory, save }; | |
| 13 | 新增: const manager = new DownloadManager(options); | |
| 14 | 新增: const begin = (name = "report.txt") => { | |
| 15 | 新增: const id = randomUUID(); | |
| 16 | 新增: manager.begin(id, name); | |
| 17 | 新增: writeFileSync(join(directory, "Downloads", id), "complete source"); | |
| 18 | 新增: return id; | |
| 19 | 新增: }; | |
| 20 | 新增: return { directory, options, manager, begin }; | |
| 21 | 新增:} | |
| 22 | 新增: | |
| 23 | 新增:function completed(manager, id) { | |
| 24 | 新增: manager.progress({ guid: id, state: "completed", receivedBytes: 15, totalBytes: 15 }); | |
| 25 | 新增: return manager.queue; | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:test("failed saves persist and can be retried after controller restart", async t => { | |
| 29 | 新增: let attempts = 0; | |
| 30 | 新增: const f = fixture(t, async (id, name) => { | |
| 31 | 新增: if (++attempts === 1) throw new Error("共享连接暂时不可用"); | |
| 32 | 新增: unlinkSync(join(f.directory, "Downloads", id)); | |
| 33 | 新增: return { ok: true, path: `/shared/Downloads/${name}`, name, bytes: 15 }; | |
| 34 | 新增: }); | |
| 35 | 新增: const id = f.begin(); | |
| 36 | 新增: await completed(f.manager, id); | |
| 37 | 新增: assert.equal(f.manager.snapshot()[0].state, "failed"); | |
| 38 | 新增: assert.equal(f.manager.snapshot()[0].retryable, true); | |
| 39 | 新增: assert.equal(statSync(join(f.directory, "download-state.json")).mode & 0o777, 0o600); | |
| 40 | 新增: const reopened = new DownloadManager(f.options); | |
| 41 | 新增: assert.equal(reopened.snapshot()[0].id, id); | |
| 42 | 新增: assert.equal(reopened.snapshot()[0].retryable, true); | |
| 43 | 新增: assert.deepEqual(reopened.retry(id), { ok: true }); | |
| 44 | 新增: assert.deepEqual(reopened.retry(id), { ok: true }, "duplicate retry should not enqueue another copy"); | |
| 45 | 新增: await reopened.queue; | |
| 46 | 新增: assert.equal(attempts, 2); | |
| 47 | 新增: assert.equal(reopened.snapshot()[0].state, "saved"); | |
| 48 | 新增: assert.equal(reopened.snapshot()[0].path, "/shared/Downloads/report.txt"); | |
| 49 | 新增: assert.equal(new DownloadManager(f.options).snapshot()[0].state, "saved"); | |
| 50 | 新增:}); | |
| 51 | 新增: | |
| 52 | 新增:test("interrupted copies are retryable only with a complete source, interrupted downloads are not", async t => { | |
| 53 | 新增: let release; | |
| 54 | 新增: const f = fixture(t, () => new Promise(resolve => { release = resolve; })); | |
| 55 | 新增: const saving = f.begin(); | |
| 56 | 新增: completed(f.manager, saving); | |
| 57 | 新增: await Promise.resolve(); | |
| 58 | 新增: const downloading = f.begin("partial.txt"); | |
| 59 | 新增: const reopened = new DownloadManager(f.options); | |
| 60 | 新增: const records = reopened.snapshot(); | |
| 61 | 新增: assert.equal(records.find(r => r.id === saving).retryable, true); | |
| 62 | 新增: assert.equal(records.find(r => r.id === downloading).retryable, false); | |
| 63 | 新增: assert.ok(records.every(r => r.state === "failed")); | |
| 64 | 新增: unlinkSync(join(f.directory, "Downloads", saving)); | |
| 65 | 新增: assert.throws(() => reopened.retry(saving), /源文件/); | |
| 66 | 新增: release({ ok: false, error: "interrupted" }); | |
| 67 | 新增: await f.manager.queue; | |
| 68 | 新增:}); | |
| 69 | 新增: | |
| 70 | 新增:test("finished download history stays bounded without losing current transfers", async t => { | |
| 71 | 新增: const f = fixture(t, async (_id, name) => ({ ok: true, path: `/shared/Downloads/${name}`, name })); | |
| 72 | 新增: const active = f.begin("still-downloading.txt"); | |
| 73 | 新增: for (let i = 0; i < 60; i++) await completed(f.manager, f.begin(`${i}.txt`)); | |
| 74 | 新增: const records = f.manager.snapshot(); | |
| 75 | 新增: assert.equal(records.filter(r => r.state === "saved").length, 50); | |
| 76 | 新增: assert.ok(records.some(r => r.id === active && r.state === "downloading")); | |
| 77 | 新增: assert.equal(JSON.parse(readFileSync(join(f.directory, "download-state.json"))).length, 51); | |
| 78 | 新增: assert.ok(records.every(r => !("sourceReady" in r) && !("url" in r))); | |
| 79 | 新增:}); | |
| @@ -0,0 +1,67 @@ | ||
| 1 | 新增:#!/usr/bin/python3 | |
| 2 | 新增:"""Stop only the legacy Cage editor before systemd takes ownership.""" | |
| 3 | 新增:import os | |
| 4 | 新增:from pathlib import Path | |
| 5 | 新增:import pwd | |
| 6 | 新增:import select | |
| 7 | 新增:import signal | |
| 8 | 新增:import sys | |
| 9 | 新增: | |
| 10 | 新增:NODE = '/usr/lib/code-server/lib/node' | |
| 11 | 新增:ROOT = '/usr/lib/code-server' | |
| 12 | 新增:ENTRY = '/usr/lib/code-server/out/node/entry.js' | |
| 13 | 新增:CONFIG = '/home/cage/.config/claude-cage/code-server.yaml' | |
| 14 | 新增: | |
| 15 | 新增: | |
| 16 | 新增:def is_legacy_editor(argv, executable, uid, cage_uid): | |
| 17 | 新增: if uid != cage_uid or executable != str(Path(NODE).resolve()): | |
| 18 | 新增: return False | |
| 19 | 新增: if len(argv) < 2 or argv[1] not in (ROOT, ENTRY): | |
| 20 | 新增: return False | |
| 21 | 新增: def value(flag): | |
| 22 | 新增: try: | |
| 23 | 新增: return argv[argv.index(flag) + 1] | |
| 24 | 新增: except (ValueError, IndexError): | |
| 25 | 新增: return None | |
| 26 | 新增: return value('--config') == CONFIG and value('--bind-addr') == '127.0.0.1:18080' | |
| 27 | 新增: | |
| 28 | 新增: | |
| 29 | 新增:def main(): | |
| 30 | 新增: cage_uid = pwd.getpwnam('cage').pw_uid | |
| 31 | 新增: for binary in (NODE, ENTRY): | |
| 32 | 新增: st = os.stat(binary) | |
| 33 | 新增: if st.st_uid != 0 or st.st_mode & 0o022: | |
| 34 | 新增: raise RuntimeError('编辑器程序身份无法确认,未停止现有进程') | |
| 35 | 新增: if not hasattr(os, 'pidfd_open') or not hasattr(signal, 'pidfd_send_signal'): | |
| 36 | 新增: raise RuntimeError('系统不支持安全识别旧编辑器进程,未停止现有进程') | |
| 37 | 新增: for proc in Path('/proc').iterdir(): | |
| 38 | 新增: if not proc.name.isdigit(): | |
| 39 | 新增: continue | |
| 40 | 新增: handle = None | |
| 41 | 新增: try: | |
| 42 | 新增: handle = os.pidfd_open(int(proc.name)) | |
| 43 | 新增: if 'cage-editor.service' in (proc / 'cgroup').read_text(): | |
| 44 | 新增: continue | |
| 45 | 新增: argv = (proc / 'cmdline').read_bytes().decode(errors='replace').rstrip('\0').split('\0') | |
| 46 | 新增: if not is_legacy_editor(argv, os.readlink(proc / 'exe'), proc.stat().st_uid, cage_uid): | |
| 47 | 新增: continue | |
| 48 | 新增: signal.pidfd_send_signal(handle, signal.SIGTERM) | |
| 49 | 新增: exited = select.poll() | |
| 50 | 新增: exited.register(handle, select.POLLIN) | |
| 51 | 新增: if not exited.poll(5000): | |
| 52 | 新增: signal.pidfd_send_signal(handle, signal.SIGKILL) | |
| 53 | 新增: if not exited.poll(2000): | |
| 54 | 新增: raise RuntimeError('旧编辑器尚未退出,请稍后重试') | |
| 55 | 新增: except (FileNotFoundError, ProcessLookupError, PermissionError): | |
| 56 | 新增: continue | |
| 57 | 新增: finally: | |
| 58 | 新增: if handle is not None: | |
| 59 | 新增: os.close(handle) | |
| 60 | 新增: | |
| 61 | 新增: | |
| 62 | 新增:if __name__ == '__main__': | |
| 63 | 新增: try: | |
| 64 | 新增: main() | |
| 65 | 新增: except Exception as error: | |
| 66 | 新增: print(str(error), file=sys.stderr) | |
| 67 | 新增: sys.exit(1) | |
| @@ -0,0 +1,33 @@ | ||
| 1 | 新增:import importlib.util | |
| 2 | 新增:from pathlib import Path | |
| 3 | 新增:import unittest | |
| 4 | 新增:import sys | |
| 5 | 新增: | |
| 6 | 新增:sys.dont_write_bytecode = True | |
| 7 | 新增: | |
| 8 | 新增:spec = importlib.util.spec_from_file_location('editor_migrate', Path(__file__).with_name('editor-migrate.py')) | |
| 9 | 新增:helper = importlib.util.module_from_spec(spec) | |
| 10 | 新增:spec.loader.exec_module(helper) | |
| 11 | 新增: | |
| 12 | 新增: | |
| 13 | 新增:class EditorIdentityTests(unittest.TestCase): | |
| 14 | 新增: def setUp(self): | |
| 15 | 新增: self.argv = [helper.NODE, helper.ROOT, '--bind-addr', '127.0.0.1:18080', '--config', helper.CONFIG, '--disable-telemetry', '/shared/project'] | |
| 16 | 新增: self.exe = str(Path(helper.NODE).resolve()) | |
| 17 | 新增: | |
| 18 | 新增: def test_only_installed_cage_editor_identity_matches(self): | |
| 19 | 新增: self.assertTrue(helper.is_legacy_editor(self.argv, self.exe, 1000, 1000)) | |
| 20 | 新增: direct = self.argv.copy() | |
| 21 | 新增: direct[1] = helper.ENTRY | |
| 22 | 新增: self.assertTrue(helper.is_legacy_editor(direct, self.exe, 1000, 1000)) | |
| 23 | 新增: self.assertFalse(helper.is_legacy_editor(self.argv, '/home/cage/fake-node', 1000, 1000)) | |
| 24 | 新增: self.assertFalse(helper.is_legacy_editor(self.argv, self.exe, 1001, 1000)) | |
| 25 | 新增: for index, value in ((1, '/home/cage/custom.js'), (3, '127.0.0.1:18081'), (5, '/home/cage/other.yaml')): | |
| 26 | 新增: other = self.argv.copy() | |
| 27 | 新增: other[index] = value | |
| 28 | 新增: self.assertFalse(helper.is_legacy_editor(other, self.exe, 1000, 1000)) | |
| 29 | 新增: self.assertFalse(helper.is_legacy_editor(['/bin/bash', '-l'], '/bin/bash', 1000, 1000)) | |
| 30 | 新增: | |
| 31 | 新增: | |
| 32 | 新增:if __name__ == '__main__': | |
| 33 | 新增: unittest.main() | |
| @@ -20,6 +20,28 @@ NODE | ||
| 20 | 20 | SCRIPT |
| 21 | 21 | sudo chmod 0755 /usr/local/bin/cage-open |
| 22 | 22 | sudo ln -sf /usr/local/bin/cage-open /usr/local/bin/xdg-open |
| 23 | 新增:sudo tee /usr/local/bin/cage-editor-start >/dev/null <<'SCRIPT' | |
| 24 | 新增:#!/bin/sh | |
| 25 | 新增:set -eu | |
| 26 | 新增:workspace=$(cat /home/cage/.config/claude-cage/editor-workspace) | |
| 27 | 新增:exec /usr/bin/code-server --bind-addr 127.0.0.1:18080 --config /home/cage/.config/claude-cage/code-server.yaml --disable-telemetry --disable-update-check --disable-workspace-trust --disable-proxy "$workspace" | |
| 28 | 新增:SCRIPT | |
| 29 | 新增:sudo chmod 0755 /usr/local/bin/cage-editor-start | |
| 30 | 新增:sudo tee /etc/systemd/system/cage-editor.service >/dev/null <<'UNIT' | |
| 31 | 新增:[Unit] | |
| 32 | 新增:Description=Cage file editor | |
| 33 | 新增:[Service] | |
| 34 | 新增:User=cage | |
| 35 | 新增:WorkingDirectory=/home/cage | |
| 36 | 新增:Environment=HOME=/home/cage | |
| 37 | 新增:EnvironmentFile=/etc/claude-cage/environment | |
| 38 | 新增:ExecStart=/usr/local/bin/cage-editor-start | |
| 39 | 新增:Restart=on-failure | |
| 40 | 新增:RestartSec=2 | |
| 41 | 新增:TimeoutStopSec=15 | |
| 42 | 新增:UNIT | |
| 43 | 新增:printf 'cage-browser ALL=(root) NOPASSWD: /usr/bin/systemctl restart cage-editor.service\n' | sudo tee /etc/sudoers.d/cage-editor >/dev/null | |
| 44 | 新增:sudo chmod 0440 /etc/sudoers.d/cage-editor | |
| 23 | 45 | sudo tee /etc/profile.d/claude-cage.sh >/dev/null <<'SCRIPT' |
| 24 | 46 | if [ -f /etc/claude-cage/environment ]; then |
| 25 | 47 | set -a |
| @@ -71,6 +93,9 @@ User=cage-browser | ||
| 71 | 93 | Environment=DISPLAY=:77 |
| 72 | 94 | EnvironmentFile=/etc/claude-cage/environment |
| 73 | 95 | ExecStart=/usr/bin/node /usr/local/lib/cage-browser-agent.mjs |
| 96 | 新增:# Let the controller close Chromium and flush its tabs and profile before | |
| 97 | 新增:# systemd terminates any remaining child processes. | |
| 98 | 新增:KillMode=mixed | |
| 74 | 99 | Restart=on-failure |
| 75 | 100 | RestartSec=2 |
| 76 | 101 | UNIT |
| @@ -48,9 +48,11 @@ if not p.exists(): | ||
| 48 | 48 | p.parent.mkdir(parents=True, exist_ok=True) |
| 49 | 49 | shutil.copyfile('/etc/claude-cage/editor-theme.json', p) |
| 50 | 50 | PYEDITOR |
| 51 | 删除:# Start editor independently of this SSH session; credentials belong to the shared Cage VM. | |
| 52 | 删除:if ! curl --noproxy '*' -fsS http://127.0.0.1:18080/healthz >/dev/null 2>&1; then | |
| 53 | 删除: nohup code-server --bind-addr 127.0.0.1:18080 --config "$HOME/.config/claude-cage/code-server.yaml" --disable-telemetry --disable-update-check --disable-workspace-trust --disable-proxy "$PWD" > "$HOME/.config/claude-cage/editor.log" 2>&1 </dev/null & | |
| 51 | 新增:# Systemd owns the editor independently of the SSH session and restarts crashes. | |
| 52 | 新增:(umask 077; printf '%s' "$PWD" > "$HOME/.config/claude-cage/editor-workspace") | |
| 53 | 新增:if ! systemctl is-active --quiet cage-editor.service; then | |
| 54 | 新增: sudo /usr/local/bin/cage-editor-migrate | |
| 55 | 新增: sudo systemctl start cage-editor.service | |
| 54 | 56 | fi |
| 55 | 57 | for i in $(seq 1 30); do |
| 56 | 58 | if curl --noproxy '*' -fsS http://127.0.0.1:18080/healthz >/dev/null 2>&1 && curl --noproxy '*' -fsS http://127.0.0.1:16080/vnc.html >/dev/null 2>&1; then |
| @@ -0,0 +1,49 @@ | ||
| 1 | 新增:# Functions are shared by first installation and an explicit in-place upgrade. | |
| 2 | 新增:# Each invocation owns its staging files and leaves caller traps unchanged. | |
| 3 | 新增:cage_install_tool() ( | |
| 4 | 新增: set -euo pipefail | |
| 5 | 新增: local tool="$1" arch current='' wanted url checksum artifact | |
| 6 | 新增: arch="$(dpkg --print-architecture)" | |
| 7 | 新增: case "$arch" in arm64|amd64) ;; *) echo 'Cage tool packages support arm64 and amd64.' >&2; exit 1 ;; esac | |
| 8 | 新增: case "$tool" in | |
| 9 | 新增: code-server) | |
| 10 | 新增: wanted="$CAGE_CODE_SERVER_VERSION" | |
| 11 | 新增: if command -v code-server >/dev/null; then current="$(code-server --version | head -n1 | cut -d' ' -f1)"; fi | |
| 12 | 新增: url="https://github.com/coder/code-server/releases/download/v$wanted/code-server_${wanted}_${arch}.deb" | |
| 13 | 新增: if [ "$arch" = arm64 ]; then checksum="$CAGE_CODE_SERVER_ARM64_SHA256"; else checksum="$CAGE_CODE_SERVER_AMD64_SHA256"; fi | |
| 14 | 新增: artifact=code-server.deb | |
| 15 | 新增: ;; | |
| 16 | 新增: mise) | |
| 17 | 新增: wanted="$CAGE_MISE_VERSION" | |
| 18 | 新增: if [ -x "$HOME/.local/bin/mise" ]; then current="$("$HOME/.local/bin/mise" --version | head -n1 | cut -d' ' -f1)"; fi | |
| 19 | 新增: if [ "$arch" = arm64 ]; then checksum="$CAGE_MISE_ARM64_SHA256"; else checksum="$CAGE_MISE_AMD64_SHA256"; fi | |
| 20 | 新增: url="https://github.com/jdx/mise/releases/download/v$wanted/mise-v$wanted-linux-$(if [ "$arch" = arm64 ]; then echo arm64; else echo x64; fi).tar.gz" | |
| 21 | 新增: artifact=mise.tar.gz | |
| 22 | 新增: ;; | |
| 23 | 新增: claude) | |
| 24 | 新增: wanted="$CAGE_CLAUDE_VERSION" | |
| 25 | 新增: if command -v claude >/dev/null; then current="$(DISABLE_AUTOUPDATER=1 claude --version | head -n1 | cut -d' ' -f1)"; fi | |
| 26 | 新增: ;; | |
| 27 | 新增: *) echo 'Unknown Cage tool.' >&2; exit 2 ;; | |
| 28 | 新增: esac | |
| 29 | 新增: if [ -n "$current" ] && dpkg --compare-versions "${current#v}" ge "$wanted"; then | |
| 30 | 新增: printf '%s already meets required version %s.\n' "$tool" "$wanted" | |
| 31 | 新增: exit 0 | |
| 32 | 新增: fi | |
| 33 | 新增: if [ "$tool" = claude ]; then | |
| 34 | 新增: npm install --prefix "$HOME/.local" --global "@anthropic-ai/claude-code@$wanted" </dev/null | |
| 35 | 新增: exit 0 | |
| 36 | 新增: fi | |
| 37 | 新增: stage="$(mktemp -d)" | |
| 38 | 新增: trap 'rm -rf "$stage"' EXIT | |
| 39 | 新增: curl --proto '=https' --tlsv1.2 --fail --location --retry 3 --connect-timeout 15 --max-time 600 "$url" -o "$stage/$artifact" | |
| 40 | 新增: printf '%s %s\n' "$checksum" "$stage/$artifact" | sha256sum --check --status || { echo 'Tool checksum mismatch; installation refused.' >&2; exit 1; } | |
| 41 | 新增: if [ "$tool" = code-server ]; then | |
| 42 | 新增: sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$stage/$artifact" </dev/null | |
| 43 | 新增: else | |
| 44 | 新增: tar -xzf "$stage/$artifact" -C "$stage" | |
| 45 | 新增: mkdir -p "$HOME/.local/bin" | |
| 46 | 新增: install -m 0755 "$stage/mise/bin/mise" "$HOME/.local/bin/.mise-new" | |
| 47 | 新增: mv -f "$HOME/.local/bin/.mise-new" "$HOME/.local/bin/mise" | |
| 48 | 新增: fi | |
| 49 | 新增:) | |
| @@ -2,8 +2,14 @@ package cage | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "al.essio.dev/pkg/shellescape" |
| 5 | 新增: "crypto/sha256" | |
| 5 | 6 | _ "embed" |
| 7 | 新增: "encoding/json" | |
| 6 | 8 | "fmt" |
| 9 | 新增: "strings" | |
| 10 | 新增: "sync" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/version" | |
| 7 | 13 | ) |
| 8 | 14 | |
| 9 | 15 | //go:embed guest-setup.sh |
| @@ -21,11 +27,20 @@ var clipboardJS string | ||
| 21 | 27 | //go:embed browser-agent.mjs |
| 22 | 28 | var browserAgent string |
| 23 | 29 | |
| 30 | 新增://go:embed browser-audit.mjs | |
| 31 | 新增:var browserAudit string | |
| 32 | 新增: | |
| 33 | 新增://go:embed browser-downloads.mjs | |
| 34 | 新增:var browserDownloads string | |
| 35 | 新增: | |
| 36 | 新增://go:embed editor-migrate.py | |
| 37 | 新增:var editorMigrate string | |
| 38 | 新增: | |
| 24 | 39 | //go:embed save-download.py |
| 25 | 40 | var saveDownload string |
| 26 | 41 | |
| 27 | 42 | func browserServices() string { |
| 28 | 删除: return guestServices + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee /usr/share/novnc/cage-clipboard.js >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE' | |
| 43 | 新增: return guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee /usr/share/novnc/cage-clipboard.js >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE' | |
| 29 | 44 | from pathlib import Path |
| 30 | 45 | import re |
| 31 | 46 | p = Path("/usr/share/novnc/vnc.html") |
| @@ -52,10 +67,79 @@ var guestStart string | ||
| 52 | 67 | //go:embed guest-env.sh |
| 53 | 68 | var guestEnv string |
| 54 | 69 | |
| 70 | 新增://go:embed tool-versions.env | |
| 71 | 新增:var toolVersions string | |
| 72 | 新增: | |
| 73 | 新增://go:embed guest-tools.sh | |
| 74 | 新增:var guestTools string | |
| 75 | 新增: | |
| 76 | 新增:func ToolInstallPrelude() string { return toolVersions + "\n" + guestTools + "\n" } | |
| 77 | 新增: | |
| 78 | 新增:func RequiredToolVersions() map[string]string { | |
| 79 | 新增: result := map[string]string{"chromium": "Debian security repository"} | |
| 80 | 新增: for _, line := range strings.Split(toolVersions, "\n") { | |
| 81 | 新增: key, value, ok := strings.Cut(line, "=") | |
| 82 | 新增: if !ok { | |
| 83 | 新增: continue | |
| 84 | 新增: } | |
| 85 | 新增: switch key { | |
| 86 | 新增: case "CAGE_CODE_SERVER_VERSION": | |
| 87 | 新增: result["code_server"] = value | |
| 88 | 新增: case "CAGE_MISE_VERSION": | |
| 89 | 新增: result["mise"] = value | |
| 90 | 新增: case "CAGE_CLAUDE_VERSION": | |
| 91 | 新增: result["claude"] = value | |
| 92 | 新增: } | |
| 93 | 新增: } | |
| 94 | 新增: return result | |
| 95 | 新增:} | |
| 96 | 新增: | |
| 97 | 新增:func ToolsUpdateScript() string { | |
| 98 | 新增: return "set -euo pipefail\nexport PATH=\"$HOME/.local/bin:$PATH\"\n" + ToolInstallPrelude() + ` | |
| 99 | 新增:sudo env DEBIAN_FRONTEND=noninteractive dpkg --configure -a </dev/null | |
| 100 | 新增:sudo env DEBIAN_FRONTEND=noninteractive apt-get update </dev/null | |
| 101 | 新增:sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --only-upgrade chromium </dev/null | |
| 102 | 新增:cage_install_tool mise | |
| 103 | 新增:cage_install_tool code-server | |
| 104 | 新增:cage_install_tool claude | |
| 105 | 新增:printf 'Cage tool packages are ready; applying browser and editor components.\n' | |
| 106 | 新增:` | |
| 107 | 新增:} | |
| 108 | 新增: | |
| 55 | 109 | func (c Config) EnvironmentScript() string { |
| 56 | 110 | return fmt.Sprintf("export CAGE_TZ=%s\nexport CAGE_LOCALE=%s\nexport CAGE_LANGUAGE=%s\n", shellescape.Quote(c.Timezone), shellescape.Quote(c.Locale), shellescape.Quote(c.BrowserLanguage)) + guestEnv |
| 57 | 111 | } |
| 58 | 112 | |
| 59 | 113 | func (c Config) StartScript() string { |
| 60 | 删除: return c.EnvironmentScript() + "\n" + browserServices() + "\nsudo tee /etc/claude-cage/editor-theme.json >/dev/null <<'CAGE_EDITOR_THEME'\n" + editorTheme + "\nCAGE_EDITOR_THEME\n" + guestStart | |
| 114 | 新增: body := c.EnvironmentScript() + "\n" + componentStartScript() | |
| 115 | 新增: return markGuestStart(body) | |
| 116 | 新增:} | |
| 117 | 新增: | |
| 118 | 新增:func componentStartScript() string { | |
| 119 | 新增: return browserServices() + "\nsudo tee /etc/claude-cage/editor-theme.json >/dev/null <<'CAGE_EDITOR_THEME'\n" + editorTheme + "\nCAGE_EDITOR_THEME\nif systemctl is-active --quiet cage-editor.service; then sudo systemctl stop cage-editor.service; fi\n" + guestStart | |
| 120 | 新增:} | |
| 121 | 新增: | |
| 122 | 新增:func markGuestStart(body string) string { | |
| 123 | 新增: manifest, _ := json.Marshal(RequiredGuestManifest()) | |
| 124 | 新增: return "set -euo pipefail\nsudo rm -f /etc/claude-cage/components.json\n(\n" + body + "\n)\nsudo python3 - <<'CAGE_COMPONENT_MANIFEST'\nfrom pathlib import Path\nimport os,tempfile\np=Path('/etc/claude-cage/components.json')\nfd,name=tempfile.mkstemp(prefix='.components-',dir=p.parent)\nwith os.fdopen(fd,'w') as f:\n f.write(" + fmt.Sprintf("%q", string(manifest)) + ")\n f.flush();os.fsync(f.fileno())\nos.chmod(name,0o644)\nos.replace(name,p)\nCAGE_COMPONENT_MANIFEST\n" | |
| 125 | 新增:} | |
| 126 | 新增: | |
| 127 | 新增:type GuestManifest struct { | |
| 128 | 新增: Protocol int `json:"protocol"` | |
| 129 | 新增: Revision string `json:"revision"` | |
| 130 | 新增: AppVersion string `json:"app_version"` | |
| 131 | 新增:} | |
| 132 | 新增: | |
| 133 | 新增:var guestRevision = sync.OnceValue(func() string { | |
| 134 | 新增: payload := strings.Join([]string{"cage-guest-protocol-1", guestDependencies, guestEnv, componentStartScript(), ToolInstallPrelude()}, "\x00") | |
| 135 | 新增: return fmt.Sprintf("%x", sha256.Sum256([]byte(payload))) | |
| 136 | 新增:}) | |
| 137 | 新增: | |
| 138 | 新增:func RequiredGuestManifest() GuestManifest { | |
| 139 | 新增: return GuestManifest{Protocol: 1, Revision: guestRevision(), AppVersion: version.Version} | |
| 140 | 新增:} | |
| 141 | 新增: | |
| 142 | 新增:func (m GuestManifest) Current() bool { | |
| 143 | 新增: required := RequiredGuestManifest() | |
| 144 | 新增: return m.Protocol == required.Protocol && m.Revision == required.Revision | |
| 61 | 145 | } |
| @@ -0,0 +1,81 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "os/exec" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestGuestManifestIsPublishedOnlyAfterSuccessfulServiceStart(t *testing.T) { | |
| 12 | 新增: for _, body := range []string{"printf started; exit 0", "printf broken; exit 7"} { | |
| 13 | 新增: t.Run(body, func(t *testing.T) { | |
| 14 | 新增: dir := t.TempDir() | |
| 15 | 新增: marker := filepath.Join(dir, "published") | |
| 16 | 新增: // Observe privileged actions without touching the host's /etc or running services. | |
| 17 | 新增: sudo := `#!/bin/sh | |
| 18 | 新增:case "$1" in | |
| 19 | 新增: rm) rm -f "$AUDIT_MARKER";; | |
| 20 | 新增: python3) cat >/dev/null; printf published > "$AUDIT_MARKER";; | |
| 21 | 新增: *) exit 91;; | |
| 22 | 新增:esac | |
| 23 | 新增:` | |
| 24 | 新增: if err := os.WriteFile(filepath.Join(dir, "sudo"), []byte(sudo), 0755); err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: if err := os.WriteFile(marker, []byte("old"), 0600); err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: cmd := exec.Command("bash", "-c", markGuestStart(body)) | |
| 31 | 新增: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "AUDIT_MARKER="+marker) | |
| 32 | 新增: _, err := cmd.CombinedOutput() | |
| 33 | 新增: data, readErr := os.ReadFile(marker) | |
| 34 | 新增: if strings.Contains(body, "exit 0") { | |
| 35 | 新增: if err != nil || readErr != nil || string(data) != "published" { | |
| 36 | 新增: t.Fatal("successful startup did not publish manifest", err, readErr) | |
| 37 | 新增: } | |
| 38 | 新增: } else if err == nil || !os.IsNotExist(readErr) { | |
| 39 | 新增: t.Fatal("failed startup retained or published a manifest", err, readErr) | |
| 40 | 新增: } | |
| 41 | 新增: }) | |
| 42 | 新增: } | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:func TestGeneratedGuestScriptsParseAsBash(t *testing.T) { | |
| 46 | 新增: for name, script := range map[string]string{"start": DefaultConfig().StartScript(), "tools": ToolsUpdateScript(), "first-install-functions": ToolInstallPrelude()} { | |
| 47 | 新增: t.Run(name, func(t *testing.T) { | |
| 48 | 新增: cmd := exec.Command("bash", "-n") | |
| 49 | 新增: cmd.Stdin = strings.NewReader(script) | |
| 50 | 新增: if out, err := cmd.CombinedOutput(); err != nil { | |
| 51 | 新增: t.Fatalf("%v: %s", err, out) | |
| 52 | 新增: } | |
| 53 | 新增: }) | |
| 54 | 新增: } | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:func TestPinnedToolInstallerRejectsWrongHashBeforeInstalling(t *testing.T) { | |
| 58 | 新增: dir := t.TempDir() | |
| 59 | 新增: commands := map[string]string{ | |
| 60 | 新增: "dpkg": "#!/bin/sh\nif [ \"$1\" = --print-architecture ]; then echo arm64; else exit 1; fi\n", | |
| 61 | 新增: "code-server": "#!/bin/sh\necho 1.0.0\n", | |
| 62 | 新增: "curl": "#!/bin/sh\nwhile [ \"$#\" -gt 0 ]; do if [ \"$1\" = -o ]; then shift; printf altered-package > \"$1\"; exit; fi; shift; done\nexit 1\n", | |
| 63 | 新增: "sha256sum": "#!/bin/sh\ncat >/dev/null\nexit 1\n", | |
| 64 | 新增: "sudo": "#!/bin/sh\nprintf attempted > \"$AUDIT_INSTALL\"\nexit 0\n", | |
| 65 | 新增: } | |
| 66 | 新增: for name, content := range commands { | |
| 67 | 新增: if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0755); err != nil { | |
| 68 | 新增: t.Fatal(err) | |
| 69 | 新增: } | |
| 70 | 新增: } | |
| 71 | 新增: installed := filepath.Join(dir, "installed") | |
| 72 | 新增: cmd := exec.Command("bash", "-c", ToolInstallPrelude()+"\ncage_install_tool code-server") | |
| 73 | 新增: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "AUDIT_INSTALL="+installed) | |
| 74 | 新增: out, err := cmd.CombinedOutput() | |
| 75 | 新增: if err == nil || !strings.Contains(string(out), "checksum mismatch") { | |
| 76 | 新增: t.Fatalf("changed download accepted: %v %s", err, out) | |
| 77 | 新增: } | |
| 78 | 新增: if _, err := os.Stat(installed); !os.IsNotExist(err) { | |
| 79 | 新增: t.Fatal("installer ran before verifying the artifact") | |
| 80 | 新增: } | |
| 81 | 新增:} | |
| @@ -1,4 +1,4 @@ | ||
| 1 | 删除:# Patch noVNC's RFB transport so a paste finishes before the next one starts. | |
| 1 | 新增:# Patch noVNC's keyboard target and serialize clipboard transfers. | |
| 2 | 2 | # The resulting rfb.js retains noVNC's MPL-2.0 license header. |
| 3 | 3 | from pathlib import Path |
| 4 | 4 | import sys |
| @@ -24,14 +24,70 @@ h = h.replace('src="cage-clipboard.js"', 'src="cage-clipboard.js?cage=3"') | ||
| 24 | 24 | def replace_once(old, new): |
| 25 | 25 | global source |
| 26 | 26 | if source.count(old) != 1: |
| 27 | 删除: raise SystemExit('Unsupported noVNC version: clipboard transport patch did not apply') | |
| 27 | 新增: raise SystemExit('Unsupported noVNC version: Cage input/clipboard patch did not apply') | |
| 28 | 28 | source = source.replace(old, new) |
| 29 | 29 | |
| 30 | 新增:# Keep noVNC's key tracking and focus lifecycle when the workbench supplies an | |
| 31 | 新增:# editable host target for IME. Legacy viewers continue to use the canvas. | |
| 32 | 新增:replace_once(''' focus(options) { | |
| 33 | 新增: this._canvas.focus(options); | |
| 34 | 新增: } | |
| 35 | 新增: | |
| 36 | 新增: blur() { | |
| 37 | 新增: this._canvas.blur(); | |
| 38 | 新增: }''', ''' cageSetKeyboardTarget(target) { | |
| 39 | 新增: this._keyboard.ungrab(); | |
| 40 | 新增: this._cageKeyboardTarget = target || this._canvas; | |
| 41 | 新增: this._keyboard = new Keyboard(this._cageKeyboardTarget); | |
| 42 | 新增: this._keyboard.onkeyevent = this._handleKeyEvent.bind(this); | |
| 43 | 新增: if (this._rfbConnectionState === 'connected' && !this._viewOnly) { | |
| 44 | 新增: this._keyboard.grab(); | |
| 45 | 新增: } | |
| 46 | 新增: } | |
| 47 | 新增: | |
| 48 | 新增: focus(options) { | |
| 49 | 新增: (this._cageKeyboardTarget || this._canvas).focus(options); | |
| 50 | 新增: } | |
| 51 | 新增: | |
| 52 | 新增: blur() { | |
| 53 | 新增: (this._cageKeyboardTarget || this._canvas).blur(); | |
| 54 | 新增: }''') | |
| 55 | 新增: | |
| 30 | 56 | replace_once(' clipboardPasteFrom(text) {', ''' // Cage: serialize the clipboard notification, data transfer and paste. |
| 31 | 57 | // A server fence confirms it has processed the provided clipboard data. |
| 58 | 新增: _cageQueueInput(action) { | |
| 59 | 新增: const result = (this._cageInputChain || Promise.resolve()).then(action); | |
| 60 | 新增: this._cageInputChain = result; | |
| 61 | 新增: const clear = () => { | |
| 62 | 新增: if (this._cageInputChain === result) this._cageInputChain = null; | |
| 63 | 新增: }; | |
| 64 | 新增: // A failed text transfer also cancels keys/clicks already queued behind | |
| 65 | 新增: // it, so an Enter cannot submit a form with the committed text missing. | |
| 66 | 新增: result.then(clear, clear); | |
| 67 | 新增: return result; | |
| 68 | 新增: } | |
| 69 | 新增: | |
| 70 | 新增: cageRunInput(action) { | |
| 71 | 新增: return this._cageQueueInput(async () => { | |
| 72 | 新增: if (this._rfbConnectionState !== 'connected' || this._viewOnly || !this._supportsFence) | |
| 73 | 新增: throw new Error('Input transport is not ready'); | |
| 74 | 新增: // Flush preceding VNC clicks/keys before a browser text insertion. | |
| 75 | 新增: await new Promise((resolve, reject) => { | |
| 76 | 新增: const id = 'cage-input-' + (this._cageInputSequence = (this._cageInputSequence || 0) + 1); | |
| 77 | 新增: const timer = setTimeout(() => { | |
| 78 | 新增: this._cageInputFence = null; | |
| 79 | 新增: reject(new Error('Input fence timed out')); | |
| 80 | 新增: }, 4000); | |
| 81 | 新增: this._cageInputFence = { id, timer, resolve }; | |
| 82 | 新增: RFB.messages.clientFence(this._sock, (1 << 31) | 1, id); | |
| 83 | 新增: }); | |
| 84 | 新增: if (this._rfbConnectionState !== 'connected') throw new Error('Input disconnected'); | |
| 85 | 新增: return action(); | |
| 86 | 新增: }); | |
| 87 | 新增: } | |
| 88 | 新增: | |
| 32 | 89 | cagePasteText(text) { |
| 33 | 删除: const previous = this._cagePasteChain || Promise.resolve(); | |
| 34 | 删除: const result = previous.then(() => new Promise((resolve, reject) => { | |
| 90 | 新增: return this._cageQueueInput(() => new Promise((resolve, reject) => { | |
| 35 | 91 | if (this._rfbConnectionState !== 'connected' || this._viewOnly || |
| 36 | 92 | !this._supportsFence || |
| 37 | 93 | !this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify] || |
| @@ -47,11 +103,33 @@ replace_once(' clipboardPasteFrom(text) {', ''' // Cage: serialize the cli | ||
| 47 | 103 | this._cagePasteJob = {id, timer, resolve, phase: 'data'}; |
| 48 | 104 | this.clipboardPasteFrom(text); |
| 49 | 105 | })); |
| 50 | 删除: this._cagePasteChain = result.catch(() => {}); | |
| 51 | 删除: return result; | |
| 52 | 106 | } |
| 53 | 107 | |
| 54 | 108 | clipboardPasteFrom(text) {''') |
| 109 | 新增: | |
| 110 | 新增:replace_once(''' sendKey(keysym, code, down) { | |
| 111 | 新增: if (this._rfbConnectionState''', ''' sendKey(keysym, code, down) { | |
| 112 | 新增: if (this._cageInputChain) { | |
| 113 | 新增: this._cageQueueInput(() => this._cageSendKey(keysym, code, down)); | |
| 114 | 新增: return; | |
| 115 | 新增: } | |
| 116 | 新增: this._cageSendKey(keysym, code, down); | |
| 117 | 新增: } | |
| 118 | 新增: | |
| 119 | 新增: _cageSendKey(keysym, code, down) { | |
| 120 | 新增: if (this._rfbConnectionState''') | |
| 121 | 新增:replace_once(''' this.sendKey(keysym, code, true); | |
| 122 | 新增: this.sendKey(keysym, code, false);''', ''' this._cageSendKey(keysym, code, true); | |
| 123 | 新增: this._cageSendKey(keysym, code, false);''') | |
| 124 | 新增:replace_once(''' _sendMouse(x, y, mask) {''', ''' _sendMouse(x, y, mask) { | |
| 125 | 新增: if (this._cageInputChain) { | |
| 126 | 新增: this._cageQueueInput(() => this._cageSendMouse(x, y, mask)); | |
| 127 | 新增: return; | |
| 128 | 新增: } | |
| 129 | 新增: this._cageSendMouse(x, y, mask); | |
| 130 | 新增: } | |
| 131 | 新增: | |
| 132 | 新增: _cageSendMouse(x, y, mask) {''') | |
| 55 | 133 | provide = 'RFB.messages.extendedClipboardProvide(this._sock, [extendedClipboardFormatText], [this._clipboardText]);' |
| 56 | 134 | replace_once(provide, provide + ''' |
| 57 | 135 | if (this._cagePasteJob?.phase === 'data') { |
| @@ -61,12 +139,20 @@ replace_once(provide, provide + ''' | ||
| 61 | 139 | replace_once(''' if (!(flags & (1<<31))) { |
| 62 | 140 | return this._fail("Unexpected fence response"); |
| 63 | 141 | }''', ''' if (!(flags & (1<<31))) { |
| 142 | 新增: const input = this._cageInputFence; | |
| 143 | 新增: if (input && payload === input.id) { | |
| 144 | 新增: clearTimeout(input.timer); | |
| 145 | 新增: this._cageInputFence = null; | |
| 146 | 新增: input.resolve(); | |
| 147 | 新增: return true; | |
| 148 | 新增: } | |
| 149 | 新增: if (payload.startsWith('cage-input-')) return true; | |
| 64 | 150 | const job = this._cagePasteJob; |
| 65 | 151 | if (job && job.phase === 'fence' && payload === job.id) { |
| 66 | 删除: this.sendKey(0xffe3, 'ControlLeft', true); | |
| 67 | 删除: this.sendKey(0x76, 'KeyV', true); | |
| 68 | 删除: this.sendKey(0x76, 'KeyV', false); | |
| 69 | 删除: this.sendKey(0xffe3, 'ControlLeft', false); | |
| 152 | 新增: this._cageSendKey(0xffe3, 'ControlLeft', true); | |
| 153 | 新增: this._cageSendKey(0x76, 'KeyV', true); | |
| 154 | 新增: this._cageSendKey(0x76, 'KeyV', false); | |
| 155 | 新增: this._cageSendKey(0xffe3, 'ControlLeft', false); | |
| 70 | 156 | job.phase = 'keys'; |
| 71 | 157 | RFB.messages.clientFence(this._sock, (1 << 31) | 1, job.id + '-keys'); |
| 72 | 158 | return true; |
| @@ -1,44 +1,158 @@ | ||
| 1 | 1 | #!/usr/bin/python3 |
| 2 | 删除:"""Copy a completed browser download into the selected shared project's Downloads.""" | |
| 2 | 新增:"""Publish one completed browser download into the fixed shared workspace.""" | |
| 3 | 新增:import errno | |
| 3 | 4 | import json |
| 4 | 5 | import os |
| 5 | 6 | import pwd |
| 6 | 7 | import re |
| 7 | 删除:import shutil | |
| 8 | 新增:import secrets | |
| 8 | 9 | import stat |
| 9 | 10 | import sys |
| 10 | 11 | |
| 11 | 删除:source_name = sys.argv[1] if len(sys.argv) == 3 else '' | |
| 12 | 删除:name = sys.argv[2] if len(sys.argv) == 3 else '' | |
| 13 | 删除:if not re.fullmatch(r'[a-fA-F0-9-]{36}', source_name): | |
| 14 | 删除: raise SystemExit(2) | |
| 15 | 删除:if not name or name != os.path.basename(name) or name in ('.', '..'): | |
| 16 | 删除: raise SystemExit(2) | |
| 17 | 删除:with open('/etc/claude-cage/browser-control.json') as f: | |
| 18 | 删除: workspace = json.load(f)['workspace'] | |
| 19 | 删除:source = os.open('/home/cage-browser/Downloads/' + source_name, os.O_RDONLY | os.O_NOFOLLOW) | |
| 20 | 删除:if not stat.S_ISREG(os.fstat(source).st_mode): | |
| 21 | 删除: raise SystemExit(2) | |
| 22 | 删除:user = pwd.getpwnam('cage') | |
| 23 | 删除:# Work as the coding user while writing into the share, not as root. | |
| 24 | 删除:os.setgroups([user.pw_gid]) | |
| 25 | 删除:os.setgid(user.pw_gid) | |
| 26 | 删除:os.setuid(user.pw_uid) | |
| 27 | 删除:parent = os.open(workspace, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) | |
| 28 | 删除:try: | |
| 29 | 删除: os.mkdir('Downloads', mode=0o755, dir_fd=parent) | |
| 30 | 删除:except FileExistsError: | |
| 31 | 删除: pass | |
| 32 | 删除:destination = os.open('Downloads', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) | |
| 33 | 删除:root, extension = os.path.splitext(name) | |
| 34 | 删除:for number in range(1000): | |
| 35 | 删除: candidate = name if number == 0 else f'{root} ({number}){extension}' | |
| 12 | 新增: | |
| 13 | 新增:def checked_download(source_name, name): | |
| 14 | 新增: if not re.fullmatch(r'[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}', source_name): | |
| 15 | 新增: raise ValueError('下载标识无效') | |
| 16 | 新增: if not name or name != os.path.basename(name) or name in ('.', '..') or '\0' in name: | |
| 17 | 新增: raise ValueError('下载文件名无效') | |
| 18 | 新增: | |
| 19 | 新增: | |
| 20 | 新增:def copy_to_workspace(source, size, workspace, name): | |
| 21 | 新增: """Run as the coding user; final names only become visible after fsync.""" | |
| 22 | 新增: parent = os.open(workspace, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) | |
| 23 | 新增: destination = None | |
| 24 | 新增: published = None | |
| 25 | 新增: temporary = '.cage-download-' + secrets.token_hex(12) + '.part' | |
| 26 | 新增: try: | |
| 27 | 新增: try: | |
| 28 | 新增: os.mkdir('Downloads', mode=0o755, dir_fd=parent) | |
| 29 | 新增: except FileExistsError: | |
| 30 | 新增: pass | |
| 31 | 新增: destination = os.open('Downloads', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) | |
| 32 | 新增: output = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=destination) | |
| 33 | 新增: with os.fdopen(output, 'wb') as dst: | |
| 34 | 新增: remaining = size | |
| 35 | 新增: while remaining: | |
| 36 | 新增: chunk = os.read(source, min(remaining, 1024 * 1024)) | |
| 37 | 新增: if not chunk: | |
| 38 | 新增: raise OSError(errno.EIO, '下载源文件在保存过程中发生变化') | |
| 39 | 新增: dst.write(chunk) | |
| 40 | 新增: remaining -= len(chunk) | |
| 41 | 新增: dst.flush() | |
| 42 | 新增: os.fchmod(dst.fileno(), 0o644) | |
| 43 | 新增: os.fsync(dst.fileno()) | |
| 44 | 新增: root, extension = os.path.splitext(name) | |
| 45 | 新增: for number in range(1000): | |
| 46 | 新增: candidate = name if number == 0 else f'{root} ({number}){extension}' | |
| 47 | 新增: try: | |
| 48 | 新增: # The complete file is published without replacing any entry. | |
| 49 | 新增: os.link(temporary, candidate, src_dir_fd=destination, dst_dir_fd=destination, follow_symlinks=False) | |
| 50 | 新增: published = {'ok': True, 'path': os.path.join(workspace, 'Downloads', candidate), 'name': candidate, 'bytes': size} | |
| 51 | 新增: return published | |
| 52 | 新增: except FileExistsError: | |
| 53 | 新增: continue | |
| 54 | 新增: raise OSError(errno.EEXIST, '同名文件过多,请整理 Downloads 后重试') | |
| 55 | 新增: finally: | |
| 56 | 新增: if destination is not None: | |
| 57 | 新增: try: | |
| 58 | 新增: os.unlink(temporary, dir_fd=destination) | |
| 59 | 新增: except FileNotFoundError: | |
| 60 | 新增: pass | |
| 61 | 新增: except OSError: | |
| 62 | 新增: if published is None: | |
| 63 | 新增: raise | |
| 64 | 新增: published['warning'] = '文件已保存到 Mac;共享目录中的临时文件暂时无法清理。' | |
| 65 | 新增: finally: | |
| 66 | 新增: os.close(destination) | |
| 67 | 新增: os.close(parent) | |
| 68 | 新增: | |
| 69 | 新增: | |
| 70 | 新增:def remove_source_if_unchanged(directory, name, expected): | |
| 71 | 新增: """Do not remove a replacement created after the source was opened.""" | |
| 72 | 新增: try: | |
| 73 | 新增: current = os.stat(name, dir_fd=directory, follow_symlinks=False) | |
| 74 | 新增: except FileNotFoundError: | |
| 75 | 新增: return True | |
| 76 | 新增: identity = lambda st: (st.st_dev, st.st_ino, st.st_uid, st.st_size, st.st_mtime_ns) | |
| 77 | 新增: if not stat.S_ISREG(current.st_mode) or identity(current) != identity(expected): | |
| 78 | 新增: return False | |
| 79 | 新增: os.unlink(name, dir_fd=directory) | |
| 80 | 新增: return True | |
| 81 | 新增: | |
| 82 | 新增: | |
| 83 | 新增:def error_message(error): | |
| 84 | 新增: if isinstance(error, ValueError): | |
| 85 | 新增: return str(error) | |
| 86 | 新增: if isinstance(error, OSError): | |
| 87 | 新增: if error.errno == errno.ENOSPC: | |
| 88 | 新增: return '空间不足,文件尚未保存到 Mac。清理空间后可重试。' | |
| 89 | 新增: if error.errno in (errno.EACCES, errno.EPERM, errno.EROFS): | |
| 90 | 新增: return '无法写入共享下载目录。检查目录权限和共享连接后可重试。' | |
| 91 | 新增: if error.errno in (errno.ELOOP, errno.ENOTDIR): | |
| 92 | 新增: return '下载目录包含符号链接或已不再是目录,请修复后重试。' | |
| 93 | 新增: if error.errno == errno.ENOENT: | |
| 94 | 新增: return '下载源文件或共享目录不可用,请检查后重试。' | |
| 95 | 新增: return '文件尚未保存到 Mac。检查共享连接和可用空间后可重试。' | |
| 96 | 新增: | |
| 97 | 新增: | |
| 98 | 新增:def main(): | |
| 99 | 新增: source_name, name = sys.argv[1:] if len(sys.argv) == 3 else ('', '') | |
| 100 | 新增: checked_download(source_name, name) | |
| 101 | 新增: with open('/etc/claude-cage/browser-control.json') as config: | |
| 102 | 新增: workspace = json.load(config)['workspace'] | |
| 103 | 新增: directory = os.open('/home/cage-browser/Downloads', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) | |
| 104 | 新增: source = None | |
| 105 | 新增: try: | |
| 106 | 新增: browser_uid = pwd.getpwnam('cage-browser').pw_uid | |
| 107 | 新增: if os.fstat(directory).st_uid != browser_uid: | |
| 108 | 新增: raise ValueError('下载目录所有者无效') | |
| 109 | 新增: source = os.open(source_name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) | |
| 110 | 新增: source_stat = os.fstat(source) | |
| 111 | 新增: if not stat.S_ISREG(source_stat.st_mode) or source_stat.st_uid != browser_uid: | |
| 112 | 新增: raise ValueError('下载源文件不是普通文件') | |
| 113 | 新增: user = pwd.getpwnam('cage') | |
| 114 | 新增: receive, send = os.pipe() | |
| 115 | 新增: child = os.fork() | |
| 116 | 新增: if child == 0: | |
| 117 | 新增: os.close(receive) | |
| 118 | 新增: try: | |
| 119 | 新增: # Only the parent retains permission to clean up browser files. | |
| 120 | 新增: os.setgroups([user.pw_gid]) | |
| 121 | 新增: os.setgid(user.pw_gid) | |
| 122 | 新增: os.setuid(user.pw_uid) | |
| 123 | 新增: result = copy_to_workspace(source, source_stat.st_size, workspace, name) | |
| 124 | 新增: except Exception as error: | |
| 125 | 新增: result = {'ok': False, 'error': error_message(error)} | |
| 126 | 新增: with os.fdopen(send, 'wb') as pipe: | |
| 127 | 新增: pipe.write(json.dumps(result, ensure_ascii=False).encode()) | |
| 128 | 新增: os._exit(0 if result['ok'] else 1) | |
| 129 | 新增: os.close(send) | |
| 130 | 新增: with os.fdopen(receive, 'rb') as pipe: | |
| 131 | 新增: data = pipe.read(16385) | |
| 132 | 新增: _, status = os.waitpid(child, 0) | |
| 133 | 新增: if len(data) > 16384: | |
| 134 | 新增: raise ValueError('下载保存结果无效') | |
| 135 | 新增: result = json.loads(data) | |
| 136 | 新增: if os.waitstatus_to_exitcode(status) != 0 or not result.get('ok'): | |
| 137 | 新增: print(json.dumps({'ok': False, 'error': result.get('error', '下载保存未完成')}, ensure_ascii=False)) | |
| 138 | 新增: return 1 | |
| 139 | 新增: try: | |
| 140 | 新增: cleaned = remove_source_if_unchanged(directory, source_name, source_stat) | |
| 141 | 新增: except OSError: | |
| 142 | 新增: cleaned = False | |
| 143 | 新增: if not cleaned: | |
| 144 | 新增: result['warning'] = '文件已保存到 Mac;客机中的下载源文件发生变化或暂时无法清理。' | |
| 145 | 新增: print(json.dumps(result, ensure_ascii=False)) | |
| 146 | 新增: return 0 | |
| 147 | 新增: finally: | |
| 148 | 新增: if source is not None: | |
| 149 | 新增: os.close(source) | |
| 150 | 新增: os.close(directory) | |
| 151 | 新增: | |
| 152 | 新增: | |
| 153 | 新增:if __name__ == '__main__': | |
| 36 | 154 | try: |
| 37 | 删除: output = os.open(candidate, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644, dir_fd=destination) | |
| 38 | 删除: break | |
| 39 | 删除: except FileExistsError: | |
| 40 | 删除: continue | |
| 41 | 删除:else: | |
| 42 | 删除: raise SystemExit(1) | |
| 43 | 删除:with os.fdopen(source, 'rb') as src, os.fdopen(output, 'wb') as dst: | |
| 44 | 删除: shutil.copyfileobj(src, dst) | |
| 155 | 新增: sys.exit(main()) | |
| 156 | 新增: except Exception as error: | |
| 157 | 新增: print(json.dumps({'ok': False, 'error': error_message(error)}, ensure_ascii=False)) | |
| 158 | 新增: sys.exit(1) | |
| @@ -0,0 +1,95 @@ | ||
| 1 | 新增:import errno | |
| 2 | 新增:import importlib.util | |
| 3 | 新增:import os | |
| 4 | 新增:from pathlib import Path | |
| 5 | 新增:import tempfile | |
| 6 | 新增:import sys | |
| 7 | 新增:import unittest | |
| 8 | 新增:from unittest import mock | |
| 9 | 新增: | |
| 10 | 新增:sys.dont_write_bytecode = True | |
| 11 | 新增: | |
| 12 | 新增:spec = importlib.util.spec_from_file_location('save_download', Path(__file__).with_name('save-download.py')) | |
| 13 | 新增:helper = importlib.util.module_from_spec(spec) | |
| 14 | 新增:spec.loader.exec_module(helper) | |
| 15 | 新增: | |
| 16 | 新增: | |
| 17 | 新增:class DownloadSaveTests(unittest.TestCase): | |
| 18 | 新增: def setUp(self): | |
| 19 | 新增: self.temp = tempfile.TemporaryDirectory(prefix='cage-download-test-') | |
| 20 | 新增: self.addCleanup(self.temp.cleanup) | |
| 21 | 新增: self.root = Path(self.temp.name) | |
| 22 | 新增: self.source = self.root / 'source' | |
| 23 | 新增: self.source.write_bytes(b'complete download\x00data') | |
| 24 | 新增: self.workspace = self.root / 'workspace' | |
| 25 | 新增: self.workspace.mkdir() | |
| 26 | 新增: | |
| 27 | 新增: def copy(self, name='report.txt'): | |
| 28 | 新增: fd = os.open(self.source, os.O_RDONLY | os.O_NOFOLLOW) | |
| 29 | 新增: try: | |
| 30 | 新增: return helper.copy_to_workspace(fd, self.source.stat().st_size, str(self.workspace), name) | |
| 31 | 新增: finally: | |
| 32 | 新增: os.close(fd) | |
| 33 | 新增: | |
| 34 | 新增: def test_atomic_publish_does_not_overwrite_existing_file_or_symlink(self): | |
| 35 | 新增: destination = self.workspace / 'Downloads' | |
| 36 | 新增: destination.mkdir() | |
| 37 | 新增: (destination / 'report.txt').write_text('original') | |
| 38 | 新增: (destination / 'report (1).txt').symlink_to(self.source) | |
| 39 | 新增: result = self.copy() | |
| 40 | 新增: self.assertEqual(Path(result['path']).name, 'report (2).txt') | |
| 41 | 新增: self.assertEqual(Path(result['path']).read_bytes(), self.source.read_bytes()) | |
| 42 | 新增: self.assertEqual((destination / 'report.txt').read_text(), 'original') | |
| 43 | 新增: self.assertTrue((destination / 'report (1).txt').is_symlink()) | |
| 44 | 新增: self.assertFalse(list(destination.glob('.cage-download-*'))) | |
| 45 | 新增: | |
| 46 | 新增: def test_write_failure_keeps_source_and_publishes_no_partial_file(self): | |
| 47 | 新增: with mock.patch.object(helper.os, 'fsync', side_effect=OSError(errno.ENOSPC, 'full')): | |
| 48 | 新增: with self.assertRaises(OSError): | |
| 49 | 新增: self.copy() | |
| 50 | 新增: self.assertTrue(self.source.exists()) | |
| 51 | 新增: self.assertEqual(list((self.workspace / 'Downloads').iterdir()), []) | |
| 52 | 新增: result = self.copy() | |
| 53 | 新增: self.assertEqual(Path(result['path']).read_bytes(), self.source.read_bytes()) | |
| 54 | 新增: | |
| 55 | 新增: def test_symlink_download_directory_is_refused(self): | |
| 56 | 新增: outside = self.root / 'outside' | |
| 57 | 新增: outside.mkdir() | |
| 58 | 新增: (self.workspace / 'Downloads').symlink_to(outside, target_is_directory=True) | |
| 59 | 新增: with self.assertRaises(OSError): | |
| 60 | 新增: self.copy() | |
| 61 | 新增: self.assertEqual(list(outside.iterdir()), []) | |
| 62 | 新增: | |
| 63 | 新增: def test_cleanup_does_not_delete_replaced_source(self): | |
| 64 | 新增: directory = os.open(self.root, os.O_RDONLY | os.O_DIRECTORY) | |
| 65 | 新增: self.addCleanup(os.close, directory) | |
| 66 | 新增: original = self.source.stat() | |
| 67 | 新增: self.source.rename(self.root / 'original') | |
| 68 | 新增: self.source.write_text('replacement') | |
| 69 | 新增: self.assertFalse(helper.remove_source_if_unchanged(directory, 'source', original)) | |
| 70 | 新增: self.assertEqual(self.source.read_text(), 'replacement') | |
| 71 | 新增: current = self.source.stat() | |
| 72 | 新增: self.assertTrue(helper.remove_source_if_unchanged(directory, 'source', current)) | |
| 73 | 新增: self.assertFalse(self.source.exists()) | |
| 74 | 新增: | |
| 75 | 新增: def test_only_fixed_guid_and_leaf_names_are_accepted(self): | |
| 76 | 新增: valid = '01234567-89ab-cdef-0123-456789abcdef' | |
| 77 | 新增: helper.checked_download(valid, '中文文件.txt') | |
| 78 | 新增: for name in ('../outside', '/absolute', '.', '..', 'bad\0name'): | |
| 79 | 新增: with self.assertRaises(ValueError): | |
| 80 | 新增: helper.checked_download(valid, name) | |
| 81 | 新增: with self.assertRaises(ValueError): | |
| 82 | 新增: helper.checked_download('../outside', 'report.txt') | |
| 83 | 新增: | |
| 84 | 新增: def test_cleanup_keeps_source_modified_after_copy(self): | |
| 85 | 新增: directory = os.open(self.root, os.O_RDONLY | os.O_DIRECTORY) | |
| 86 | 新增: self.addCleanup(os.close, directory) | |
| 87 | 新增: original = self.source.stat() | |
| 88 | 新增: with self.source.open('ab') as changed: | |
| 89 | 新增: changed.write(b'new bytes') | |
| 90 | 新增: self.assertFalse(helper.remove_source_if_unchanged(directory, 'source', original)) | |
| 91 | 新增: self.assertTrue(self.source.read_bytes().endswith(b'new bytes')) | |
| 92 | 新增: | |
| 93 | 新增: | |
| 94 | 新增:if __name__ == '__main__': | |
| 95 | 新增: unittest.main() | |
| @@ -0,0 +1,8 @@ | ||
| 1 | 新增:# Fixed upstream release assets; provenance is documented in docs/releasing.md. | |
| 2 | 新增:CAGE_CODE_SERVER_VERSION=4.144.0 | |
| 3 | 新增:CAGE_CODE_SERVER_ARM64_SHA256=6baef72b340da08e76e5cf1e9504f657d00e80c8776bdaf86e97c30a80cd48e8 | |
| 4 | 新增:CAGE_CODE_SERVER_AMD64_SHA256=45f5533b502edac68b7eb09c5cec44fd281f80264af9a87fde0bfb2c5e190615 | |
| 5 | 新增:CAGE_MISE_VERSION=2026.10.25 | |
| 6 | 新增:CAGE_MISE_ARM64_SHA256=a7d1e2add53441ff76e7e971e7a3fb15c117741836ce51c026f5fb7eebe7dbcf | |
| 7 | 新增:CAGE_MISE_AMD64_SHA256=199966edaad1b208eb4c72955f1722dafb8fa799f575db720dea05aaa8216546 | |
| 8 | 新增:CAGE_CLAUDE_VERSION=2.1.314 | |
| @@ -11,6 +11,7 @@ import ( | ||
| 11 | 11 | "time" |
| 12 | 12 | |
| 13 | 13 | agentvm "github.com/sylvinus/agent-vm" |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 14 | 15 | "github.com/sylvinus/agent-vm/internal/env" |
| 15 | 16 | "github.com/sylvinus/agent-vm/internal/host" |
| 16 | 17 | "github.com/sylvinus/agent-vm/internal/state" |
| @@ -525,7 +526,7 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int) | ||
| 525 | 526 | |
| 526 | 527 | func cageInstallEnv() string { |
| 527 | 528 | if os.Getenv("CLAUDE_CAGE_CONFIG") != "" { |
| 528 | 删除: return "export CLAUDE_CAGE=1\n" | |
| 529 | 新增: return "export CLAUDE_CAGE=1\n" + cage.ToolInstallPrelude() | |
| 529 | 530 | } |
| 530 | 531 | return "" |
| 531 | 532 | } |
| @@ -8,6 +8,7 @@ import ( | ||
| 8 | 8 | "encoding/json" |
| 9 | 9 | "errors" |
| 10 | 10 | "fmt" |
| 11 | 新增: "io" | |
| 11 | 12 | "os" |
| 12 | 13 | "path/filepath" |
| 13 | 14 | "strings" |
| @@ -18,6 +19,7 @@ import ( | ||
| 18 | 19 | |
| 19 | 20 | const Group = "CAGE" |
| 20 | 21 | const MaxImport = 8 << 20 |
| 22 | 新增:const maxStoreSize = 32 << 20 | |
| 21 | 23 | |
| 22 | 24 | type Node struct { |
| 23 | 25 | ID string `json:"id"` |
| @@ -59,14 +61,19 @@ func Socket(profile string) string { | ||
| 59 | 61 | } |
| 60 | 62 | func Load(profile string) (Store, error) { |
| 61 | 63 | var s Store |
| 62 | 删除: b, err := os.ReadFile(filepath.Join(Dir(profile), "sources.json")) | |
| 64 | 新增: f, err := os.Open(filepath.Join(Dir(profile), "sources.json")) | |
| 63 | 65 | if os.IsNotExist(err) { |
| 64 | 66 | return Store{Version: 1, Port: 17896, Auth: Token(), Sources: []Source{}}, nil |
| 65 | 67 | } |
| 66 | 68 | if err != nil { |
| 67 | 69 | return s, err |
| 68 | 70 | } |
| 69 | 删除: if len(b) > 32<<20 || json.Unmarshal(b, &s) != nil || s.Version != 1 || s.Port < 1024 || s.Port > 65535 || len(s.Auth) != 48 { | |
| 71 | 新增: defer f.Close() | |
| 72 | 新增: b, err := io.ReadAll(io.LimitReader(f, maxStoreSize+1)) | |
| 73 | 新增: if err != nil { | |
| 74 | 新增: return s, err | |
| 75 | 新增: } | |
| 76 | 新增: if len(b) > maxStoreSize || json.Unmarshal(b, &s) != nil || s.Version != 1 || s.Port < 1024 || s.Port > 65535 || len(s.Auth) != 48 { | |
| 70 | 77 | return s, errors.New("Cage 代理配置无效,请恢复私有配置备份") |
| 71 | 78 | } |
| 72 | 79 | return s, nil |
| @@ -99,6 +106,9 @@ func (s Store) Save(profile string) error { | ||
| 99 | 106 | if err != nil { |
| 100 | 107 | return err |
| 101 | 108 | } |
| 109 | 新增: if len(b) > maxStoreSize { | |
| 110 | 新增: return errors.New("代理来源配置总大小超过 32 MiB,请减少来源或节点;原配置已保留") | |
| 111 | 新增: } | |
| 102 | 112 | return Write(filepath.Join(Dir(profile), "sources.json"), b) |
| 103 | 113 | } |
| 104 | 114 | func (s Store) Endpoint() string { return fmt.Sprintf("socks5://cage:%[email protected]:%d", s.Auth, s.Port) } |
| @@ -1,7 +1,9 @@ | ||
| 1 | 1 | package managedproxy |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "bytes" | |
| 4 | 5 | "context" |
| 6 | 新增: "fmt" | |
| 5 | 7 | "io" |
| 6 | 8 | "net/http" |
| 7 | 9 | "net/http/httptest" |
| @@ -14,6 +16,88 @@ import ( | ||
| 14 | 16 | "go.yaml.in/yaml/v3" |
| 15 | 17 | ) |
| 16 | 18 | |
| 19 | 新增:func TestCumulativeImportsPreserveReadableStoreOnOverflow(t *testing.T) { | |
| 20 | 新增: profile := t.TempDir() | |
| 21 | 新增: s, err := Load(profile) | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: t.Fatal(err) | |
| 24 | 新增: } | |
| 25 | 新增: data := []byte("proxies:\n - name: synthetic\n type: socks5\n server: example.com\n port: 1080\n password: " + strings.Repeat("x", 7<<20) + "\n") | |
| 26 | 新增: for i := 0; i < 4; i++ { | |
| 27 | 新增: if err := s.Import(fmt.Sprintf("source-%d", i), "", data, "", 0, ""); err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: if err := s.Save(profile); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: } | |
| 34 | 新增: path := filepath.Join(Dir(profile), "sources.json") | |
| 35 | 新增: before, err := os.ReadFile(path) | |
| 36 | 新增: if err != nil { | |
| 37 | 新增: t.Fatal(err) | |
| 38 | 新增: } | |
| 39 | 新增: if err := s.Import("overflow", "", data, "", 0, ""); err != nil { | |
| 40 | 新增: t.Fatal("individual import should remain within its input limit", err) | |
| 41 | 新增: } | |
| 42 | 新增: if err := s.Save(profile); err == nil { | |
| 43 | 新增: t.Fatal("cumulative imports saved an unreadable store") | |
| 44 | 新增: } | |
| 45 | 新增: after, err := os.ReadFile(path) | |
| 46 | 新增: if err != nil || !bytes.Equal(before, after) { | |
| 47 | 新增: t.Fatal("failed save changed the previous file", err) | |
| 48 | 新增: } | |
| 49 | 新增: loaded, err := Load(profile) | |
| 50 | 新增: if err != nil || len(loaded.Sources) != 4 || loaded.Auth != s.Auth { | |
| 51 | 新增: t.Fatal("previous sources could not be recovered after rejected import", err) | |
| 52 | 新增: } | |
| 53 | 新增: // Normal source removal must still work after the rejected import. | |
| 54 | 新增: loaded.Sources = loaded.Sources[:3] | |
| 55 | 新增: if err := loaded.Save(profile); err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: if loaded, err := Load(profile); err != nil || len(loaded.Sources) != 3 { | |
| 59 | 新增: t.Fatal("source removal failed after rejected import", err) | |
| 60 | 新增: } | |
| 61 | 新增:} | |
| 62 | 新增: | |
| 63 | 新增:func TestStoreLimitCoversSerializedBytesAndAllowsExactLimit(t *testing.T) { | |
| 64 | 新增: profile := t.TempDir() | |
| 65 | 新增: s, _ := Load(profile) | |
| 66 | 新增: if err := s.Import("source", "", []byte(testNodes), "source", 0, ""); err != nil { | |
| 67 | 新增: t.Fatal(err) | |
| 68 | 新增: } | |
| 69 | 新增: s.Sources[0].Nodes[0].Config["password"] = "" | |
| 70 | 新增: if err := s.Save(profile); err != nil { | |
| 71 | 新增: t.Fatal(err) | |
| 72 | 新增: } | |
| 73 | 新增: path := filepath.Join(Dir(profile), "sources.json") | |
| 74 | 新增: base, err := os.Stat(path) | |
| 75 | 新增: if err != nil { | |
| 76 | 新增: t.Fatal(err) | |
| 77 | 新增: } | |
| 78 | 新增: padding := strings.Repeat("x", maxStoreSize-int(base.Size())) | |
| 79 | 新增: s.Sources[0].Nodes[0].Config["password"] = padding | |
| 80 | 新增: if err := s.Save(profile); err != nil { | |
| 81 | 新增: t.Fatal("exact limit was rejected", err) | |
| 82 | 新增: } | |
| 83 | 新增: if info, err := os.Stat(path); err != nil || info.Size() != maxStoreSize { | |
| 84 | 新增: t.Fatal("fixture did not reach the exact serialized limit", err) | |
| 85 | 新增: } | |
| 86 | 新增: if _, err := Load(profile); err != nil { | |
| 87 | 新增: t.Fatal("exact-size saved store was not readable", err) | |
| 88 | 新增: } | |
| 89 | 新增: // The raw string has the same byte length, but JSON escapes '<' into six | |
| 90 | 新增: // bytes. Limits must cover the persisted representation, not input lengths. | |
| 91 | 新增: s.Sources[0].Nodes[0].Config["password"] = padding[:len(padding)-1] + "<" | |
| 92 | 新增: if err := s.Save(profile); err == nil { | |
| 93 | 新增: t.Fatal("JSON expansion bypassed the persisted-size limit") | |
| 94 | 新增: } | |
| 95 | 新增: loaded, err := Load(profile) | |
| 96 | 新增: if err != nil || loaded.Sources[0].Nodes[0].Config["password"] != padding { | |
| 97 | 新增: t.Fatal("overflow replaced the exact-size previous store", err) | |
| 98 | 新增: } | |
| 99 | 新增:} | |
| 100 | 新增: | |
| 17 | 101 | const testNodes = `mixed-port: 7890 |
| 18 | 102 | external-controller: 0.0.0.0:9090 |
| 19 | 103 | tun: {enable: true} |
| @@ -0,0 +1,28 @@ | ||
| 1 | 新增:package version | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/sha256" | |
| 5 | 新增: "fmt" | |
| 6 | 新增: "io" | |
| 7 | 新增: "os" | |
| 8 | 新增: "sync" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:// ExecutableIdentity is fixed when first read. A running service must not adopt | |
| 12 | 新增:// the identity of a replacement subsequently installed at the same path. | |
| 13 | 新增:var ExecutableIdentity = sync.OnceValues(func() (string, error) { | |
| 14 | 新增: path, err := os.Executable() | |
| 15 | 新增: if err != nil { | |
| 16 | 新增: return "", err | |
| 17 | 新增: } | |
| 18 | 新增: f, err := os.Open(path) | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: return "", err | |
| 21 | 新增: } | |
| 22 | 新增: defer f.Close() | |
| 23 | 新增: h := sha256.New() | |
| 24 | 新增: if _, err = io.Copy(h, f); err != nil { | |
| 25 | 新增: return "", err | |
| 26 | 新增: } | |
| 27 | 新增: return fmt.Sprintf("%x", h.Sum(nil)), nil | |
| 28 | 新增:}) | |
| @@ -1,11 +1,20 @@ | ||
| 1 | 删除:// Package version is agent-vm's semantic version. | |
| 1 | 新增:// Package version provides the application version and version comparisons. | |
| 2 | 2 | package version |
| 3 | 3 | |
| 4 | 删除:import "strings" | |
| 4 | 新增:import ( | |
| 5 | 新增: agentvm "github.com/sylvinus/agent-vm" | |
| 6 | 新增: "strings" | |
| 7 | 新增:) | |
| 5 | 8 | |
| 6 | 9 | // Version is set at build time (-ldflags -X); integrators gate on it with |
| 7 | 10 | // `agent-vm version --min`. |
| 8 | 删除:var Version = "0.3.0-dev" | |
| 11 | 新增:var Version string | |
| 12 | 新增: | |
| 13 | 新增:func init() { | |
| 14 | 新增: if Version == "" { | |
| 15 | 新增: Version = strings.TrimSpace(agentvm.CageVersion) | |
| 16 | 新增: } | |
| 17 | 新增:} | |
| 9 | 18 | |
| 10 | 19 | // AtLeast reports whether version have is want or later. The numbers before |
| 11 | 20 | // any "-" compare first, anything but digits in a component dropped, a |
| @@ -0,0 +1,44 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "io" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestDownloadRetryUsesAuthenticatedFixedGuestAction(t *testing.T) { | |
| 12 | 新增: s := testServer(t) | |
| 13 | 新增: s.ready = true | |
| 14 | 新增: s.credentials.Token = "guest-test-token" | |
| 15 | 新增: called := 0 | |
| 16 | 新增: s.guestClient = &http.Client{Transport: browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 17 | 新增: called++ | |
| 18 | 新增: if r.URL.String() != "http://127.0.0.1:18500/download-retry" || r.Header.Get("Authorization") != "Bearer guest-test-token" { | |
| 19 | 新增: t.Fatal("retry did not use the fixed authenticated guest endpoint") | |
| 20 | 新增: } | |
| 21 | 新增: var input struct{ ID string } | |
| 22 | 新增: if err := json.NewDecoder(r.Body).Decode(&input); err != nil || input.ID != "download-id" { | |
| 23 | 新增: t.Fatal("retry lost the selected download", err) | |
| 24 | 新增: } | |
| 25 | 新增: return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"ok":true}`))}, nil | |
| 26 | 新增: })} | |
| 27 | 新增: for _, action := range []string{"download-retry", "editor-restart"} { | |
| 28 | 新增: if w := request(s, "POST", "/api/browser/"+action, s.origin, `{}`, false); w.Code != 401 { | |
| 29 | 新增: t.Fatal("recovery accepted without session", action, w.Code) | |
| 30 | 新增: } | |
| 31 | 新增: if w := request(s, "POST", "/api/browser/"+action, "https://example.com", `{}`, true); w.Code != 403 { | |
| 32 | 新增: t.Fatal("cross-origin recovery accepted", action, w.Code) | |
| 33 | 新增: } | |
| 34 | 新增: if w := request(s, "POST", "/api/browser/"+action, s.origin, `{"unit":"ssh.service"}`, true); w.Code != 400 { | |
| 35 | 新增: t.Fatal("arbitrary service parameters accepted", action, w.Code) | |
| 36 | 新增: } | |
| 37 | 新增: } | |
| 38 | 新增: if called != 0 { | |
| 39 | 新增: t.Fatal("rejected request reached the guest") | |
| 40 | 新增: } | |
| 41 | 新增: if w := request(s, "POST", "/api/browser/download-retry", s.origin, `{"id":"download-id"}`, true); w.Code != 200 || called != 1 { | |
| 42 | 新增: t.Fatal("authorized retry failed", w.Code, w.Body.String()) | |
| 43 | 新增: } | |
| 44 | 新增:} | |
| @@ -0,0 +1,49 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "io" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestBrowserTextRequiresSessionAndExplicitTarget(t *testing.T) { | |
| 12 | 新增: s := testServer(t) | |
| 13 | 新增: s.ready = true | |
| 14 | 新增: s.credentials.Token = "guest-test-token" | |
| 15 | 新增: calls := 0 | |
| 16 | 新增: s.guestClient = &http.Client{Transport: browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 17 | 新增: calls++ | |
| 18 | 新增: if r.URL.String() != "http://127.0.0.1:18500/insert-text" || r.Header.Get("Authorization") != "Bearer guest-test-token" { | |
| 19 | 新增: t.Fatal("wrong text destination or authentication") | |
| 20 | 新增: } | |
| 21 | 新增: var input struct { | |
| 22 | 新增: ID string | |
| 23 | 新增: Text string | |
| 24 | 新增: } | |
| 25 | 新增: if err := json.NewDecoder(r.Body).Decode(&input); err != nil || input.ID != "tab-1" || input.Text != "是,大奥🙂" { | |
| 26 | 新增: t.Fatal("text or target changed", err) | |
| 27 | 新增: } | |
| 28 | 新增: return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"ok":true}`))}, nil | |
| 29 | 新增: })} | |
| 30 | 新增: path := "/api/browser/insert-text" | |
| 31 | 新增: valid := `{"id":"tab-1","text":"是,大奥🙂"}` | |
| 32 | 新增: if w := request(s, "POST", path, s.origin, valid, false); w.Code != 401 { | |
| 33 | 新增: t.Fatal("unauthenticated input accepted", w.Code) | |
| 34 | 新增: } | |
| 35 | 新增: if w := request(s, "POST", path, "https://example.com", valid, true); w.Code != 403 { | |
| 36 | 新增: t.Fatal("cross-origin input accepted", w.Code) | |
| 37 | 新增: } | |
| 38 | 新增: for _, body := range []string{`{"text":"是"}`, `{"id":"tab-1"}`, `{"id":"tab-1","text":""}`, `{"id":"tab-1","text":"` + strings.Repeat("中", 3000) + `"}`} { | |
| 39 | 新增: if w := request(s, "POST", path, s.origin, body, true); w.Code != 400 { | |
| 40 | 新增: t.Fatal("invalid input accepted", w.Code) | |
| 41 | 新增: } | |
| 42 | 新增: } | |
| 43 | 新增: if calls != 0 { | |
| 44 | 新增: t.Fatal("rejected input reached guest") | |
| 45 | 新增: } | |
| 46 | 新增: if w := request(s, "POST", path, s.origin, valid, true); w.Code != 200 || calls != 1 { | |
| 47 | 新增: t.Fatal("valid input rejected", w.Code, w.Body.String()) | |
| 48 | 新增: } | |
| 49 | 新增:} | |
| @@ -0,0 +1,66 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "fmt" | |
| 7 | 新增: "os" | |
| 8 | 新增: "os/exec" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "runtime" | |
| 11 | 新增: "strconv" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "time" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:type legacyProcessIdentity struct { | |
| 17 | 新增: PID int | |
| 18 | 新增: Executable, Started string | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 21 | 新增:// Legacy controllers have no atomic handoff endpoint. This compatibility path | |
| 22 | 新增:// runs only after an explicit stop-and-update request, never during startup. | |
| 23 | 新增:// The private PID record alone is not authority to signal a process. | |
| 24 | 新增:func identifyLegacyController(profile string, record controlFile) (legacyProcessIdentity, error) { | |
| 25 | 新增: refused := errors.New("无法确认旧后台进程身份,未停止任何进程。请保留现有环境并重试更新。") | |
| 26 | 新增: if runtime.GOOS != "darwin" || record.PID <= 1 || record.PID == os.Getpid() { | |
| 27 | 新增: return legacyProcessIdentity{}, refused | |
| 28 | 新增: } | |
| 29 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
| 30 | 新增: defer cancel() | |
| 31 | 新增: read := func(binary string, args ...string) (string, error) { | |
| 32 | 新增: b, err := exec.CommandContext(ctx, binary, args...).Output() | |
| 33 | 新增: return strings.TrimSpace(string(b)), err | |
| 34 | 新增: } | |
| 35 | 新增: pid := strconv.Itoa(record.PID) | |
| 36 | 新增: uid, err := read("/bin/ps", "-p", pid, "-o", "uid=") | |
| 37 | 新增: if err != nil || uid != strconv.Itoa(os.Getuid()) { | |
| 38 | 新增: return legacyProcessIdentity{}, refused | |
| 39 | 新增: } | |
| 40 | 新增: started, err := read("/bin/ps", "-p", pid, "-o", "lstart=") | |
| 41 | 新增: if err != nil || started == "" { | |
| 42 | 新增: return legacyProcessIdentity{}, refused | |
| 43 | 新增: } | |
| 44 | 新增: executable, err := read("/bin/ps", "-p", pid, "-o", "comm=") | |
| 45 | 新增: if err != nil || !filepath.IsAbs(executable) || filepath.Base(executable) != "cage" { | |
| 46 | 新增: return legacyProcessIdentity{}, refused | |
| 47 | 新增: } | |
| 48 | 新增: command, err := read("/bin/ps", "-ww", "-p", pid, "-o", "command=") | |
| 49 | 新增: if err != nil || command != executable+" serve" { | |
| 50 | 新增: return legacyProcessIdentity{}, refused | |
| 51 | 新增: } | |
| 52 | 新增: cwd, err := read("/usr/sbin/lsof", "-a", "-p", pid, "-d", "cwd", "-Fn") | |
| 53 | 新增: realProfile, pathErr := filepath.EvalSymlinks(profile) | |
| 54 | 新增: if err != nil || pathErr != nil || !strings.Contains("\n"+cwd+"\n", "\nn"+realProfile+"\n") { | |
| 55 | 新增: return legacyProcessIdentity{}, refused | |
| 56 | 新增: } | |
| 57 | 新增: listener, err := read("/usr/sbin/lsof", "-nP", "-a", "-p", pid, fmt.Sprintf("-iTCP:%d", record.Port), "-sTCP:LISTEN", "-Fn") | |
| 58 | 新增: if err != nil || !strings.Contains("\n"+listener+"\n", fmt.Sprintf("\nn127.0.0.1:%d\n", record.Port)) { | |
| 59 | 新增: return legacyProcessIdentity{}, refused | |
| 60 | 新增: } | |
| 61 | 新增: finalStart, err := read("/bin/ps", "-p", pid, "-o", "lstart=") | |
| 62 | 新增: if err != nil || finalStart != started { | |
| 63 | 新增: return legacyProcessIdentity{}, refused | |
| 64 | 新增: } | |
| 65 | 新增: return legacyProcessIdentity{PID: record.PID, Executable: executable, Started: started}, nil | |
| 66 | 新增:} | |
| @@ -0,0 +1,109 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "syscall" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/managedproxy" | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/version" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:const controlProtocol = 1 | |
| 15 | 新增: | |
| 16 | 新增:type ControllerIdentity struct { | |
| 17 | 新增: Version string `json:"version"` | |
| 18 | 新增: Build string `json:"build"` | |
| 19 | 新增: Protocol int `json:"protocol"` | |
| 20 | 新增: PID int `json:"pid"` | |
| 21 | 新增:} | |
| 22 | 新增: | |
| 23 | 新增:func currentController() (ControllerIdentity, error) { | |
| 24 | 新增: build, err := version.ExecutableIdentity() | |
| 25 | 新增: return ControllerIdentity{Version: version.Version, Build: build, Protocol: controlProtocol, PID: os.Getpid()}, err | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:func (identity ControllerIdentity) matches(other ControllerIdentity) bool { | |
| 29 | 新增: return identity.Build != "" && identity.Build == other.Build && identity.Protocol == other.Protocol | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:type launchResponse struct { | |
| 33 | 新增: URL string `json:"url"` | |
| 34 | 新增: Controller ControllerIdentity `json:"controller"` | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func (s *Server) launcherAuthenticated(w http.ResponseWriter, r *http.Request) bool { | |
| 38 | 新增: var input struct { | |
| 39 | 新增: Token string `json:"token"` | |
| 40 | 新增: } | |
| 41 | 新增: if !readJSON(w, r, &input) { | |
| 42 | 新增: return false | |
| 43 | 新增: } | |
| 44 | 新增: if !equalSecret(input.Token, s.token) { | |
| 45 | 新增: http.Error(w, "Launcher refused", http.StatusUnauthorized) | |
| 46 | 新增: return false | |
| 47 | 新增: } | |
| 48 | 新增: return true | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:func (s *Server) handoff(w http.ResponseWriter, r *http.Request) { | |
| 52 | 新增: if !s.launcherAuthenticated(w, r) { | |
| 53 | 新增: return | |
| 54 | 新增: } | |
| 55 | 新增: if !s.op.TryLock() { | |
| 56 | 新增: http.Error(w, "请先保存工作并停止环境,再完成更新。", http.StatusConflict) | |
| 57 | 新增: return | |
| 58 | 新增: } | |
| 59 | 新增: s.mu.Lock() | |
| 60 | 新增: busy := s.job.Running || controllerHasVM(s.profile) | |
| 61 | 新增: for _, terminal := range s.terminals { | |
| 62 | 新增: terminal.mu.Lock() | |
| 63 | 新增: busy = busy || !terminal.closed | |
| 64 | 新增: terminal.mu.Unlock() | |
| 65 | 新增: } | |
| 66 | 新增: if busy || s.shutdown == nil { | |
| 67 | 新增: s.mu.Unlock() | |
| 68 | 新增: s.op.Unlock() | |
| 69 | 新增: http.Error(w, "请先保存工作并停止环境,再完成更新。", http.StatusConflict) | |
| 70 | 新增: return | |
| 71 | 新增: } | |
| 72 | 新增: s.closing = true | |
| 73 | 新增: s.mu.Unlock() | |
| 74 | 新增: if err := managedproxy.Stop(s.profile); err != nil { | |
| 75 | 新增: s.mu.Lock() | |
| 76 | 新增: s.closing = false | |
| 77 | 新增: s.mu.Unlock() | |
| 78 | 新增: s.op.Unlock() | |
| 79 | 新增: http.Error(w, "代理尚未停止,未继续后台更新。", http.StatusConflict) | |
| 80 | 新增: return | |
| 81 | 新增: } | |
| 82 | 新增: jsonReply(w, map[string]bool{"stopping": true}) | |
| 83 | 新增: // Keep the lifecycle lock until the listener and current HTTP handlers close. | |
| 84 | 新增: // No new job or terminal may start after the idle decision. | |
| 85 | 新增: go func() { s.shutdown(); s.op.Unlock() }() | |
| 86 | 新增:} | |
| 87 | 新增: | |
| 88 | 新增:func controllerHasVM(profile string) bool { | |
| 89 | 新增: records, err := filepath.Glob(filepath.Join(profile, "state", "lima", "*", "cage-running.json")) | |
| 90 | 新增: if err != nil { | |
| 91 | 新增: return true | |
| 92 | 新增: } | |
| 93 | 新增: for _, path := range records { | |
| 94 | 新增: b, err := os.ReadFile(path) | |
| 95 | 新增: if err != nil { | |
| 96 | 新增: return true | |
| 97 | 新增: } | |
| 98 | 新增: var record struct { | |
| 99 | 新增: PID int `json:"pid"` | |
| 100 | 新增: } | |
| 101 | 新增: if json.Unmarshal(b, &record) != nil || record.PID <= 0 { | |
| 102 | 新增: return true | |
| 103 | 新增: } | |
| 104 | 新增: if err := syscall.Kill(record.PID, 0); err == nil || err != syscall.ESRCH { | |
| 105 | 新增: return true | |
| 106 | 新增: } | |
| 107 | 新增: } | |
| 108 | 新增: return false | |
| 109 | 新增:} | |
| @@ -0,0 +1,148 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "net" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "net/http/httptest" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "strconv" | |
| 10 | 新增: "sync/atomic" | |
| 11 | 新增: "syscall" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:func TestHandoffRequiresLauncherSecretAndIdleEnvironment(t *testing.T) { | |
| 17 | 新增: for _, busy := range []string{"none", "job", "terminal", "vm", "operation"} { | |
| 18 | 新增: t.Run(busy, func(t *testing.T) { | |
| 19 | 新增: s := testServer(t) | |
| 20 | 新增: var stopped atomic.Bool | |
| 21 | 新增: s.shutdown = func() { stopped.Store(true) } | |
| 22 | 新增: switch busy { | |
| 23 | 新增: case "job": | |
| 24 | 新增: s.job = Job{ID: "active", Running: true} | |
| 25 | 新增: case "terminal": | |
| 26 | 新增: s.terminals["live"] = &terminalSession{} | |
| 27 | 新增: case "vm": | |
| 28 | 新增: path := filepath.Join(s.profile, "state", "lima", "base-building", "cage-running.json") | |
| 29 | 新增: if err := writePrivate(path, map[string]int{"pid": os.Getpid()}); err != nil { | |
| 30 | 新增: t.Fatal(err) | |
| 31 | 新增: } | |
| 32 | 新增: case "operation": | |
| 33 | 新增: s.op.Lock() | |
| 34 | 新增: defer s.op.Unlock() | |
| 35 | 新增: } | |
| 36 | 新增: if w := request(s, "POST", "/api/handoff", s.origin, `{"token":"wrong"}`, true); w.Code != 401 { | |
| 37 | 新增: t.Fatalf("session bypassed launcher secret: %d", w.Code) | |
| 38 | 新增: } | |
| 39 | 新增: if w := request(s, "POST", "/api/handoff", "https://elsewhere.example", `{"token":"`+s.token+`"}`, false); w.Code != 403 { | |
| 40 | 新增: t.Fatalf("cross-origin handoff: %d", w.Code) | |
| 41 | 新增: } | |
| 42 | 新增: w := request(s, "POST", "/api/handoff", s.origin, `{"token":"`+s.token+`"}`, false) | |
| 43 | 新增: if busy != "none" { | |
| 44 | 新增: if w.Code != 409 || stopped.Load() { | |
| 45 | 新增: t.Fatalf("terminated busy controller: %d", w.Code) | |
| 46 | 新增: } | |
| 47 | 新增: return | |
| 48 | 新增: } | |
| 49 | 新增: if w.Code != 200 { | |
| 50 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 51 | 新增: } | |
| 52 | 新增: deadline := time.Now().Add(time.Second) | |
| 53 | 新增: for !stopped.Load() && time.Now().Before(deadline) { | |
| 54 | 新增: time.Sleep(time.Millisecond) | |
| 55 | 新增: } | |
| 56 | 新增: if !stopped.Load() { | |
| 57 | 新增: t.Fatal("idle controller did not shut down") | |
| 58 | 新增: } | |
| 59 | 新增: launchResult := httptest.NewRecorder() | |
| 60 | 新增: s.launch(launchResult, "start", func() error { t.Error("new work started after handoff"); return nil }) | |
| 61 | 新增: if launchResult.Code != http.StatusServiceUnavailable { | |
| 62 | 新增: t.Fatalf("new job accepted after handoff: %d", launchResult.Code) | |
| 63 | 新增: } | |
| 64 | 新增: if w := request(s, "POST", "/api/terminals", s.origin, `{}`, true); w.Code != 503 { | |
| 65 | 新增: t.Fatalf("terminal accepted after handoff: %d", w.Code) | |
| 66 | 新增: } | |
| 67 | 新增: }) | |
| 68 | 新增: } | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:func TestDesktopRejectsUnknownAndDifferentBuildsWithoutStoppingThem(t *testing.T) { | |
| 72 | 新增: current, err := currentController() | |
| 73 | 新增: if err != nil { | |
| 74 | 新增: t.Fatal(err) | |
| 75 | 新增: } | |
| 76 | 新增: for _, kind := range []string{"same", "same-version-other-build", "legacy"} { | |
| 77 | 新增: t.Run(kind, func(t *testing.T) { | |
| 78 | 新增: profile := t.TempDir() | |
| 79 | 新增: identity := current | |
| 80 | 新增: if kind == "same-version-other-build" { | |
| 81 | 新增: identity.Build = "different-build" | |
| 82 | 新增: } | |
| 83 | 新增: if kind == "legacy" { | |
| 84 | 新增: identity = ControllerIdentity{} | |
| 85 | 新增: } | |
| 86 | 新增: var stopCalled bool | |
| 87 | 新增: var origin string | |
| 88 | 新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 89 | 新增: switch r.URL.Path { | |
| 90 | 新增: case "/api/launch": | |
| 91 | 新增: jsonReply(w, launchResponse{URL: origin + "/#ticket", Controller: identity}) | |
| 92 | 新增: case "/api/handoff": | |
| 93 | 新增: http.Error(w, "busy", 409) | |
| 94 | 新增: case "/api/stop": | |
| 95 | 新增: stopCalled = true | |
| 96 | 新增: http.Error(w, "unexpected", 500) | |
| 97 | 新增: default: | |
| 98 | 新增: http.NotFound(w, r) | |
| 99 | 新增: } | |
| 100 | 新增: })) | |
| 101 | 新增: defer server.Close() | |
| 102 | 新增: _, portString, _ := net.SplitHostPort(server.Listener.Addr().String()) | |
| 103 | 新增: port, _ := strconv.Atoi(portString) | |
| 104 | 新增: origin = "http://localhost:" + portString | |
| 105 | 新增: if err := writePrivate(filepath.Join(profile, "control.json"), controlFile{Port: port, Token: string(make([]byte, 64)), PID: os.Getpid()}); err != nil { | |
| 106 | 新增: t.Fatal(err) | |
| 107 | 新增: } | |
| 108 | 新增: entry, err := Desktop(filepath.Join(profile, "config.json"), DesktopOptions{}) | |
| 109 | 新增: if err != nil { | |
| 110 | 新增: t.Fatal(err) | |
| 111 | 新增: } | |
| 112 | 新增: if kind == "same" { | |
| 113 | 新增: if entry.Status != "ready" || entry.URL == "" { | |
| 114 | 新增: t.Fatalf("same build refused: %+v", entry) | |
| 115 | 新增: } | |
| 116 | 新增: } else if entry.Status != "upgrade_pending" || entry.URL != "" { | |
| 117 | 新增: t.Fatalf("old build silently connected: %+v", entry) | |
| 118 | 新增: } | |
| 119 | 新增: if stopCalled { | |
| 120 | 新增: t.Fatal("startup stopped existing work") | |
| 121 | 新增: } | |
| 122 | 新增: if kind == "legacy" { | |
| 123 | 新增: if _, err := Desktop(filepath.Join(profile, "config.json"), DesktopOptions{CompleteUpdate: true}); err == nil { | |
| 124 | 新增: t.Fatal("unverified legacy PID accepted") | |
| 125 | 新增: } | |
| 126 | 新增: if stopCalled { | |
| 127 | 新增: t.Fatal("signalled or stopped unverified legacy process") | |
| 128 | 新增: } | |
| 129 | 新增: } | |
| 130 | 新增: }) | |
| 131 | 新增: } | |
| 132 | 新增:} | |
| 133 | 新增: | |
| 134 | 新增:func TestPrepareUpdateDoesNotAcceptUnresponsiveLockedController(t *testing.T) { | |
| 135 | 新增: profile := t.TempDir() | |
| 136 | 新增: f, err := os.OpenFile(filepath.Join(profile, "control.lock"), os.O_CREATE|os.O_RDWR, 0600) | |
| 137 | 新增: if err != nil { | |
| 138 | 新增: t.Fatal(err) | |
| 139 | 新增: } | |
| 140 | 新增: defer f.Close() | |
| 141 | 新增: if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { | |
| 142 | 新增: t.Fatal(err) | |
| 143 | 新增: } | |
| 144 | 新增: defer syscall.Flock(int(f.Fd()), syscall.LOCK_UN) | |
| 145 | 新增: if _, err := PrepareUpdate(filepath.Join(profile, "config.json"), false); err == nil { | |
| 146 | 新增: t.Fatal("locked offline service accepted as safe to replace") | |
| 147 | 新增: } | |
| 148 | 新增:} | |
| @@ -5,81 +5,335 @@ import ( | ||
| 5 | 5 | "encoding/json" |
| 6 | 6 | "errors" |
| 7 | 7 | "fmt" |
| 8 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 9 | 新增: "io" | |
| 8 | 10 | "net/http" |
| 11 | 新增: "net/http/cookiejar" | |
| 12 | 新增: "net/url" | |
| 9 | 13 | "os" |
| 10 | 14 | "os/exec" |
| 11 | 15 | "path/filepath" |
| 12 | 16 | "syscall" |
| 13 | 17 | "time" |
| 14 | 删除: | |
| 15 | 删除: "github.com/sylvinus/agent-vm/internal/cage" | |
| 16 | 18 | ) |
| 17 | 19 | |
| 18 | 删除:// Desktop returns a bootstrap URL only to the local launcher. The token stays | |
| 19 | 删除:// in the fragment, is exchanged once the trusted UI loads, then leaves the URL. | |
| 20 | 删除:func Desktop(configPath string) (string, error) { | |
| 20 | 新增:type DesktopOptions struct{ CompleteUpdate, UseExisting bool } | |
| 21 | 新增:type DesktopResult struct { | |
| 22 | 新增: Status string `json:"status"` | |
| 23 | 新增: URL string `json:"url,omitempty"` | |
| 24 | 新增: Message string `json:"message,omitempty"` | |
| 25 | 新增: Legacy bool `json:"legacy,omitempty"` | |
| 26 | 新增: Controller ControllerIdentity `json:"controller"` | |
| 27 | 新增:} | |
| 28 | 新增:type controllerClient struct { | |
| 29 | 新增: profile, origin string | |
| 30 | 新增: record controlFile | |
| 31 | 新增: launch launchResponse | |
| 32 | 新增: client *http.Client | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:var errControllerUnavailable = errors.New("control service is unavailable") | |
| 36 | 新增: | |
| 37 | 新增:func connectController(profile string) (*controllerClient, error) { | |
| 38 | 新增: b, err := os.ReadFile(filepath.Join(profile, "control.json")) | |
| 39 | 新增: if os.IsNotExist(err) { | |
| 40 | 新增: return nil, errControllerUnavailable | |
| 41 | 新增: } | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: return nil, err | |
| 44 | 新增: } | |
| 45 | 新增: var record controlFile | |
| 46 | 新增: if json.Unmarshal(b, &record) != nil || record.Port < 1024 || record.Port > 65535 || len(record.Token) != 64 || record.PID < 1 { | |
| 47 | 新增: return nil, errors.New("后台记录无效,请保留现有环境并检查私有配置。") | |
| 48 | 新增: } | |
| 49 | 新增: jar, _ := cookiejar.New(nil) | |
| 50 | 新增: c := &controllerClient{profile: profile, record: record, origin: fmt.Sprintf("http://localhost:%d", record.Port), client: &http.Client{Timeout: 5 * time.Second, Jar: jar, Transport: &http.Transport{Proxy: nil}, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }}} | |
| 51 | 新增: status, err := c.call("POST", "/api/launch", map[string]string{"token": record.Token}, &c.launch) | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: c.close() | |
| 54 | 新增: var networkError *url.Error | |
| 55 | 新增: if errors.As(err, &networkError) { | |
| 56 | 新增: return nil, errControllerUnavailable | |
| 57 | 新增: } | |
| 58 | 新增: return nil, err | |
| 59 | 新增: } | |
| 60 | 新增: if status != http.StatusOK { | |
| 61 | 新增: c.close() | |
| 62 | 新增: return nil, errors.New("无法认证已有后台,未尝试终止或替换它。") | |
| 63 | 新增: } | |
| 64 | 新增: u, err := url.Parse(c.launch.URL) | |
| 65 | 新增: if err != nil || u.Scheme != "http" || u.Host != fmt.Sprintf("localhost:%d", record.Port) || u.User != nil || u.Fragment == "" { | |
| 66 | 新增: c.close() | |
| 67 | 新增: return nil, errors.New("后台返回了无效入口,未连接旧工作台。") | |
| 68 | 新增: } | |
| 69 | 新增: if c.launch.Controller.Protocol != 0 && c.launch.Controller.PID != record.PID { | |
| 70 | 新增: c.close() | |
| 71 | 新增: return nil, errors.New("后台身份已变化,请重试连接。") | |
| 72 | 新增: } | |
| 73 | 新增: return c, nil | |
| 74 | 新增:} | |
| 75 | 新增:func (c *controllerClient) close() { c.client.CloseIdleConnections() } | |
| 76 | 新增:func (c *controllerClient) call(method, path string, input, output any) (int, error) { | |
| 77 | 新增: var body []byte | |
| 78 | 新增: var err error | |
| 79 | 新增: if input != nil { | |
| 80 | 新增: body, err = json.Marshal(input) | |
| 81 | 新增: if err != nil { | |
| 82 | 新增: return 0, err | |
| 83 | 新增: } | |
| 84 | 新增: } | |
| 85 | 新增: req, err := http.NewRequest(method, c.origin+path, bytes.NewReader(body)) | |
| 86 | 新增: if err != nil { | |
| 87 | 新增: return 0, err | |
| 88 | 新增: } | |
| 89 | 新增: req.Header.Set("Origin", c.origin) | |
| 90 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 91 | 新增: res, err := c.client.Do(req) | |
| 92 | 新增: if err != nil { | |
| 93 | 新增: return 0, err | |
| 94 | 新增: } | |
| 95 | 新增: defer res.Body.Close() | |
| 96 | 新增: if res.StatusCode == http.StatusOK && output != nil { | |
| 97 | 新增: if err = json.NewDecoder(io.LimitReader(res.Body, 256<<10)).Decode(output); err != nil { | |
| 98 | 新增: return res.StatusCode, errors.New("后台响应无效,未继续更新。") | |
| 99 | 新增: } | |
| 100 | 新增: } | |
| 101 | 新增: return res.StatusCode, nil | |
| 102 | 新增:} | |
| 103 | 新增:func pendingUpdate(c *controllerClient) DesktopResult { | |
| 104 | 新增: return DesktopResult{Status: "upgrade_pending", Legacy: c.launch.Controller.Protocol == 0, Controller: c.launch.Controller, Message: "新版已准备好,当前后台仍在运行。请先打开现有环境保存文件,再选择“保存后停止环境并完成更新”。终端任务会结束,项目和登录状态会保留。"} | |
| 105 | 新增:} | |
| 106 | 新增: | |
| 107 | 新增:// Desktop never silently loads a different build's UI. Completing an update is | |
| 108 | 新增:// an explicit user action because it stops the existing environment's work. | |
| 109 | 新增:func Desktop(configPath string, options DesktopOptions) (DesktopResult, error) { | |
| 21 | 110 | profile := filepath.Dir(configPath) |
| 22 | 删除: read := func() (string, bool) { | |
| 23 | 删除: b, e := os.ReadFile(filepath.Join(profile, "control.json")) | |
| 24 | 删除: if e != nil { | |
| 25 | 删除: return "", false | |
| 111 | 新增: want, err := currentController() | |
| 112 | 新增: if err != nil { | |
| 113 | 新增: return DesktopResult{}, err | |
| 114 | 新增: } | |
| 115 | 新增: current, err := connectController(profile) | |
| 116 | 新增: if err == nil { | |
| 117 | 新增: defer current.close() | |
| 118 | 新增: if options.CompleteUpdate { | |
| 119 | 新增: if err = current.stopAndHandoff(); err != nil { | |
| 120 | 新增: return DesktopResult{}, err | |
| 121 | 新增: } | |
| 122 | 新增: } else if want.matches(current.launch.Controller) || options.UseExisting { | |
| 123 | 新增: status := "ready" | |
| 124 | 新增: if !want.matches(current.launch.Controller) { | |
| 125 | 新增: status = "existing" | |
| 126 | 新增: } | |
| 127 | 新增: return DesktopResult{Status: status, URL: current.launch.URL, Controller: current.launch.Controller, Legacy: current.launch.Controller.Protocol == 0}, nil | |
| 128 | 新增: } else { | |
| 129 | 新增: if current.launch.Controller.Protocol != controlProtocol { | |
| 130 | 新增: return pendingUpdate(current), nil | |
| 131 | 新增: } | |
| 132 | 新增: status, handoffErr := current.call("POST", "/api/handoff", map[string]string{"token": current.record.Token}, nil) | |
| 133 | 新增: if handoffErr != nil { | |
| 134 | 新增: return DesktopResult{}, handoffErr | |
| 135 | 新增: } | |
| 136 | 新增: if status != http.StatusOK { | |
| 137 | 新增: return pendingUpdate(current), nil | |
| 138 | 新增: } | |
| 139 | 新增: if err = current.waitForExit(); err != nil { | |
| 140 | 新增: return DesktopResult{}, err | |
| 141 | 新增: } | |
| 142 | 新增: } | |
| 143 | 新增: } else if !errors.Is(err, errControllerUnavailable) { | |
| 144 | 新增: return DesktopResult{}, err | |
| 145 | 新增: } | |
| 146 | 新增: if err = startController(configPath); err != nil { | |
| 147 | 新增: return DesktopResult{}, err | |
| 148 | 新增: } | |
| 149 | 新增: for i := 0; i < 60; i++ { | |
| 150 | 新增: c, readErr := connectController(profile) | |
| 151 | 新增: if readErr == nil { | |
| 152 | 新增: c.close() | |
| 153 | 新增: if want.matches(c.launch.Controller) { | |
| 154 | 新增: return DesktopResult{Status: "ready", URL: c.launch.URL, Controller: c.launch.Controller}, nil | |
| 155 | 新增: } | |
| 156 | 新增: return pendingUpdate(c), nil | |
| 157 | 新增: } | |
| 158 | 新增: time.Sleep(200 * time.Millisecond) | |
| 159 | 新增: } | |
| 160 | 新增: return DesktopResult{}, errors.New("工作台未能启动,请查看私有配置中的 control.log 后重试。") | |
| 161 | 新增:} | |
| 162 | 新增: | |
| 163 | 新增:// PrepareUpdate is shared by the explicit migration button and the installer. | |
| 164 | 新增:// It returns only after the old service has released its profile lock. | |
| 165 | 新增:func PrepareUpdate(configPath string, stop bool) (DesktopResult, error) { | |
| 166 | 新增: c, err := connectController(filepath.Dir(configPath)) | |
| 167 | 新增: if errors.Is(err, errControllerUnavailable) { | |
| 168 | 新增: lock, lockErr := os.OpenFile(filepath.Join(filepath.Dir(configPath), "control.lock"), os.O_RDWR, 0600) | |
| 169 | 新增: if lockErr == nil { | |
| 170 | 新增: defer lock.Close() | |
| 171 | 新增: if syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) != nil { | |
| 172 | 新增: return DesktopResult{}, errors.New("后台暂时无法连接且尚未退出,请恢复连接后重试更新。") | |
| 173 | 新增: } | |
| 174 | 新增: defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) | |
| 175 | 新增: } else if !os.IsNotExist(lockErr) { | |
| 176 | 新增: return DesktopResult{}, lockErr | |
| 177 | 新增: } | |
| 178 | 新增: if controllerHasVM(filepath.Dir(configPath)) { | |
| 179 | 新增: return DesktopResult{}, errors.New("后台无法连接,但仍有环境进程。请恢复工作台连接并保存停止后再更新。") | |
| 26 | 180 | } |
| 27 | 删除: var v controlFile | |
| 28 | 删除: if json.Unmarshal(b, &v) != nil || v.Port < 1024 || v.Port > 65535 || len(v.Token) != 64 { | |
| 29 | 删除: return "", false | |
| 181 | 新增: return DesktopResult{Status: "prepared"}, nil | |
| 182 | 新增: } | |
| 183 | 新增: if err != nil { | |
| 184 | 新增: return DesktopResult{}, err | |
| 185 | 新增: } | |
| 186 | 新增: defer c.close() | |
| 187 | 新增: if stop { | |
| 188 | 新增: if err = c.stopAndHandoff(); err != nil { | |
| 189 | 新增: return DesktopResult{}, err | |
| 190 | 新增: } | |
| 191 | 新增: return DesktopResult{Status: "prepared"}, nil | |
| 192 | 新增: } | |
| 193 | 新增: if c.launch.Controller.Protocol == controlProtocol { | |
| 194 | 新增: status, err := c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil) | |
| 195 | 新增: if err != nil { | |
| 196 | 新增: return DesktopResult{}, err | |
| 197 | 新增: } | |
| 198 | 新增: if status == http.StatusOK { | |
| 199 | 新增: if err = c.waitForExit(); err != nil { | |
| 200 | 新增: return DesktopResult{}, err | |
| 201 | 新增: } | |
| 202 | 新增: return DesktopResult{Status: "prepared"}, nil | |
| 203 | 新增: } | |
| 204 | 新增: } | |
| 205 | 新增: return DesktopResult{Status: "stop_required", Message: "请保存文件后确认停止环境并安装更新。终端任务会结束,项目和登录状态会保留。"}, nil | |
| 206 | 新增:} | |
| 207 | 新增:func (c *controllerClient) stopAndHandoff() error { | |
| 208 | 新增: legacy := c.launch.Controller.Protocol == 0 | |
| 209 | 新增: var owner legacyProcessIdentity | |
| 210 | 新增: var err error | |
| 211 | 新增: if legacy { | |
| 212 | 新增: owner, err = identifyLegacyController(c.profile, c.record) | |
| 213 | 新增: if err != nil { | |
| 214 | 新增: return err | |
| 215 | 新增: } | |
| 216 | 新增: } else if c.launch.Controller.Protocol != controlProtocol { | |
| 217 | 新增: return errors.New("当前后台协议不受此版本支持,已保留运行环境。请使用匹配的 Cage 版本停止环境。") | |
| 218 | 新增: } | |
| 219 | 新增: u, _ := url.Parse(c.launch.URL) | |
| 220 | 新增: status, err := c.call("POST", "/api/session", map[string]string{"token": u.Fragment}, nil) | |
| 221 | 新增: if err != nil { | |
| 222 | 新增: return err | |
| 223 | 新增: } | |
| 224 | 新增: if status != http.StatusOK { | |
| 225 | 新增: return errors.New("无法建立停止会话,请重试。") | |
| 226 | 新增: } | |
| 227 | 新增: var requested Job | |
| 228 | 新增: status, err = c.call("POST", "/api/stop", map[string]any{}, &requested) | |
| 229 | 新增: if err != nil { | |
| 230 | 新增: return err | |
| 231 | 新增: } | |
| 232 | 新增: if status != http.StatusOK || requested.ID == "" { | |
| 233 | 新增: return errors.New("后台未接受停止请求,已取消本次更新。") | |
| 234 | 新增: } | |
| 235 | 新增: deadline := time.Now().Add(2 * time.Minute) | |
| 236 | 新增: for { | |
| 237 | 新增: var state struct { | |
| 238 | 新增: VMRunning *bool `json:"vm_running"` | |
| 239 | 新增: Job Job `json:"job"` | |
| 240 | 新增: } | |
| 241 | 新增: status, err = c.call("GET", "/api/status", nil, &state) | |
| 242 | 新增: if err != nil { | |
| 243 | 新增: return err | |
| 244 | 新增: } | |
| 245 | 新增: if status != http.StatusOK || state.VMRunning == nil || state.Job.ID != requested.ID { | |
| 246 | 新增: return errors.New("停止状态发生变化,未终止后台;请确认现有任务后重试。") | |
| 247 | 新增: } | |
| 248 | 新增: if !state.Job.Running { | |
| 249 | 新增: if state.Job.Error != "" || *state.VMRunning { | |
| 250 | 新增: return errors.New("环境未能安全停止,未继续更新。请在原工作台查看停止结果。") | |
| 251 | 新增: } | |
| 252 | 新增: break | |
| 253 | 新增: } | |
| 254 | 新增: if time.Now().After(deadline) { | |
| 255 | 新增: return errors.New("停止环境超时,后台保持运行,请稍后重试更新。") | |
| 30 | 256 | } |
| 31 | 删除: origin := fmt.Sprintf("http://localhost:%d", v.Port) | |
| 32 | 删除: body, _ := json.Marshal(map[string]string{"token": v.Token}) | |
| 33 | 删除: req, _ := http.NewRequest("POST", origin+"/api/launch", bytes.NewReader(body)) | |
| 34 | 删除: req.Header.Set("Origin", origin) | |
| 35 | 删除: req.Header.Set("Content-Type", "application/json") | |
| 36 | 删除: client := &http.Client{Timeout: time.Second, Transport: &http.Transport{Proxy: nil}} | |
| 37 | 删除: res, e := client.Do(req) | |
| 38 | 删除: if e != nil { | |
| 39 | 删除: return "", false | |
| 257 | 新增: time.Sleep(200 * time.Millisecond) | |
| 258 | 新增: } | |
| 259 | 新增: var terminals []struct { | |
| 260 | 新增: Closed bool `json:"closed"` | |
| 261 | 新增: } | |
| 262 | 新增: status, err = c.call("GET", "/api/terminals", nil, &terminals) | |
| 263 | 新增: if err != nil { | |
| 264 | 新增: return err | |
| 265 | 新增: } | |
| 266 | 新增: if status != http.StatusOK { | |
| 267 | 新增: return errors.New("无法确认终端已停止,未继续更新。") | |
| 268 | 新增: } | |
| 269 | 新增: for _, terminal := range terminals { | |
| 270 | 新增: if !terminal.Closed { | |
| 271 | 新增: return errors.New("仍有终端运行,未继续更新。") | |
| 272 | 新增: } | |
| 273 | 新增: } | |
| 274 | 新增: if legacy { | |
| 275 | 新增: verified, err := identifyLegacyController(c.profile, c.record) | |
| 276 | 新增: if err != nil || verified != owner { | |
| 277 | 新增: return errors.New("旧后台进程身份已变化,未发送退出信号;请重试更新。") | |
| 278 | 新增: } | |
| 279 | 新增: var final struct { | |
| 280 | 新增: VMRunning *bool `json:"vm_running"` | |
| 281 | 新增: Job Job `json:"job"` | |
| 282 | 新增: } | |
| 283 | 新增: status, err = c.call("GET", "/api/status", nil, &final) | |
| 284 | 新增: if err != nil || status != http.StatusOK || final.VMRunning == nil || *final.VMRunning || final.Job.ID != requested.ID || final.Job.Running || final.Job.Error != "" || controllerHasVM(c.profile) { | |
| 285 | 新增: return errors.New("停止后又有环境工作,未终止旧后台;请保存停止后重试。") | |
| 40 | 286 | } |
| 41 | 删除: defer res.Body.Close() | |
| 42 | 删除: if res.StatusCode != 200 { | |
| 43 | 删除: return "", false | |
| 287 | 新增: if err = syscall.Kill(owner.PID, syscall.SIGTERM); err != nil { | |
| 288 | 新增: return errors.New("旧后台未能退出,未替换应用。") | |
| 44 | 289 | } |
| 45 | 删除: var response struct { | |
| 46 | 删除: URL string `json:"url"` | |
| 290 | 新增: } else { | |
| 291 | 新增: status, err = c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil) | |
| 292 | 新增: if err != nil { | |
| 293 | 新增: return err | |
| 47 | 294 | } |
| 48 | 删除: if json.NewDecoder(res.Body).Decode(&response) != nil { | |
| 49 | 删除: return "", false | |
| 295 | 新增: if status != http.StatusOK { | |
| 296 | 新增: return errors.New("后台仍在执行工作,未继续更新。请保存并停止后重试。") | |
| 50 | 297 | } |
| 51 | 删除: return response.URL, true | |
| 52 | 298 | } |
| 53 | 删除: if u, ok := read(); ok { | |
| 54 | 删除: return u, nil | |
| 299 | 新增: return c.waitForExit() | |
| 300 | 新增:} | |
| 301 | 新增:func (c *controllerClient) waitForExit() error { | |
| 302 | 新增: f, err := os.OpenFile(filepath.Join(c.profile, "control.lock"), os.O_RDWR, 0600) | |
| 303 | 新增: if err != nil { | |
| 304 | 新增: return errors.New("无法确认后台已退出,未继续更新。") | |
| 305 | 新增: } | |
| 306 | 新增: defer f.Close() | |
| 307 | 新增: for i := 0; i < 100; i++ { | |
| 308 | 新增: if syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) == nil { | |
| 309 | 新增: _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN) | |
| 310 | 新增: return nil | |
| 311 | 新增: } | |
| 312 | 新增: time.Sleep(100 * time.Millisecond) | |
| 55 | 313 | } |
| 56 | 删除: if e := os.MkdirAll(profile, 0700); e != nil { | |
| 57 | 删除: return "", e | |
| 314 | 新增: return errors.New("后台尚未退出,未强制结束进程。请稍后重试更新。") | |
| 315 | 新增:} | |
| 316 | 新增:func startController(configPath string) error { | |
| 317 | 新增: profile := filepath.Dir(configPath) | |
| 318 | 新增: if err := os.MkdirAll(profile, 0700); err != nil { | |
| 319 | 新增: return err | |
| 58 | 320 | } |
| 59 | 删除: exe, e := os.Executable() | |
| 60 | 删除: if e != nil { | |
| 61 | 删除: return "", e | |
| 321 | 新增: exe, err := os.Executable() | |
| 322 | 新增: if err != nil { | |
| 323 | 新增: return err | |
| 62 | 324 | } |
| 63 | 删除: log, e := os.OpenFile(filepath.Join(profile, "control.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) | |
| 64 | 删除: if e != nil { | |
| 65 | 删除: return "", e | |
| 325 | 新增: log, err := os.OpenFile(filepath.Join(profile, "control.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) | |
| 326 | 新增: if err != nil { | |
| 327 | 新增: return err | |
| 66 | 328 | } |
| 67 | 329 | defer log.Close() |
| 68 | 330 | cmd := exec.Command(exe, "serve") |
| 69 | 331 | cmd.Dir = profile |
| 70 | 332 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath) |
| 71 | 删除: cmd.Stdout = log | |
| 72 | 删除: cmd.Stderr = log | |
| 333 | 新增: cmd.Stdout, cmd.Stderr = log, log | |
| 73 | 334 | cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| 74 | 删除: if e = cmd.Start(); e != nil { | |
| 75 | 删除: return "", e | |
| 76 | 删除: } | |
| 77 | 删除: _ = cmd.Process.Release() | |
| 78 | 删除: for i := 0; i < 60; i++ { | |
| 79 | 删除: if u, ok := read(); ok { | |
| 80 | 删除: return u, nil | |
| 81 | 删除: } | |
| 82 | 删除: time.Sleep(200 * time.Millisecond) | |
| 335 | 新增: if err = cmd.Start(); err != nil { | |
| 336 | 新增: return err | |
| 83 | 337 | } |
| 84 | 删除: return "", errors.New("工作台未能启动,请查看 ~/.claude-cage/control.log 后重试") | |
| 338 | 新增: return cmd.Process.Release() | |
| 85 | 339 | } |
| @@ -0,0 +1,210 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "os/exec" | |
| 9 | 新增: "strings" | |
| 10 | 新增: "time" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/managedproxy" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:var errGuestUpdateRequired = errors.New("环境组件需要更新,请先保存浏览器和编辑器中的修改。工作台终端与磁盘保留,编辑器内终端可能结束。") | |
| 17 | 新增: | |
| 18 | 新增:const guestConnectionSnapshot = `sudo cat /etc/claude-cage/browser-control.json; printf '\n'; cat "$HOME/.config/claude-cage/browser-password"; printf '\n'; if sudo test -f /etc/claude-cage/components.json; then sudo cat /etc/claude-cage/components.json; else printf 'null'; fi` | |
| 19 | 新增: | |
| 20 | 新增:func parseGuestConnection(data []byte) (guestCredentials, *cage.GuestManifest, error) { | |
| 21 | 新增: lines := strings.SplitN(strings.TrimSpace(string(data)), "\n", 3) | |
| 22 | 新增: var credentials guestCredentials | |
| 23 | 新增: if len(lines) != 3 || json.Unmarshal([]byte(lines[0]), &credentials) != nil || credentials.Token == "" || strings.TrimSpace(lines[1]) == "" { | |
| 24 | 新增: return credentials, nil, errors.New("浏览器控制服务尚未安装") | |
| 25 | 新增: } | |
| 26 | 新增: credentials.VNCPassword = strings.TrimSpace(lines[1]) | |
| 27 | 新增: var manifest *cage.GuestManifest | |
| 28 | 新增: if json.Unmarshal([]byte(lines[2]), &manifest) != nil || manifest == nil || !manifest.Current() { | |
| 29 | 新增: return credentials, manifest, errGuestUpdateRequired | |
| 30 | 新增: } | |
| 31 | 新增: return credentials, manifest, nil | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:type componentVersions struct { | |
| 35 | 新增: Status string `json:"status"` | |
| 36 | 新增: UpdateRequired bool `json:"update_required"` | |
| 37 | 新增: Required cage.GuestManifest `json:"required"` | |
| 38 | 新增: Current *cage.GuestManifest `json:"current"` | |
| 39 | 新增:} | |
| 40 | 新增:type toolVersion struct { | |
| 41 | 新增: Current string `json:"current"` | |
| 42 | 新增: Required string `json:"required"` | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:// Version commands run only for this explicit request, never in status polling. | |
| 46 | 新增:func (s *Server) environmentVersions(w http.ResponseWriter, r *http.Request) { | |
| 47 | 新增: ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second) | |
| 48 | 新增: defer cancel() | |
| 49 | 新增: running := s.vmRunning() | |
| 50 | 新增: components := componentVersions{Status: "stopped", Required: cage.RequiredGuestManifest()} | |
| 51 | 新增: tools := map[string]toolVersion{} | |
| 52 | 新增: for name, required := range cage.RequiredToolVersions() { | |
| 53 | 新增: tools[name] = toolVersion{Required: required} | |
| 54 | 新增: } | |
| 55 | 新增: var detail string | |
| 56 | 新增: if running { | |
| 57 | 新增: data, err := s.guest(ctx, `python3 - <<'CAGE_VERSIONS' | |
| 58 | 新增:import json,subprocess,os | |
| 59 | 新增:from pathlib import Path | |
| 60 | 新增:p=Path('/etc/claude-cage/components.json') | |
| 61 | 新增:try: manifest=json.loads(p.read_text()) | |
| 62 | 新增:except (OSError,ValueError): manifest=None | |
| 63 | 新增:versions={} | |
| 64 | 新增:env={**os.environ,'DISABLE_AUTOUPDATER':'1','PATH':str(Path.home()/'.local/bin')+':'+os.environ.get('PATH','')} | |
| 65 | 新增:for name,args in {'chromium':['chromium','--version'],'code_server':['code-server','--version'],'claude':['claude','--version'],'mise':[str(Path.home()/'.local/bin/mise'),'--version']}.items(): | |
| 66 | 新增: try: | |
| 67 | 新增: result=subprocess.run(args,env=env,capture_output=True,text=True,timeout=4) | |
| 68 | 新增: versions[name]=result.stdout.strip().splitlines()[0][:200] if result.returncode==0 and result.stdout.strip() else '' | |
| 69 | 新增: except (OSError,subprocess.TimeoutExpired): versions[name]='' | |
| 70 | 新增:print(json.dumps({'manifest':manifest,'tools':versions})) | |
| 71 | 新增:CAGE_VERSIONS`) | |
| 72 | 新增: var snapshot struct { | |
| 73 | 新增: Manifest *cage.GuestManifest `json:"manifest"` | |
| 74 | 新增: Tools map[string]string `json:"tools"` | |
| 75 | 新增: } | |
| 76 | 新增: if err != nil || json.Unmarshal(data, &snapshot) != nil { | |
| 77 | 新增: components.Status = "unknown" | |
| 78 | 新增: detail = "环境版本暂时无法读取,请恢复连接后重试。" | |
| 79 | 新增: } else { | |
| 80 | 新增: components.Current = snapshot.Manifest | |
| 81 | 新增: components.UpdateRequired = snapshot.Manifest == nil || !snapshot.Manifest.Current() | |
| 82 | 新增: components.Status = "current" | |
| 83 | 新增: if components.UpdateRequired { | |
| 84 | 新增: components.Status = "update_required" | |
| 85 | 新增: } | |
| 86 | 新增: for name, current := range snapshot.Tools { | |
| 87 | 新增: entry := tools[name] | |
| 88 | 新增: entry.Current = current | |
| 89 | 新增: tools[name] = entry | |
| 90 | 新增: } | |
| 91 | 新增: } | |
| 92 | 新增: } | |
| 93 | 新增: var proxy struct { | |
| 94 | 新增: Version string `json:"version"` | |
| 95 | 新增: } | |
| 96 | 新增: _ = managedproxy.API(ctx, s.profile, "GET", "/version", nil, &proxy) | |
| 97 | 新增: requiredProxy := "" | |
| 98 | 新增: if core, err := managedproxy.CorePath(); err == nil { | |
| 99 | 新增: probeCtx, done := context.WithTimeout(ctx, 2*time.Second) | |
| 100 | 新增: b, e := exec.CommandContext(probeCtx, core, "-v").Output() | |
| 101 | 新增: done() | |
| 102 | 新增: if e == nil { | |
| 103 | 新增: fields := strings.Fields(strings.SplitN(string(b), "\n", 2)[0]) | |
| 104 | 新增: if len(fields) >= 3 && fields[0] == "Mihomo" { | |
| 105 | 新增: requiredProxy = fields[2] | |
| 106 | 新增: } | |
| 107 | 新增: } | |
| 108 | 新增: } | |
| 109 | 新增: tools["proxy"] = toolVersion{Current: proxy.Version, Required: requiredProxy} | |
| 110 | 新增: s.mu.Lock() | |
| 111 | 新增: busy := s.job.Running | |
| 112 | 新增: allowed := s.toolsNetworkAllowedLocked() | |
| 113 | 新增: identity := s.identity | |
| 114 | 新增: s.mu.Unlock() | |
| 115 | 新增: jsonReply(w, map[string]any{"vm_running": running, "busy": busy, "components": components, "controller": identity, "tools": tools, "tools_update_allowed": allowed && components.Status == "current" && !busy, "error": detail}) | |
| 116 | 新增:} | |
| 117 | 新增: | |
| 118 | 新增:func (s *Server) updateEnvironment(w http.ResponseWriter, r *http.Request) { | |
| 119 | 新增: s.launch(w, "environment-update", s.synchronizeEnvironment) | |
| 120 | 新增:} | |
| 121 | 新增:func (s *Server) updateEnvironmentTools(w http.ResponseWriter, r *http.Request) { | |
| 122 | 新增: s.launch(w, "environment-tools", s.upgradeEnvironmentTools) | |
| 123 | 新增:} | |
| 124 | 新增: | |
| 125 | 新增:func (s *Server) synchronizeEnvironment() error { | |
| 126 | 新增: if !s.vmRunning() { | |
| 127 | 新增: return errors.New("请先启动 Cage 环境。") | |
| 128 | 新增: } | |
| 129 | 新增: if err := s.closeProxyGate("正在更新环境组件,外网暂时关闭"); err != nil { | |
| 130 | 新增: return err | |
| 131 | 新增: } | |
| 132 | 新增: s.mu.Lock() | |
| 133 | 新增: s.ready = false | |
| 134 | 新增: s.guestUpdateRequired = true | |
| 135 | 新增: s.guestUpdateError = "环境组件更新尚未完成,请等待结果;失败时可以重试。" | |
| 136 | 新增: s.mu.Unlock() | |
| 137 | 新增: s.setMessage("正在重启浏览器与编辑器组件,工作台终端保持运行…") | |
| 138 | 新增: if err := s.runCage("up"); err != nil { | |
| 139 | 新增: return err | |
| 140 | 新增: } | |
| 141 | 新增: if err := s.attach(); err != nil { | |
| 142 | 新增: return err | |
| 143 | 新增: } | |
| 144 | 新增: s.mu.Lock() | |
| 145 | 新增: paused := s.networkPaused | |
| 146 | 新增: s.mu.Unlock() | |
| 147 | 新增: if paused { | |
| 148 | 新增: return nil | |
| 149 | 新增: } | |
| 150 | 新增: return s.runSafetyCheck() | |
| 151 | 新增:} | |
| 152 | 新增: | |
| 153 | 新增:func (s *Server) toolsNetworkAllowedLocked() bool { | |
| 154 | 新增: gate := s.safety.Gate | |
| 155 | 新增: return s.ready && !s.networkPaused && gate != nil && gate.Mode == cage.GateOpen && gate.Until.After(time.Now()) | |
| 156 | 新增:} | |
| 157 | 新增:func (s *Server) upgradeEnvironmentTools() error { | |
| 158 | 新增: if !s.vmRunning() { | |
| 159 | 新增: return errors.New("请先启动 Cage 环境。") | |
| 160 | 新增: } | |
| 161 | 新增: s.mu.Lock() | |
| 162 | 新增: allowed := s.toolsNetworkAllowedLocked() | |
| 163 | 新增: manifest := s.guestManifest | |
| 164 | 新增: s.mu.Unlock() | |
| 165 | 新增: if !allowed { | |
| 166 | 新增: return errors.New("工具升级需要已放行的网络。请先恢复外网并通过检查,再重新点击更新。") | |
| 167 | 新增: } | |
| 168 | 新增: if manifest == nil || !manifest.Current() { | |
| 169 | 新增: return errGuestUpdateRequired | |
| 170 | 新增: } | |
| 171 | 新增: client, err := s.gateClient() | |
| 172 | 新增: if err != nil { | |
| 173 | 新增: return err | |
| 174 | 新增: } | |
| 175 | 新增: state, err := client.Status(s.operationContext()) | |
| 176 | 新增: if err != nil || state.Mode != cage.GateOpen || !state.Until.After(time.Now()) { | |
| 177 | 新增: return errors.New("网络放行已失效,请先重新检查再更新工具。") | |
| 178 | 新增: } | |
| 179 | 新增: monitorContext, stopMonitor := context.WithCancel(s.operationContext()) | |
| 180 | 新增: monitorDone := make(chan struct{}) | |
| 181 | 新增: go func() { | |
| 182 | 新增: defer close(monitorDone) | |
| 183 | 新增: ticker := time.NewTicker(10 * time.Second) | |
| 184 | 新增: defer ticker.Stop() | |
| 185 | 新增: for { | |
| 186 | 新增: select { | |
| 187 | 新增: case <-monitorContext.Done(): | |
| 188 | 新增: return | |
| 189 | 新增: case <-ticker.C: | |
| 190 | 新增: s.monitorSafety() | |
| 191 | 新增: } | |
| 192 | 新增: } | |
| 193 | 新增: }() | |
| 194 | 新增: finishMonitor := func() { | |
| 195 | 新增: stopMonitor() | |
| 196 | 新增: s.mu.Lock() | |
| 197 | 新增: if s.monitorCancel != nil { | |
| 198 | 新增: s.monitorCancel() | |
| 199 | 新增: } | |
| 200 | 新增: s.mu.Unlock() | |
| 201 | 新增: <-monitorDone | |
| 202 | 新增: } | |
| 203 | 新增: s.setMessage("正在更新 Chromium、编辑器和开发工具,工作台终端与磁盘保持运行…") | |
| 204 | 新增: err = s.runCage("run", "bash", "-c", cage.ToolsUpdateScript()) | |
| 205 | 新增: finishMonitor() | |
| 206 | 新增: if err != nil { | |
| 207 | 新增: return err | |
| 208 | 新增: } | |
| 209 | 新增: return s.synchronizeEnvironment() | |
| 210 | 新增:} | |
| @@ -0,0 +1,147 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增: "time" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestGuestConnectionRequiresSuccessfulMatchingManifest(t *testing.T) { | |
| 15 | 新增: required := cage.RequiredGuestManifest() | |
| 16 | 新增: for _, name := range []string{"current", "missing", "old-revision", "old-protocol", "broken"} { | |
| 17 | 新增: t.Run(name, func(t *testing.T) { | |
| 18 | 新增: manifest := required | |
| 19 | 新增: if name == "old-revision" { | |
| 20 | 新增: manifest.Revision = "previous" | |
| 21 | 新增: } | |
| 22 | 新增: if name == "old-protocol" { | |
| 23 | 新增: manifest.Protocol++ | |
| 24 | 新增: } | |
| 25 | 新增: encoded, _ := json.Marshal(manifest) | |
| 26 | 新增: if name == "missing" { | |
| 27 | 新增: encoded = []byte("null") | |
| 28 | 新增: } | |
| 29 | 新增: if name == "broken" { | |
| 30 | 新增: encoded = []byte("{") | |
| 31 | 新增: } | |
| 32 | 新增: credentials, current, err := parseGuestConnection(append([]byte("{\"token\":\"guest-test\"}\npassword\n"), encoded...)) | |
| 33 | 新增: if name == "current" { | |
| 34 | 新增: if err != nil || current == nil || credentials.Token != "guest-test" || credentials.VNCPassword != "password" { | |
| 35 | 新增: t.Fatal(current, err) | |
| 36 | 新增: } | |
| 37 | 新增: } else if !errors.Is(err, errGuestUpdateRequired) { | |
| 38 | 新增: t.Fatalf("stale guest accepted: %v", err) | |
| 39 | 新增: } | |
| 40 | 新增: }) | |
| 41 | 新增: } | |
| 42 | 新增:} | |
| 43 | 新增: | |
| 44 | 新增:func grantedToolUpdateServer(t *testing.T) (*Server, *cage.EgressGate) { | |
| 45 | 新增: t.Helper() | |
| 46 | 新增: s, gate := interfaceMonitorServer(t) | |
| 47 | 新增: state := gate.Status() | |
| 48 | 新增: report := cage.SafetyReport{Policy: cage.SafetyPolicyVersion, ID: "tool-update-test", RunID: state.RunID, CheckID: state.CheckID, Configuration: state.Configuration, CreatedAt: time.Now()} | |
| 49 | 新增: for _, id := range []string{"egress_policy", "proxy_transport", "dns_transport", "guest_settings", "browser_settings", "filesystem_boundary", "management_boundary", "fail_closed", "udp_policy", "ipv6_policy", "exit_consistency"} { | |
| 50 | 新增: report.Checks = append(report.Checks, cage.SafetyCheck{ID: id, Title: id, Critical: true, State: cage.CheckPassed, Evidence: "synthetic isolated fixture", CheckedAt: report.CreatedAt}) | |
| 51 | 新增: } | |
| 52 | 新增: if err := gate.Grant(report); err != nil { | |
| 53 | 新增: t.Fatal(err) | |
| 54 | 新增: } | |
| 55 | 新增: s.ready = true | |
| 56 | 新增: required := cage.RequiredGuestManifest() | |
| 57 | 新增: s.guestManifest = &required | |
| 58 | 新增: s.job = Job{ID: "tools", Kind: "environment-tools", Running: true} | |
| 59 | 新增: s.publishGate(gate.Status()) | |
| 60 | 新增: return s, gate | |
| 61 | 新增:} | |
| 62 | 新增: | |
| 63 | 新增:func TestToolUpdateLeaseHonorsPauseStopAndConfigurationAtRenewal(t *testing.T) { | |
| 64 | 新增: for _, condition := range []string{"allowed", "paused", "stop", "configuration-changed"} { | |
| 65 | 新增: t.Run(condition, func(t *testing.T) { | |
| 66 | 新增: s, gate := grantedToolUpdateServer(t) | |
| 67 | 新增: client, err := s.gateClient() | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: t.Fatal(err) | |
| 70 | 新增: } | |
| 71 | 新增: before := gate.Status() | |
| 72 | 新增: switch condition { | |
| 73 | 新增: case "paused": | |
| 74 | 新增: if err := s.pauseNetworkNow("test user pause"); err != nil { | |
| 75 | 新增: t.Fatal(err) | |
| 76 | 新增: } | |
| 77 | 新增: case "stop": | |
| 78 | 新增: s.job = Job{ID: "stop", Kind: "stop", Running: true} | |
| 79 | 新增: case "configuration-changed": | |
| 80 | 新增: cfg, err := loadConfig(s.configPath) | |
| 81 | 新增: if err != nil { | |
| 82 | 新增: t.Fatal(err) | |
| 83 | 新增: } | |
| 84 | 新增: cfg.Timezone = "Etc/UTC" | |
| 85 | 新增: if cfg.Fingerprint() == before.Configuration { | |
| 86 | 新增: cfg.Timezone = "Asia/Tokyo" | |
| 87 | 新增: } | |
| 88 | 新增: if err := writePrivate(s.configPath, cfg); err != nil { | |
| 89 | 新增: t.Fatal(err) | |
| 90 | 新增: } | |
| 91 | 新增: } | |
| 92 | 新增: s.finishSafetyMonitor(context.Background(), client, before, "192.0.2.1", "") | |
| 93 | 新增: after := gate.Status() | |
| 94 | 新增: switch condition { | |
| 95 | 新增: case "allowed": | |
| 96 | 新增: if after.Mode != cage.GateOpen || !after.Until.After(before.Until) { | |
| 97 | 新增: t.Fatal("tool update lease was not renewed") | |
| 98 | 新增: } | |
| 99 | 新增: case "paused", "configuration-changed": | |
| 100 | 新增: if after.Mode != cage.GateClosed { | |
| 101 | 新增: t.Fatal("denied network was renewed") | |
| 102 | 新增: } | |
| 103 | 新增: case "stop": | |
| 104 | 新增: if after.Until != before.Until { | |
| 105 | 新增: t.Fatal("stopping job allowed a lease renewal") | |
| 106 | 新增: } | |
| 107 | 新增: } | |
| 108 | 新增: }) | |
| 109 | 新增: } | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:func TestToolUpdateDoesNotRestorePausedOrExpiredNetworking(t *testing.T) { | |
| 113 | 新增: for _, paused := range []bool{true, false} { | |
| 114 | 新增: s, gate := grantedToolUpdateServer(t) | |
| 115 | 新增: if paused { | |
| 116 | 新增: if err := s.pauseNetworkNow("manual"); err != nil { | |
| 117 | 新增: t.Fatal(err) | |
| 118 | 新增: } | |
| 119 | 新增: } else { | |
| 120 | 新增: gate.Close("expired") | |
| 121 | 新增: } | |
| 122 | 新增: err := s.upgradeEnvironmentTools() | |
| 123 | 新增: if err == nil || !strings.Contains(err.Error(), "网络") { | |
| 124 | 新增: t.Fatalf("closed gate accepted: %v", err) | |
| 125 | 新增: } | |
| 126 | 新增: if gate.Status().Mode != cage.GateClosed { | |
| 127 | 新增: t.Fatal("tool update restored closed network") | |
| 128 | 新增: } | |
| 129 | 新增: } | |
| 130 | 新增:} | |
| 131 | 新增: | |
| 132 | 新增:func TestEnvironmentVersionRoutesRequireHostSession(t *testing.T) { | |
| 133 | 新增: s := testServer(t) | |
| 134 | 新增: for _, path := range []string{"/api/environment/versions", "/api/environment/update", "/api/environment/tools"} { | |
| 135 | 新增: method := "POST" | |
| 136 | 新增: if strings.HasSuffix(path, "versions") { | |
| 137 | 新增: method = "GET" | |
| 138 | 新增: } | |
| 139 | 新增: if w := request(s, method, path, s.origin, "{}", false); w.Code != 401 { | |
| 140 | 新增: t.Fatalf("untrusted version action accepted: %d", w.Code) | |
| 141 | 新增: } | |
| 142 | 新增: } | |
| 143 | 新增: w := request(s, "GET", "/api/environment/versions", s.origin, "", true) | |
| 144 | 新增: if w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"stopped"`) { | |
| 145 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 146 | 新增: } | |
| 147 | 新增:} | |
| @@ -0,0 +1,152 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "net/url" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "slices" | |
| 11 | 新增: "strings" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:type Favorite struct { | |
| 15 | 新增: ID string `json:"id"` | |
| 16 | 新增: Title string `json:"title"` | |
| 17 | 新增: URL string `json:"url"` | |
| 18 | 新增: FolderID string `json:"folder_id"` | |
| 19 | 新增:} | |
| 20 | 新增:type FavoriteFolder struct { | |
| 21 | 新增: ID string `json:"id"` | |
| 22 | 新增: Title string `json:"title"` | |
| 23 | 新增:} | |
| 24 | 新增:type Favorites struct { | |
| 25 | 新增: Items []Favorite `json:"items"` | |
| 26 | 新增: Folders []FavoriteFolder `json:"folders"` | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:func (s *Server) readFavorites() (Favorites, error) { | |
| 30 | 新增: f := Favorites{Items: []Favorite{}, Folders: []FavoriteFolder{}} | |
| 31 | 新增: b, err := os.ReadFile(filepath.Join(s.profile, "favorites.json")) | |
| 32 | 新增: if os.IsNotExist(err) { | |
| 33 | 新增: return f, nil | |
| 34 | 新增: } | |
| 35 | 新增: if err != nil { | |
| 36 | 新增: return f, errors.New("无法读取收藏,请检查配置目录权限") | |
| 37 | 新增: } | |
| 38 | 新增: if json.Unmarshal(b, &f) != nil { | |
| 39 | 新增: return f, errors.New("收藏文件无法读取,请保留文件并修复后重试") | |
| 40 | 新增: } | |
| 41 | 新增: if f.Items == nil { | |
| 42 | 新增: f.Items = []Favorite{} | |
| 43 | 新增: } | |
| 44 | 新增: if f.Folders == nil { | |
| 45 | 新增: f.Folders = []FavoriteFolder{} | |
| 46 | 新增: } | |
| 47 | 新增: return f, nil | |
| 48 | 新增:} | |
| 49 | 新增: | |
| 50 | 新增:func (s *Server) getFavorites(w http.ResponseWriter, r *http.Request) { | |
| 51 | 新增: s.favoritesMu.Lock() | |
| 52 | 新增: defer s.favoritesMu.Unlock() | |
| 53 | 新增: f, err := s.readFavorites() | |
| 54 | 新增: if err != nil { | |
| 55 | 新增: requestError(w, err) | |
| 56 | 新增: return | |
| 57 | 新增: } | |
| 58 | 新增: jsonReply(w, f) | |
| 59 | 新增:} | |
| 60 | 新增: | |
| 61 | 新增:// Each mutation reads the current file under the same lock. Two windows adding | |
| 62 | 新增:// favorites cannot replace one another's collections with stale snapshots. | |
| 63 | 新增:func (s *Server) mutateFavorites(w http.ResponseWriter, r *http.Request) { | |
| 64 | 新增: var input struct { | |
| 65 | 新增: Action string `json:"action"` | |
| 66 | 新增: ID string `json:"id"` | |
| 67 | 新增: Title string `json:"title"` | |
| 68 | 新增: URL string `json:"url"` | |
| 69 | 新增: FolderID string `json:"folder_id"` | |
| 70 | 新增: } | |
| 71 | 新增: if !readJSON(w, r, &input) { | |
| 72 | 新增: return | |
| 73 | 新增: } | |
| 74 | 新增: s.favoritesMu.Lock() | |
| 75 | 新增: defer s.favoritesMu.Unlock() | |
| 76 | 新增: f, err := s.readFavorites() | |
| 77 | 新增: if err != nil { | |
| 78 | 新增: requestError(w, err) | |
| 79 | 新增: return | |
| 80 | 新增: } | |
| 81 | 新增: input.Title = strings.TrimSpace(input.Title) | |
| 82 | 新增: input.URL = strings.TrimSpace(input.URL) | |
| 83 | 新增: itemIndex := slices.IndexFunc(f.Items, func(item Favorite) bool { return item.ID == input.ID }) | |
| 84 | 新增: folderIndex := slices.IndexFunc(f.Folders, func(folder FavoriteFolder) bool { return folder.ID == input.ID }) | |
| 85 | 新增: fail := func(message string) { requestError(w, errors.New(message)) } | |
| 86 | 新增: switch input.Action { | |
| 87 | 新增: case "save", "save_folder": | |
| 88 | 新增: if input.Title == "" || len(input.Title) > 1000 { | |
| 89 | 新增: fail("请输入名称;名称过长时请缩短后重试") | |
| 90 | 新增: return | |
| 91 | 新增: } | |
| 92 | 新增: if input.Action == "save_folder" { | |
| 93 | 新增: if input.ID == "" { | |
| 94 | 新增: f.Folders = append(f.Folders, FavoriteFolder{ID: randomToken()[:24], Title: input.Title}) | |
| 95 | 新增: } else if folderIndex >= 0 { | |
| 96 | 新增: f.Folders[folderIndex].Title = input.Title | |
| 97 | 新增: } else { | |
| 98 | 新增: fail("收藏夹已不存在,请重新打开收藏夹") | |
| 99 | 新增: return | |
| 100 | 新增: } | |
| 101 | 新增: break | |
| 102 | 新增: } | |
| 103 | 新增: u, parseErr := url.Parse(input.URL) | |
| 104 | 新增: if parseErr != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || len(input.URL) > 16384 { | |
| 105 | 新增: fail("收藏地址须为不含用户名和密码的 HTTP(S) 网址") | |
| 106 | 新增: return | |
| 107 | 新增: } | |
| 108 | 新增: if input.FolderID != "" && !slices.ContainsFunc(f.Folders, func(folder FavoriteFolder) bool { return folder.ID == input.FolderID }) { | |
| 109 | 新增: fail("所选收藏夹已不存在,请重新选择") | |
| 110 | 新增: return | |
| 111 | 新增: } | |
| 112 | 新增: if input.ID == "" { | |
| 113 | 新增: // Repeated clicks on a page's star update its existing favorite. | |
| 114 | 新增: itemIndex = slices.IndexFunc(f.Items, func(item Favorite) bool { return item.URL == input.URL }) | |
| 115 | 新增: if itemIndex >= 0 { | |
| 116 | 新增: input.ID = f.Items[itemIndex].ID | |
| 117 | 新增: } else { | |
| 118 | 新增: input.ID = randomToken()[:24] | |
| 119 | 新增: } | |
| 120 | 新增: } else if itemIndex < 0 { | |
| 121 | 新增: fail("收藏已不存在,请重新打开收藏夹") | |
| 122 | 新增: return | |
| 123 | 新增: } | |
| 124 | 新增: item := Favorite{ID: input.ID, Title: input.Title, URL: input.URL, FolderID: input.FolderID} | |
| 125 | 新增: if itemIndex < 0 { | |
| 126 | 新增: f.Items = append(f.Items, item) | |
| 127 | 新增: } else { | |
| 128 | 新增: f.Items[itemIndex] = item | |
| 129 | 新增: } | |
| 130 | 新增: case "delete": | |
| 131 | 新增: if itemIndex >= 0 { | |
| 132 | 新增: f.Items = slices.Delete(f.Items, itemIndex, itemIndex+1) | |
| 133 | 新增: } | |
| 134 | 新增: case "delete_folder": | |
| 135 | 新增: if folderIndex >= 0 { | |
| 136 | 新增: f.Folders = slices.Delete(f.Folders, folderIndex, folderIndex+1) | |
| 137 | 新增: for i := range f.Items { | |
| 138 | 新增: if f.Items[i].FolderID == input.ID { | |
| 139 | 新增: f.Items[i].FolderID = "" | |
| 140 | 新增: } | |
| 141 | 新增: } | |
| 142 | 新增: } | |
| 143 | 新增: default: | |
| 144 | 新增: fail("未知收藏操作") | |
| 145 | 新增: return | |
| 146 | 新增: } | |
| 147 | 新增: if err := writePrivate(filepath.Join(s.profile, "favorites.json"), f); err != nil { | |
| 148 | 新增: fail("收藏未能保存,请检查磁盘空间和权限后重试") | |
| 149 | 新增: return | |
| 150 | 新增: } | |
| 151 | 新增: jsonReply(w, f) | |
| 152 | 新增:} | |
| @@ -0,0 +1,105 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "fmt" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "sync" | |
| 9 | 新增: "testing" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func TestFavoritesPersistenceAndFolders(t *testing.T) { | |
| 13 | 新增: s := testServer(t) | |
| 14 | 新增: post := func(body string) Favorites { | |
| 15 | 新增: t.Helper() | |
| 16 | 新增: w := request(s, "POST", "/api/favorites", s.origin, body, true) | |
| 17 | 新增: if w.Code != 200 { | |
| 18 | 新增: t.Fatalf("%d: %s", w.Code, w.Body.String()) | |
| 19 | 新增: } | |
| 20 | 新增: var f Favorites | |
| 21 | 新增: if err := json.Unmarshal(w.Body.Bytes(), &f); err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: return f | |
| 25 | 新增: } | |
| 26 | 新增: f := post(`{"action":"save_folder","title":"开发"}`) | |
| 27 | 新增: folder := f.Folders[0].ID | |
| 28 | 新增: f = post(fmt.Sprintf(`{"action":"save","title":"文档","url":"https://example.com/docs","folder_id":%q}`, folder)) | |
| 29 | 新增: id := f.Items[0].ID | |
| 30 | 新增: f = post(`{"action":"save","title":"文档新版","url":"https://example.com/docs"}`) | |
| 31 | 新增: if len(f.Items) != 1 || f.Items[0].ID != id || f.Items[0].Title != "文档新版" { | |
| 32 | 新增: t.Fatal("repeated save duplicated a favorite") | |
| 33 | 新增: } | |
| 34 | 新增: f = post(fmt.Sprintf(`{"action":"save","id":%q,"title":"已移动","url":"https://example.com/new","folder_id":%q}`, id, folder)) | |
| 35 | 新增: if f.Items[0].FolderID != folder { | |
| 36 | 新增: t.Fatal("move failed") | |
| 37 | 新增: } | |
| 38 | 新增: post(fmt.Sprintf(`{"action":"save_folder","id":%q,"title":"工作"}`, folder)) | |
| 39 | 新增: // A new server instance reads the saved file without an active VM. | |
| 40 | 新增: reopened := &Server{profile: s.profile} | |
| 41 | 新增: f, err := reopened.readFavorites() | |
| 42 | 新增: if err != nil || f.Folders[0].Title != "工作" || f.Items[0].URL != "https://example.com/new" { | |
| 43 | 新增: t.Fatalf("persistence: %+v %v", f, err) | |
| 44 | 新增: } | |
| 45 | 新增: info, err := os.Stat(filepath.Join(s.profile, "favorites.json")) | |
| 46 | 新增: if err != nil || info.Mode().Perm() != 0600 { | |
| 47 | 新增: t.Fatal("favorites file must be private") | |
| 48 | 新增: } | |
| 49 | 新增: f = post(fmt.Sprintf(`{"action":"delete_folder","id":%q}`, folder)) | |
| 50 | 新增: if len(f.Folders) != 0 || len(f.Items) != 1 || f.Items[0].FolderID != "" { | |
| 51 | 新增: t.Fatal("deleting folder must retain its favorites in unfiled") | |
| 52 | 新增: } | |
| 53 | 新增: f = post(fmt.Sprintf(`{"action":"delete","id":%q}`, id)) | |
| 54 | 新增: if len(f.Items) != 0 { | |
| 55 | 新增: t.Fatal("delete failed") | |
| 56 | 新增: } | |
| 57 | 新增:} | |
| 58 | 新增: | |
| 59 | 新增:func TestFavoritesBoundaryAndFailedWrites(t *testing.T) { | |
| 60 | 新增: s := testServer(t) | |
| 61 | 新增: if w := request(s, "GET", "/api/favorites", "", "", false); w.Code != 401 { | |
| 62 | 新增: t.Fatal("unauthenticated favorites readable") | |
| 63 | 新增: } | |
| 64 | 新增: if w := request(s, "POST", "/api/favorites", "https://example.com", `{}`, true); w.Code != 403 { | |
| 65 | 新增: t.Fatal("cross-origin mutation accepted") | |
| 66 | 新增: } | |
| 67 | 新增: for _, body := range []string{ | |
| 68 | 新增: `{"action":"save","title":"x","url":"javascript:alert(1)"}`, | |
| 69 | 新增: `{"action":"save","title":"x","url":"file:///etc/passwd"}`, | |
| 70 | 新增: `{"action":"save","title":"x","url":"https://user:[email protected]"}`, | |
| 71 | 新增: `{"action":"save","title":"x","url":"https://example.com","folder_id":"missing"}`, | |
| 72 | 新增: `{"action":"save_folder","title":" "}`, | |
| 73 | 新增: } { | |
| 74 | 新增: if w := request(s, "POST", "/api/favorites", s.origin, body, true); w.Code == 200 { | |
| 75 | 新增: t.Fatalf("accepted invalid favorite: %s", body) | |
| 76 | 新增: } | |
| 77 | 新增: } | |
| 78 | 新增: path := filepath.Join(s.profile, "favorites.json") | |
| 79 | 新增: if err := os.WriteFile(path, []byte("broken"), 0600); err != nil { | |
| 80 | 新增: t.Fatal(err) | |
| 81 | 新增: } | |
| 82 | 新增: w := request(s, "POST", "/api/favorites", s.origin, `{"action":"save_folder","title":"x"}`, true) | |
| 83 | 新增: b, _ := os.ReadFile(path) | |
| 84 | 新增: if w.Code == 200 || string(b) != "broken" { | |
| 85 | 新增: t.Fatal("unreadable saved data was overwritten") | |
| 86 | 新增: } | |
| 87 | 新增:} | |
| 88 | 新增: | |
| 89 | 新增:func TestConcurrentFavoritesKeepBothAdditions(t *testing.T) { | |
| 90 | 新增: s := testServer(t) | |
| 91 | 新增: var wg sync.WaitGroup | |
| 92 | 新增: for i := 0; i < 8; i++ { | |
| 93 | 新增: wg.Go(func() { | |
| 94 | 新增: body := fmt.Sprintf(`{"action":"save","title":"Page %d","url":"https://example.com/%d"}`, i, i) | |
| 95 | 新增: if w := request(s, "POST", "/api/favorites", s.origin, body, true); w.Code != 200 { | |
| 96 | 新增: t.Errorf("save: %d", w.Code) | |
| 97 | 新增: } | |
| 98 | 新增: }) | |
| 99 | 新增: } | |
| 100 | 新增: wg.Wait() | |
| 101 | 新增: f, err := s.readFavorites() | |
| 102 | 新增: if err != nil || len(f.Items) != 8 { | |
| 103 | 新增: t.Fatalf("concurrent additions lost: %+v, %v", f, err) | |
| 104 | 新增: } | |
| 105 | 新增:} | |
| @@ -0,0 +1,65 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "fmt" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:type networkIntent struct { | |
| 12 | 新增: Version int `json:"version"` | |
| 13 | 新增: Paused bool `json:"paused"` | |
| 14 | 新增: PauseVersion uint64 `json:"pause_version"` | |
| 15 | 新增:} | |
| 16 | 新增: | |
| 17 | 新增:// An absent record can belong to an older profile whose pause was memory-only. | |
| 18 | 新增:// Keep it offline until an explicit user operation establishes a durable intent. | |
| 19 | 新增:func (s *Server) restoreNetworkIntent() error { | |
| 20 | 新增: paused, generation := true, uint64(0) | |
| 21 | 新增: data, err := os.ReadFile(filepath.Join(s.profile, "network-intent.json")) | |
| 22 | 新增: if err == nil { | |
| 23 | 新增: var record struct { | |
| 24 | 新增: Version int `json:"version"` | |
| 25 | 新增: Paused *bool `json:"paused"` | |
| 26 | 新增: PauseVersion *uint64 `json:"pause_version"` | |
| 27 | 新增: } | |
| 28 | 新增: if json.Unmarshal(data, &record) != nil || record.Version != 1 || record.Paused == nil || record.PauseVersion == nil { | |
| 29 | 新增: err = errors.New("保存的网络暂停状态无效") | |
| 30 | 新增: } else { | |
| 31 | 新增: paused, generation = *record.Paused, *record.PauseVersion | |
| 32 | 新增: } | |
| 33 | 新增: } | |
| 34 | 新增: s.mu.Lock() | |
| 35 | 新增: s.networkPaused, s.safety.pauseVersion = paused, generation | |
| 36 | 新增: s.mu.Unlock() | |
| 37 | 新增: if err != nil && !os.IsNotExist(err) { | |
| 38 | 新增: return errors.New("无法读取网络暂停状态,外网保持关闭;请确认后手动恢复。") | |
| 39 | 新增: } | |
| 40 | 新增: return nil | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:// Caller holds mu so a later pause cannot be overwritten by a pending resume. | |
| 44 | 新增:func (s *Server) saveNetworkIntentLocked(paused bool) error { | |
| 45 | 新增: if err := writePrivate(filepath.Join(s.profile, "network-intent.json"), networkIntent{Version: 1, Paused: paused, PauseVersion: s.safety.pauseVersion}); err != nil { | |
| 46 | 新增: s.networkPaused = true | |
| 47 | 新增: return fmt.Errorf("无法保存网络暂停状态,当前外网保持关闭;请解决配置写入问题后重试:%w", err) | |
| 48 | 新增: } | |
| 49 | 新增: s.networkPaused = paused | |
| 50 | 新增: return nil | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 53 | 新增:func (s *Server) resumeNetworkIntentAt(generation uint64) error { | |
| 54 | 新增: s.mu.Lock() | |
| 55 | 新增: if generation != s.safety.pauseVersion { | |
| 56 | 新增: s.mu.Unlock() | |
| 57 | 新增: return nil | |
| 58 | 新增: } | |
| 59 | 新增: err := s.saveNetworkIntentLocked(false) | |
| 60 | 新增: s.mu.Unlock() | |
| 61 | 新增: if err != nil { | |
| 62 | 新增: _ = s.closeProxyGate("网络恢复意图无法保存,外网保持关闭") | |
| 63 | 新增: } | |
| 64 | 新增: return err | |
| 65 | 新增:} | |
| @@ -0,0 +1,177 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "net/http/httptest" | |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增: "time" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func reloadedIntentServer(t *testing.T, previous *Server) *Server { | |
| 16 | 新增: t.Helper() | |
| 17 | 新增: reloaded := &Server{profile: previous.profile, configPath: previous.configPath, origin: previous.origin, token: previous.token, session: previous.session, preferences: previous.preferences, terminals: map[string]*terminalSession{}} | |
| 18 | 新增: return reloaded | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 21 | 新增:func TestReloadedManualPauseSurvivesAutomaticSubscriptionRefresh(t *testing.T) { | |
| 22 | 新增: for _, record := range []string{"saved", "corrupt", "missing"} { | |
| 23 | 新增: t.Run(record, func(t *testing.T) { | |
| 24 | 新增: original, gate, started, finish := pendingProxyApply(t) | |
| 25 | 新增: pauseProxyNetwork(t, original) | |
| 26 | 新增: intentPath := filepath.Join(original.profile, "network-intent.json") | |
| 27 | 新增: if record == "corrupt" { | |
| 28 | 新增: if err := os.WriteFile(intentPath, []byte(`{"paused":false}`), 0600); err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: } | |
| 32 | 新增: if record == "missing" { | |
| 33 | 新增: if err := os.Remove(intentPath); err != nil { | |
| 34 | 新增: t.Fatal(err) | |
| 35 | 新增: } | |
| 36 | 新增: } | |
| 37 | 新增: reloaded := reloadedIntentServer(t, original) | |
| 38 | 新增: err := reloaded.restoreNetworkIntent() | |
| 39 | 新增: if record == "corrupt" { | |
| 40 | 新增: if err == nil { | |
| 41 | 新增: t.Fatal("corrupt intent was accepted") | |
| 42 | 新增: } | |
| 43 | 新增: } else if err != nil { | |
| 44 | 新增: t.Fatal(err) | |
| 45 | 新增: } | |
| 46 | 新增: if !reloaded.networkPaused { | |
| 47 | 新增: t.Fatal("service reload discarded manual pause") | |
| 48 | 新增: } | |
| 49 | 新增: if record == "saved" { | |
| 50 | 新增: stat, err := os.Stat(intentPath) | |
| 51 | 新增: if err != nil || stat.Mode().Perm() != 0600 { | |
| 52 | 新增: t.Fatal("intent is not private", err) | |
| 53 | 新增: } | |
| 54 | 新增: if reloaded.safety.pauseVersion != original.safety.pauseVersion { | |
| 55 | 新增: t.Fatal("pause generation was lost") | |
| 56 | 新增: } | |
| 57 | 新增: } | |
| 58 | 新增: reloaded.op.Lock() | |
| 59 | 新增: reloaded.refreshProxySubscriptions() | |
| 60 | 新增: reloaded.op.Unlock() | |
| 61 | 新增: awaitProxyStart(t, started) | |
| 62 | 新增: finish() | |
| 63 | 新增: assertProxyStayedPaused(t, reloaded, gate) | |
| 64 | 新增: again := reloadedIntentServer(t, reloaded) | |
| 65 | 新增: _ = again.restoreNetworkIntent() | |
| 66 | 新增: if !again.networkPaused { | |
| 67 | 新增: t.Fatal("automatic refresh persisted a resume") | |
| 68 | 新增: } | |
| 69 | 新增: }) | |
| 70 | 新增: } | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:func TestExplicitResumePersistsAcrossServiceReload(t *testing.T) { | |
| 74 | 新增: for _, kind := range []string{"start", "safety", "restore"} { | |
| 75 | 新增: t.Run(kind, func(t *testing.T) { | |
| 76 | 新增: s, gate := interfaceMonitorServer(t) | |
| 77 | 新增: pauseProxyNetwork(t, s) | |
| 78 | 新增: finished := make(chan struct{}) | |
| 79 | 新增: response := httptest.NewRecorder() | |
| 80 | 新增: s.launch(response, kind, func() error { close(finished); return nil }) | |
| 81 | 新增: if response.Code != 200 { | |
| 82 | 新增: t.Fatal(response.Code, response.Body.String()) | |
| 83 | 新增: } | |
| 84 | 新增: select { | |
| 85 | 新增: case <-finished: | |
| 86 | 新增: case <-time.After(3 * time.Second): | |
| 87 | 新增: t.Fatal("explicit resume job did not finish") | |
| 88 | 新增: } | |
| 89 | 新增: s.op.Lock() | |
| 90 | 新增: s.op.Unlock() | |
| 91 | 新增: reloaded := reloadedIntentServer(t, s) | |
| 92 | 新增: if err := reloaded.restoreNetworkIntent(); err != nil { | |
| 93 | 新增: t.Fatal(err) | |
| 94 | 新增: } | |
| 95 | 新增: if reloaded.networkPaused { | |
| 96 | 新增: t.Fatal("explicit resume was not persisted") | |
| 97 | 新增: } | |
| 98 | 新增: if gate.Status().Mode != cage.GateClosed { | |
| 99 | 新增: t.Fatal("recording intent itself granted networking") | |
| 100 | 新增: } | |
| 101 | 新增: }) | |
| 102 | 新增: } | |
| 103 | 新增:} | |
| 104 | 新增: | |
| 105 | 新增:func TestPauseAndResumeStorageFailuresKeepGateClosed(t *testing.T) { | |
| 106 | 新增: for _, operation := range []string{"pause", "resume"} { | |
| 107 | 新增: t.Run(operation, func(t *testing.T) { | |
| 108 | 新增: s, gate := grantedToolUpdateServer(t) | |
| 109 | 新增: s.job = Job{} | |
| 110 | 新增: if err := os.Mkdir(filepath.Join(s.profile, "network-intent.json"), 0700); err != nil { | |
| 111 | 新增: t.Fatal(err) | |
| 112 | 新增: } | |
| 113 | 新增: var response *httptest.ResponseRecorder | |
| 114 | 新增: if operation == "pause" { | |
| 115 | 新增: response = request(s, "POST", "/api/safety/close", s.origin, "{}", true) | |
| 116 | 新增: } else { | |
| 117 | 新增: response = httptest.NewRecorder() | |
| 118 | 新增: s.launch(response, "start", func() error { t.Error("resume ran without durable intent"); return nil }) | |
| 119 | 新增: } | |
| 120 | 新增: if response.Code != 400 || !strings.Contains(response.Body.String(), "无法保存") { | |
| 121 | 新增: t.Fatalf("storage failure not reported: %d %s", response.Code, response.Body.String()) | |
| 122 | 新增: } | |
| 123 | 新增: if !s.networkPaused || gate.Status().Mode != cage.GateClosed { | |
| 124 | 新增: t.Fatal("storage failure left external networking enabled") | |
| 125 | 新增: } | |
| 126 | 新增: }) | |
| 127 | 新增: } | |
| 128 | 新增:} | |
| 129 | 新增: | |
| 130 | 新增:func TestQueuedSettingsApplyCannotClearLaterPersistentPause(t *testing.T) { | |
| 131 | 新增: s, gate := interfaceMonitorServer(t) | |
| 132 | 新增: pauseProxyNetwork(t, s) | |
| 133 | 新增: // Keep the real settings write, but there is no live VM to stop in this fixture. | |
| 134 | 新增: if err := os.Remove(filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir()), "cage-running.json")); err != nil { | |
| 135 | 新增: t.Fatal(err) | |
| 136 | 新增: } | |
| 137 | 新增: cfg, err := loadConfig(s.configPath) | |
| 138 | 新增: if err != nil { | |
| 139 | 新增: t.Fatal(err) | |
| 140 | 新增: } | |
| 141 | 新增: cfg.Timezone = "Asia/Tokyo" | |
| 142 | 新增: next := savedProfile{Config: cfg, Preferences: s.preferences} | |
| 143 | 新增: finished := make(chan error, 1) | |
| 144 | 新增: s.op.Lock() | |
| 145 | 新增: response := httptest.NewRecorder() | |
| 146 | 新增: s.launch(response, "settings", func() error { err := s.apply(next, false); finished <- err; return err }) | |
| 147 | 新增: if response.Code != 200 { | |
| 148 | 新增: s.op.Unlock() | |
| 149 | 新增: t.Fatal(response.Code) | |
| 150 | 新增: } | |
| 151 | 新增: pauseProxyNetwork(t, s) | |
| 152 | 新增: s.op.Unlock() | |
| 153 | 新增: select { | |
| 154 | 新增: case err := <-finished: | |
| 155 | 新增: if err != nil { | |
| 156 | 新增: t.Fatal(err) | |
| 157 | 新增: } | |
| 158 | 新增: case <-time.After(3 * time.Second): | |
| 159 | 新增: t.Fatal("settings apply did not finish") | |
| 160 | 新增: } | |
| 161 | 新增: s.op.Lock() | |
| 162 | 新增: s.op.Unlock() | |
| 163 | 新增: if !s.networkPaused || gate.Status().Mode != cage.GateClosed { | |
| 164 | 新增: t.Fatal("older settings action cleared a later pause") | |
| 165 | 新增: } | |
| 166 | 新增: reloaded := reloadedIntentServer(t, s) | |
| 167 | 新增: if err := reloaded.restoreNetworkIntent(); err != nil { | |
| 168 | 新增: t.Fatal(err) | |
| 169 | 新增: } | |
| 170 | 新增: if !reloaded.networkPaused { | |
| 171 | 新增: t.Fatal("older settings action persisted a resume") | |
| 172 | 新增: } | |
| 173 | 新增: actual, err := loadConfig(s.configPath) | |
| 174 | 新增: if err != nil || actual.Timezone != "Asia/Tokyo" { | |
| 175 | 新增: t.Fatal("settings did not complete", err) | |
| 176 | 新增: } | |
| 177 | 新增:} | |
| @@ -183,13 +183,15 @@ func TestProjectActionsUseExplicitDirectoryWithoutSwitchingProject(t *testing.T) | ||
| 183 | 183 | editorWorkspace = input.Workspace |
| 184 | 184 | return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"id":"editor"}`)), Header: http.Header{}}, nil |
| 185 | 185 | })} |
| 186 | 删除: w = request(s, "POST", "/api/browser/editor", s.origin, string(body), true) | |
| 187 | 删除: if w.Code != 200 || editorWorkspace != a || s.workspace() != b { | |
| 188 | 删除: t.Fatalf("editor changed the selected project or ignored its directory: %s", w.Body.String()) | |
| 186 | 新增: for _, action := range []string{"editor", "editor-restart"} { | |
| 187 | 新增: w = request(s, "POST", "/api/browser/"+action, s.origin, string(body), true) | |
| 188 | 新增: if w.Code != 200 || editorWorkspace != a || s.workspace() != b { | |
| 189 | 新增: t.Fatalf("%s changed the selected project or ignored its directory: %s", action, w.Body.String()) | |
| 190 | 新增: } | |
| 189 | 191 | } |
| 190 | 192 | for _, path := range []string{t.TempDir(), s.profile} { |
| 191 | 193 | body, _ = json.Marshal(map[string]string{"workspace": path}) |
| 192 | 删除: for _, endpoint := range []string{"/api/terminals", "/api/browser/editor"} { | |
| 194 | 新增: for _, endpoint := range []string{"/api/terminals", "/api/browser/editor", "/api/browser/editor-restart"} { | |
| 193 | 195 | w = request(s, "POST", endpoint, s.origin, string(body), true) |
| 194 | 196 | if w.Code != 400 { |
| 195 | 197 | t.Fatalf("unopened directory accepted by %s: %d", endpoint, w.Code) |
| @@ -12,6 +12,12 @@ import ( | ||
| 12 | 12 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 13 | 13 | ) |
| 14 | 14 | |
| 15 | 新增:var ( | |
| 16 | 新增: validateProxyCore = managedproxy.Validate | |
| 17 | 新增: startProxyCore = managedproxy.Start | |
| 18 | 新增: fetchProxySource = managedproxy.Fetch | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 15 | 21 | type proxyInput struct { |
| 16 | 22 | ID string `json:"id"` |
| 17 | 23 | Name string `json:"name"` |
| @@ -94,7 +100,10 @@ func (s *Server) proxyMutation(w http.ResponseWriter, r *http.Request) { | ||
| 94 | 100 | http.NotFound(w, r) |
| 95 | 101 | return |
| 96 | 102 | } |
| 97 | 删除: s.launch(w, "proxy", func() error { return s.changeProxy(action, input) }) | |
| 103 | 新增: s.mu.Lock() | |
| 104 | 新增: pauseVersion := s.safety.pauseVersion | |
| 105 | 新增: s.mu.Unlock() | |
| 106 | 新增: s.launch(w, "proxy", func() error { return s.changeProxy(action, input, &pauseVersion) }) | |
| 98 | 107 | } |
| 99 | 108 | func (s *Server) subscriptionClient(host bool) (*http.Client, error) { |
| 100 | 109 | if host { |
| @@ -118,7 +127,7 @@ func (s *Server) subscriptionClient(host bool) (*http.Client, error) { | ||
| 118 | 127 | return nil |
| 119 | 128 | }}, nil |
| 120 | 129 | } |
| 121 | 删除:func (s *Server) changeProxy(action string, in proxyInput) error { | |
| 130 | 新增:func (s *Server) changeProxy(action string, in proxyInput, resumeVersion *uint64) error { | |
| 122 | 131 | p, err := managedproxy.Load(s.profile) |
| 123 | 132 | if err != nil { |
| 124 | 133 | return err |
| @@ -147,7 +156,7 @@ func (s *Server) changeProxy(action string, in proxyInput) error { | ||
| 147 | 156 | } |
| 148 | 157 | p.Port = in.Port |
| 149 | 158 | } |
| 150 | 删除: return s.activateProxy(p, cfg) | |
| 159 | 新增: return s.applyProxy(p, cfg, resumeVersion) | |
| 151 | 160 | } |
| 152 | 161 | index := -1 |
| 153 | 162 | for i, src := range p.Sources { |
| @@ -202,7 +211,7 @@ func (s *Server) changeProxy(action string, in proxyInput) error { | ||
| 202 | 211 | return e |
| 203 | 212 | } |
| 204 | 213 | defer client.CloseIdleConnections() |
| 205 | 删除: data, usage, err = managedproxy.Fetch(ctx, client, in.URL) | |
| 214 | 新增: data, usage, err = fetchProxySource(ctx, client, in.URL) | |
| 206 | 215 | if err != nil { |
| 207 | 216 | if index >= 0 { |
| 208 | 217 | p.Sources[index].Error = err.Error() |
| @@ -223,7 +232,7 @@ func (s *Server) changeProxy(action string, in proxyInput) error { | ||
| 223 | 232 | if _, ok := candidate.Find(candidate.Selected); !ok { |
| 224 | 233 | candidate.Selected = candidate.Sources[0].Nodes[0].ID |
| 225 | 234 | } |
| 226 | 删除: if err = managedproxy.Validate(ctx, s.profile, candidate); err != nil { | |
| 235 | 新增: if err = validateProxyCore(ctx, s.profile, candidate); err != nil { | |
| 227 | 236 | s.proxySourceFailure(in.ID, err) |
| 228 | 237 | return err |
| 229 | 238 | } |
| @@ -241,7 +250,7 @@ func (s *Server) changeProxy(action string, in proxyInput) error { | ||
| 241 | 250 | } |
| 242 | 251 | return p.Save(s.profile) |
| 243 | 252 | } |
| 244 | 删除: return s.activateProxy(p, cfg) | |
| 253 | 新增: return s.applyProxy(p, cfg, resumeVersion) | |
| 245 | 254 | } |
| 246 | 255 | return p.Save(s.profile) |
| 247 | 256 | } |
| @@ -271,17 +280,19 @@ func (s *Server) closeProxyGate(reason string) error { | ||
| 271 | 280 | } |
| 272 | 281 | |
| 273 | 282 | func (s *Server) activateProxy(p managedproxy.Store, old cage.Config) (returned error) { |
| 274 | 删除: return s.applyProxy(p, old, true) | |
| 283 | 新增: // The explicit start operation already requested networking. A pause made | |
| 284 | 新增: // after that request must survive any core recovery within the start. | |
| 285 | 新增: return s.applyProxy(p, old, nil) | |
| 275 | 286 | } |
| 276 | 287 | |
| 277 | 删除:func (s *Server) applyProxy(p managedproxy.Store, old cage.Config, resume bool) (returned error) { | |
| 288 | 新增:func (s *Server) applyProxy(p managedproxy.Store, old cage.Config, resumeVersion *uint64) (returned error) { | |
| 278 | 289 | ctx := s.operationContext() |
| 279 | 290 | previous, err := managedproxy.Load(s.profile) |
| 280 | 291 | if err != nil { |
| 281 | 292 | return err |
| 282 | 293 | } |
| 283 | 294 | s.setMessage("正在验证节点配置…") |
| 284 | 删除: if err := managedproxy.Validate(ctx, s.profile, p); err != nil { | |
| 295 | 新增: if err := validateProxyCore(ctx, s.profile, p); err != nil { | |
| 285 | 296 | return err |
| 286 | 297 | } |
| 287 | 298 | // Changing the endpoint requires an environment restart; node-only switches |
| @@ -316,14 +327,18 @@ func (s *Server) applyProxy(p managedproxy.Store, old cage.Config, resume bool) | ||
| 316 | 327 | if err := writePrivate(s.configPath, cfg); err != nil { |
| 317 | 328 | return err |
| 318 | 329 | } |
| 319 | 删除: if err := managedproxy.Start(ctx, s.profile, p); err != nil { | |
| 330 | 新增: if err := startProxyCore(ctx, s.profile, p); err != nil { | |
| 320 | 331 | return err |
| 321 | 332 | } |
| 322 | 333 | committed = true |
| 323 | 删除: s.mu.Lock() | |
| 324 | 删除: if resume { | |
| 325 | 删除: s.networkPaused = false | |
| 334 | 新增: if resumeVersion != nil { | |
| 335 | 新增: if err := s.resumeNetworkIntentAt(*resumeVersion); err != nil { | |
| 336 | 新增: return err | |
| 337 | 新增: } | |
| 326 | 338 | } |
| 339 | 新增: s.mu.Lock() | |
| 340 | 新增: // Only a user request may resume networking, and a later pause wins even | |
| 341 | 新增: // when it arrived while subscription download or core startup was pending. | |
| 327 | 342 | paused := s.networkPaused |
| 328 | 343 | s.networkError = "" |
| 329 | 344 | s.location = nil |
| @@ -444,7 +459,7 @@ func (s *Server) refreshProxySubscriptions() { | ||
| 444 | 459 | for _, src := range p.Sources { |
| 445 | 460 | if src.URL != "" && src.Interval > 0 && time.Since(src.Updated) >= time.Duration(src.Interval)*time.Hour && time.Since(src.Attempted) > 15*time.Minute { |
| 446 | 461 | // Automatic refresh never opts into a host-network fallback. |
| 447 | 删除: s.launch(&discardResponse{}, "proxy-update", func() error { return s.changeProxy("refresh", proxyInput{ID: src.ID}) }) | |
| 462 | 新增: s.launch(&discardResponse{}, "proxy-update", func() error { return s.changeProxy("refresh", proxyInput{ID: src.ID}, nil) }) | |
| 448 | 463 | return |
| 449 | 464 | } |
| 450 | 465 | } |
| @@ -55,5 +55,5 @@ func (s *Server) rebindProxyInterface() error { | ||
| 55 | 55 | if err != nil { |
| 56 | 56 | return err |
| 57 | 57 | } |
| 58 | 删除: return s.applyProxy(p, cfg, false) | |
| 58 | 新增: return s.applyProxy(p, cfg, nil) | |
| 59 | 59 | } |
| @@ -0,0 +1,168 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "sync" | |
| 9 | 新增: "testing" | |
| 10 | 新增: "time" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/managedproxy" | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:// Keep the real request, job, source persistence and gate-control paths. Only | |
| 18 | 新增:// external subscription traffic and the installed proxy process are replaced. | |
| 19 | 新增:func pendingProxyApply(t *testing.T) (*Server, *cage.EgressGate, <-chan struct{}, func()) { | |
| 20 | 新增: t.Helper() | |
| 21 | 新增: s, gate := interfaceMonitorServer(t) | |
| 22 | 新增: p, err := managedproxy.Load(s.profile) | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: p.Sources[0].URL = "https://subscription.example/nodes" | |
| 27 | 新增: p.Sources[0].Interval = 1 | |
| 28 | 新增: p.Sources[0].Updated = time.Now().Add(-2 * time.Hour) | |
| 29 | 新增: p.Sources[0].Attempted = p.Sources[0].Updated | |
| 30 | 新增: if err := p.Save(s.profile); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: validate, start, fetch := validateProxyCore, startProxyCore, fetchProxySource | |
| 34 | 新增: t.Cleanup(func() { validateProxyCore, startProxyCore, fetchProxySource = validate, start, fetch }) | |
| 35 | 新增: validateProxyCore = func(_ context.Context, profile string, candidate managedproxy.Store) error { | |
| 36 | 新增: _, err := candidate.Runtime(profile) | |
| 37 | 新增: return err | |
| 38 | 新增: } | |
| 39 | 新增: fetchProxySource = func(_ context.Context, _ *http.Client, _ string) ([]byte, string, error) { | |
| 40 | 新增: return []byte(`proxies: [{name: qa, type: socks5, server: 127.0.0.1, port: 1, password: updated-test-value}]`), "", nil | |
| 41 | 新增: } | |
| 42 | 新增: started, release := make(chan struct{}), make(chan struct{}) | |
| 43 | 新增: var once sync.Once | |
| 44 | 新增: finish := func() { once.Do(func() { close(release) }) } | |
| 45 | 新增: startProxyCore = func(ctx context.Context, _ string, _ managedproxy.Store) error { | |
| 46 | 新增: close(started) | |
| 47 | 新增: select { | |
| 48 | 新增: case <-release: | |
| 49 | 新增: return nil | |
| 50 | 新增: case <-ctx.Done(): | |
| 51 | 新增: return ctx.Err() | |
| 52 | 新增: } | |
| 53 | 新增: } | |
| 54 | 新增: t.Cleanup(func() { finish(); s.op.Lock(); s.op.Unlock() }) | |
| 55 | 新增: return s, gate, started, finish | |
| 56 | 新增:} | |
| 57 | 新增: | |
| 58 | 新增:func awaitProxyStart(t *testing.T, started <-chan struct{}) { | |
| 59 | 新增: t.Helper() | |
| 60 | 新增: select { | |
| 61 | 新增: case <-started: | |
| 62 | 新增: case <-time.After(3 * time.Second): | |
| 63 | 新增: t.Fatal("proxy application did not reach core startup") | |
| 64 | 新增: } | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:func pauseProxyNetwork(t *testing.T, s *Server) { | |
| 68 | 新增: t.Helper() | |
| 69 | 新增: if w := request(s, "POST", "/api/safety/close", s.origin, "{}", true); w.Code != 200 { | |
| 70 | 新增: t.Fatalf("pause rejected: %d %s", w.Code, w.Body.String()) | |
| 71 | 新增: } | |
| 72 | 新增:} | |
| 73 | 新增: | |
| 74 | 新增:func assertProxyStayedPaused(t *testing.T, s *Server, gate *cage.EgressGate) { | |
| 75 | 新增: t.Helper() | |
| 76 | 新增: s.op.Lock() | |
| 77 | 新增: defer s.op.Unlock() | |
| 78 | 新增: s.mu.Lock() | |
| 79 | 新增: paused, job := s.networkPaused, s.job | |
| 80 | 新增: s.mu.Unlock() | |
| 81 | 新增: if job.Running || job.Error != "" { | |
| 82 | 新增: t.Fatalf("proxy update did not complete: %+v", job) | |
| 83 | 新增: } | |
| 84 | 新增: if !paused || gate.Status().Mode != cage.GateClosed { | |
| 85 | 新增: t.Fatal("proxy update revoked manual pause") | |
| 86 | 新增: } | |
| 87 | 新增: p, err := managedproxy.Load(s.profile) | |
| 88 | 新增: if err != nil || p.Revision == "test-revision" { | |
| 89 | 新增: t.Fatal("proxy update did not persist a new revision", err) | |
| 90 | 新增: } | |
| 91 | 新增: cfg, err := loadConfig(s.configPath) | |
| 92 | 新增: if err != nil || gate.Status().Configuration != cfg.Fingerprint() { | |
| 93 | 新增: t.Fatal("paused gate was not synchronized to the applied proxy", err) | |
| 94 | 新增: } | |
| 95 | 新增:} | |
| 96 | 新增: | |
| 97 | 新增:func TestAutomaticSubscriptionUpdatePreservesManualPause(t *testing.T) { | |
| 98 | 新增: for _, pauseBefore := range []bool{true, false} { | |
| 99 | 新增: name := "paused before automatic refresh" | |
| 100 | 新增: if !pauseBefore { | |
| 101 | 新增: name = "paused while automatic refresh applies" | |
| 102 | 新增: } | |
| 103 | 新增: t.Run(name, func(t *testing.T) { | |
| 104 | 新增: s, gate, started, finish := pendingProxyApply(t) | |
| 105 | 新增: if pauseBefore { | |
| 106 | 新增: pauseProxyNetwork(t, s) | |
| 107 | 新增: } | |
| 108 | 新增: s.op.Lock() | |
| 109 | 新增: s.refreshProxySubscriptions() | |
| 110 | 新增: s.op.Unlock() | |
| 111 | 新增: awaitProxyStart(t, started) | |
| 112 | 新增: if !pauseBefore { | |
| 113 | 新增: pauseProxyNetwork(t, s) | |
| 114 | 新增: } | |
| 115 | 新增: finish() | |
| 116 | 新增: assertProxyStayedPaused(t, s, gate) | |
| 117 | 新增: p, _ := managedproxy.Load(s.profile) | |
| 118 | 新增: if p.Sources[0].Nodes[0].Config["password"] != "updated-test-value" { | |
| 119 | 新增: t.Fatal("automatic refresh did not consume the new subscription") | |
| 120 | 新增: } | |
| 121 | 新增: }) | |
| 122 | 新增: } | |
| 123 | 新增:} | |
| 124 | 新增: | |
| 125 | 新增:func TestManualProxySelectionHonorsLaterPause(t *testing.T) { | |
| 126 | 新增: s, gate, started, finish := pendingProxyApply(t) | |
| 127 | 新增: pauseProxyNetwork(t, s) | |
| 128 | 新增: p, _ := managedproxy.Load(s.profile) | |
| 129 | 新增: if w := request(s, "POST", "/api/proxy/select", s.origin, `{"node_id":"`+p.Selected+`"}`, true); w.Code != 200 { | |
| 130 | 新增: t.Fatalf("selection rejected: %d %s", w.Code, w.Body.String()) | |
| 131 | 新增: } | |
| 132 | 新增: awaitProxyStart(t, started) | |
| 133 | 新增: pauseProxyNetwork(t, s) | |
| 134 | 新增: finish() | |
| 135 | 新增: assertProxyStayedPaused(t, s, gate) | |
| 136 | 新增: reloaded := reloadedIntentServer(t, s) | |
| 137 | 新增: if err := reloaded.restoreNetworkIntent(); err != nil || !reloaded.networkPaused { | |
| 138 | 新增: t.Fatal("later manual pause was not durable", err) | |
| 139 | 新增: } | |
| 140 | 新增:} | |
| 141 | 新增: | |
| 142 | 新增:func TestManualProxySelectionMayResumeExistingPause(t *testing.T) { | |
| 143 | 新增: s, _, started, finish := pendingProxyApply(t) | |
| 144 | 新增: pauseProxyNetwork(t, s) | |
| 145 | 新增: // No VM is running in this case, so selecting a node may prepare networking | |
| 146 | 新增: // without trying to start a real guest as part of this unit test. | |
| 147 | 新增: path := filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir()), "cage-running.json") | |
| 148 | 新增: if err := os.Remove(path); err != nil { | |
| 149 | 新增: t.Fatal(err) | |
| 150 | 新增: } | |
| 151 | 新增: p, _ := managedproxy.Load(s.profile) | |
| 152 | 新增: if w := request(s, "POST", "/api/proxy/select", s.origin, `{"node_id":"`+p.Selected+`"}`, true); w.Code != 200 { | |
| 153 | 新增: t.Fatalf("selection rejected: %d %s", w.Code, w.Body.String()) | |
| 154 | 新增: } | |
| 155 | 新增: awaitProxyStart(t, started) | |
| 156 | 新增: finish() | |
| 157 | 新增: s.op.Lock() | |
| 158 | 新增: defer s.op.Unlock() | |
| 159 | 新增: s.mu.Lock() | |
| 160 | 新增: defer s.mu.Unlock() | |
| 161 | 新增: if s.job.Running || s.job.Error != "" || s.networkPaused { | |
| 162 | 新增: t.Fatalf("explicit selection failed to resume the existing pause: %+v", s.job) | |
| 163 | 新增: } | |
| 164 | 新增: reloaded := reloadedIntentServer(t, s) | |
| 165 | 新增: if err := reloaded.restoreNetworkIntent(); err != nil || reloaded.networkPaused { | |
| 166 | 新增: t.Fatal("explicit node resume was not durable", err) | |
| 167 | 新增: } | |
| 168 | 新增:} | |
| @@ -42,7 +42,7 @@ func TestFailedSubscriptionRefreshKeepsWorkingNodesAndSecretsPrivate(t *testing. | ||
| 42 | 42 | t.Fatal(err) |
| 43 | 43 | } |
| 44 | 44 | before := p.Sources[0] |
| 45 | 删除: if err = s.changeProxy("refresh", proxyInput{ID: "source"}); err == nil { | |
| 45 | 新增: if err = s.changeProxy("refresh", proxyInput{ID: "source"}, nil); err == nil { | |
| 46 | 46 | t.Fatal("broken subscription accepted") |
| 47 | 47 | } |
| 48 | 48 | after, err := managedproxy.Load(s.profile) |
| @@ -12,7 +12,6 @@ import ( | ||
| 12 | 12 | "os" |
| 13 | 13 | "os/exec" |
| 14 | 14 | "path/filepath" |
| 15 | 删除: "strings" | |
| 16 | 15 | "syscall" |
| 17 | 16 | "time" |
| 18 | 17 | |
| @@ -68,16 +67,26 @@ func (s *Server) attach() error { | ||
| 68 | 67 | } |
| 69 | 68 | ctx, cancel := controlContext() |
| 70 | 69 | defer cancel() |
| 71 | 删除: b, err := s.guest(ctx, `sudo cat /etc/claude-cage/browser-control.json; printf '\n'; cat "$HOME/.config/claude-cage/browser-password"`) | |
| 70 | 新增: b, err := s.guest(ctx, guestConnectionSnapshot) | |
| 72 | 71 | if err != nil { |
| 73 | 72 | return errors.New("环境尚未准备好") |
| 74 | 73 | } |
| 75 | 删除: lines := bytes.SplitN(bytes.TrimSpace(b), []byte("\n"), 2) | |
| 76 | 删除: var credentials guestCredentials | |
| 77 | 删除: if len(lines) != 2 || json.Unmarshal(lines[0], &credentials) != nil || credentials.Token == "" { | |
| 78 | 删除: return errors.New("浏览器控制服务尚未安装") | |
| 74 | 新增: credentials, manifest, err := parseGuestConnection(b) | |
| 75 | 新增: s.mu.Lock() | |
| 76 | 新增: s.guestManifest = manifest | |
| 77 | 新增: s.guestUpdateRequired = errors.Is(err, errGuestUpdateRequired) | |
| 78 | 新增: s.guestUpdateError = "" | |
| 79 | 新增: if err != nil { | |
| 80 | 新增: s.ready = false | |
| 81 | 新增: s.guestUpdateError = err.Error() | |
| 82 | 新增: } | |
| 83 | 新增: s.mu.Unlock() | |
| 84 | 新增: if err != nil { | |
| 85 | 新增: if errors.Is(err, errGuestUpdateRequired) { | |
| 86 | 新增: _ = s.closeProxyGate("环境组件需要更新,外网保持关闭") | |
| 87 | 新增: } | |
| 88 | 新增: return err | |
| 79 | 89 | } |
| 80 | 删除: credentials.VNCPassword = strings.TrimSpace(string(lines[1])) | |
| 81 | 90 | if _, err = s.guestAPI(ctx, credentials.Token, "GET", "/health", nil); err != nil { |
| 82 | 91 | return err |
| 83 | 92 | } |
| @@ -198,7 +207,11 @@ func (s *Server) startEnvironment(syncTimezone bool) error { | ||
| 198 | 207 | } |
| 199 | 208 | } |
| 200 | 209 | |
| 201 | 删除: if err := s.attach(); err == nil { | |
| 210 | 新增: attachErr := s.attach() | |
| 211 | 新增: if errors.Is(attachErr, errGuestUpdateRequired) { | |
| 212 | 新增: return s.synchronizeEnvironment() | |
| 213 | 新增: } | |
| 214 | 新增: if attachErr == nil { | |
| 202 | 215 | client, gateErr := s.gateClient() |
| 203 | 216 | if gateErr == nil { |
| 204 | 217 | state, e := client.Status(context.Background()) |
| @@ -322,6 +335,9 @@ func (s *Server) stopEnvironment() (returned error) { | ||
| 322 | 335 | } |
| 323 | 336 | s.ready = false |
| 324 | 337 | s.credentials = guestCredentials{} |
| 338 | 新增: s.guestManifest = nil | |
| 339 | 新增: s.guestUpdateRequired = false | |
| 340 | 新增: s.guestUpdateError = "" | |
| 325 | 341 | s.safety.Error = "" |
| 326 | 342 | s.mu.Unlock() |
| 327 | 343 | for _, t := range sessions { |
| @@ -348,6 +364,10 @@ func (s *Server) apply(v savedProfile, validate bool) error { | ||
| 348 | 364 | v.Config.ProxyURL, v.Config.ProxyRevision = old.ProxyURL, old.ProxyRevision |
| 349 | 365 | s.mu.Lock() |
| 350 | 366 | oldPrefs := s.preferences |
| 367 | 新增: resumeVersion := s.safety.pauseVersion | |
| 368 | 新增: if s.activeJobID != "" { | |
| 369 | 新增: resumeVersion = s.activePauseVersion | |
| 370 | 新增: } | |
| 351 | 371 | wasReady := vmAlive(s.profile, s.environmentDir()) |
| 352 | 372 | s.mu.Unlock() |
| 353 | 373 | changed := old != v.Config || oldPrefs.AutoTimezone != v.Preferences.AutoTimezone || oldPrefs.AutoLanguage != v.Preferences.AutoLanguage |
| @@ -375,9 +395,9 @@ func (s *Server) apply(v savedProfile, validate bool) error { | ||
| 375 | 395 | } |
| 376 | 396 | } |
| 377 | 397 | if changed { |
| 378 | 删除: s.mu.Lock() | |
| 379 | 删除: s.networkPaused = false | |
| 380 | 删除: s.mu.Unlock() | |
| 398 | 新增: if err := s.resumeNetworkIntentAt(resumeVersion); err != nil { | |
| 399 | 新增: return err | |
| 400 | 新增: } | |
| 381 | 401 | if s.operationContext().Err() != nil { |
| 382 | 402 | return s.operationContext().Err() |
| 383 | 403 | } |
| @@ -441,6 +461,11 @@ func (s *Server) guestAPI(ctx context.Context, token, method, path string, body | ||
| 441 | 461 | auditClient.Timeout = 20 * time.Second |
| 442 | 462 | client = &auditClient |
| 443 | 463 | } |
| 464 | 新增: if path == "/editor-restart" { | |
| 465 | 新增: recoveryClient := *client | |
| 466 | 新增: recoveryClient.Timeout = 30 * time.Second | |
| 467 | 新增: client = &recoveryClient | |
| 468 | 新增: } | |
| 444 | 469 | req, _ := http.NewRequestWithContext(ctx, method, "http://127.0.0.1:18500"+path, bytes.NewReader(body)) |
| 445 | 470 | req.Header.Set("Authorization", "Bearer "+token) |
| 446 | 471 | if body != nil { |
| @@ -465,7 +490,7 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) { | ||
| 465 | 490 | if r.Method == "GET" { |
| 466 | 491 | action = "tabs" |
| 467 | 492 | } |
| 468 | 删除: allowed := map[string]bool{"tabs": true, "new": true, "activate": true, "close": true, "navigate": true, "back": true, "forward": true, "reload": true, "editor": true, "resize": true} | |
| 493 | 新增: allowed := map[string]bool{"tabs": true, "new": true, "activate": true, "close": true, "navigate": true, "back": true, "forward": true, "reload": true, "editor": true, "editor-restart": true, "download-retry": true, "resize": true, "insert-text": true} | |
| 469 | 494 | if !allowed[action] { |
| 470 | 495 | http.NotFound(w, r) |
| 471 | 496 | return |
| @@ -485,16 +510,21 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) { | ||
| 485 | 510 | Width int `json:"width,omitempty"` |
| 486 | 511 | Height int `json:"height,omitempty"` |
| 487 | 512 | Workspace string `json:"workspace,omitempty"` |
| 513 | 新增: Text string `json:"text,omitempty"` | |
| 488 | 514 | } |
| 489 | 515 | if !readJSON(w, r, &input) { |
| 490 | 516 | return |
| 491 | 517 | } |
| 518 | 新增: if action == "insert-text" && (input.ID == "" || input.Text == "" || len(input.Text) > 8192) { | |
| 519 | 新增: http.Error(w, "输入文字或目标标签无效", http.StatusBadRequest) | |
| 520 | 新增: return | |
| 521 | 新增: } | |
| 492 | 522 | if action == "new" && input.URL == "" { |
| 493 | 523 | s.mu.Lock() |
| 494 | 524 | input.URL = browserHomeURL(s.preferences) |
| 495 | 525 | s.mu.Unlock() |
| 496 | 526 | } |
| 497 | 删除: if action == "editor" { | |
| 527 | 新增: if action == "editor" || action == "editor-restart" { | |
| 498 | 528 | if !s.op.TryLock() { |
| 499 | 529 | http.Error(w, "环境正在执行其他操作", 409) |
| 500 | 530 | return |
| @@ -25,11 +25,12 @@ import ( | ||
| 25 | 25 | var guestSafetyProbe string |
| 26 | 26 | |
| 27 | 27 | type safetyState struct { |
| 28 | 删除: Gate *cage.GateStatus `json:"gate,omitempty"` | |
| 29 | 删除: Report *cage.SafetyReport `json:"report,omitempty"` | |
| 30 | 删除: Error string `json:"error,omitempty"` | |
| 31 | 删除: ExitIP string `json:"exit_ip,omitempty"` | |
| 32 | 删除: VerifiedAt time.Time `json:"verified_at,omitempty"` | |
| 28 | 新增: pauseVersion uint64 | |
| 29 | 新增: Gate *cage.GateStatus `json:"gate,omitempty"` | |
| 30 | 新增: Report *cage.SafetyReport `json:"report,omitempty"` | |
| 31 | 新增: Error string `json:"error,omitempty"` | |
| 32 | 新增: ExitIP string `json:"exit_ip,omitempty"` | |
| 33 | 新增: VerifiedAt time.Time `json:"verified_at,omitempty"` | |
| 33 | 34 | } |
| 34 | 35 | |
| 35 | 36 | type networkObservation struct { |
| @@ -102,9 +103,12 @@ func (s *Server) pauseNetworkNow(reason string) error { | ||
| 102 | 103 | } |
| 103 | 104 | |
| 104 | 105 | func (s *Server) revokeNetworkNow(reason string, pause bool) error { |
| 106 | 新增: var intentErr error | |
| 105 | 107 | s.mu.Lock() |
| 106 | 108 | if pause { |
| 107 | 109 | s.networkPaused = true |
| 110 | 新增: s.safety.pauseVersion++ | |
| 111 | 新增: intentErr = s.saveNetworkIntentLocked(true) | |
| 108 | 112 | } |
| 109 | 113 | if s.checkCancel != nil { |
| 110 | 114 | s.checkCancel() |
| @@ -117,13 +121,13 @@ func (s *Server) revokeNetworkNow(reason string, pause bool) error { | ||
| 117 | 121 | defer s.safetyOp.Unlock() |
| 118 | 122 | client, err := s.gateClient() |
| 119 | 123 | if err != nil { |
| 120 | 删除: return err | |
| 124 | 新增: return errors.Join(intentErr, err) | |
| 121 | 125 | } |
| 122 | 126 | state, err := client.Close(context.Background(), reason) |
| 123 | 127 | if err == nil { |
| 124 | 128 | s.publishGate(state) |
| 125 | 129 | } |
| 126 | 删除: return err | |
| 130 | 新增: return errors.Join(intentErr, err) | |
| 127 | 131 | } |
| 128 | 132 | |
| 129 | 133 | func (s *Server) safetyExport(w http.ResponseWriter, r *http.Request) { |
| @@ -530,7 +534,7 @@ func (s *Server) runSafetyCheck() (returned error) { | ||
| 530 | 534 | // failure drill. Lost supervision eventually closes existing guest connections. |
| 531 | 535 | func (s *Server) monitorSafety() { |
| 532 | 536 | s.mu.Lock() |
| 533 | 删除: ready, busy, last := s.ready, s.job.Running || s.networkPaused, s.safety.VerifiedAt | |
| 537 | 新增: ready, busy, last := s.ready, (s.job.Running && s.job.Kind != "environment-tools") || s.networkPaused, s.safety.VerifiedAt | |
| 534 | 538 | s.mu.Unlock() |
| 535 | 539 | if !ready || busy || time.Since(last) < 30*time.Second { |
| 536 | 540 | return |
| @@ -594,10 +598,15 @@ func (s *Server) monitorSafety() { | ||
| 594 | 598 | issue = "浏览器时区或语言的运行状态无法确认,请重新检测" |
| 595 | 599 | } |
| 596 | 600 | } |
| 601 | 新增: s.finishSafetyMonitor(ctx, client, state, ip, issue) | |
| 602 | 新增:} | |
| 603 | 新增: | |
| 604 | 新增:// Recheck the user operation and configuration at the actual lease write. | |
| 605 | 新增:func (s *Server) finishSafetyMonitor(ctx context.Context, client *cage.GateClient, state cage.GateStatus, ip, issue string) { | |
| 597 | 606 | s.safetyOp.Lock() |
| 598 | 607 | defer s.safetyOp.Unlock() |
| 599 | 608 | s.mu.Lock() |
| 600 | 删除: busy = s.job.Running || s.networkPaused | |
| 609 | 新增: busy := (s.job.Running && s.job.Kind != "environment-tools") || s.networkPaused | |
| 601 | 610 | s.mu.Unlock() |
| 602 | 611 | if busy { |
| 603 | 612 | return |
| @@ -30,19 +30,28 @@ var assets embed.FS | ||
| 30 | 30 | const cookieName = "cage_session" |
| 31 | 31 | |
| 32 | 32 | type controlFile struct { |
| 33 | 删除: Port int `json:"port"` | |
| 34 | 删除: Token string `json:"token"` | |
| 35 | 删除: PID int `json:"pid"` | |
| 33 | 新增: Port int `json:"port"` | |
| 34 | 新增: Token string `json:"token"` | |
| 35 | 新增: PID int `json:"pid"` | |
| 36 | 新增: Controller ControllerIdentity `json:"controller"` | |
| 36 | 37 | } |
| 37 | 38 | type Job struct { |
| 38 | 删除: ID string `json:"id"` | |
| 39 | 删除: Kind string `json:"kind"` | |
| 40 | 删除: Running bool `json:"running"` | |
| 41 | 删除: Message string `json:"message"` | |
| 42 | 删除: Error string `json:"error,omitempty"` | |
| 43 | 删除: Log string `json:"log,omitempty"` | |
| 39 | 新增: pauseVersion uint64 | |
| 40 | 新增: ID string `json:"id"` | |
| 41 | 新增: Kind string `json:"kind"` | |
| 42 | 新增: Running bool `json:"running"` | |
| 43 | 新增: Message string `json:"message"` | |
| 44 | 新增: Error string `json:"error,omitempty"` | |
| 45 | 新增: Log string `json:"log,omitempty"` | |
| 44 | 46 | } |
| 45 | 47 | type Server struct { |
| 48 | 新增: identity ControllerIdentity | |
| 49 | 新增: guestManifest *cage.GuestManifest | |
| 50 | 新增: guestUpdateRequired bool | |
| 51 | 新增: guestUpdateError string | |
| 52 | 新增: closing bool | |
| 53 | 新增: shutdown func() | |
| 54 | 新增: favoritesMu sync.Mutex | |
| 46 | 55 | terminalSequence int |
| 47 | 56 | tickets map[string]time.Time |
| 48 | 57 | guestClient *http.Client |
| @@ -68,6 +77,7 @@ type Server struct { | ||
| 68 | 77 | jobCancel context.CancelFunc |
| 69 | 78 | activeContext context.Context |
| 70 | 79 | activeJobID string |
| 80 | 新增: activePauseVersion uint64 | |
| 71 | 81 | } |
| 72 | 82 | |
| 73 | 83 | func randomToken() string { |
| @@ -110,12 +120,19 @@ func Serve(configPath string) error { | ||
| 110 | 120 | } |
| 111 | 121 | defer listener.Close() |
| 112 | 122 | s := &Server{profile: profile, configPath: configPath, exe: exe, origin: fmt.Sprintf("http://localhost:%d", port), token: randomToken(), session: randomToken(), preferences: Preferences{Keyboard: "mac"}, terminals: map[string]*terminalSession{}} |
| 123 | 新增: s.identity, err = currentController() | |
| 124 | 新增: if err != nil { | |
| 125 | 新增: return err | |
| 126 | 新增: } | |
| 113 | 127 | if b, e := os.ReadFile(filepath.Join(profile, "workbench.json")); e == nil { |
| 114 | 128 | _ = json.Unmarshal(b, &s.preferences) |
| 115 | 129 | } |
| 116 | 130 | if err = s.prepareEnvironment(); err != nil { |
| 117 | 131 | return err |
| 118 | 132 | } |
| 133 | 新增: if intentErr := s.restoreNetworkIntent(); intentErr != nil { | |
| 134 | 新增: s.networkError = intentErr.Error() | |
| 135 | 新增: } | |
| 119 | 136 | if s.preferences.Keyboard == "" { |
| 120 | 137 | s.preferences.Keyboard = "mac" |
| 121 | 138 | } |
| @@ -124,34 +141,44 @@ func Serve(configPath string) error { | ||
| 124 | 141 | return e |
| 125 | 142 | } |
| 126 | 143 | } |
| 127 | 删除: if err = writePrivate(filepath.Join(profile, "control.json"), controlFile{port, s.token, os.Getpid()}); err != nil { | |
| 144 | 新增: if err = writePrivate(filepath.Join(profile, "control.json"), controlFile{Port: port, Token: s.token, PID: os.Getpid(), Controller: s.identity}); err != nil { | |
| 128 | 145 | return err |
| 129 | 146 | } |
| 130 | 147 | // A previously running VM cannot keep an unmanaged endpoint online. |
| 131 | 148 | if cfg, e := loadConfig(configPath); e != nil || cfg.RequireManagedProxy(profile) != nil { |
| 132 | 149 | _ = s.closeProxyGate("尚未配置有效节点,外网保持关闭") |
| 133 | 150 | } |
| 151 | 新增: if s.networkPaused { | |
| 152 | 新增: _ = s.closeProxyGate("网络保持暂停,请手动恢复后再联网") | |
| 153 | 新增: } | |
| 134 | 154 | go s.monitor() |
| 135 | 155 | go s.monitorNetwork() |
| 136 | 156 | server := &http.Server{Handler: s.handler(), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} |
| 137 | 删除: return server.Serve(listener) | |
| 157 | 新增: shutdownDone := make(chan struct{}) | |
| 158 | 新增: s.shutdown = func() { | |
| 159 | 新增: defer close(shutdownDone) | |
| 160 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) | |
| 161 | 新增: defer cancel() | |
| 162 | 新增: _ = server.Shutdown(ctx) | |
| 163 | 新增: _ = server.Close() | |
| 164 | 新增: } | |
| 165 | 新增: err = server.Serve(listener) | |
| 166 | 新增: if errors.Is(err, http.ErrServerClosed) { | |
| 167 | 新增: <-shutdownDone | |
| 168 | 新增: return nil | |
| 169 | 新增: } | |
| 170 | 新增: return err | |
| 138 | 171 | } |
| 139 | 172 | func (s *Server) handler() http.Handler { |
| 140 | 173 | mux := http.NewServeMux() |
| 141 | 174 | mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { jsonReply(w, map[string]bool{"ready": true}) }) |
| 142 | 175 | mux.HandleFunc("POST /api/launch", func(w http.ResponseWriter, r *http.Request) { |
| 143 | 删除: var v struct { | |
| 144 | 删除: Token string `json:"token"` | |
| 145 | 删除: } | |
| 146 | 删除: if !readJSON(w, r, &v) { | |
| 147 | 删除: return | |
| 148 | 删除: } | |
| 149 | 删除: if !equalSecret(v.Token, s.token) { | |
| 150 | 删除: http.Error(w, "Launcher refused", 401) | |
| 176 | 新增: if !s.launcherAuthenticated(w, r) { | |
| 151 | 177 | return |
| 152 | 178 | } |
| 153 | 删除: jsonReply(w, map[string]string{"url": s.origin + "/?launch=" + randomToken()[:8] + "#" + s.issueTicket()}) | |
| 179 | 新增: jsonReply(w, launchResponse{URL: s.origin + "/?launch=" + randomToken()[:8] + "#" + s.issueTicket(), Controller: s.identity}) | |
| 154 | 180 | }) |
| 181 | 新增: mux.HandleFunc("POST /api/handoff", s.handoff) | |
| 155 | 182 | mux.HandleFunc("POST /api/session", func(w http.ResponseWriter, r *http.Request) { |
| 156 | 183 | var v struct { |
| 157 | 184 | Token string `json:"token"` |
| @@ -168,9 +195,14 @@ func (s *Server) handler() http.Handler { | ||
| 168 | 195 | }) |
| 169 | 196 | mux.HandleFunc("GET /api/status", s.status) |
| 170 | 197 | mux.HandleFunc("GET /api/settings", s.getSettings) |
| 198 | 新增: mux.HandleFunc("GET /api/environment/versions", s.environmentVersions) | |
| 199 | 新增: mux.HandleFunc("POST /api/environment/update", s.updateEnvironment) | |
| 200 | 新增: mux.HandleFunc("POST /api/environment/tools", s.updateEnvironmentTools) | |
| 171 | 201 | mux.HandleFunc("GET /api/host/git", s.hostGit) |
| 172 | 202 | mux.HandleFunc("POST /api/host/git", s.enableHostGit) |
| 173 | 203 | mux.HandleFunc("GET /api/appearance", s.getAppearance) |
| 204 | 新增: mux.HandleFunc("GET /api/favorites", s.getFavorites) | |
| 205 | 新增: mux.HandleFunc("POST /api/favorites", s.mutateFavorites) | |
| 174 | 206 | mux.HandleFunc("POST /api/appearance", s.saveAppearance) |
| 175 | 207 | mux.HandleFunc("GET /api/appearance/codex", s.codexAppearance) |
| 176 | 208 | mux.HandleFunc("POST /api/settings/probe", s.probe) |
| @@ -222,13 +254,20 @@ func (s *Server) handler() http.Handler { | ||
| 222 | 254 | return |
| 223 | 255 | } |
| 224 | 256 | } |
| 225 | 删除: if strings.HasPrefix(r.URL.Path, "/api/") && r.URL.Path != "/api/session" && r.URL.Path != "/api/launch" { | |
| 257 | 新增: if strings.HasPrefix(r.URL.Path, "/api/") && r.URL.Path != "/api/session" && r.URL.Path != "/api/launch" && r.URL.Path != "/api/handoff" { | |
| 226 | 258 | c, e := r.Cookie(s.cookieName()) |
| 227 | 259 | if e != nil || !equalSecret(c.Value, s.session) { |
| 228 | 260 | http.Error(w, "请从 Cage 应用重新打开工作台", 401) |
| 229 | 261 | return |
| 230 | 262 | } |
| 231 | 263 | } |
| 264 | 新增: s.mu.Lock() | |
| 265 | 新增: closing := s.closing | |
| 266 | 新增: s.mu.Unlock() | |
| 267 | 新增: if closing { | |
| 268 | 新增: http.Error(w, "后台正在更新,请重新打开 Cage。", http.StatusServiceUnavailable) | |
| 269 | 新增: return | |
| 270 | 新增: } | |
| 232 | 271 | mux.ServeHTTP(w, r) |
| 233 | 272 | }) |
| 234 | 273 | } |
| @@ -264,6 +303,11 @@ func requestError(w http.ResponseWriter, err error) { | ||
| 264 | 303 | func (s *Server) busy() bool { s.mu.Lock(); defer s.mu.Unlock(); return s.job.Running } |
| 265 | 304 | func (s *Server) launch(w http.ResponseWriter, kind string, fn func() error) { |
| 266 | 305 | s.mu.Lock() |
| 306 | 新增: if s.closing { | |
| 307 | 新增: s.mu.Unlock() | |
| 308 | 新增: http.Error(w, "后台正在更新,请重新打开 Cage。", http.StatusServiceUnavailable) | |
| 309 | 新增: return | |
| 310 | 新增: } | |
| 267 | 311 | if s.job.Running { |
| 268 | 312 | if kind == "stop" && s.job.Kind == "stop" { |
| 269 | 313 | job := s.job |
| @@ -280,12 +324,17 @@ func (s *Server) launch(w http.ResponseWriter, kind string, fn func() error) { | ||
| 280 | 324 | s.jobCancel() |
| 281 | 325 | } |
| 282 | 326 | } |
| 283 | 删除: ctx, cancel := context.WithCancel(context.Background()) | |
| 284 | 删除: s.jobCancel = cancel | |
| 285 | 327 | if kind == "start" || kind == "safety" || kind == "restore" { |
| 286 | 删除: s.networkPaused = false | |
| 328 | 新增: if err := s.saveNetworkIntentLocked(false); err != nil { | |
| 329 | 新增: s.mu.Unlock() | |
| 330 | 新增: _ = s.closeProxyGate("网络恢复意图无法保存,外网保持关闭") | |
| 331 | 新增: requestError(w, err) | |
| 332 | 新增: return | |
| 333 | 新增: } | |
| 287 | 334 | } |
| 288 | 删除: s.job = Job{ID: randomToken()[:12], Kind: kind, Running: true, Message: "正在准备…"} | |
| 335 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 336 | 新增: s.jobCancel = cancel | |
| 337 | 新增: s.job = Job{ID: randomToken()[:12], Kind: kind, Running: true, Message: "正在准备…", pauseVersion: s.safety.pauseVersion} | |
| 289 | 338 | if s.monitorCancel != nil { |
| 290 | 339 | s.monitorCancel() |
| 291 | 340 | } |
| @@ -301,11 +350,13 @@ func (s *Server) launch(w http.ResponseWriter, kind string, fn func() error) { | ||
| 301 | 350 | return |
| 302 | 351 | } |
| 303 | 352 | s.activeContext, s.activeJobID = ctx, job.ID |
| 353 | 新增: s.activePauseVersion = job.pauseVersion | |
| 304 | 354 | s.mu.Unlock() |
| 305 | 355 | err := fn() |
| 306 | 356 | s.mu.Lock() |
| 307 | 357 | defer s.mu.Unlock() |
| 308 | 358 | s.activeContext, s.activeJobID = nil, "" |
| 359 | 新增: s.activePauseVersion = 0 | |
| 309 | 360 | if s.job.ID != job.ID { |
| 310 | 361 | return |
| 311 | 362 | } |
| @@ -348,7 +399,7 @@ func (s *Server) status(w http.ResponseWriter, r *http.Request) { | ||
| 348 | 399 | s.mu.Lock() |
| 349 | 400 | defer s.mu.Unlock() |
| 350 | 401 | _, e := os.Stat(filepath.Join(s.profile, "previous-profile.json")) |
| 351 | 删除: jsonReply(w, map[string]any{"projects": projects, "ready": s.ready, "vm_running": vmAlive(s.profile, s.environmentDir()), "workspace": s.preferences.Workspace, "environment_workspace": s.preferences.Workspace == s.environmentDir(), "environment_directory": s.environmentDir(), "project_error": s.projectError, "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.job, "location": s.location, "network_error": s.networkError, "can_restore": e == nil, "safety": s.safety}) | |
| 402 | 新增: jsonReply(w, map[string]any{"projects": projects, "ready": s.ready, "vm_running": vmAlive(s.profile, s.environmentDir()), "workspace": s.preferences.Workspace, "environment_workspace": s.preferences.Workspace == s.environmentDir(), "environment_directory": s.environmentDir(), "project_error": s.projectError, "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.job, "location": s.location, "network_error": s.networkError, "can_restore": e == nil, "safety": s.safety, "environment_update_required": s.guestUpdateRequired, "environment_update_error": s.guestUpdateError}) | |
| 352 | 403 | } |
| 353 | 404 | func (s *Server) getSettings(w http.ResponseWriter, r *http.Request) { |
| 354 | 405 | c, err := loadConfig(s.configPath) |
| @@ -0,0 +1,175 @@ | ||
| 1 | 新增:// Run in the Linux guest with a separate X display and temporary browser profile: | |
| 2 | 新增:// DISPLAY=:179 node scripts/browser-audit-smoke.mjs | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { spawn } from "node:child_process"; | |
| 5 | 新增:import { once } from "node:events"; | |
| 6 | 新增:import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | 新增:import { tmpdir } from "node:os"; | |
| 8 | 新增:import { join } from "node:path"; | |
| 9 | 新增:import { setTimeout as delay } from "node:timers/promises"; | |
| 10 | 新增:import { auditBrowser } from "../internal/cage/browser-audit.mjs"; | |
| 11 | 新增: | |
| 12 | 新增:assert.equal(process.platform, "linux", "Run this check in the Linux guest"); | |
| 13 | 新增:assert.ok(process.env.DISPLAY, "Provide an isolated X display"); | |
| 14 | 新增:const directory = await mkdtemp(join(tmpdir(), "cage-audit-smoke-")); | |
| 15 | 新增:const chrome = spawn( | |
| 16 | 新增: process.env.CAGE_TEST_CHROMIUM || "/usr/bin/chromium", | |
| 17 | 新增: [ | |
| 18 | 新增: `--user-data-dir=${directory}`, | |
| 19 | 新增: "--remote-debugging-pipe", | |
| 20 | 新增: "--no-first-run", | |
| 21 | 新增: "--no-default-browser-check", | |
| 22 | 新增: "--disable-background-networking", | |
| 23 | 新增: "about:blank", | |
| 24 | 新增: ], | |
| 25 | 新增: { stdio: ["ignore", "ignore", "pipe", "pipe", "pipe"] }, | |
| 26 | 新增:); | |
| 27 | 新增:let sequence = 0, | |
| 28 | 新增: buffer = Buffer.alloc(0), | |
| 29 | 新增: stderr = "", | |
| 30 | 新增: exit; | |
| 31 | 新增:const pending = new Map(); | |
| 32 | 新增:chrome.stderr.on("data", (chunk) => { | |
| 33 | 新增: stderr = (stderr + chunk).slice(-64000); | |
| 34 | 新增:}); | |
| 35 | 新增:chrome.stdio[3].on("error", () => {}); | |
| 36 | 新增:chrome.on("exit", (code, signal) => { | |
| 37 | 新增: exit = { code, signal }; | |
| 38 | 新增: for (const call of pending.values()) { | |
| 39 | 新增: clearTimeout(call.timer); | |
| 40 | 新增: call.reject(new Error(`Chromium exited: ${JSON.stringify(exit)}`)); | |
| 41 | 新增: } | |
| 42 | 新增: pending.clear(); | |
| 43 | 新增:}); | |
| 44 | 新增:chrome.stdio[4].on("data", (chunk) => { | |
| 45 | 新增: buffer = Buffer.concat([buffer, chunk]); | |
| 46 | 新增: let end; | |
| 47 | 新增: while ((end = buffer.indexOf(0)) >= 0) { | |
| 48 | 新增: const message = JSON.parse(buffer.subarray(0, end)); | |
| 49 | 新增: buffer = buffer.subarray(end + 1); | |
| 50 | 新增: const call = pending.get(message.id); | |
| 51 | 新增: if (!call) continue; | |
| 52 | 新增: pending.delete(message.id); | |
| 53 | 新增: clearTimeout(call.timer); | |
| 54 | 新增: if (message.error) call.reject(new Error(message.error.message)); | |
| 55 | 新增: else call.resolve(message.result); | |
| 56 | 新增: } | |
| 57 | 新增:}); | |
| 58 | 新增:function cdp(method, params = {}, sessionId, timeout = 10000) { | |
| 59 | 新增: return new Promise((resolve, reject) => { | |
| 60 | 新增: if (exit) | |
| 61 | 新增: return reject(new Error(`Chromium exited: ${JSON.stringify(exit)}`)); | |
| 62 | 新增: const id = ++sequence; | |
| 63 | 新增: const timer = setTimeout(() => { | |
| 64 | 新增: pending.delete(id); | |
| 65 | 新增: reject(new Error(`Timeout: ${method}`)); | |
| 66 | 新增: }, timeout); | |
| 67 | 新增: pending.set(id, { resolve, reject, timer }); | |
| 68 | 新增: chrome.stdio[3].write( | |
| 69 | 新增: JSON.stringify({ id, method, params, sessionId }) + "\0", | |
| 70 | 新增: ); | |
| 71 | 新增: }); | |
| 72 | 新增:} | |
| 73 | 新增:try { | |
| 74 | 新增: const version = await cdp("Browser.getVersion"); | |
| 75 | 新增: console.log(JSON.stringify({ browser: version.product })); | |
| 76 | 新增: await cdp("Target.setDiscoverTargets", { discover: true }); | |
| 77 | 新增: const { targetInfos } = await cdp("Target.getTargets"); | |
| 78 | 新增: const userPage = targetInfos.find((page) => page.type === "page"); | |
| 79 | 新增: assert.ok(userPage); | |
| 80 | 新增: const { sessionId } = await cdp("Target.attachToTarget", { | |
| 81 | 新增: targetId: userPage.targetId, | |
| 82 | 新增: flatten: true, | |
| 83 | 新增: }); | |
| 84 | 新增: await cdp( | |
| 85 | 新增: "Runtime.evaluate", | |
| 86 | 新增: { | |
| 87 | 新增: expression: | |
| 88 | 新增: "document.title = 'Cage test page'; document.body.innerHTML = '<input value=unsaved-text>'; window.cageTestState = 42;", | |
| 89 | 新增: }, | |
| 90 | 新增: sessionId, | |
| 91 | 新增: ); | |
| 92 | 新增: const state = async () => | |
| 93 | 新增: ( | |
| 94 | 新增: await cdp( | |
| 95 | 新增: "Runtime.evaluate", | |
| 96 | 新增: { | |
| 97 | 新增: expression: | |
| 98 | 新增: "JSON.stringify({title:document.title,input:document.querySelector('input').value,state:window.cageTestState,focus:document.hasFocus()})", | |
| 99 | 新增: returnByValue: true, | |
| 100 | 新增: }, | |
| 101 | 新增: sessionId, | |
| 102 | 新增: ) | |
| 103 | 新增: ).result.value; | |
| 104 | 新增: const before = await state(); | |
| 105 | 新增: const excluded = new Set(); | |
| 106 | 新增: const clean = async () => { | |
| 107 | 新增: assert.equal(excluded.size, 0); | |
| 108 | 新增: assert.deepEqual( | |
| 109 | 新增: (await cdp("Target.getBrowserContexts")).browserContextIds, | |
| 110 | 新增: [], | |
| 111 | 新增: ); | |
| 112 | 新增: assert.deepEqual( | |
| 113 | 新增: (await cdp("Target.getTargets")).targetInfos | |
| 114 | 新增: .filter((page) => page.type === "page") | |
| 115 | 新增: .map((page) => page.targetId), | |
| 116 | 新增: [userPage.targetId], | |
| 117 | 新增: ); | |
| 118 | 新增: assert.equal(await state(), before, "The user's page or focus changed"); | |
| 119 | 新增: }; | |
| 120 | 新增: for (let index = 0; index < 20; index++) { | |
| 121 | 新增: const result = await auditBrowser(cdp, excluded, false, "UTC"); | |
| 122 | 新增: assert.equal(result.expected_timezone, "UTC"); | |
| 123 | 新增: assert.match(result.platform, /Linux/); | |
| 124 | 新增: await clean(); | |
| 125 | 新增: } | |
| 126 | 新增: await assert.rejects( | |
| 127 | 新增: auditBrowser(cdp, excluded, false, "Invalid/Timezone"), | |
| 128 | 新增: /浏览器诊断未完成/, | |
| 129 | 新增: ); | |
| 130 | 新增: await clean(); | |
| 131 | 新增: // The guest's existing diagnostic endpoint exercises navigation and fetch. | |
| 132 | 新增: let networkStatus = "diagnostic endpoint unavailable"; | |
| 133 | 新增: try { | |
| 134 | 新增: const network = await auditBrowser(cdp, excluded, true, "UTC"); | |
| 135 | 新增: assert.equal(typeof network.network.status, "number"); | |
| 136 | 新增: networkStatus = network.network.status; | |
| 137 | 新增: } catch (error) { | |
| 138 | 新增: // The diagnostic endpoint is only served during network verification. | |
| 139 | 新增: // Outside that window, verify cleanup of the failed navigation as well. | |
| 140 | 新增: assert.match(error.message, /诊断页面无法连接|诊断页面尚未就绪/); | |
| 141 | 新增: } | |
| 142 | 新增: await clean(); | |
| 143 | 新增: console.log( | |
| 144 | 新增: JSON.stringify({ | |
| 145 | 新增: audits: 22, | |
| 146 | 新增: networkStatus, | |
| 147 | 新增: resourcesClean: true, | |
| 148 | 新增: userPagePreserved: true, | |
| 149 | 新增: }), | |
| 150 | 新增: ); | |
| 151 | 新增: // Chromium 156 waits 60 seconds before destroying a referenced context. | |
| 152 | 新增: // A short smoke test would pass even with the original crash. | |
| 153 | 新增: for (let seconds = 5; seconds <= 75; seconds += 5) { | |
| 154 | 新增: await delay(5000); | |
| 155 | 新增: await clean(); | |
| 156 | 新增: if (seconds % 15 === 0) | |
| 157 | 新增: console.log(JSON.stringify({ aliveSeconds: seconds })); | |
| 158 | 新增: } | |
| 159 | 新增: assert.ok( | |
| 160 | 新增: !stderr.includes("rph_with_bc_reference"), | |
| 161 | 新增: "Chromium reported a dangling context", | |
| 162 | 新增: ); | |
| 163 | 新增: console.log( | |
| 164 | 新增: "PASS: browser survived deferred cleanup with its page and focus intact", | |
| 165 | 新增: ); | |
| 166 | 新增:} finally { | |
| 167 | 新增: if (!exit) { | |
| 168 | 新增: const exited = once(chrome, "exit"); | |
| 169 | 新增: chrome.kill("SIGTERM"); | |
| 170 | 新增: const kill = setTimeout(() => chrome.kill("SIGKILL"), 5000); | |
| 171 | 新增: await exited; | |
| 172 | 新增: clearTimeout(kill); | |
| 173 | 新增: } | |
| 174 | 新增: await rm(directory, { recursive: true, force: true }); | |
| 175 | 新增:} | |
| @@ -0,0 +1,153 @@ | ||
| 1 | 新增:// Run in the Linux guest on a separate X display: | |
| 2 | 新增:// DISPLAY=:183 node scripts/browser-controls-smoke.mjs | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { spawn } from "node:child_process"; | |
| 5 | 新增:import { randomBytes } from "node:crypto"; | |
| 6 | 新增:import { once } from "node:events"; | |
| 7 | 新增:import { mkdtemp, readFile, writeFile, copyFile, rm } from "node:fs/promises"; | |
| 8 | 新增:import http from "node:http"; | |
| 9 | 新增:import { tmpdir } from "node:os"; | |
| 10 | 新增:import { join } from "node:path"; | |
| 11 | 新增:import { setTimeout as delay } from "node:timers/promises"; | |
| 12 | 新增: | |
| 13 | 新增:assert.equal(process.platform, "linux", "Run in the Linux guest"); | |
| 14 | 新增:assert.ok(process.env.DISPLAY, "Provide an isolated X display"); | |
| 15 | 新增:const directory = await mkdtemp(join(tmpdir(), "cage-controls-smoke-")); | |
| 16 | 新增:const reports = new Map(); | |
| 17 | 新增:const site = http.createServer(async (req, res) => { | |
| 18 | 新增: const url = new URL(req.url, "http://localhost"); | |
| 19 | 新增: if (url.pathname === "/report") { | |
| 20 | 新增: let body = ""; | |
| 21 | 新增: for await (const chunk of req) body += chunk; | |
| 22 | 新增: const path = url.searchParams.get("path"); | |
| 23 | 新增: const previous = reports.get(path); | |
| 24 | 新增: reports.set(path, { ...JSON.parse(body), visits: (previous?.visits || 0) + 1 }); | |
| 25 | 新增: res.end("ok"); | |
| 26 | 新增: return; | |
| 27 | 新增: } | |
| 28 | 新增: res.setHeader("Content-Type", "text/html"); | |
| 29 | 新增: if (url.pathname === "/first") | |
| 30 | 新增: res.setHeader("Set-Cookie", "cage_smoke=1; SameSite=Lax"); | |
| 31 | 新增: res.end(`<!doctype html><title>${url.pathname}</title><p>Browser smoke test</p> | |
| 32 | 新增: <script>fetch('/report?path='+encodeURIComponent(location.pathname), { | |
| 33 | 新增: method:'POST',body:JSON.stringify({webdriver:navigator.webdriver, | |
| 34 | 新增: cookie:document.cookie.includes('cage_smoke=1')}) | |
| 35 | 新增: });</script>`); | |
| 36 | 新增:}); | |
| 37 | 新增:await new Promise((resolve) => site.listen(0, "127.0.0.1", resolve)); | |
| 38 | 新增:const origin = `http://127.0.0.1:${site.address().port}`; | |
| 39 | 新增:const token = randomBytes(32).toString("hex"); | |
| 40 | 新增:let agent, control, stderr = ""; | |
| 41 | 新增:async function waitFor(read, label) { | |
| 42 | 新增: const deadline = Date.now() + 15000; | |
| 43 | 新增: while (Date.now() < deadline) { | |
| 44 | 新增: const value = await read(); | |
| 45 | 新增: if (value) return value; | |
| 46 | 新增: if (agent?.exitCode !== null) | |
| 47 | 新增: throw new Error(`Browser agent exited during ${label}: ${stderr.slice(-2000)}`); | |
| 48 | 新增: await delay(100); | |
| 49 | 新增: } | |
| 50 | 新增: throw new Error(`Timeout: ${label}`); | |
| 51 | 新增:} | |
| 52 | 新增:async function api(path, body) { | |
| 53 | 新增: const response = await fetch(control + path, { | |
| 54 | 新增: method: body === undefined ? "GET" : "POST", | |
| 55 | 新增: headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, | |
| 56 | 新增: ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 57 | 新增: }); | |
| 58 | 新增: const result = await response.json(); | |
| 59 | 新增: assert.equal(response.status, 200, JSON.stringify(result)); | |
| 60 | 新增: return result; | |
| 61 | 新增:} | |
| 62 | 新增:async function start() { | |
| 63 | 新增: control = undefined; | |
| 64 | 新增: let output = ""; | |
| 65 | 新增: agent = spawn(process.execPath, [join(directory, "agent.mjs")], { | |
| 66 | 新增: stdio: ["ignore", "pipe", "pipe"], | |
| 67 | 新增: }); | |
| 68 | 新增: agent.stdout.on("data", (chunk) => { | |
| 69 | 新增: output += chunk; | |
| 70 | 新增: const match = output.match(/CONTROL_PORT=(\d+)/); | |
| 71 | 新增: if (match) control = `http://127.0.0.1:${match[1]}`; | |
| 72 | 新增: }); | |
| 73 | 新增: agent.stderr.on("data", (chunk) => { stderr = (stderr + chunk).slice(-8000); }); | |
| 74 | 新增: await waitFor(() => control, "control listener"); | |
| 75 | 新增: await waitFor(async () => { | |
| 76 | 新增: const response = await fetch(control + "/health", { | |
| 77 | 新增: headers: { Authorization: `Bearer ${token}` }, | |
| 78 | 新增: }); | |
| 79 | 新增: return response.ok; | |
| 80 | 新增: }, "browser readiness"); | |
| 81 | 新增:} | |
| 82 | 新增:async function stop() { | |
| 83 | 新增: if (!agent || agent.exitCode !== null) return; | |
| 84 | 新增: const exited = once(agent, "exit"); | |
| 85 | 新增: agent.kill("SIGTERM"); | |
| 86 | 新增: const force = setTimeout(() => agent.kill("SIGKILL"), 5000); | |
| 87 | 新增: await exited; | |
| 88 | 新增: clearTimeout(force); | |
| 89 | 新增:} | |
| 90 | 新增:try { | |
| 91 | 新增: // Redirect deployment paths and the control listener only. The Chromium | |
| 92 | 新增: // flags and all browser-control handlers come from the production agent. | |
| 93 | 新增: const source = await readFile(new URL("../internal/cage/browser-agent.mjs", import.meta.url), "utf8"); | |
| 94 | 新增: const listen = 'server.listen(18500, "127.0.0.1");'; | |
| 95 | 新增: assert.ok(source.includes(listen), "Update the isolated control-listener adapter"); | |
| 96 | 新增: await writeFile(join(directory, "agent.mjs"), source | |
| 97 | 新增: .replaceAll("/home/cage-browser", directory) | |
| 98 | 新增: .replace("/etc/claude-cage/browser-control.json", join(directory, "control.json")) | |
| 99 | 新增: .replace(listen, 'server.listen(0, "127.0.0.1", () => console.log("CONTROL_PORT=" + server.address().port));')); | |
| 100 | 新增: await copyFile(new URL("../internal/cage/browser-audit.mjs", import.meta.url), join(directory, "browser-audit.mjs")); | |
| 101 | 新增: await copyFile(new URL("../internal/cage/browser-downloads.mjs", import.meta.url), join(directory, "browser-downloads.mjs")); | |
| 102 | 新增: await writeFile(join(directory, "control.json"), JSON.stringify({ token, workspace: directory })); | |
| 103 | 新增: await writeFile(join(directory, "homepage.json"), JSON.stringify({ url: origin + "/first" })); | |
| 104 | 新增: await start(); | |
| 105 | 新增: await waitFor(() => reports.get("/first"), "initial page"); | |
| 106 | 新增: assert.equal(reports.get("/first").webdriver, false, "Human browsing exposes the automation marker"); | |
| 107 | 新增: assert.equal((await fetch(control + "/tabs")).status, 401); | |
| 108 | 新增: assert.equal((await fetch(control + "/tabs", { | |
| 109 | 新增: headers: { Authorization: `Bearer ${token}`, Origin: "https://example.com" }, | |
| 110 | 新增: })).status, 403); | |
| 111 | 新增: const original = (await api("/tabs")).active; | |
| 112 | 新增: const second = await api("/new", { url: origin + "/second" }); | |
| 113 | 新增: await waitFor(() => reports.get("/second"), "new tab"); | |
| 114 | 新增: assert.equal(reports.get("/second").webdriver, false); | |
| 115 | 新增: assert.equal((await api("/tabs")).active, second.id); | |
| 116 | 新增: await api("/activate", { id: original }); | |
| 117 | 新增: assert.equal((await api("/tabs")).active, original); | |
| 118 | 新增: await api("/navigate", { id: original, url: origin + "/third" }); | |
| 119 | 新增: await waitFor(() => reports.get("/third"), "navigation"); | |
| 120 | 新增: assert.equal((await api("/tabs")).back, true); | |
| 121 | 新增: await api("/back", { id: original }); | |
| 122 | 新增: await waitFor(async () => (await api("/tabs")).tabs.some(t => t.id === original && t.url === origin + "/first"), "back"); | |
| 123 | 新增: assert.equal((await api("/tabs")).forward, true); | |
| 124 | 新增: await api("/forward", { id: original }); | |
| 125 | 新增: await waitFor(async () => (await api("/tabs")).tabs.some(t => t.id === original && t.url === origin + "/third"), "forward"); | |
| 126 | 新增: const visits = reports.get("/third").visits; | |
| 127 | 新增: await api("/reload", { id: original }); | |
| 128 | 新增: await waitFor(() => reports.get("/third").visits > visits, "reload"); | |
| 129 | 新增: await api("/close", { id: second.id }); | |
| 130 | 新增: assert.equal((await api("/tabs")).tabs.length, 1); | |
| 131 | 新增: await api("/audit", { timezone: "UTC", network: false }); | |
| 132 | 新增: const beforeRestart = reports.get("/third").visits; | |
| 133 | 新增: await stop(); | |
| 134 | 新增: await start(); | |
| 135 | 新增: await waitFor(() => reports.get("/third").visits > beforeRestart, "session restoration"); | |
| 136 | 新增: assert.equal(reports.get("/third").cookie, true, "Browser cookies did not persist"); | |
| 137 | 新增: assert.equal(reports.get("/third").webdriver, false); | |
| 138 | 新增: const restored = await api("/tabs"); | |
| 139 | 新增: assert.equal(restored.tabs.length, 1); | |
| 140 | 新增: assert.equal(restored.tabs[0].url, origin + "/third"); | |
| 141 | 新增: await api("/close", { id: restored.active }); | |
| 142 | 新增: assert.equal((await api("/tabs")).tabs.length, 1, "Closing the last tab must create a homepage tab"); | |
| 143 | 新增: console.log(JSON.stringify({ | |
| 144 | 新增: webdriver: false, newTab: true, activate: true, navigate: true, | |
| 145 | 新增: back: true, forward: true, reload: true, close: true, | |
| 146 | 新增: sessionRestored: true, cookiesPreserved: true, lastTabReplaced: true, | |
| 147 | 新增: unauthenticatedRejected: true, crossOriginRejected: true, | |
| 148 | 新增: })); | |
| 149 | 新增:} finally { | |
| 150 | 新增: await stop(); | |
| 151 | 新增: await new Promise(resolve => site.close(resolve)); | |
| 152 | 新增: await rm(directory, { recursive: true, force: true }); | |
| 153 | 新增:} | |
| @@ -3,6 +3,22 @@ set -euo pipefail | ||
| 3 | 3 | cd "$(dirname "$0")/.." |
| 4 | 4 | if [[ "$(uname -s)" != Darwin ]]; then echo 'Cage.app must be built on macOS.' >&2; exit 1; fi |
| 5 | 5 | case "${1:-}" in ''|--install) ;; *) echo 'Usage: scripts/build-app.sh [--install]' >&2; exit 2 ;; esac |
| 6 | 新增:app_destination="${CAGE_BUILD_OUTPUT:-$PWD/_output/Cage.app}" | |
| 7 | 新增:if [[ "$app_destination" != /*.app ]]; then echo 'CAGE_BUILD_OUTPUT must be an absolute .app path.' >&2; exit 2; fi | |
| 8 | 新增:check_destination() { | |
| 9 | 新增: local target="$1" | |
| 10 | 新增: [[ ! -e "$target" ]] && return 0 | |
| 11 | 新增: if [[ "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$target/Contents/Info.plist" 2>/dev/null)" != io.github.lee-xeo.claude-cage ]]; then | |
| 12 | 新增: echo 'Build destination is not a Cage application.' >&2; exit 1 | |
| 13 | 新增: fi | |
| 14 | 新增: local running_pids | |
| 15 | 新增: running_pids="$(/usr/sbin/lsof -t "$target/Contents/MacOS/Cage" "$target/Contents/Resources/cage" 2>/dev/null || true)" | |
| 16 | 新增: if [[ -n "$running_pids" ]]; then | |
| 17 | 新增: echo 'Cage is running from this destination. Quit it, or choose a separate CAGE_BUILD_OUTPUT.' >&2; exit 1 | |
| 18 | 新增: fi | |
| 19 | 新增:} | |
| 20 | 新增:check_destination "$app_destination" | |
| 21 | 新增:if [[ "${1:-}" == --install ]]; then check_destination "$HOME/Applications/Cage.app"; fi | |
| 6 | 22 | version="$(tr -d '\n\r' < VERSION)" |
| 7 | 23 | if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]]; then echo 'Invalid VERSION.' >&2; exit 1; fi |
| 8 | 24 | short_version="${version%%-*}" |
| @@ -16,14 +32,16 @@ export CGO_CFLAGS="${CGO_CFLAGS:-} -mmacosx-version-min=14.0" | ||
| 16 | 32 | export CGO_LDFLAGS="${CGO_LDFLAGS:-} -mmacosx-version-min=14.0" |
| 17 | 33 | bash scripts/fetch-proxy-core.sh |
| 18 | 34 | make cage VERSION="$version" |
| 19 | 删除:bundle="$PWD/_output/Cage.app" | |
| 20 | 删除:# Do not leave stale signed resources from a previous build in the bundle. | |
| 21 | 删除:rm -rf "$bundle" | |
| 35 | 新增:build_stage="$(mktemp -d "$PWD/_output/app-build.XXXXXX")" | |
| 36 | 新增:install_stage='' | |
| 37 | 新增:trap 'rm -rf "$build_stage"; if [[ -n "$install_stage" ]]; then rm -rf "$install_stage"; fi' EXIT | |
| 38 | 新增:bundle="$build_stage/Cage.app" | |
| 22 | 39 | mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources" |
| 23 | 删除:swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework WebKit desktop/Cage.swift -o "$bundle/Contents/MacOS/Cage" | |
| 40 | 新增:swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework WebKit -framework Security desktop/Cage.swift desktop/Updates.swift -o "$bundle/Contents/MacOS/Cage" | |
| 41 | 新增:swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework Security desktop/Updates.swift desktop/UpdateInstaller.swift -o "$bundle/Contents/Resources/CageUpdateInstaller" | |
| 24 | 42 | cp _output/bin/cage "$bundle/Contents/Resources/cage" |
| 25 | 43 | cp _output/proxy-core/mihomo "$bundle/Contents/Resources/mihomo" |
| 26 | 删除:for executable in "$bundle/Contents/MacOS/Cage" "$bundle/Contents/Resources/cage" "$bundle/Contents/Resources/mihomo"; do | |
| 44 | 新增:for executable in "$bundle/Contents/MacOS/Cage" "$bundle/Contents/Resources/CageUpdateInstaller" "$bundle/Contents/Resources/cage" "$bundle/Contents/Resources/mihomo"; do | |
| 27 | 45 | minimum="$(otool -l "$executable" | awk '$1 == "minos" {print $2}')" |
| 28 | 46 | if [[ -z "$minimum" ]] || ! awk -v version="$minimum" 'BEGIN {split(version,v,"."); exit !(v[1] < 14 || (v[1] == 14 && v[2] == 0 && v[3]+0 == 0))}'; then |
| 29 | 47 | printf 'Unsupported deployment target %s in %s (expected macOS 14.0 or earlier).\n' "$minimum" "$executable" >&2 |
| @@ -57,12 +75,36 @@ sign=(codesign --force --sign "$identity") | ||
| 57 | 75 | if [[ "$identity" != - ]]; then sign+=(--timestamp --options runtime); fi |
| 58 | 76 | "${sign[@]}" --entitlements third_party/lima/vz.entitlements "$bundle/Contents/Resources/cage" |
| 59 | 77 | "${sign[@]}" "$bundle/Contents/Resources/mihomo" |
| 78 | 新增:"${sign[@]}" "$bundle/Contents/Resources/CageUpdateInstaller" | |
| 60 | 79 | "${sign[@]}" "$bundle/Contents/MacOS/Cage" |
| 61 | 80 | "${sign[@]}" "$bundle" |
| 62 | 81 | codesign --verify --deep --strict --verbose=2 "$bundle" |
| 82 | 新增:# Keep the working App until the replacement has passed signature verification. | |
| 83 | 新增:check_destination "$app_destination" | |
| 84 | 新增:mkdir -p "$(dirname "$app_destination")" | |
| 85 | 新增:if [[ -e "$app_destination" ]]; then mv "$app_destination" "$build_stage/previous.app"; fi | |
| 86 | 新增:if ! mv "$bundle" "$app_destination"; then | |
| 87 | 新增: if [[ -d "$build_stage/previous.app" ]]; then mv "$build_stage/previous.app" "$app_destination"; fi | |
| 88 | 新增: exit 1 | |
| 89 | 新增:fi | |
| 90 | 新增:bundle="$app_destination" | |
| 63 | 91 | printf 'Built: %s\n' "$bundle" |
| 64 | 92 | if [[ "${1:-}" == "--install" ]]; then |
| 65 | 93 | mkdir -p "$HOME/Applications" |
| 66 | 删除: ditto "$bundle" "$HOME/Applications/Cage.app" | |
| 94 | 新增: install_stage="$(mktemp -d "$HOME/Applications/.Cage-install.XXXXXX")" | |
| 95 | 新增: ditto "$bundle" "$install_stage/Cage.app" | |
| 96 | 新增: codesign --verify --deep --strict --verbose=2 "$install_stage/Cage.app" | |
| 97 | 新增: check_destination "$HOME/Applications/Cage.app" | |
| 98 | 新增: if [[ -e "$HOME/Applications/Cage.app" ]]; then mv "$HOME/Applications/Cage.app" "$install_stage/previous.app"; fi | |
| 99 | 新增: if ! mv "$install_stage/Cage.app" "$HOME/Applications/Cage.app"; then | |
| 100 | 新增: if [[ -d "$install_stage/previous.app" ]]; then mv "$install_stage/previous.app" "$HOME/Applications/Cage.app"; fi | |
| 101 | 新增: exit 1 | |
| 102 | 新增: fi | |
| 67 | 103 | printf 'Installed: %s/Applications/Cage.app\n' "$HOME" |
| 104 | 新增: node scripts/cleanup-apps.mjs --keep "$bundle" --keep "$HOME/Applications/Cage.app" \ | |
| 105 | 新增: --root "$PWD/_output" --root "$HOME/Applications" --root /Applications | |
| 106 | 新增:else | |
| 107 | 新增: if [[ -z "${CAGE_BUILD_OUTPUT:-}" ]]; then | |
| 108 | 新增: node scripts/cleanup-apps.mjs --keep "$bundle" --root "$PWD/_output" | |
| 109 | 新增: fi | |
| 68 | 110 | fi |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增:import assert from 'node:assert/strict'; | |
| 2 | 新增:import fs from 'node:fs'; | |
| 3 | 新增:import path from 'node:path'; | |
| 4 | 新增:import { fileURLToPath } from 'node:url'; | |
| 5 | 新增:const root=fileURLToPath(new URL('../',import.meta.url)); | |
| 6 | 新增:const version=fs.readFileSync(path.join(root,'VERSION'),'utf8').trim(); | |
| 7 | 新增:assert.match(version,/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/); | |
| 8 | 新增:for(const directory of ['ui','www']){ | |
| 9 | 新增: const pkg=JSON.parse(fs.readFileSync(path.join(root,directory,'package.json'),'utf8')); | |
| 10 | 新增: const lock=JSON.parse(fs.readFileSync(path.join(root,directory,'package-lock.json'),'utf8')); | |
| 11 | 新增: for(const actual of [pkg.version,lock.version,lock.packages[''].version]) assert.equal(actual,version,`${directory}: version differs from VERSION`); | |
| 12 | 新增:} | |
| 13 | 新增:console.log(`Application package versions match VERSION: ${version}`); | |
| @@ -0,0 +1,89 @@ | ||
| 1 | 新增:#!/usr/bin/env node | |
| 2 | 新增:// Remove Cage bundles only after the caller has verified the replacement. | |
| 3 | 新增:import { execFileSync } from "node:child_process"; | |
| 4 | 新增:import { lstat, readdir, realpath, rm } from "node:fs/promises"; | |
| 5 | 新增:import path from "node:path"; | |
| 6 | 新增:import { pathToFileURL } from "node:url"; | |
| 7 | 新增: | |
| 8 | 新增:const bundleID = "io.github.lee-xeo.claude-cage"; | |
| 9 | 新增:function isCage(bundle) { | |
| 10 | 新增: try { | |
| 11 | 新增: return ( | |
| 12 | 新增: execFileSync( | |
| 13 | 新增: "/usr/libexec/PlistBuddy", | |
| 14 | 新增: [ | |
| 15 | 新增: "-c", | |
| 16 | 新增: "Print :CFBundleIdentifier", | |
| 17 | 新增: path.join(bundle, "Contents/Info.plist"), | |
| 18 | 新增: ], | |
| 19 | 新增: { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }, | |
| 20 | 新增: ).trim() === bundleID | |
| 21 | 新增: ); | |
| 22 | 新增: } catch { | |
| 23 | 新增: return false; | |
| 24 | 新增: } | |
| 25 | 新增:} | |
| 26 | 新增:function inUse(bundle) { | |
| 27 | 新增: const files = ["Contents/MacOS/Cage", "Contents/Resources/cage"].map((file) => path.join(bundle, file)); | |
| 28 | 新增: try { | |
| 29 | 新增: return execFileSync("/usr/sbin/lsof", ["-t", ...files], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() !== ""; | |
| 30 | 新增: } catch (error) { | |
| 31 | 新增: if (String(error.stdout || "").trim()) return true; | |
| 32 | 新增: if (error.status === 1) return false; | |
| 33 | 新增: throw error; | |
| 34 | 新增: } | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:export async function cleanupApps({ keep, roots }) { | |
| 38 | 新增: if (!keep.length) | |
| 39 | 新增: throw new Error("At least one verified Cage.app must be kept."); | |
| 40 | 新增: const retained = new Set(); | |
| 41 | 新增: for (const bundle of keep) { | |
| 42 | 新增: if (!isCage(bundle)) throw new Error(`Invalid replacement App: ${bundle}`); | |
| 43 | 新增: retained.add(await realpath(bundle)); | |
| 44 | 新增: } | |
| 45 | 新增: const removed = []; | |
| 46 | 新增: async function visit(directory) { | |
| 47 | 新增: let stat; | |
| 48 | 新增: try { | |
| 49 | 新增: stat = await lstat(directory); | |
| 50 | 新增: } catch (error) { | |
| 51 | 新增: if (error.code === "ENOENT") return; | |
| 52 | 新增: throw error; | |
| 53 | 新增: } | |
| 54 | 新增: if (!stat.isDirectory() || stat.isSymbolicLink()) return; | |
| 55 | 新增: const canonical = await realpath(directory); | |
| 56 | 新增: if (retained.has(canonical)) return; | |
| 57 | 新增: if (directory.endsWith(".app")) { | |
| 58 | 新增: if (isCage(directory) && !inUse(directory)) { | |
| 59 | 新增: await rm(directory, { recursive: true }); | |
| 60 | 新增: removed.push(directory); | |
| 61 | 新增: } | |
| 62 | 新增: return; | |
| 63 | 新增: } | |
| 64 | 新增: for (const entry of await readdir(directory)) | |
| 65 | 新增: await visit(path.join(directory, entry)); | |
| 66 | 新增: } | |
| 67 | 新增: for (const root of roots) await visit(path.resolve(root)); | |
| 68 | 新增: return removed; | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:if ( | |
| 72 | 新增: process.argv[1] && | |
| 73 | 新增: import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href | |
| 74 | 新增:) { | |
| 75 | 新增: const keep = [], | |
| 76 | 新增: roots = []; | |
| 77 | 新增: for (let i = 2; i < process.argv.length; i += 2) { | |
| 78 | 新增: const flag = process.argv[i], | |
| 79 | 新增: value = process.argv[i + 1]; | |
| 80 | 新增: if (!value || !["--keep", "--root"].includes(flag)) | |
| 81 | 新增: throw new Error( | |
| 82 | 新增: "Usage: cleanup-apps.mjs --keep <verified-app> [--keep <app>] --root <directory> ...", | |
| 83 | 新增: ); | |
| 84 | 新增: (flag === "--keep" ? keep : roots).push(value); | |
| 85 | 新增: } | |
| 86 | 新增: if (!roots.length) throw new Error("At least one cleanup root is required."); | |
| 87 | 新增: for (const bundle of await cleanupApps({ keep, roots })) | |
| 88 | 新增: console.log(`Removed old App: ${bundle}`); | |
| 89 | 新增:} | |
| @@ -0,0 +1,89 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { | |
| 3 | 新增: mkdtemp, | |
| 4 | 新增: mkdir, | |
| 5 | 新增: writeFile, | |
| 6 | 新增: symlink, | |
| 7 | 新增: access, | |
| 8 | 新增: rm, | |
| 9 | 新增: copyFile, | |
| 10 | 新增:} from "node:fs/promises"; | |
| 11 | 新增:import os from "node:os"; | |
| 12 | 新增:import path from "node:path"; | |
| 13 | 新增:import test from "node:test"; | |
| 14 | 新增:import { spawn } from "node:child_process"; | |
| 15 | 新增:import { cleanupApps } from "./cleanup-apps.mjs"; | |
| 16 | 新增: | |
| 17 | 新增:const cageID = "io.github.lee-xeo.claude-cage"; | |
| 18 | 新增:test("cleanup preserves a Cage executable still in use", { skip: process.platform !== "darwin" }, async () => { | |
| 19 | 新增: const directory = await mkdtemp(path.join(os.tmpdir(), "cage-cleanup-running-")); | |
| 20 | 新增: let child; | |
| 21 | 新增: try { | |
| 22 | 新增: const latest = await app(path.join(directory, "new.app")); | |
| 23 | 新增: const running = await app(path.join(directory, "running.app")); | |
| 24 | 新增: await mkdir(path.join(running, "Contents/MacOS")); | |
| 25 | 新增: const executable = path.join(running, "Contents/MacOS/Cage"); | |
| 26 | 新增: await copyFile("/bin/sleep", executable); | |
| 27 | 新增: child = spawn(executable, ["30"], { stdio: "ignore" }); | |
| 28 | 新增: await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); }); | |
| 29 | 新增: assert.deepEqual(await cleanupApps({ keep: [latest], roots: [directory] }), []); | |
| 30 | 新增: await access(executable); | |
| 31 | 新增: await new Promise((resolve) => { child.once("exit", resolve); child.kill("SIGTERM"); }); | |
| 32 | 新增: child = null; | |
| 33 | 新增: assert.deepEqual(await cleanupApps({ keep: [latest], roots: [directory] }), [running]); | |
| 34 | 新增: } finally { | |
| 35 | 新增: if (child && child.exitCode === null) await new Promise((resolve) => { child.once("exit", resolve); child.kill("SIGTERM"); }); | |
| 36 | 新增: await rm(directory, { recursive: true, force: true }); | |
| 37 | 新增: } | |
| 38 | 新增:}); | |
| 39 | 新增:async function app(directory, id = cageID) { | |
| 40 | 新增: await mkdir(path.join(directory, "Contents"), { recursive: true }); | |
| 41 | 新增: await writeFile( | |
| 42 | 新增: path.join(directory, "Contents/Info.plist"), | |
| 43 | 新增: `<?xml version="1.0"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>${id}</string></dict></plist>`, | |
| 44 | 新增: ); | |
| 45 | 新增: return directory; | |
| 46 | 新增:} | |
| 47 | 新增: | |
| 48 | 新增:test( | |
| 49 | 新增: "cleanup removes old Cage copies while retaining replacement, foreign apps and linked directories", | |
| 50 | 新增: { skip: process.platform !== "darwin" }, | |
| 51 | 新增: async (t) => { | |
| 52 | 新增: const directory = await mkdtemp(path.join(os.tmpdir(), "cage-cleanup-")); | |
| 53 | 新增: t.after(() => rm(directory, { recursive: true, force: true })); | |
| 54 | 新增: const root = path.join(directory, "output"), | |
| 55 | 新增: outside = path.join(directory, "outside"); | |
| 56 | 新增: const latest = await app(path.join(root, "Cage.app")); | |
| 57 | 新增: const old = await app(path.join(root, "qa backup", "previous-Cage.app")); | |
| 58 | 新增: const foreign = await app(path.join(root, "Other.app"), "example.other"); | |
| 59 | 新增: const external = await app(path.join(outside, "Cage.app")); | |
| 60 | 新增: await symlink(outside, path.join(root, "linked-backup")); | |
| 61 | 新增: assert.deepEqual( | |
| 62 | 新增: await cleanupApps({ | |
| 63 | 新增: keep: [latest], | |
| 64 | 新增: roots: [root, path.join(directory, "missing")], | |
| 65 | 新增: }), | |
| 66 | 新增: [old], | |
| 67 | 新增: ); | |
| 68 | 新增: await assert.rejects(access(old), { code: "ENOENT" }); | |
| 69 | 新增: for (const preserved of [latest, foreign, external]) | |
| 70 | 新增: await access(preserved); | |
| 71 | 新增: }, | |
| 72 | 新增:); | |
| 73 | 新增: | |
| 74 | 新增:test( | |
| 75 | 新增: "cleanup refuses to delete anything without a valid Cage replacement", | |
| 76 | 新增: { skip: process.platform !== "darwin" }, | |
| 77 | 新增: async (t) => { | |
| 78 | 新增: const directory = await mkdtemp(path.join(os.tmpdir(), "cage-cleanup-")); | |
| 79 | 新增: t.after(() => rm(directory, { recursive: true, force: true })); | |
| 80 | 新增: const old = await app(path.join(directory, "old.app")); | |
| 81 | 新增: const foreign = await app( | |
| 82 | 新增: path.join(directory, "Other.app"), | |
| 83 | 新增: "example.other", | |
| 84 | 新增: ); | |
| 85 | 新增: await assert.rejects(cleanupApps({ keep: [], roots: [directory] })); | |
| 86 | 新增: await assert.rejects(cleanupApps({ keep: [foreign], roots: [directory] })); | |
| 87 | 新增: await access(old); | |
| 88 | 新增: }, | |
| 89 | 新增:); | |
| @@ -0,0 +1,52 @@ | ||
| 1 | 新增:// Run only with disposable builds. Every service uses a newly created profile. | |
| 2 | 新增:// Usage: node scripts/control-upgrade-smoke.mjs <legacy-cage> <current-cage> <different-build-cage> | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { spawn, execFile } from "node:child_process"; | |
| 5 | 新增:import { promisify } from "node:util"; | |
| 6 | 新增:import { mkdtemp, readFile, rm } from "node:fs/promises"; | |
| 7 | 新增:import { tmpdir } from "node:os"; | |
| 8 | 新增:import path from "node:path"; | |
| 9 | 新增: | |
| 10 | 新增:const runFile = promisify(execFile); | |
| 11 | 新增:const [legacy, current, next] = process.argv.slice(2).map((file) => path.resolve(file)); | |
| 12 | 新增:assert(legacy && current && next, "Pass three cage executables"); | |
| 13 | 新增:const profile = await mkdtemp(path.join(tmpdir(), "cage-control-upgrade-")); | |
| 14 | 新增:const env = { ...process.env, CLAUDE_CAGE_CONFIG: path.join(profile, "config.json") }; | |
| 15 | 新增:const call = async (binary, ...args) => { | |
| 16 | 新增: const { stdout } = await runFile(binary, [...args, "--json"], { env, timeout: 150_000, maxBuffer: 512 * 1024 }); | |
| 17 | 新增: return JSON.parse(stdout); | |
| 18 | 新增:}; | |
| 19 | 新增:const record = async () => JSON.parse(await readFile(path.join(profile, "control.json"), "utf8")); | |
| 20 | 新增:const wait = async (test) => { | |
| 21 | 新增: for (let i = 0; i < 100; i++) { | |
| 22 | 新增: try { if (await test()) return; } catch {} | |
| 23 | 新增: await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 24 | 新增: } | |
| 25 | 新增: throw new Error("Timed out waiting for the disposable controller"); | |
| 26 | 新增:}; | |
| 27 | 新增:const old = spawn(legacy, ["serve"], { cwd: profile, env, stdio: "ignore" }); | |
| 28 | 新增:try { | |
| 29 | 新增: await wait(async () => (await record()).pid === old.pid); | |
| 30 | 新增: assert.equal((await call(current, "desktop")).status, "upgrade_pending"); | |
| 31 | 新增: assert.equal((await call(current, "desktop", "--existing")).status, "existing"); | |
| 32 | 新增: assert.equal((await call(current, "prepare-update")).status, "stop_required"); | |
| 33 | 新增: assert.equal((await call(current, "prepare-update", "--stop")).status, "prepared"); | |
| 34 | 新增: await wait(() => old.exitCode !== null || old.signalCode !== null); | |
| 35 | 新增: assert.equal((await call(current, "desktop")).status, "ready"); | |
| 36 | 新增: const first = await record(); | |
| 37 | 新增: assert.equal((await call(current, "desktop")).status, "ready"); | |
| 38 | 新增: assert.equal((await record()).pid, first.pid, "Same build must reuse its controller"); | |
| 39 | 新增: assert.equal((await call(next, "desktop")).status, "ready"); | |
| 40 | 新增: const replacement = await record(); | |
| 41 | 新增: assert.notEqual(replacement.pid, first.pid, "Different build must replace an idle controller"); | |
| 42 | 新增: assert.notEqual(replacement.controller.build, first.controller.build); | |
| 43 | 新增: assert.equal(replacement.controller.version, first.controller.version, "Exercise same-version distinct builds"); | |
| 44 | 新增: assert.equal((await call(next, "prepare-update")).status, "prepared"); | |
| 45 | 新增: console.log("PASS: legacy requires explicit stop, verified legacy migration, same-build reuse, same-version build replacement, and graceful shutdown"); | |
| 46 | 新增:} finally { | |
| 47 | 新增: // Only this fresh profile is addressed. Never target the user's normal profile. | |
| 48 | 新增: await call(current, "prepare-update", "--stop").catch(() => {}); | |
| 49 | 新增: if (old.exitCode === null && old.signalCode === null) old.kill("SIGTERM"); | |
| 50 | 新增: await rm(profile, { recursive: true, force: true }); | |
| 51 | 新增: await rm(profile + "-workspace", { recursive: true, force: true }); | |
| 52 | 新增:} | |
| @@ -74,4 +74,5 @@ curl --fail --location --retry 2 --connect-timeout 15 --max-time 180 \ | ||
| 74 | 74 | mv "$release/$core_source.part" "$release/$core_source" |
| 75 | 75 | tar -tzf "$release/$core_source" > /dev/null |
| 76 | 76 | (cd "$release" && shasum -a 256 "$artifact" "$core_source" > SHA256SUMS) |
| 77 | 新增:node scripts/cleanup-apps.mjs --keep "$bundle" --root "$PWD/_output" | |
| 77 | 78 | printf 'Verified release artifacts:\n%s/%s\n%s/%s\n%s/SHA256SUMS\n' "$release" "$artifact" "$release" "$core_source" "$release" |
| @@ -0,0 +1,8 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:cd "$(dirname "$0")/.." | |
| 4 | 新增:temporary="$(mktemp -d)" | |
| 5 | 新增:trap 'rm -rf "$temporary"' EXIT | |
| 6 | 新增:swiftc -O -parse-as-library -framework Cocoa -framework Security desktop/Updates.swift desktop/UpdatesTests.swift -o "$temporary/updates-tests" | |
| 7 | 新增:"$temporary/updates-tests" "$@" | |
| 8 | 新增:go test ./internal/appupdate | |
| @@ -0,0 +1,36 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:# Validate the actual downloaded distribution without installing or launching it. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:directory="${1:?Usage: scripts/verify-macos-release.sh <release-directory>}" | |
| 5 | 新增:# stapler contacts Apple's CloudKit even for a stapled artifact. Hosted runners | |
| 6 | 新增:# can lose this connection; retry service failures without bypassing validation. | |
| 7 | 新增:validate_ticket() { | |
| 8 | 新增: local attempt status | |
| 9 | 新增: for attempt in 1 2 3; do | |
| 10 | 新增: if xcrun stapler validate "$1"; then return 0; else status=$?; fi | |
| 11 | 新增: if [[ "$status" != 68 || "$attempt" == 3 ]]; then return "$status"; fi | |
| 12 | 新增: echo "Apple ticket service unavailable; retry $attempt/2." >&2 | |
| 13 | 新增: sleep 5 | |
| 14 | 新增: done | |
| 15 | 新增:} | |
| 16 | 新增:shopt -s nullglob | |
| 17 | 新增:archives=("$directory"/Cage-*-macos-arm64.dmg) | |
| 18 | 新增:if [[ ${#archives[@]} != 1 ]]; then echo 'Expected exactly one Cage DMG.' >&2; exit 1; fi | |
| 19 | 新增:archive="${archives[0]}" | |
| 20 | 新增:version="${archive##*/Cage-}" | |
| 21 | 新增:version="${version%-macos-arm64.dmg}" | |
| 22 | 新增:(cd "$directory" && shasum -a 256 --check SHA256SUMS) | |
| 23 | 新增:codesign --verify --strict --verbose=2 "$archive" | |
| 24 | 新增:validate_ticket "$archive" | |
| 25 | 新增:spctl --assess --type open --context context:primary-signature --verbose=2 "$archive" | |
| 26 | 新增:mount="$(mktemp -d)" | |
| 27 | 新增:cleanup() { hdiutil detach "$mount" >/dev/null 2>&1 || true; rmdir "$mount" 2>/dev/null || true; } | |
| 28 | 新增:trap cleanup EXIT | |
| 29 | 新增:hdiutil attach -readonly -nobrowse -mountpoint "$mount" "$archive" >/dev/null | |
| 30 | 新增:bundle="$mount/Cage.app" | |
| 31 | 新增:test "$(/usr/libexec/PlistBuddy -c 'Print :CageVersion' "$bundle/Contents/Info.plist")" = "$version" | |
| 32 | 新增:codesign --verify --deep --strict --verbose=2 \ | |
| 33 | 新增: -R='anchor apple generic and identifier "io.github.lee-xeo.claude-cage" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists' "$bundle" | |
| 34 | 新增:validate_ticket "$bundle" | |
| 35 | 新增:spctl --assess --type execute --verbose=2 "$bundle" | |
| 36 | 新增:echo "Verified Developer ID, notarization, Gatekeeper, and version: Cage $version" | |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 删除: "version": "0.1.0", | |
| 3 | 新增: "version": "0.1.0-alpha.1", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "cage-workbench", |
| 9 | 删除: "version": "0.1.0", | |
| 9 | 新增: "version": "0.1.0-alpha.1", | |
| 10 | 10 | "dependencies": { |
| 11 | 11 | "@xterm/addon-fit": "0.11.0", |
| 12 | 12 | "@xterm/xterm": "6.0.0", |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 3 | "private": true, |
| 4 | 删除: "version": "0.1.0", | |
| 4 | 新增: "version": "0.1.0-alpha.1", | |
| 5 | 5 | "type": "module", |
| 6 | 6 | "scripts": { |
| 7 | 7 | "prepare-vnc": "node scripts/prepare-vnc.mjs", |
| @@ -0,0 +1,348 @@ | ||
| 1 | 新增:// Real DOM pointer interactions and real favorites persistence; browser/VM tabs | |
| 2 | 新增:// use the existing isolated fixture and never touch the user's environment. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import fs from "node:fs/promises"; | |
| 5 | 新增:import os from "node:os"; | |
| 6 | 新增:import path from "node:path"; | |
| 7 | 新增:import { spawn } from "node:child_process"; | |
| 8 | 新增:import { fileURLToPath } from "node:url"; | |
| 9 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 10 | 新增: | |
| 11 | 新增:const root = fileURLToPath(new URL("../../", import.meta.url)); | |
| 12 | 新增:const output = path.join( | |
| 13 | 新增: root, | |
| 14 | 新增: "docs/test-reports/2026-11-01-browser-tabs-favorites", | |
| 15 | 新增:); | |
| 16 | 新增:await fs.mkdir(output, { recursive: true }); | |
| 17 | 新增:const profile = await fs.mkdtemp(path.join(os.tmpdir(), "cage-favorites-qa-")); | |
| 18 | 新增:await fs.writeFile(path.join(profile, "config.json"), "{}", { mode: 0o600 }); | |
| 19 | 新增:await fs.writeFile( | |
| 20 | 新增: path.join(profile, "workbench.json"), | |
| 21 | 新增: JSON.stringify({ workspace: path.join(profile, "workspace") }), | |
| 22 | 新增: { mode: 0o600 }, | |
| 23 | 新增:); | |
| 24 | 新增:let service, origin, cookie, browser; | |
| 25 | 新增:const checks = []; | |
| 26 | 新增:async function stop() { | |
| 27 | 新增: if (!service || service.exitCode !== null) return; | |
| 28 | 新增: await new Promise((resolve) => { | |
| 29 | 新增: service.once("exit", resolve); | |
| 30 | 新增: service.kill("SIGTERM"); | |
| 31 | 新增: }); | |
| 32 | 新增:} | |
| 33 | 新增:async function start() { | |
| 34 | 新增: await fs.rm(path.join(profile, "control.json"), { force: true }); | |
| 35 | 新增: service = spawn(path.join(root, "_output/bin/cage"), ["serve"], { | |
| 36 | 新增: env: { | |
| 37 | 新增: ...process.env, | |
| 38 | 新增: CLAUDE_CAGE_CONFIG: path.join(profile, "config.json"), | |
| 39 | 新增: }, | |
| 40 | 新增: stdio: "ignore", | |
| 41 | 新增: }); | |
| 42 | 新增: let control; | |
| 43 | 新增: for (let i = 0; i < 100; i++) { | |
| 44 | 新增: try { | |
| 45 | 新增: control = JSON.parse( | |
| 46 | 新增: await fs.readFile(path.join(profile, "control.json"), "utf8"), | |
| 47 | 新增: ); | |
| 48 | 新增: break; | |
| 49 | 新增: } catch { | |
| 50 | 新增: await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 51 | 新增: } | |
| 52 | 新增: } | |
| 53 | 新增: assert.ok(control, "isolated control service did not start"); | |
| 54 | 新增: origin = `http://localhost:${control.port}`; | |
| 55 | 新增: const launch = await fetch(origin + "/api/launch", { | |
| 56 | 新增: method: "POST", | |
| 57 | 新增: headers: { Origin: origin, "Content-Type": "application/json" }, | |
| 58 | 新增: body: JSON.stringify({ token: control.token }), | |
| 59 | 新增: }); | |
| 60 | 新增: const { url } = await launch.json(); | |
| 61 | 新增: const session = await fetch(origin + "/api/session", { | |
| 62 | 新增: method: "POST", | |
| 63 | 新增: headers: { Origin: origin, "Content-Type": "application/json" }, | |
| 64 | 新增: body: JSON.stringify({ token: new URL(url).hash.slice(1) }), | |
| 65 | 新增: }); | |
| 66 | 新增: cookie = session.headers.get("set-cookie").split(";")[0]; | |
| 67 | 新增:} | |
| 68 | 新增:try { | |
| 69 | 新增: await start(); | |
| 70 | 新增: const fixture = await createWorkbench({ | |
| 71 | 新增: favoritesRequest: async (request) => { | |
| 72 | 新增: const response = await fetch(origin + "/api/favorites", { | |
| 73 | 新增: method: request.method(), | |
| 74 | 新增: headers: { | |
| 75 | 新增: Origin: origin, | |
| 76 | 新增: Cookie: cookie, | |
| 77 | 新增: "Content-Type": "application/json", | |
| 78 | 新增: }, | |
| 79 | 新增: body: request.postData() || undefined, | |
| 80 | 新增: }); | |
| 81 | 新增: return { | |
| 82 | 新增: status: response.status, | |
| 83 | 新增: contentType: response.headers.get("content-type"), | |
| 84 | 新增: body: await response.text(), | |
| 85 | 新增: }; | |
| 86 | 新增: }, | |
| 87 | 新增: }); | |
| 88 | 新增: browser = fixture.browser; | |
| 89 | 新增: const { page, state, errors } = fixture; | |
| 90 | 新增: const shot = (name) => | |
| 91 | 新增: page.screenshot({ | |
| 92 | 新增: path: path.join(output, name + ".png"), | |
| 93 | 新增: animations: "disabled", | |
| 94 | 新增: }); | |
| 95 | 新增: const tabs = page.getByRole("tablist", { name: "浏览器标签页" }); | |
| 96 | 新增: await page | |
| 97 | 新增: .getByRole("button", { name: "启动 Cage 环境", exact: true }) | |
| 98 | 新增: .click(); | |
| 99 | 新增: await page | |
| 100 | 新增: .getByRole("heading", { name: "Cage 环境已就绪", exact: true }) | |
| 101 | 新增: .waitFor(); | |
| 102 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 103 | 新增: await tabs.getByRole("tab").waitFor(); | |
| 104 | 新增: await page.getByRole("button", { name: "新建网页", exact: true }).click(); | |
| 105 | 新增: await page.waitForFunction( | |
| 106 | 新增: () => document.querySelectorAll('.browser-tabs [role="tab"]').length === 2, | |
| 107 | 新增: ); | |
| 108 | 新增: for (let i = 3; i <= 8; i++) | |
| 109 | 新增: state.tabs.push({ | |
| 110 | 新增: id: "qa-" + i, | |
| 111 | 新增: kind: "web", | |
| 112 | 新增: title: "设计文档 " + i, | |
| 113 | 新增: url: `https://example.com/${i}`, | |
| 114 | 新增: }); | |
| 115 | 新增: await page.waitForFunction( | |
| 116 | 新增: () => document.querySelectorAll('.browser-tabs [role="tab"]').length === 8, | |
| 117 | 新增: ); | |
| 118 | 新增: await page.waitForFunction(() => { | |
| 119 | 新增: const list = document.querySelector(".browser-tabs"); | |
| 120 | 新增: return ( | |
| 121 | 新增: list.querySelector(".active").getBoundingClientRect().width > | |
| 122 | 新增: list.querySelector(".browser-tab:not(.active)").getBoundingClientRect() | |
| 123 | 新增: .width + | |
| 124 | 新增: 20 | |
| 125 | 新增: ); | |
| 126 | 新增: }); | |
| 127 | 新增: let layout = await page.evaluate(() => { | |
| 128 | 新增: const list = document.querySelector(".browser-tabs"); | |
| 129 | 新增: const active = list.querySelector(".active").getBoundingClientRect(); | |
| 130 | 新增: const add = document | |
| 131 | 新增: .querySelector(".browser-new-tab") | |
| 132 | 新增: .getBoundingClientRect(); | |
| 133 | 新增: return { | |
| 134 | 新增: overflow: list.scrollWidth > list.clientWidth + 1, | |
| 135 | 新增: active: active.width, | |
| 136 | 新增: other: list.querySelector(":not(.active)").getBoundingClientRect().width, | |
| 137 | 新增: centers: Math.abs(active.y + active.height / 2 - add.y - add.height / 2), | |
| 138 | 新增: }; | |
| 139 | 新增: }); | |
| 140 | 新增: assert.equal(layout.overflow, false); | |
| 141 | 新增: assert.ok(layout.active > layout.other); | |
| 142 | 新增: assert.ok(layout.centers < 1); | |
| 143 | 新增: await shot("desktop-tabs"); | |
| 144 | 新增: const from = tabs.getByRole("tab", { name: "设计文档 3", exact: true }); | |
| 145 | 新增: const to = tabs.getByRole("tab", { name: "设计文档 6", exact: true }); | |
| 146 | 新增: const initial = await from.boundingBox(), | |
| 147 | 新增: target = await to.boundingBox(); | |
| 148 | 新增: const before = await to.boundingBox(); | |
| 149 | 新增: await page.mouse.move(initial.x + initial.width / 2, initial.y + 16); | |
| 150 | 新增: await page.mouse.down(); | |
| 151 | 新增: await page.mouse.move(target.x + target.width - 6, target.y + 16, { | |
| 152 | 新增: steps: 18, | |
| 153 | 新增: }); | |
| 154 | 新增: await page.locator(".browser-tab.dragging").waitFor(); | |
| 155 | 新增: assert.ok( | |
| 156 | 新增: Math.abs((await from.boundingBox()).x - initial.x) > 100, | |
| 157 | 新增: "dragged tab must follow pointer before mouseup", | |
| 158 | 新增: ); | |
| 159 | 新增: await page.waitForFunction( | |
| 160 | 新增: (x) => | |
| 161 | 新增: document.querySelector('[data-tab-id="qa-6"]').getBoundingClientRect().x < | |
| 162 | 新增: x - 20, | |
| 163 | 新增: before.x, | |
| 164 | 新增: ); | |
| 165 | 新增: await shot("drag-in-progress"); | |
| 166 | 新增: await page.mouse.up(); | |
| 167 | 新增: await page.waitForFunction( | |
| 168 | 新增: () => | |
| 169 | 新增: [...document.querySelectorAll(".browser-tab")].findIndex( | |
| 170 | 新增: (e) => e.dataset.tabId === "qa-3", | |
| 171 | 新增: ) > | |
| 172 | 新增: [...document.querySelectorAll(".browser-tab")].findIndex( | |
| 173 | 新增: (e) => e.dataset.tabId === "qa-6", | |
| 174 | 新增: ), | |
| 175 | 新增: ); | |
| 176 | 新增: const ordered = await tabs.getByRole("tab").allTextContents(); | |
| 177 | 新增: const again = await from.boundingBox(); | |
| 178 | 新增: await page.mouse.move(again.x + 20, again.y + 16); | |
| 179 | 新增: await page.mouse.down(); | |
| 180 | 新增: await page.mouse.move(again.x - 200, again.y + 16, { steps: 12 }); | |
| 181 | 新增: await page.keyboard.press("Escape"); | |
| 182 | 新增: await page.mouse.up(); | |
| 183 | 新增: assert.deepEqual(await tabs.getByRole("tab").allTextContents(), ordered); | |
| 184 | 新增: await page.reload(); | |
| 185 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 186 | 新增: assert.deepEqual(await tabs.getByRole("tab").allTextContents(), ordered); | |
| 187 | 新增: checks.push( | |
| 188 | 新增: "8 tabs: aligned add button, active expansion, pointer tracking and live neighbor movement, Escape cancellation, persisted order", | |
| 189 | 新增: ); | |
| 190 | 新增: | |
| 191 | 新增: await tabs.getByRole("tab", { name: "设计文档 3", exact: true }).click(); | |
| 192 | 新增: await page.getByRole("button", { name: "收藏此页", exact: true }).click(); | |
| 193 | 新增: await page.getByLabel("收藏名称", { exact: true }).fill("Cage 设计资料"); | |
| 194 | 新增: await page.getByLabel("新收藏夹名称", { exact: true }).fill("工作资料"); | |
| 195 | 新增: await page.getByRole("button", { name: "保存", exact: true }).click(); | |
| 196 | 新增: await page | |
| 197 | 新增: .getByRole("dialog", { name: "添加收藏", exact: true }) | |
| 198 | 新增: .waitFor({ state: "hidden" }); | |
| 199 | 新增: await page | |
| 200 | 新增: .getByRole("button", { name: "编辑此页收藏", exact: true }) | |
| 201 | 新增: .waitFor(); | |
| 202 | 新增: let saved = JSON.parse( | |
| 203 | 新增: await fs.readFile(path.join(profile, "favorites.json"), "utf8"), | |
| 204 | 新增: ); | |
| 205 | 新增: assert.equal(saved.items[0].title, "Cage 设计资料"); | |
| 206 | 新增: assert.equal(saved.folders[0].title, "工作资料"); | |
| 207 | 新增: await page.keyboard.press("Meta+d"); | |
| 208 | 新增: await page.getByLabel("收藏名称", { exact: true }).fill("待重试的收藏"); | |
| 209 | 新增: // Make the real persistence path unreadable as a file, then restore it. | |
| 210 | 新增: await fs.rename( | |
| 211 | 新增: path.join(profile, "favorites.json"), | |
| 212 | 新增: path.join(profile, "favorites.backup"), | |
| 213 | 新增: ); | |
| 214 | 新增: await fs.mkdir(path.join(profile, "favorites.json")); | |
| 215 | 新增: await page.getByRole("button", { name: "保存", exact: true }).click(); | |
| 216 | 新增: await page | |
| 217 | 新增: .getByRole("dialog", { name: "编辑收藏", exact: true }) | |
| 218 | 新增: .getByRole("alert") | |
| 219 | 新增: .waitFor(); | |
| 220 | 新增: assert.equal( | |
| 221 | 新增: await page.getByLabel("收藏名称", { exact: true }).inputValue(), | |
| 222 | 新增: "待重试的收藏", | |
| 223 | 新增: ); | |
| 224 | 新增: await fs.rmdir(path.join(profile, "favorites.json")); | |
| 225 | 新增: await fs.rename( | |
| 226 | 新增: path.join(profile, "favorites.backup"), | |
| 227 | 新增: path.join(profile, "favorites.json"), | |
| 228 | 新增: ); | |
| 229 | 新增: await page.getByRole("button", { name: "保存", exact: true }).click(); | |
| 230 | 新增: await page | |
| 231 | 新增: .getByRole("dialog", { name: "编辑收藏", exact: true }) | |
| 232 | 新增: .waitFor({ state: "hidden" }); | |
| 233 | 新增: await stop(); | |
| 234 | 新增: await start(); | |
| 235 | 新增: await page.reload(); | |
| 236 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 237 | 新增: await page.keyboard.press("Meta+Shift+o"); | |
| 238 | 新增: const panel = page.getByRole("dialog", { name: "收藏夹", exact: true }); | |
| 239 | 新增: await panel | |
| 240 | 新增: .getByRole("button", { name: "编辑收藏 待重试的收藏", exact: true }) | |
| 241 | 新增: .waitFor(); | |
| 242 | 新增: await shot("favorites"); | |
| 243 | 新增: await page.getByLabel("搜索收藏", { exact: true }).fill("不存在"); | |
| 244 | 新增: await panel.getByText("没有匹配的收藏").waitFor(); | |
| 245 | 新增: await page.getByLabel("搜索收藏", { exact: true }).fill("example.com/3"); | |
| 246 | 新增: await panel | |
| 247 | 新增: .getByRole("button", { name: "编辑收藏 待重试的收藏", exact: true }) | |
| 248 | 新增: .click(); | |
| 249 | 新增: await page.getByLabel("保存到收藏夹", { exact: true }).selectOption(""); | |
| 250 | 新增: await page.getByRole("button", { name: "保存", exact: true }).click(); | |
| 251 | 新增: await page | |
| 252 | 新增: .getByRole("dialog", { name: "编辑收藏", exact: true }) | |
| 253 | 新增: .waitFor({ state: "hidden" }); | |
| 254 | 新增: saved = JSON.parse( | |
| 255 | 新增: await fs.readFile(path.join(profile, "favorites.json"), "utf8"), | |
| 256 | 新增: ); | |
| 257 | 新增: assert.equal(saved.items[0].folder_id, ""); | |
| 258 | 新增: await page.getByLabel("搜索收藏", { exact: true }).fill(""); | |
| 259 | 新增: await page | |
| 260 | 新增: .getByLabel("筛选收藏夹", { exact: true }) | |
| 261 | 新增: .selectOption(saved.folders[0].id); | |
| 262 | 新增: await page.getByRole("button", { name: "重命名收藏夹", exact: true }).click(); | |
| 263 | 新增: await page.getByLabel("收藏名称", { exact: true }).fill("常用资料"); | |
| 264 | 新增: await page.getByRole("button", { name: "保存", exact: true }).click(); | |
| 265 | 新增: await page | |
| 266 | 新增: .getByRole("dialog", { name: "重命名收藏夹", exact: true }) | |
| 267 | 新增: .waitFor({ state: "hidden" }); | |
| 268 | 新增: await page | |
| 269 | 新增: .getByRole("button", { name: "删除收藏夹,收藏移至未分类", exact: true }) | |
| 270 | 新增: .click(); | |
| 271 | 新增: await page | |
| 272 | 新增: .getByRole("button", { name: "重命名收藏夹", exact: true }) | |
| 273 | 新增: .waitFor({ state: "hidden" }); | |
| 274 | 新增: await panel.getByRole("button", { name: /^待重试的收藏/ }).click(); | |
| 275 | 新增: await panel.waitFor({ state: "hidden" }); | |
| 276 | 新增: assert.equal(state.tabs.at(-1).url, "https://example.com/3"); | |
| 277 | 新增: await page.getByRole("button", { name: "编辑此页收藏", exact: true }).click(); | |
| 278 | 新增: await page.getByRole("button", { name: "删除收藏", exact: true }).click(); | |
| 279 | 新增: await page.getByRole("button", { name: "收藏此页", exact: true }).waitFor(); | |
| 280 | 新增: saved = JSON.parse( | |
| 281 | 新增: await fs.readFile(path.join(profile, "favorites.json"), "utf8"), | |
| 282 | 新增: ); | |
| 283 | 新增: assert.equal(saved.items.length, 0); | |
| 284 | 新增: assert.equal(saved.folders.length, 0); | |
| 285 | 新增: checks.push( | |
| 286 | 新增: "Real favorites service: create folder and favorite, edit, failed persistence retains input, retry, restart, search, move, folder rename/delete, open via guest tab API, delete favorite", | |
| 287 | 新增: ); | |
| 288 | 新增: | |
| 289 | 新增: for (let i = 9; i <= 32; i++) | |
| 290 | 新增: state.tabs.push({ | |
| 291 | 新增: id: "qa-" + i, | |
| 292 | 新增: kind: "web", | |
| 293 | 新增: title: "参考网页 " + i, | |
| 294 | 新增: url: `https://example.com/${i}`, | |
| 295 | 新增: }); | |
| 296 | 新增: await page.waitForFunction( | |
| 297 | 新增: () => document.querySelectorAll('.browser-tabs [role="tab"]').length === 33, | |
| 298 | 新增: ); | |
| 299 | 新增: for (const width of [1280, 820, 375]) { | |
| 300 | 新增: await page.setViewportSize({ width, height: 850 }); | |
| 301 | 新增: await page.waitForFunction(() => { | |
| 302 | 新增: const list = document.querySelector(".browser-tabs"); | |
| 303 | 新增: return list.scrollWidth <= list.clientWidth + 1; | |
| 304 | 新增: }); | |
| 305 | 新增: await shot("many-tabs-" + width); | |
| 306 | 新增: } | |
| 307 | 新增: await page.setViewportSize({ width: 820, height: 558 }); | |
| 308 | 新增: await page.getByRole("button", { name: "搜索标签页", exact: true }).click(); | |
| 309 | 新增: await page | |
| 310 | 新增: .getByLabel("搜索已打开的标签页", { exact: true }) | |
| 311 | 新增: .fill("参考网页 28"); | |
| 312 | 新增: await page | |
| 313 | 新增: .getByRole("dialog", { name: "搜索标签页", exact: true }) | |
| 314 | 新增: .getByRole("button", { name: "参考网页 28", exact: true }) | |
| 315 | 新增: .click(); | |
| 316 | 新增: await page.waitForFunction( | |
| 317 | 新增: () => | |
| 318 | 新增: document.querySelector('.browser-tabs [aria-selected="true"]') | |
| 319 | 新增: .textContent === "参考网页 28", | |
| 320 | 新增: ); | |
| 321 | 新增: await page.evaluate(() => | |
| 322 | 新增: document.documentElement.style.setProperty("--ui-font-size", "20px"), | |
| 323 | 新增: ); | |
| 324 | 新增: await shot("narrow-large-text"); | |
| 325 | 新增: checks.push( | |
| 326 | 新增: "33 tabs: no horizontal scroll at 1280/820/375, tab search selects crowded tabs, 820px large text", | |
| 327 | 新增: ); | |
| 328 | 新增: assert.deepEqual(errors, []); | |
| 329 | 新增: await fs.writeFile( | |
| 330 | 新增: path.join(output, "result.json"), | |
| 331 | 新增: JSON.stringify( | |
| 332 | 新增: { | |
| 333 | 新增: passed: true, | |
| 334 | 新增: checks, | |
| 335 | 新增: pageErrors: errors, | |
| 336 | 新增: scope: | |
| 337 | 新增: "Real DOM and favorites Go service; VM pages, navigation and noVNC are simulated.", | |
| 338 | 新增: }, | |
| 339 | 新增: null, | |
| 340 | 新增: 2, | |
| 341 | 新增: ), | |
| 342 | 新增: ); | |
| 343 | 新增: console.log(JSON.stringify({ passed: true, checks }, null, 2)); | |
| 344 | 新增:} finally { | |
| 345 | 新增: await browser?.close(); | |
| 346 | 新增: await stop(); | |
| 347 | 新增: await fs.rm(profile, { recursive: true, force: true }); | |
| 348 | 新增:} | |
| @@ -0,0 +1,42 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import os from "node:os"; | |
| 4 | 新增:import path from "node:path"; | |
| 5 | 新增:import { execFile } from "node:child_process"; | |
| 6 | 新增:import { promisify } from "node:util"; | |
| 7 | 新增:import { createRequire } from "node:module"; | |
| 8 | 新增: | |
| 9 | 新增:const run = promisify(execFile); | |
| 10 | 新增:const bundle = process.argv[2]; | |
| 11 | 新增:assert.ok(bundle?.startsWith("/") && bundle.endsWith(".app"), "supply an absolute packaged App path"); | |
| 12 | 新增:const cage = path.join(bundle, "Contents/Resources/cage"); | |
| 13 | 新增:const profile = await fs.mkdtemp(path.join(os.tmpdir(), "cage-packaged-")); | |
| 14 | 新增:const env = { ...process.env, CLAUDE_CAGE_CONFIG: path.join(profile, "config.json") }; | |
| 15 | 新增:const require = createRequire(import.meta.url); | |
| 16 | 新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); | |
| 17 | 新增:let browser; | |
| 18 | 新增:try { | |
| 19 | 新增: const { stdout } = await run(cage, ["desktop", "--json"], { env }); | |
| 20 | 新增: const entry = JSON.parse(stdout); | |
| 21 | 新增: assert.equal(entry.status, "ready"); | |
| 22 | 新增: assert.equal(entry.controller.version, (await fs.readFile(new URL("../../VERSION", import.meta.url), "utf8")).trim()); | |
| 23 | 新增: browser = await chromium.launch({ headless: true }); | |
| 24 | 新增: const page = await browser.newPage(); | |
| 25 | 新增: const errors = []; | |
| 26 | 新增: page.on("pageerror", (error) => errors.push(error.message)); | |
| 27 | 新增: const statusResponse = page.waitForResponse((response) => response.url().endsWith("/api/status") && response.ok()); | |
| 28 | 新增: await page.goto(entry.url); | |
| 29 | 新增: const status = await (await statusResponse).json(); | |
| 30 | 新增: assert.equal(status.vm_running, false); | |
| 31 | 新增: await page.getByRole("button", { name: "配置网络与代理", exact: true }).waitFor(); | |
| 32 | 新增: assert.equal(new URL(page.url()).hash, "", "launch ticket was not removed"); | |
| 33 | 新增: await page.getByRole("button", { name: "配置网络与代理", exact: true }).click(); | |
| 34 | 新增: await page.getByText("添加来源", { exact: true }).first().waitFor(); | |
| 35 | 新增: assert.deepEqual(errors, []); | |
| 36 | 新增: console.log(JSON.stringify({ checks: ["packaged helper bootstrap", "real session and APIs", "embedded production UI loaded", "private profile onboarding", "launch ticket removed"], version: entry.controller.version })); | |
| 37 | 新增:} finally { | |
| 38 | 新增: await browser?.close(); | |
| 39 | 新增: await run(cage, ["prepare-update", "--json"], { env }); | |
| 40 | 新增: await fs.rm(profile, { recursive: true, force: true }); | |
| 41 | 新增: await fs.rm(profile + "-workspace", { recursive: true, force: true }); | |
| 42 | 新增:} | |
| @@ -0,0 +1,103 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import { fileURLToPath } from "node:url"; | |
| 4 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 新增: | |
| 6 | 新增:const output = new URL("../../docs/test-reports/2026-11-01-system-remediation/", import.meta.url); | |
| 7 | 新增:await fs.mkdir(output, { recursive: true }); | |
| 8 | 新增:const calls = []; | |
| 9 | 新增:let update = { phase: "available", currentVersion: "0.2.0-alpha.1", latestVersion: "0.2.0-alpha.2", message: "发现新版本,可下载更新", retryable: true }; | |
| 10 | 新增:const fixture = await createWorkbench({ nativeRequest: async (body) => { | |
| 11 | 新增: calls.push(body); | |
| 12 | 新增: if (body.action === "workbenchReady") return true; | |
| 13 | 新增: if (body.action !== "appUpdate") return null; | |
| 14 | 新增: if (body.operation === "install") update = { ...update, phase: "downloading", receivedBytes: 50, totalBytes: 100, message: "正在下载更新" }; | |
| 15 | 新增: if (body.operation === "cancel") update = { ...update, phase: "available", message: "更新已暂停,可稍后继续" }; | |
| 16 | 新增: return update; | |
| 17 | 新增:} }); | |
| 18 | 新增:const { browser, page, state, errors } = fixture; | |
| 19 | 新增:const checks = []; | |
| 20 | 新增:try { | |
| 21 | 新增: await page.getByRole("button", { name: "下载更新", exact: true }).waitFor(); | |
| 22 | 新增: const button = page.getByRole("button", { name: "下载更新", exact: true }); | |
| 23 | 新增: assert.equal(await button.getAttribute("title"), "下载更新"); | |
| 24 | 新增: const bounds = await button.boundingBox(); | |
| 25 | 新增: assert.ok(bounds.x < 248 && bounds.y > 700, "update action is not in the bottom-left sidebar"); | |
| 26 | 新增: await page.screenshot({ path: fileURLToPath(new URL("update-available.png", output)) }); | |
| 27 | 新增: await button.click(); | |
| 28 | 新增: assert.equal(calls.filter((call) => call.operation === "install").length, 1); | |
| 29 | 新增: await page.getByRole("progressbar", { name: "更新下载进度" }).waitFor(); | |
| 30 | 新增: assert.equal(await page.getByRole("progressbar").getAttribute("value"), "50"); | |
| 31 | 新增: await page.getByRole("button", { name: "取消下载", exact: true }).click(); | |
| 32 | 新增: assert.equal(calls.filter((call) => call.operation === "cancel").length, 1); | |
| 33 | 新增: await page.getByRole("dialog", { name: "Cage 更新" }).getByRole("button", { name: "关闭", exact: true }).click(); | |
| 34 | 新增: await page.evaluate(() => window.dispatchEvent(new CustomEvent("cage-app-update", { detail: { phase: "failed", message: "更新源暂不可访问,仓库尚未公开", retryable: true } }))); | |
| 35 | 新增: await page.getByRole("button", { name: "查看更新状态", exact: true }).click(); | |
| 36 | 新增: await page.getByText("更新源暂不可访问,仓库尚未公开", { exact: true }).waitFor(); | |
| 37 | 新增: await page.getByRole("dialog", { name: "Cage 更新" }).getByRole("button", { name: "关闭", exact: true }).click(); | |
| 38 | 新增: checks.push("bottom-left update affordance", "single install request", "download progress and cancel", "private source failure visible"); | |
| 39 | 新增: | |
| 40 | 新增: const downloads = [{ id: "qa-download", name: "report.txt", state: "failed", error: "目标目录暂时无法写入", retryable: true }]; | |
| 41 | 新增: let retries = 0, editorRestarts = 0, componentUpdates = 0; | |
| 42 | 新增: await page.route("**/api/browser/tabs", (route) => route.fulfill({ json: { tabs: state.tabs, active: state.active, downloads } })); | |
| 43 | 新增: await page.route("**/api/browser/download-retry", (route) => { | |
| 44 | 新增: assert.deepEqual(route.request().postDataJSON(), { id: "qa-download" }); | |
| 45 | 新增: retries++; | |
| 46 | 新增: Object.assign(downloads[0], { state: "saved", retryable: false, error: "", path: "/Users/you/Cage/Downloads/report.txt" }); | |
| 47 | 新增: return route.fulfill({ json: { ok: true } }); | |
| 48 | 新增: }); | |
| 49 | 新增: await page.route("**/api/browser/editor-restart", (route) => { | |
| 50 | 新增: assert.equal(route.request().postDataJSON().workspace, state.settings.workspace); | |
| 51 | 新增: editorRestarts++; | |
| 52 | 新增: return route.fulfill({ json: { ok: true } }); | |
| 53 | 新增: }); | |
| 54 | 新增: await page.route("**/api/environment/versions", (route) => route.fulfill({ json: { | |
| 55 | 新增: vm_running: true, controller: { version: "0.2.0-alpha.2" }, components: { status: "update_required", update_required: true }, | |
| 56 | 新增: tools: { chromium: { current: "156", required: "系统安全更新" }, code_server: { current: "4.100", required: "4.144.0" } }, tools_update_allowed: false, | |
| 57 | 新增: } })); | |
| 58 | 新增: await page.route("**/api/environment/update", (route) => { componentUpdates++; return route.fulfill({ json: { id: "qa-components" } }); }); | |
| 59 | 新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click(); | |
| 60 | 新增: await page.getByRole("heading", { name: "Cage 环境已就绪", exact: true }).waitFor(); | |
| 61 | 新增: await page.getByText("“report.txt”未能保存:目标目录暂时无法写入", { exact: true }).waitFor(); | |
| 62 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 63 | 新增: await page.getByRole("button", { name: "浏览器下载", exact: true }).click(); | |
| 64 | 新增: await page.getByRole("button", { name: "重试保存", exact: true }).click(); | |
| 65 | 新增: await page.getByText("已保存到本机", { exact: true }).waitFor(); | |
| 66 | 新增: assert.equal(retries, 1); | |
| 67 | 新增: await page.screenshot({ path: fileURLToPath(new URL("download-recovery.png", output)) }); | |
| 68 | 新增: await page.getByRole("dialog", { name: "浏览器下载" }).getByRole("button", { name: "关闭面板" }).click(); | |
| 69 | 新增: await page.getByRole("button", { name: "项目文件", exact: true }).click(); | |
| 70 | 新增: await page.getByRole("button", { name: "恢复编辑器", exact: true }).click(); | |
| 71 | 新增: await page.getByRole("dialog", { name: "重启编辑器?" }).getByRole("button", { name: "重启编辑器", exact: true }).click(); | |
| 72 | 新增: await page.getByText("编辑器已恢复", { exact: true }).waitFor(); | |
| 73 | 新增: assert.equal(editorRestarts, 1); | |
| 74 | 新增: assert.equal(state.status.vm_running, true); | |
| 75 | 新增: checks.push("download retry reports durable save", "editor recovery leaves VM running"); | |
| 76 | 新增: await page.getByRole("button", { name: "设置", exact: false }).first().click(); | |
| 77 | 新增: await page.getByRole("button", { name: "环境与恢复", exact: true }).click(); | |
| 78 | 新增: await page.getByRole("region", { name: "环境版本" }).getByText("需要更新", { exact: true }).waitFor(); | |
| 79 | 新增: assert.equal(await page.getByRole("button", { name: "更新环境工具", exact: true }).isDisabled(), true); | |
| 80 | 新增: await page.getByRole("button", { name: "更新环境工具", exact: true }).scrollIntoViewIfNeeded(); | |
| 81 | 新增: await page.screenshot({ path: fileURLToPath(new URL("environment-versions.png", output)) }); | |
| 82 | 新增: await page.getByRole("button", { name: "更新环境组件", exact: true }).click(); | |
| 83 | 新增: await page.getByRole("dialog", { name: "更新环境组件?" }).getByRole("button", { name: "更新组件", exact: true }).click(); | |
| 84 | 新增: await page.waitForTimeout(50); | |
| 85 | 新增: assert.equal(componentUpdates, 1); | |
| 86 | 新增: assert.ok(calls.some((call) => call.action === "workbenchReady"), "successful initialized workbench did not acknowledge launch"); | |
| 87 | 新增: assert.deepEqual(errors, []); | |
| 88 | 新增: checks.push("environment versions and guarded tool update", "explicit component update", "initialized workbench launch acknowledgement"); | |
| 89 | 新增:} finally { await browser.close(); } | |
| 90 | 新增: | |
| 91 | 新增:let prematureReady = false; | |
| 92 | 新增:const broken = await createWorkbench({ startupFailure: true, nativeRequest: async (body) => { | |
| 93 | 新增: if (body.action === "workbenchReady") prematureReady = true; | |
| 94 | 新增: return { phase: "current", currentVersion: "0.2.0-alpha.2" }; | |
| 95 | 新增:} }); | |
| 96 | 新增:try { | |
| 97 | 新增: await broken.page.waitForResponse((response) => response.url().endsWith("/api/status") && response.status() === 503); | |
| 98 | 新增: await broken.page.waitForTimeout(100); | |
| 99 | 新增: assert.equal(prematureReady, false, "failed API initialization acknowledged update success"); | |
| 100 | 新增: checks.push("startup failure never acknowledges upgrade"); | |
| 101 | 新增:} finally { await broken.browser.close(); } | |
| 102 | 新增:await fs.writeFile(new URL("ui-checks.json", output), JSON.stringify({ checks }, null, 2)); | |
| 103 | 新增:console.log(JSON.stringify({ checks })); | |
| @@ -0,0 +1,316 @@ | ||
| 1 | 新增:// Start the UI dev server first. Uses the real noVNC keyboard and RFB encoder, | |
| 2 | 新增:// with an in-memory socket; this does not replace native IME/guest acceptance. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { createRequire } from "node:module"; | |
| 5 | 新增:const require = createRequire(import.meta.url); | |
| 6 | 新增:const { chromium } = require( | |
| 7 | 新增: process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", | |
| 8 | 新增:); | |
| 9 | 新增:const browser = await chromium.launch({ headless: true }); | |
| 10 | 新增:const page = await browser.newPage(); | |
| 11 | 新增:const errors = []; | |
| 12 | 新增:page.on("pageerror", (error) => errors.push(error.message)); | |
| 13 | 新增:const origin = process.env.CAGE_UI_URL || "http://127.0.0.1:5173"; | |
| 14 | 新增:try { | |
| 15 | 新增: await page.route("**/remote-input-smoke", (route) => | |
| 16 | 新增: route.fulfill({ | |
| 17 | 新增: contentType: "text/html; charset=utf-8", | |
| 18 | 新增: body: '<div id="remote"><canvas tabindex="-1"></canvas></div><input aria-label="本机地址栏">', | |
| 19 | 新增: }), | |
| 20 | 新增: ); | |
| 21 | 新增: await page.goto(origin + "/remote-input-smoke"); | |
| 22 | 新增: await page.evaluate(async () => { | |
| 23 | 新增: const [{ default: RFB }, { default: Keyboard }, { installRemoteInput }] = | |
| 24 | 新增: await Promise.all([ | |
| 25 | 新增: import("/.generated/novnc/core/rfb.js"), | |
| 26 | 新增: import("/.generated/novnc/core/input/keyboard.js"), | |
| 27 | 新增: import("/src/remote-input.js"), | |
| 28 | 新增: ]); | |
| 29 | 新增: const container = document.querySelector("#remote"); | |
| 30 | 新增: const rfb = new EventTarget(); | |
| 31 | 新增: // Use production methods through the final wire encoder, without opening | |
| 32 | 新增: // a guest connection or capturing any user clipboard content. | |
| 33 | 新增: for (const name of [ | |
| 34 | 新增: "sendKey", | |
| 35 | 新增: "_cageSendKey", | |
| 36 | 新增: "_cageQueueInput", | |
| 37 | 新增: "_handleKeyEvent", | |
| 38 | 新增: "cageSetKeyboardTarget", | |
| 39 | 新增: "focus", | |
| 40 | 新增: "blur", | |
| 41 | 新增: ]) | |
| 42 | 新增: rfb[name] = RFB.prototype[name].bind(rfb); | |
| 43 | 新增: rfb._canvas = container.querySelector("canvas"); | |
| 44 | 新增: rfb._keyboard = new Keyboard(rfb._canvas); | |
| 45 | 新增: rfb._rfbConnectionState = "connected"; | |
| 46 | 新增: rfb._remoteCapsLock = rfb._remoteNumLock = null; | |
| 47 | 新增: const packets = []; | |
| 48 | 新增: let bytes = []; | |
| 49 | 新增: rfb._sock = { | |
| 50 | 新增: sQpush8(value) { | |
| 51 | 新增: bytes.push(value); | |
| 52 | 新增: }, | |
| 53 | 新增: sQpush16(value) { | |
| 54 | 新增: bytes.push((value >> 8) & 255, value & 255); | |
| 55 | 新增: }, | |
| 56 | 新增: sQpush32(value) { | |
| 57 | 新增: bytes.push( | |
| 58 | 新增: value >>> 24, | |
| 59 | 新增: (value >> 16) & 255, | |
| 60 | 新增: (value >> 8) & 255, | |
| 61 | 新增: value & 255, | |
| 62 | 新增: ); | |
| 63 | 新增: }, | |
| 64 | 新增: flush() { | |
| 65 | 新增: packets.push(bytes); | |
| 66 | 新增: bytes = []; | |
| 67 | 新增: }, | |
| 68 | 新增: }; | |
| 69 | 新增: const texts = []; | |
| 70 | 新增: rfb.cagePasteText = (text) => | |
| 71 | 新增: rfb._cageQueueInput(() => { | |
| 72 | 新增: texts.push(text); | |
| 73 | 新增: }); | |
| 74 | 新增: let active = true; | |
| 75 | 新增: const options = { | |
| 76 | 新增: mode: () => "mac", | |
| 77 | 新增: isActive: () => active, | |
| 78 | 新增: insertText: (text) => rfb.cagePasteText(text), | |
| 79 | 新增: onStatus() {}, | |
| 80 | 新增: onFallback() {}, | |
| 81 | 新增: }; | |
| 82 | 新增: const install = () => installRemoteInput(rfb, container, options); | |
| 83 | 新增: window.probe = { | |
| 84 | 新增: rfb, | |
| 85 | 新增: packets, | |
| 86 | 新增: texts, | |
| 87 | 新增: input: install(), | |
| 88 | 新增: install, | |
| 89 | 新增: setActive: (value) => { | |
| 90 | 新增: active = value; | |
| 91 | 新增: }, | |
| 92 | 新增: }; | |
| 93 | 新增: rfb.focus(); | |
| 94 | 新增: }); | |
| 95 | 新增: const target = page.getByLabel("Cage 网页输入"); | |
| 96 | 新增: const keys = () => | |
| 97 | 新增: page.evaluate(() => | |
| 98 | 新增: probe.packets.map((p) => { | |
| 99 | 新增: if (p.length !== 8 || p[0] !== 4) | |
| 100 | 新增: throw new Error("Unexpected RFB key packet"); | |
| 101 | 新增: return { | |
| 102 | 新增: down: p[1], | |
| 103 | 新增: sym: ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]) >>> 0, | |
| 104 | 新增: }; | |
| 105 | 新增: }), | |
| 106 | 新增: ); | |
| 107 | 新增: const texts = () => page.evaluate(() => [...probe.texts]); | |
| 108 | 新增: const clear = () => | |
| 109 | 新增: page.evaluate(() => { | |
| 110 | 新增: probe.packets.length = 0; | |
| 111 | 新增: probe.texts.length = 0; | |
| 112 | 新增: }); | |
| 113 | 新增: const dispatch = (type, detail) => | |
| 114 | 新增: target.evaluate( | |
| 115 | 新增: (node, { type, detail }) => { | |
| 116 | 新增: const EventType = type.startsWith("composition") | |
| 117 | 新增: ? CompositionEvent | |
| 118 | 新增: : InputEvent; | |
| 119 | 新增: node.dispatchEvent(new EventType(type, { bubbles: true, ...detail })); | |
| 120 | 新增: }, | |
| 121 | 新增: { type, detail }, | |
| 122 | 新增: ); | |
| 123 | 新增: const compose = async (text) => { | |
| 124 | 新增: await dispatch("compositionstart", { data: "" }); | |
| 125 | 新增: await dispatch("input", { | |
| 126 | 新增: data: "nihao", | |
| 127 | 新增: isComposing: true, | |
| 128 | 新增: inputType: "insertCompositionText", | |
| 129 | 新增: }); | |
| 130 | 新增: await dispatch("compositionend", { data: text }); | |
| 131 | 新增: await dispatch("input", { data: text, inputType: "insertFromComposition" }); | |
| 132 | 新增: }; | |
| 133 | 新增: await page.keyboard.type("abc"); | |
| 134 | 新增: assert.deepEqual( | |
| 135 | 新增: (await keys()).filter((k) => k.down).map((k) => k.sym), | |
| 136 | 新增: [97, 98, 99], | |
| 137 | 新增: ); | |
| 138 | 新增: assert.equal(await target.inputValue(), ""); | |
| 139 | 新增: await clear(); | |
| 140 | 新增: // Exercise Chromium's composition implementation as well as the explicit | |
| 141 | 新增: // cross-engine event sequences below. This still does not use macOS Pinyin. | |
| 142 | 新增: const cdp = await page.context().newCDPSession(page); | |
| 143 | 新增: await cdp.send("Input.imeSetComposition", { | |
| 144 | 新增: text: "nihao", | |
| 145 | 新增: selectionStart: 5, | |
| 146 | 新增: selectionEnd: 5, | |
| 147 | 新增: }); | |
| 148 | 新增: assert.equal(await target.inputValue(), "nihao"); | |
| 149 | 新增: assert.deepEqual(await keys(), []); | |
| 150 | 新增: await cdp.send("Input.insertText", { text: "你好" }); | |
| 151 | 新增: assert.deepEqual(await texts(), ["你好"]); | |
| 152 | 新增: assert.deepEqual(await keys(), []); | |
| 153 | 新增: assert.equal(await target.inputValue(), ""); | |
| 154 | 新增: await clear(); | |
| 155 | 新增: await cdp.send("Input.insertText", { text: "🙂" }); | |
| 156 | 新增: assert.deepEqual(await texts(), ["🙂"]); | |
| 157 | 新增: await clear(); | |
| 158 | 新增: await cdp.detach(); | |
| 159 | 新增: await dispatch("compositionstart", { data: "" }); | |
| 160 | 新增: const accepted = await target.evaluate((node) => | |
| 161 | 新增: node.dispatchEvent( | |
| 162 | 新增: new KeyboardEvent("keydown", { | |
| 163 | 新增: key: "Process", | |
| 164 | 新增: code: "KeyN", | |
| 165 | 新增: keyCode: 229, | |
| 166 | 新增: bubbles: true, | |
| 167 | 新增: cancelable: true, | |
| 168 | 新增: isComposing: true, | |
| 169 | 新增: }), | |
| 170 | 新增: ), | |
| 171 | 新增: ); | |
| 172 | 新增: assert.equal( | |
| 173 | 新增: accepted, | |
| 174 | 新增: true, | |
| 175 | 新增: "host IME key default action must remain enabled", | |
| 176 | 新增: ); | |
| 177 | 新增: await page.keyboard.press("Space"); | |
| 178 | 新增: assert.deepEqual( | |
| 179 | 新增: await keys(), | |
| 180 | 新增: [], | |
| 181 | 新增: "candidate selection must not reach the guest", | |
| 182 | 新增: ); | |
| 183 | 新增: await dispatch("compositionend", { data: "你好🙂" }); | |
| 184 | 新增: await dispatch("input", { | |
| 185 | 新增: data: "你好🙂", | |
| 186 | 新增: inputType: "insertFromComposition", | |
| 187 | 新增: }); | |
| 188 | 新增: await page.keyboard.press("Enter"); | |
| 189 | 新增: assert.deepEqual( | |
| 190 | 新增: (await keys()).filter((k) => k.down).map((k) => k.sym), | |
| 191 | 新增: [0xff0d], | |
| 192 | 新增: ); | |
| 193 | 新增: assert.equal(await target.inputValue(), ""); | |
| 194 | 新增: await clear(); | |
| 195 | 新增: await compose("你"); | |
| 196 | 新增: await compose("你"); | |
| 197 | 新增: assert.deepEqual(await texts(), ["你", "你"]); | |
| 198 | 新增: await clear(); | |
| 199 | 新增: // A delayed commit must keep subsequent Enter behind text completion. | |
| 200 | 新增: await page.evaluate(() => { | |
| 201 | 新增: probe.rfb._cageQueueInput( | |
| 202 | 新增: () => | |
| 203 | 新增: new Promise((resolve) => { | |
| 204 | 新增: probe.finishText = resolve; | |
| 205 | 新增: }), | |
| 206 | 新增: ); | |
| 207 | 新增: }); | |
| 208 | 新增: await page.keyboard.press("Enter"); | |
| 209 | 新增: assert.deepEqual(await keys(), []); | |
| 210 | 新增: await page.evaluate(() => probe.finishText()); | |
| 211 | 新增: assert.deepEqual( | |
| 212 | 新增: (await keys()).map((k) => k.sym), | |
| 213 | 新增: [0xff0d, 0xff0d], | |
| 214 | 新增: ); | |
| 215 | 新增: await clear(); | |
| 216 | 新增: // On transfer failure, do not submit a form with the committed text missing. | |
| 217 | 新增: await page.evaluate(() => { | |
| 218 | 新增: probe.rfb._cageQueueInput( | |
| 219 | 新增: () => | |
| 220 | 新增: new Promise((resolve, reject) => { | |
| 221 | 新增: probe.failText = reject; | |
| 222 | 新增: }), | |
| 223 | 新增: ); | |
| 224 | 新增: }); | |
| 225 | 新增: await page.keyboard.press("Enter"); | |
| 226 | 新增: await page.evaluate(() => probe.failText(new Error("test transfer failure"))); | |
| 227 | 新增: assert.deepEqual(await keys(), []); | |
| 228 | 新增: await compose(""); | |
| 229 | 新增: assert.deepEqual(await keys(), []); | |
| 230 | 新增: await page.keyboard.down("Shift"); | |
| 231 | 新增: await dispatch("compositionstart", { data: "" }); | |
| 232 | 新增: await page.keyboard.up("Shift"); | |
| 233 | 新增: assert.deepEqual( | |
| 234 | 新增: (await keys()).map((k) => k.down), | |
| 235 | 新增: [1, 0], | |
| 236 | 新增: "modifiers released during composition must not stick", | |
| 237 | 新增: ); | |
| 238 | 新增: assert.equal( | |
| 239 | 新增: await page.evaluate(() => probe.input.edit("undo")), | |
| 240 | 新增: false, | |
| 241 | 新增: "native menus must edit the host composition", | |
| 242 | 新增: ); | |
| 243 | 新增: await dispatch("compositionend", { data: "" }); | |
| 244 | 新增: await clear(); | |
| 245 | 新增: await page.getByLabel("本机地址栏").fill("本机文字"); | |
| 246 | 新增: assert.deepEqual(await keys(), []); | |
| 247 | 新增: await page.evaluate(() => probe.rfb.focus()); | |
| 248 | 新增: await page.keyboard.press("Meta+f"); | |
| 249 | 新增: assert.deepEqual( | |
| 250 | 新增: (await keys()).filter((k) => k.down).map((k) => k.sym), | |
| 251 | 新增: [0xffe3, 102], | |
| 252 | 新增: ); | |
| 253 | 新增: await clear(); | |
| 254 | 新增: await page.evaluate(() => probe.setActive(false)); | |
| 255 | 新增: await compose("后台不提交"); | |
| 256 | 新增: assert.deepEqual(await keys(), []); | |
| 257 | 新增: await page.evaluate(() => { | |
| 258 | 新增: probe.setActive(true); | |
| 259 | 新增: probe.input.dispose(); | |
| 260 | 新增: probe.input = probe.install(); | |
| 261 | 新增: probe.rfb.focus(); | |
| 262 | 新增: }); | |
| 263 | 新增: assert.equal(await target.count(), 1); | |
| 264 | 新增: await page.keyboard.press("b"); | |
| 265 | 新增: assert.deepEqual( | |
| 266 | 新增: (await keys()).filter((k) => k.down).map((k) => k.sym), | |
| 267 | 新增: [98], | |
| 268 | 新增: ); | |
| 269 | 新增: await clear(); | |
| 270 | 新增: await page.evaluate(() => { | |
| 271 | 新增: const oldTarget = document.activeElement; | |
| 272 | 新增: probe.input.dispose(); | |
| 273 | 新增: oldTarget.dispatchEvent( | |
| 274 | 新增: new CompositionEvent("compositionend", { data: "迟到的文字" }), | |
| 275 | 新增: ); | |
| 276 | 新增: probe.rfb.focus(); | |
| 277 | 新增: }); | |
| 278 | 新增: assert.equal(await target.count(), 0); | |
| 279 | 新增: assert.equal( | |
| 280 | 新增: await page.evaluate(() => document.activeElement.tagName), | |
| 281 | 新增: "CANVAS", | |
| 282 | 新增: ); | |
| 283 | 新增: assert.deepEqual(await keys(), []); | |
| 284 | 新增: assert.deepEqual(errors, []); | |
| 285 | 新增: console.log( | |
| 286 | 新增: JSON.stringify( | |
| 287 | 新增: { | |
| 288 | 新增: passed: true, | |
| 289 | 新增: checks: [ | |
| 290 | 新增: "real noVNC keyboard and RFB encoding", | |
| 291 | 新增: "English input", | |
| 292 | 新增: "Chromium IME engine commit", | |
| 293 | 新增: "composition default action", | |
| 294 | 新增: "candidate suppression", | |
| 295 | 新增: "Unicode text transfer", | |
| 296 | 新增: "text and Enter order", | |
| 297 | 新增: "failed transfer cancels queued Enter", | |
| 298 | 新增: "repeated commits", | |
| 299 | 新增: "cancel", | |
| 300 | 新增: "modifier release", | |
| 301 | 新增: "native edit routing", | |
| 302 | 新增: "local field isolation", | |
| 303 | 新增: "Command mapping", | |
| 304 | 新增: "inactive view", | |
| 305 | 新增: "reconnect and disposal", | |
| 306 | 新增: ], | |
| 307 | 新增: limitation: | |
| 308 | 新增: "Covers the Chromium composition engine and simulated event sequences; native macOS IME and guest rendering require separate acceptance.", | |
| 309 | 新增: }, | |
| 310 | 新增: null, | |
| 311 | 新增: 2, | |
| 312 | 新增: ), | |
| 313 | 新增: ); | |
| 314 | 新增:} finally { | |
| 315 | 新增: await browser.close(); | |
| 316 | 新增:} | |
| @@ -0,0 +1,102 @@ | ||
| 1 | 新增:// Exercise the shipped noVNC client through its real RFB handshake and raw frames. | |
| 2 | 新增:// The fixture owns all requests and never reaches a user's VM. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import fs from "node:fs/promises"; | |
| 5 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 6 | 新增: | |
| 7 | 新增:const { startDisplay } = await import("./rfb-wire-fixture.mjs"); | |
| 8 | 新增:const display = await startDisplay(process.env.CAGE_UI_URL || "http://127.0.0.1:5199"); | |
| 9 | 新增:const fixture = await createWorkbench({ mockWebSockets: false, url: display.url }); | |
| 10 | 新增:const { page, state, browser, errors } = fixture; | |
| 11 | 新增:const report = display.stats; | |
| 12 | 新增:report.checks = []; | |
| 13 | 新增:const browserErrors = []; | |
| 14 | 新增:page.on("console", (message) => { | |
| 15 | 新增: if (message.type() === "error") browserErrors.push(message.text()); | |
| 16 | 新增:}); | |
| 17 | 新增:try { | |
| 18 | 新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click(); | |
| 19 | 新增: await page.getByRole("heading", { name: "Cage 环境已就绪", exact: true }).waitFor(); | |
| 20 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 21 | 新增: await page.waitForFunction(() => Boolean(document.querySelector(".remote-canvas canvas"))); | |
| 22 | 新增: await page.getByText("正在连接画面", { exact: true }).waitFor({ state: "hidden" }); | |
| 23 | 新增: assert.ok(report.connections > 0); | |
| 24 | 新增: const deadline = Date.now() + 3000; | |
| 25 | 新增: while (report.frames < 5 && Date.now() < deadline) | |
| 26 | 新增: await new Promise((resolve) => setTimeout(resolve, 20)); | |
| 27 | 新增: assert.ok(report.frames >= 5, "display did not deliver its first frames"); | |
| 28 | 新增: const originalTabs = structuredClone(state.tabs); | |
| 29 | 新增: const before = report.frames; | |
| 30 | 新增: await page.waitForFunction(() => document.querySelector(".remote-canvas canvas")?.width > 0); | |
| 31 | 新增: await page.getByRole("button", { name: "工作台", exact: true }).click(); | |
| 32 | 新增: // Bounded observation proves frames stop, rather than only inspecting CSS. | |
| 33 | 新增: await new Promise((resolve) => setTimeout(resolve, 500)); | |
| 34 | 新增: const hiddenStart = report.frames; | |
| 35 | 新增: await new Promise((resolve) => setTimeout(resolve, 1000)); | |
| 36 | 新增: report.hiddenFrames = report.frames - hiddenStart; | |
| 37 | 新增: report.visibleFrames = before; | |
| 38 | 新增: if (!process.env.CAGE_PERF_BASELINE) { | |
| 39 | 新增: assert.equal(report.hiddenFrames, 0, "hidden workbench continued receiving frames"); | |
| 40 | 新增: assert.ok(report.closed > 0, "display connection was not closed"); | |
| 41 | 新增: } | |
| 42 | 新增: assert.deepEqual(state.tabs, originalTabs, "hiding the display changed guest tabs"); | |
| 43 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 44 | 新增: await page.getByText("正在连接画面", { exact: true }).waitFor({ state: "hidden" }); | |
| 45 | 新增: await page.waitForFunction(() => document.querySelector(".remote-canvas canvas")?.width > 0); | |
| 46 | 新增: const resumed = report.frames; | |
| 47 | 新增: await new Promise((resolve) => setTimeout(resolve, 250)); | |
| 48 | 新增: assert.ok(report.frames > resumed, "display frames did not resume"); | |
| 49 | 新增: if (!process.env.CAGE_PERF_BASELINE) { | |
| 50 | 新增: await page.evaluate(() => { | |
| 51 | 新增: window.cageWindowVisible = false; | |
| 52 | 新增: window.dispatchEvent(new Event("cage-window-visibility")); | |
| 53 | 新增: }); | |
| 54 | 新增: await new Promise((resolve) => setTimeout(resolve, 300)); | |
| 55 | 新增: const paused = report.frames; | |
| 56 | 新增: await new Promise((resolve) => setTimeout(resolve, 300)); | |
| 57 | 新增: assert.equal(report.frames, paused, "occluded native window continued receiving frames"); | |
| 58 | 新增: await page.evaluate(() => { | |
| 59 | 新增: window.cageWindowVisible = true; | |
| 60 | 新增: window.dispatchEvent(new Event("cage-window-visibility")); | |
| 61 | 新增: }); | |
| 62 | 新增: await page.getByText("正在连接画面", { exact: true }).waitFor({ state: "hidden" }); | |
| 63 | 新增: await new Promise((resolve) => setTimeout(resolve, 250)); | |
| 64 | 新增: assert.ok(report.frames > paused, "native window visibility did not resume frames"); | |
| 65 | 新增: } | |
| 66 | 新增: assert.deepEqual(errors, []); | |
| 67 | 新增: report.checks.push("real RFB frames", "tabs preserved", "frames resumed"); | |
| 68 | 新增: if (!process.env.CAGE_PERF_BASELINE) report.checks.push("hidden frames stopped", "native occlusion paused"); | |
| 69 | 新增: const soakSeconds = Number(process.env.CAGE_PERF_SOAK_SECONDS || 0); | |
| 70 | 新增: if (soakSeconds > 0) { | |
| 71 | 新增: const session = await page.context().newCDPSession(page); | |
| 72 | 新增: await session.send("Performance.enable"); | |
| 73 | 新增: report.soak = []; | |
| 74 | 新增: const started = Date.now(); | |
| 75 | 新增: while ((Date.now() - started) / 1000 < soakSeconds) { | |
| 76 | 新增: const beforeResume = report.frames; | |
| 77 | 新增: await page.evaluate(() => { window.cageWindowVisible = true; window.dispatchEvent(new Event("cage-window-visibility")); }); | |
| 78 | 新增: await page.getByText("正在连接画面", { exact: true }).waitFor({ state: "hidden" }); | |
| 79 | 新增: await new Promise((resolve) => setTimeout(resolve, 1000)); | |
| 80 | 新增: assert.ok(report.frames > beforeResume, "soak: visible display did not resume frames"); | |
| 81 | 新增: await page.evaluate(() => { window.cageWindowVisible = false; window.dispatchEvent(new Event("cage-window-visibility")); }); | |
| 82 | 新增: await new Promise((resolve) => setTimeout(resolve, 500)); | |
| 83 | 新增: const hidden = report.frames; | |
| 84 | 新增: await new Promise((resolve) => setTimeout(resolve, 8500)); | |
| 85 | 新增: assert.equal(report.frames, hidden, "soak: frames continued in hidden window"); | |
| 86 | 新增: const { metrics } = await session.send("Performance.getMetrics"); | |
| 87 | 新增: report.soak.push({ seconds: (Date.now() - started) / 1000, ...Object.fromEntries(metrics.filter((x) => ["JSHeapUsedSize", "JSHeapTotalSize", "TaskDuration", "Documents", "Nodes"].includes(x.name)).map((x) => [x.name, x.value])) }); | |
| 88 | 新增: if (process.env.CAGE_PERF_REPORT) await fs.writeFile(process.env.CAGE_PERF_REPORT, JSON.stringify(report, null, 2)); | |
| 89 | 新增: } | |
| 90 | 新增: report.checks.push(`${soakSeconds}s repeated display reconnect soak`); | |
| 91 | 新增: await session.detach(); | |
| 92 | 新增: } | |
| 93 | 新增: const output = process.env.CAGE_PERF_REPORT; | |
| 94 | 新增: if (output) await fs.writeFile(output, JSON.stringify(report, null, 2)); | |
| 95 | 新增: console.log(JSON.stringify(report)); | |
| 96 | 新增:} catch (error) { | |
| 97 | 新增: console.error(JSON.stringify({ report, errors, browserErrors, visible: await page.locator("body").innerText() })); | |
| 98 | 新增: throw error; | |
| 99 | 新增:} finally { | |
| 100 | 新增: await browser.close(); | |
| 101 | 新增: await display.close(); | |
| 102 | 新增:} | |
| @@ -0,0 +1,92 @@ | ||
| 1 | 新增:import http from "node:http"; | |
| 2 | 新增:import { createHash } from "node:crypto"; | |
| 3 | 新增: | |
| 4 | 新增:// A bounded RFB display over real browser WebSockets. Playwright's WebSocket | |
| 5 | 新增:// replacement lacks the prototype properties checked by the shipped noVNC. | |
| 6 | 新增:export async function startDisplay(upstream) { | |
| 7 | 新增: const stats = { connections: 0, closed: 0, frames: 0 }; | |
| 8 | 新增: const sockets = new Set(); | |
| 9 | 新增: const server = http.createServer((req, res) => { | |
| 10 | 新增: if (req.url.startsWith("/api/")) { | |
| 11 | 新增: res.writeHead(503); res.end("Unmocked fixture request"); return; | |
| 12 | 新增: } | |
| 13 | 新增: const target = new URL(req.url, upstream); | |
| 14 | 新增: const proxy = http.get(target, (response) => { | |
| 15 | 新增: res.writeHead(response.statusCode, response.headers); | |
| 16 | 新增: response.pipe(res); | |
| 17 | 新增: }); | |
| 18 | 新增: proxy.on("error", () => { res.writeHead(502); res.end(); }); | |
| 19 | 新增: }); | |
| 20 | 新增: server.on("upgrade", (req, socket) => { | |
| 21 | 新增: if (req.url !== "/api/vnc") { socket.destroy(); return; } | |
| 22 | 新增: sockets.add(socket); | |
| 23 | 新增: stats.connections++; | |
| 24 | 新增: const key = createHash("sha1").update(req.headers["sec-websocket-key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64"); | |
| 25 | 新增: socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${key}\r\n\r\n`); | |
| 26 | 新增: const send = (payload, opcode = 2) => { | |
| 27 | 新增: if (socket.destroyed) return; | |
| 28 | 新增: const length = payload.length; | |
| 29 | 新增: const header = Buffer.alloc(length < 126 ? 2 : length < 65536 ? 4 : 10); | |
| 30 | 新增: header[0] = 0x80 | opcode; | |
| 31 | 新增: header[1] = length < 126 ? length : length < 65536 ? 126 : 127; | |
| 32 | 新增: if (header.length === 4) header.writeUInt16BE(length, 2); | |
| 33 | 新增: if (header.length === 10) header.writeBigUInt64BE(BigInt(length), 2); | |
| 34 | 新增: socket.write(Buffer.concat([header, payload])); | |
| 35 | 新增: }; | |
| 36 | 新增: let wire = Buffer.alloc(0), rfb = Buffer.alloc(0), phase = 0, timer; | |
| 37 | 新增: const consume = (data) => { | |
| 38 | 新增: rfb = Buffer.concat([rfb, data]); | |
| 39 | 新增: if (phase === 0 && rfb.length >= 12) { rfb = rfb.subarray(12); phase = 1; send(Buffer.from([1, 1])); } | |
| 40 | 新增: if (phase === 1 && rfb.length >= 1) { rfb = rfb.subarray(1); phase = 2; send(Buffer.alloc(4)); } | |
| 41 | 新增: if (phase === 2 && rfb.length >= 1) { | |
| 42 | 新增: phase = 3; | |
| 43 | 新增: const name = Buffer.from("Cage test display"); | |
| 44 | 新增: const init = Buffer.alloc(24 + name.length); | |
| 45 | 新增: init.writeUInt16BE(640, 0); init.writeUInt16BE(480, 2); | |
| 46 | 新增: init.set([32, 24, 0, 1], 4); | |
| 47 | 新增: for (const offset of [8, 10, 12]) init.writeUInt16BE(255, offset); | |
| 48 | 新增: init.set([16, 8, 0], 14); | |
| 49 | 新增: init.writeUInt32BE(name.length, 20); name.copy(init, 24); send(init); | |
| 50 | 新增: const frame = Buffer.alloc(16 + 640 * 480 * 4); | |
| 51 | 新增: frame.writeUInt16BE(1, 2); frame.writeUInt16BE(640, 8); frame.writeUInt16BE(480, 10); | |
| 52 | 新增: timer = setInterval(() => { | |
| 53 | 新增: if (socket.writableLength > frame.length * 2) return; | |
| 54 | 新增: frame.fill(stats.frames % 255, 16); | |
| 55 | 新增: send(frame); stats.frames++; | |
| 56 | 新增: }, 50); | |
| 57 | 新增: } | |
| 58 | 新增: if (phase === 3) rfb = Buffer.alloc(0); | |
| 59 | 新增: }; | |
| 60 | 新增: socket.on("data", (data) => { | |
| 61 | 新增: wire = Buffer.concat([wire, data]); | |
| 62 | 新增: while (wire.length >= 2) { | |
| 63 | 新增: const opcode = wire[0] & 15, masked = Boolean(wire[1] & 128); | |
| 64 | 新增: let length = wire[1] & 127, offset = 2; | |
| 65 | 新增: if (length === 126) { if (wire.length < 4) return; length = wire.readUInt16BE(2); offset = 4; } | |
| 66 | 新增: if (length === 127) { if (wire.length < 10) return; length = Number(wire.readBigUInt64BE(2)); offset = 10; } | |
| 67 | 新增: if (length > 65536) { socket.destroy(); return; } | |
| 68 | 新增: const maskBytes = masked ? 4 : 0; | |
| 69 | 新增: if (wire.length < offset + maskBytes + length) return; | |
| 70 | 新增: const payload = Buffer.from(wire.subarray(offset + maskBytes, offset + maskBytes + length)); | |
| 71 | 新增: if (masked) for (let i = 0; i < length; i++) payload[i] ^= wire[offset + (i % 4)]; | |
| 72 | 新增: wire = wire.subarray(offset + maskBytes + length); | |
| 73 | 新增: if (opcode === 8) { send(payload, 8); socket.end(); return; } | |
| 74 | 新增: if (opcode === 9) send(payload, 10); | |
| 75 | 新增: if (opcode === 1 || opcode === 2) consume(payload); | |
| 76 | 新增: } | |
| 77 | 新增: }); | |
| 78 | 新增: socket.on("error", () => {}); | |
| 79 | 新增: socket.on("close", () => { clearInterval(timer); sockets.delete(socket); stats.closed++; }); | |
| 80 | 新增: send(Buffer.from("RFB 003.008\n")); | |
| 81 | 新增: }); | |
| 82 | 新增: await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); | |
| 83 | 新增: return { | |
| 84 | 新增: url: `http://127.0.0.1:${server.address().port}`, | |
| 85 | 新增: stats, | |
| 86 | 新增: close: async () => { | |
| 87 | 新增: for (const socket of sockets) socket.destroy(); | |
| 88 | 新增: server.closeAllConnections(); | |
| 89 | 新增: await new Promise((resolve) => server.close(resolve)); | |
| 90 | 新增: }, | |
| 91 | 新增: }; | |
| 92 | 新增:} | |
| @@ -5,6 +5,11 @@ const require = createRequire(import.meta.url); | ||
| 5 | 5 | export async function createWorkbench({ |
| 6 | 6 | viewport = { width: 1280, height: 850 }, |
| 7 | 7 | recordVideo, |
| 8 | 新增: favoritesRequest, | |
| 9 | 新增: mockWebSockets = true, | |
| 10 | 新增: url, | |
| 11 | 新增: nativeRequest, | |
| 12 | 新增: startupFailure = false, | |
| 8 | 13 | } = {}) { |
| 9 | 14 | const { chromium } = require( |
| 10 | 15 | process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", |
| @@ -73,20 +78,22 @@ export async function createWorkbench({ | ||
| 73 | 78 | sequence: 0, |
| 74 | 79 | }; |
| 75 | 80 | await page.exposeFunction("chooseTestFolder", () => state.chosenFolder); |
| 81 | 新增: await page.exposeFunction("requestNativeForTest", async (body) => nativeRequest ? nativeRequest(body) : null); | |
| 76 | 82 | await page.addInitScript(() => { |
| 77 | 83 | window.webkit = { |
| 78 | 84 | messageHandlers: { |
| 79 | 85 | cage: { |
| 80 | 删除: postMessage: async ({ action }) => { | |
| 86 | 新增: postMessage: async (body) => { | |
| 87 | 新增: const { action } = body; | |
| 81 | 88 | if (action === "chooseFolder") return window.chooseTestFolder(); |
| 82 | 89 | if (action === "clipboardRead") return "fixture clipboard"; |
| 83 | 删除: return null; | |
| 90 | 新增: return window.requestNativeForTest(body); | |
| 84 | 91 | }, |
| 85 | 92 | }, |
| 86 | 93 | }, |
| 87 | 94 | }; |
| 88 | 95 | }); |
| 89 | 删除: await page.routeWebSocket("**/api/**", (socket) => { | |
| 96 | 新增: if (mockWebSockets) await page.routeWebSocket("**/api/**", (socket) => { | |
| 90 | 97 | if (socket.url().includes("/terminals/")) { |
| 91 | 98 | state.terminalConnections++; |
| 92 | 99 | socket.send( |
| @@ -101,7 +108,12 @@ export async function createWorkbench({ | ||
| 101 | 108 | const path = new URL(request.url()).pathname.replace("/api", ""); |
| 102 | 109 | const body = request.postDataJSON(); |
| 103 | 110 | state.requests.push({ path, method: request.method(), body }); |
| 111 | 新增: if (startupFailure && path === "/status") return route.fulfill({ status: 503, body: "测试:控制服务暂不可用" }); | |
| 104 | 112 | let result = {}; |
| 113 | 新增: if (path === "/favorites") { | |
| 114 | 新增: if (favoritesRequest) return route.fulfill(await favoritesRequest(request)); | |
| 115 | 新增: return route.fulfill({ json: { items: [], folders: [] } }); | |
| 116 | 新增: } | |
| 105 | 117 | if (path === "/host/git") { |
| 106 | 118 | if (request.method() === "POST") { |
| 107 | 119 | if (!body?.confirm) |
| @@ -276,7 +288,7 @@ export async function createWorkbench({ | ||
| 276 | 288 | }; |
| 277 | 289 | return route.fulfill({ json: result }); |
| 278 | 290 | }); |
| 279 | 删除: await page.goto(process.env.CAGE_UI_URL || "http://127.0.0.1:5198"); | |
| 280 | 删除: await page.getByRole("heading", { name: "先启动 Cage 环境" }).waitFor(); | |
| 291 | 新增: await page.goto(url || process.env.CAGE_UI_URL || "http://127.0.0.1:5198"); | |
| 292 | 新增: if (!startupFailure) await page.getByRole("heading", { name: "先启动 Cage 环境" }).waitFor(); | |
| 281 | 293 | return { browser, context, page, state, errors }; |
| 282 | 294 | } |
| @@ -0,0 +1,115 @@ | ||
| 1 | 新增:import React, { useEffect, useRef, useState } from "react"; | |
| 2 | 新增:import { ArrowDownToLine, Check, LoaderCircle, RefreshCw } from "lucide-react"; | |
| 3 | 新增:import { native, nativeAvailable } from "./api"; | |
| 4 | 新增:import { Modal } from "./views"; | |
| 5 | 新增: | |
| 6 | 新增:const activePhases = new Set(["checking", "downloading", "downloaded", "verifying", "installing"]); | |
| 7 | 新增:export function useAppUpdates() { | |
| 8 | 新增: const [state, setState] = useState({ phase: "idle", message: "" }); | |
| 9 | 新增: const current = useRef(state); | |
| 10 | 新增: current.current = state; | |
| 11 | 新增: const available = nativeAvailable(); | |
| 12 | 新增: const run = async (operation) => { | |
| 13 | 新增: if (!available) return; | |
| 14 | 新增: try { | |
| 15 | 新增: const next = await native("appUpdate", { operation }); | |
| 16 | 新增: if (next?.phase) setState(next); | |
| 17 | 新增: } catch (error) { | |
| 18 | 新增: setState((previous) => ({ ...previous, phase: "failed", message: error.message, retryable: true })); | |
| 19 | 新增: } | |
| 20 | 新增: }; | |
| 21 | 新增: useEffect(() => { | |
| 22 | 新增: if (!available) return; | |
| 23 | 新增: let live = true; | |
| 24 | 新增: const receive = (event) => { | |
| 25 | 新增: if (event.detail?.phase) setState(event.detail); | |
| 26 | 新增: }; | |
| 27 | 新增: window.addEventListener("cage-app-update", receive); | |
| 28 | 新增: (async () => { | |
| 29 | 新增: try { | |
| 30 | 新增: let next = await native("appUpdate", { operation: "status" }); | |
| 31 | 新增: if (!live) return; | |
| 32 | 新增: if (!next || next.phase === "idle") next = await native("appUpdate", { operation: "check" }); | |
| 33 | 新增: if (live && next?.phase) setState(next); | |
| 34 | 新增: } catch (error) { | |
| 35 | 新增: if (live) setState({ phase: "failed", message: error.message, retryable: true }); | |
| 36 | 新增: } | |
| 37 | 新增: })(); | |
| 38 | 新增: const timer = setInterval(() => { | |
| 39 | 新增: if (["idle", "current", "failed"].includes(current.current.phase)) void run("check"); | |
| 40 | 新增: }, 6 * 60 * 60 * 1000); | |
| 41 | 新增: return () => { | |
| 42 | 新增: live = false; | |
| 43 | 新增: clearInterval(timer); | |
| 44 | 新增: window.removeEventListener("cage-app-update", receive); | |
| 45 | 新增: }; | |
| 46 | 新增: }, [available]); | |
| 47 | 新增: return { state, run, available }; | |
| 48 | 新增:} | |
| 49 | 新增: | |
| 50 | 新增:export function AppUpdateButton({ updates }) { | |
| 51 | 新增: const [details, setDetails] = useState(false); | |
| 52 | 新增: const { state, run, available } = updates; | |
| 53 | 新增: if (!available) return null; | |
| 54 | 新增: const busy = activePhases.has(state.phase); | |
| 55 | 新增: const downloadable = ["available", "ready"].includes(state.phase); | |
| 56 | 新增: const percent = state.totalBytes > 0 | |
| 57 | 新增: ? Math.min(100, Math.floor((state.receivedBytes || 0) / state.totalBytes * 100)) | |
| 58 | 新增: : null; | |
| 59 | 新增: const label = state.phase === "available" ? "下载更新" | |
| 60 | 新增: : state.phase === "ready" ? "安装更新并重启" | |
| 61 | 新增: : state.phase === "downloading" ? `正在下载更新${percent === null ? "" : ` ${percent}%`}` | |
| 62 | 新增: : state.phase === "verifying" || state.phase === "downloaded" ? "正在校验更新" | |
| 63 | 新增: : state.phase === "installing" ? "正在安装更新" | |
| 64 | 新增: : state.phase === "checking" ? "正在检查更新" | |
| 65 | 新增: : state.phase === "failed" ? "查看更新状态" | |
| 66 | 新增: : "检查更新"; | |
| 67 | 新增: const Icon = busy ? LoaderCircle : downloadable ? ArrowDownToLine : state.phase === "current" ? Check : RefreshCw; | |
| 68 | 新增: return ( | |
| 69 | 新增: <> | |
| 70 | 新增: <button | |
| 71 | 新增: className={`icon-button app-update-button ${downloadable ? "available" : ""}`} | |
| 72 | 新增: aria-label={label} | |
| 73 | 新增: title={state.phase === "failed" ? state.message || label : label} | |
| 74 | 新增: onClick={() => { | |
| 75 | 新增: setDetails(true); | |
| 76 | 新增: if (downloadable) void run("install"); | |
| 77 | 新增: else if (["idle", "current"].includes(state.phase)) void run("check"); | |
| 78 | 新增: }} | |
| 79 | 新增: > | |
| 80 | 新增: <Icon size={17} className={busy ? "spin" : ""} /> | |
| 81 | 新增: {state.phase === "available" && <i className="update-available-dot" />} | |
| 82 | 新增: </button> | |
| 83 | 新增: {details && ( | |
| 84 | 新增: <Modal title="Cage 更新" onClose={() => setDetails(false)}> | |
| 85 | 新增: <div className="app-update-details"> | |
| 86 | 新增: <p>{state.message || "检查是否有可安装的新版本。"}</p> | |
| 87 | 新增: <dl> | |
| 88 | 新增: {state.currentVersion && <><dt>当前版本</dt><dd>{state.currentVersion}</dd></>} | |
| 89 | 新增: {state.latestVersion && <><dt>可用版本</dt><dd>{state.latestVersion}</dd></>} | |
| 90 | 新增: </dl> | |
| 91 | 新增: {state.phase === "downloading" && ( | |
| 92 | 新增: <> | |
| 93 | 新增: <progress aria-label="更新下载进度" value={percent ?? undefined} max="100" /> | |
| 94 | 新增: <p>{percent === null ? "正在下载…" : `已下载 ${percent}%`}</p> | |
| 95 | 新增: </> | |
| 96 | 新增: )} | |
| 97 | 新增: {state.phase === "ready" && <p>更新已下载。保存工作后可继续安装,项目与登录状态会保留。</p>} | |
| 98 | 新增: <div className="modal-actions"> | |
| 99 | 新增: {state.phase === "downloading" && <button onClick={() => run("cancel")}>取消下载</button>} | |
| 100 | 新增: {!busy && ( | |
| 101 | 新增: <button onClick={() => run("check")}>重新检查</button> | |
| 102 | 新增: )} | |
| 103 | 新增: {!busy && (downloadable || (state.phase === "failed" && state.latestVersion)) && ( | |
| 104 | 新增: <button className="primary" onClick={() => run("install")}> | |
| 105 | 新增: {state.phase === "ready" ? "安装并重启" : state.phase === "failed" ? "重试更新" : "下载更新"} | |
| 106 | 新增: </button> | |
| 107 | 新增: )} | |
| 108 | 新增: <button onClick={() => setDetails(false)}>关闭</button> | |
| 109 | 新增: </div> | |
| 110 | 新增: </div> | |
| 111 | 新增: </Modal> | |
| 112 | 新增: )} | |
| 113 | 新增: </> | |
| 114 | 新增: ); | |
| 115 | 新增:} | |
| @@ -0,0 +1,51 @@ | ||
| 1 | 新增:import React, { useEffect, useRef, useState } from "react"; | |
| 2 | 新增:import { ArrowDownToLine, CircleAlert } from "lucide-react"; | |
| 3 | 新增:import { api } from "./api"; | |
| 4 | 新增:import { Modal } from "./views"; | |
| 5 | 新增: | |
| 6 | 新增:export function useDownloadNotifications(downloads = [], onStatus) { | |
| 7 | 新增: const previous = useRef(new Map()); | |
| 8 | 新增: useEffect(() => { | |
| 9 | 新增: for (const item of downloads) { | |
| 10 | 新增: if (item.state === "failed" && previous.current.get(item.id) !== "failed") | |
| 11 | 新增: onStatus(`“${item.name}”未能保存:${item.error || "请在下载列表中重试"}`); | |
| 12 | 新增: } | |
| 13 | 新增: previous.current = new Map(downloads.map((item) => [item.id, item.state])); | |
| 14 | 新增: }, [downloads]); | |
| 15 | 新增:} | |
| 16 | 新增: | |
| 17 | 新增:export function BrowserDownloads({ downloads = [], ready, onStatus }) { | |
| 18 | 新增: const [open, setOpen] = useState(false), [retrying, setRetrying] = useState(""); | |
| 19 | 新增: const failed = downloads.some((item) => item.state === "failed"); | |
| 20 | 新增: const labels = { downloading: "正在下载", saving: "正在保存到本机", saved: "已保存到本机", failed: "保存失败", canceled: "下载已取消" }; | |
| 21 | 新增: return ( | |
| 22 | 新增: <> | |
| 23 | 新增: <button className="icon-button browser-download-button" aria-label="浏览器下载" title={failed ? "有下载未能保存,点击查看" : "浏览器下载"} onClick={() => setOpen(true)}> | |
| 24 | 新增: {failed ? <CircleAlert size={16} /> : <ArrowDownToLine size={16} />} | |
| 25 | 新增: </button> | |
| 26 | 新增: {open && ( | |
| 27 | 新增: <Modal title="浏览器下载" onClose={() => setOpen(false)}> | |
| 28 | 新增: <div className="browser-download-list"> | |
| 29 | 新增: {!downloads.length && <p>暂无下载。文件会保存到默认工作区的 Downloads 文件夹。</p>} | |
| 30 | 新增: {downloads.map((item) => ( | |
| 31 | 新增: <article key={item.id} className="browser-download-item"> | |
| 32 | 新增: <strong>{item.name}</strong> | |
| 33 | 新增: <p>{labels[item.state] || "状态待确认"} | |
| 34 | 新增: {item.state === "downloading" && item.totalBytes > 0 && ` · ${Math.min(100, Math.floor(item.receivedBytes / item.totalBytes * 100))}%`} | |
| 35 | 新增: </p> | |
| 36 | 新增: {item.path && <p className="download-path">{item.path}</p>} | |
| 37 | 新增: {item.error && <p role="status">{item.error}</p>} | |
| 38 | 新增: {item.retryable && <button disabled={!ready || Boolean(retrying)} onClick={async () => { | |
| 39 | 新增: setRetrying(item.id); | |
| 40 | 新增: try { await api("/browser/download-retry", { id: item.id }); } | |
| 41 | 新增: catch (error) { onStatus(error.message); } | |
| 42 | 新增: finally { setRetrying(""); } | |
| 43 | 新增: }}>{retrying === item.id ? "正在重试…" : "重试保存"}</button>} | |
| 44 | 新增: </article> | |
| 45 | 新增: ))} | |
| 46 | 新增: </div> | |
| 47 | 新增: </Modal> | |
| 48 | 新增: )} | |
| 49 | 新增: </> | |
| 50 | 新增: ); | |
| 51 | 新增:} | |
| @@ -0,0 +1,474 @@ | ||
| 1 | 新增:import React, { useEffect, useRef, useState } from "react"; | |
| 2 | 新增:import { createPortal } from "react-dom"; | |
| 3 | 新增:import { | |
| 4 | 新增: Folder, | |
| 5 | 新增: FolderPlus, | |
| 6 | 新增: Pencil, | |
| 7 | 新增: Search, | |
| 8 | 新增: Star, | |
| 9 | 新增: Trash2, | |
| 10 | 新增: X, | |
| 11 | 新增:} from "lucide-react"; | |
| 12 | 新增:import { api } from "./api"; | |
| 13 | 新增:import { Modal } from "./views"; | |
| 14 | 新增: | |
| 15 | 新增:// The saved page is primary, folder context secondary, management actions quiet. | |
| 16 | 新增:// Reuse paper/strong/muted/line tokens, 8/12/16px spacing and existing modal forms. | |
| 17 | 新增:export function BrowserFavorites({ current, ready, onOpen }) { | |
| 18 | 新增: const [data, setData] = useState(null); | |
| 19 | 新增: const [open, setOpen] = useState(false); | |
| 20 | 新增: const [editor, setEditor] = useState(null); | |
| 21 | 新增: const [folder, setFolder] = useState("all"); | |
| 22 | 新增: const [query, setQuery] = useState(""); | |
| 23 | 新增: const [error, setError] = useState(""); | |
| 24 | 新增: const [saving, setSaving] = useState(false); | |
| 25 | 新增: const search = useRef(); | |
| 26 | 新增: const toggle = useRef(); | |
| 27 | 新增: const savingRef = useRef(false); | |
| 28 | 新增: const state = useRef(); | |
| 29 | 新增: const favorite = data?.items.find((item) => item.url === current?.url); | |
| 30 | 新增: let canSave = false; | |
| 31 | 新增: try { | |
| 32 | 新增: const url = new URL(current?.url); | |
| 33 | 新增: canSave = | |
| 34 | 新增: current?.kind === "web" && | |
| 35 | 新增: ["http:", "https:"].includes(url.protocol) && | |
| 36 | 新增: !url.username && | |
| 37 | 新增: !url.password; | |
| 38 | 新增: } catch { | |
| 39 | 新增: /* Browser internal pages cannot be bookmarked. */ | |
| 40 | 新增: } | |
| 41 | 新增: const load = async () => { | |
| 42 | 新增: try { | |
| 43 | 新增: setData(await api("/favorites")); | |
| 44 | 新增: setError(""); | |
| 45 | 新增: } catch (e) { | |
| 46 | 新增: setError(e.message); | |
| 47 | 新增: } | |
| 48 | 新增: }; | |
| 49 | 新增: const addCurrent = () => { | |
| 50 | 新增: if (!canSave || !data) return; | |
| 51 | 新增: setError(""); | |
| 52 | 新增: setEditor({ | |
| 53 | 新增: kind: "item", | |
| 54 | 新增: ...(favorite || { | |
| 55 | 新增: title: current.title || current.url, | |
| 56 | 新增: url: current.url, | |
| 57 | 新增: folder_id: "", | |
| 58 | 新增: }), | |
| 59 | 新增: }); | |
| 60 | 新增: }; | |
| 61 | 新增: const show = () => { | |
| 62 | 新增: setOpen(true); | |
| 63 | 新增: void load(); | |
| 64 | 新增: }; | |
| 65 | 新增: state.current = { open, editor, addCurrent, show }; | |
| 66 | 新增: useEffect(() => { | |
| 67 | 新增: void load(); | |
| 68 | 新增: }, []); | |
| 69 | 新增: useEffect(() => { | |
| 70 | 新增: const add = () => state.current.addCurrent(); | |
| 71 | 新增: const show = () => state.current.show(); | |
| 72 | 新增: const close = () => { | |
| 73 | 新增: if (!state.current.editor && !savingRef.current) setOpen(false); | |
| 74 | 新增: }; | |
| 75 | 新增: document.addEventListener("cage-add-favorite", add); | |
| 76 | 新增: document.addEventListener("cage-show-favorites", show); | |
| 77 | 新增: document.addEventListener("cage-close-modal", close); | |
| 78 | 新增: return () => { | |
| 79 | 新增: document.removeEventListener("cage-add-favorite", add); | |
| 80 | 新增: document.removeEventListener("cage-show-favorites", show); | |
| 81 | 新增: document.removeEventListener("cage-close-modal", close); | |
| 82 | 新增: }; | |
| 83 | 新增: }, []); | |
| 84 | 新增: useEffect(() => { | |
| 85 | 新增: if (!open) return; | |
| 86 | 新增: search.current?.focus(); | |
| 87 | 新增: const key = (event) => { | |
| 88 | 新增: if ( | |
| 89 | 新增: event.key === "Escape" && | |
| 90 | 新增: !state.current.editor && | |
| 91 | 新增: !savingRef.current | |
| 92 | 新增: ) { | |
| 93 | 新增: event.preventDefault(); | |
| 94 | 新增: setOpen(false); | |
| 95 | 新增: } | |
| 96 | 新增: }; | |
| 97 | 新增: document.addEventListener("keydown", key); | |
| 98 | 新增: return () => { | |
| 99 | 新增: document.removeEventListener("keydown", key); | |
| 100 | 新增: toggle.current?.focus(); | |
| 101 | 新增: }; | |
| 102 | 新增: }, [open]); | |
| 103 | 新增: const mutation = async (body) => { | |
| 104 | 新增: const next = await api("/favorites", body); | |
| 105 | 新增: setData(next); | |
| 106 | 新增: return next; | |
| 107 | 新增: }; | |
| 108 | 新增: const run = async (operation) => { | |
| 109 | 新增: if (savingRef.current) return; | |
| 110 | 新增: savingRef.current = true; | |
| 111 | 新增: setSaving(true); | |
| 112 | 新增: setError(""); | |
| 113 | 新增: try { | |
| 114 | 新增: await operation(); | |
| 115 | 新增: } catch (e) { | |
| 116 | 新增: setError(e.message); | |
| 117 | 新增: } finally { | |
| 118 | 新增: savingRef.current = false; | |
| 119 | 新增: setSaving(false); | |
| 120 | 新增: } | |
| 121 | 新增: }; | |
| 122 | 新增: const save = (event) => { | |
| 123 | 新增: event.preventDefault(); | |
| 124 | 新增: void run(async () => { | |
| 125 | 新增: if (editor.kind === "folder") { | |
| 126 | 新增: await mutation({ | |
| 127 | 新增: action: "save_folder", | |
| 128 | 新增: id: editor.id || "", | |
| 129 | 新增: title: editor.title, | |
| 130 | 新增: }); | |
| 131 | 新增: } else { | |
| 132 | 新增: let folderID = editor.folder_id; | |
| 133 | 新增: if (editor.newFolder?.trim()) { | |
| 134 | 新增: const next = await mutation({ | |
| 135 | 新增: action: "save_folder", | |
| 136 | 新增: title: editor.newFolder.trim(), | |
| 137 | 新增: }); | |
| 138 | 新增: folderID = next.folders.at(-1).id; | |
| 139 | 新增: setEditor((draft) => ({ | |
| 140 | 新增: ...draft, | |
| 141 | 新增: folder_id: folderID, | |
| 142 | 新增: newFolder: "", | |
| 143 | 新增: })); | |
| 144 | 新增: } | |
| 145 | 新增: await mutation({ | |
| 146 | 新增: action: "save", | |
| 147 | 新增: id: editor.id || "", | |
| 148 | 新增: title: editor.title, | |
| 149 | 新增: url: editor.url, | |
| 150 | 新增: folder_id: folderID, | |
| 151 | 新增: }); | |
| 152 | 新增: } | |
| 153 | 新增: setEditor(null); | |
| 154 | 新增: }); | |
| 155 | 新增: }; | |
| 156 | 新增: const remove = (id, isFolder = false) => | |
| 157 | 新增: run(async () => { | |
| 158 | 新增: await mutation({ action: isFolder ? "delete_folder" : "delete", id }); | |
| 159 | 新增: if (isFolder) setFolder(""); | |
| 160 | 新增: else setEditor(null); | |
| 161 | 新增: }); | |
| 162 | 新增: const visible = (data?.items || []).filter( | |
| 163 | 新增: (item) => | |
| 164 | 新增: (folder === "all" || item.folder_id === folder) && | |
| 165 | 新增: `${item.title} ${item.url}`.toLowerCase().includes(query.toLowerCase()), | |
| 166 | 新增: ); | |
| 167 | 新增: const selectedFolder = data?.folders.find((item) => item.id === folder); | |
| 168 | 新增: return ( | |
| 169 | 新增: <> | |
| 170 | 新增: <div className="favorites-actions"> | |
| 171 | 新增: <button | |
| 172 | 新增: className={`icon-button favorite-star ${favorite ? "saved" : ""}`} | |
| 173 | 新增: aria-label={favorite ? "编辑此页收藏" : "收藏此页"} | |
| 174 | 新增: title={favorite ? "编辑此页收藏 ⌘D" : "收藏此页 ⌘D"} | |
| 175 | 新增: disabled={!canSave || !data} | |
| 176 | 新增: onClick={addCurrent} | |
| 177 | 新增: > | |
| 178 | 新增: <Star size={17} fill={favorite ? "currentColor" : "none"} /> | |
| 179 | 新增: </button> | |
| 180 | 新增: <button | |
| 181 | 新增: ref={toggle} | |
| 182 | 新增: className="icon-button" | |
| 183 | 新增: aria-label="收藏夹" | |
| 184 | 新增: title="收藏夹 ⌘⇧O" | |
| 185 | 新增: aria-expanded={open} | |
| 186 | 新增: onClick={() => (open ? setOpen(false) : show())} | |
| 187 | 新增: > | |
| 188 | 新增: <Folder size={17} /> | |
| 189 | 新增: </button> | |
| 190 | 新增: </div> | |
| 191 | 新增: {open && | |
| 192 | 新增: createPortal( | |
| 193 | 新增: <> | |
| 194 | 新增: <div | |
| 195 | 新增: className="favorites-dismiss" | |
| 196 | 新增: onClick={() => { | |
| 197 | 新增: if (!saving) setOpen(false); | |
| 198 | 新增: }} | |
| 199 | 新增: /> | |
| 200 | 新增: <section | |
| 201 | 新增: className="favorites-panel" | |
| 202 | 新增: role="dialog" | |
| 203 | 新增: aria-label="收藏夹" | |
| 204 | 新增: data-browser-dialog | |
| 205 | 新增: > | |
| 206 | 新增: <header> | |
| 207 | 新增: <h2>收藏夹</h2> | |
| 208 | 新增: <button | |
| 209 | 新增: className="icon-button" | |
| 210 | 新增: aria-label="新建收藏夹" | |
| 211 | 新增: title="新建收藏夹" | |
| 212 | 新增: disabled={!data || saving} | |
| 213 | 新增: onClick={() => { | |
| 214 | 新增: setError(""); | |
| 215 | 新增: setEditor({ kind: "folder", title: "" }); | |
| 216 | 新增: }} | |
| 217 | 新增: > | |
| 218 | 新增: <FolderPlus size={17} /> | |
| 219 | 新增: </button> | |
| 220 | 新增: <button | |
| 221 | 新增: className="icon-button" | |
| 222 | 新增: aria-label="关闭收藏夹" | |
| 223 | 新增: onClick={() => setOpen(false)} | |
| 224 | 新增: > | |
| 225 | 新增: <X size={17} /> | |
| 226 | 新增: </button> | |
| 227 | 新增: </header> | |
| 228 | 新增: <label className="favorites-search"> | |
| 229 | 新增: <Search size={15} /> | |
| 230 | 新增: <input | |
| 231 | 新增: ref={search} | |
| 232 | 新增: aria-label="搜索收藏" | |
| 233 | 新增: placeholder="搜索收藏" | |
| 234 | 新增: value={query} | |
| 235 | 新增: onChange={(event) => setQuery(event.target.value)} | |
| 236 | 新增: /> | |
| 237 | 新增: </label> | |
| 238 | 新增: <div className="favorites-folder-select"> | |
| 239 | 新增: <select | |
| 240 | 新增: aria-label="筛选收藏夹" | |
| 241 | 新增: value={folder} | |
| 242 | 新增: onChange={(event) => setFolder(event.target.value)} | |
| 243 | 新增: > | |
| 244 | 新增: <option value="all">全部收藏</option> | |
| 245 | 新增: <option value="">未分类</option> | |
| 246 | 新增: {data?.folders.map((item) => ( | |
| 247 | 新增: <option key={item.id} value={item.id}> | |
| 248 | 新增: {item.title} | |
| 249 | 新增: </option> | |
| 250 | 新增: ))} | |
| 251 | 新增: </select> | |
| 252 | 新增: {selectedFolder && ( | |
| 253 | 新增: <> | |
| 254 | 新增: <button | |
| 255 | 新增: className="icon-button" | |
| 256 | 新增: aria-label="重命名收藏夹" | |
| 257 | 新增: title="重命名收藏夹" | |
| 258 | 新增: disabled={saving} | |
| 259 | 新增: onClick={() => { | |
| 260 | 新增: setError(""); | |
| 261 | 新增: setEditor({ kind: "folder", ...selectedFolder }); | |
| 262 | 新增: }} | |
| 263 | 新增: > | |
| 264 | 新增: <Pencil size={15} /> | |
| 265 | 新增: </button> | |
| 266 | 新增: <button | |
| 267 | 新增: className="icon-button" | |
| 268 | 新增: aria-label="删除收藏夹,收藏移至未分类" | |
| 269 | 新增: title="删除收藏夹,收藏移至未分类" | |
| 270 | 新增: disabled={saving} | |
| 271 | 新增: onClick={() => remove(folder, true)} | |
| 272 | 新增: > | |
| 273 | 新增: <Trash2 size={15} /> | |
| 274 | 新增: </button> | |
| 275 | 新增: </> | |
| 276 | 新增: )} | |
| 277 | 新增: </div> | |
| 278 | 新增: {error && !editor && ( | |
| 279 | 新增: <div className="favorites-error" role="alert"> | |
| 280 | 新增: {error} | |
| 281 | 新增: <button onClick={load}>重试读取</button> | |
| 282 | 新增: </div> | |
| 283 | 新增: )} | |
| 284 | 新增: <div className="favorites-list"> | |
| 285 | 新增: {!data && !error && ( | |
| 286 | 新增: <p className="favorites-empty">正在读取收藏…</p> | |
| 287 | 新增: )} | |
| 288 | 新增: {data && visible.length === 0 && ( | |
| 289 | 新增: <div className="favorites-empty"> | |
| 290 | 新增: <Star size={24} /> | |
| 291 | 新增: <p>{query ? "没有匹配的收藏" : "这里还没有收藏"}</p> | |
| 292 | 新增: <span> | |
| 293 | 新增: {query | |
| 294 | 新增: ? "试试其他名称或网址。" | |
| 295 | 新增: : "点击地址栏旁的星标,保存常用网页。"} | |
| 296 | 新增: </span> | |
| 297 | 新增: </div> | |
| 298 | 新增: )} | |
| 299 | 新增: {visible.map((item) => ( | |
| 300 | 新增: <div className="favorite-row" key={item.id}> | |
| 301 | 新增: <button | |
| 302 | 新增: className="favorite-link" | |
| 303 | 新增: disabled={!ready || saving} | |
| 304 | 新增: title={item.url} | |
| 305 | 新增: onClick={() => | |
| 306 | 新增: run(async () => { | |
| 307 | 新增: if (await onOpen(item.url)) setOpen(false); | |
| 308 | 新增: }) | |
| 309 | 新增: } | |
| 310 | 新增: > | |
| 311 | 新增: <Star size={15} /> | |
| 312 | 新增: <span> | |
| 313 | 新增: <strong>{item.title}</strong> | |
| 314 | 新增: <small>{item.url}</small> | |
| 315 | 新增: </span> | |
| 316 | 新增: </button> | |
| 317 | 新增: <button | |
| 318 | 新增: className="icon-button" | |
| 319 | 新增: aria-label={`编辑收藏 ${item.title}`} | |
| 320 | 新增: title="编辑收藏" | |
| 321 | 新增: disabled={saving} | |
| 322 | 新增: onClick={() => { | |
| 323 | 新增: setError(""); | |
| 324 | 新增: setEditor({ kind: "item", ...item }); | |
| 325 | 新增: }} | |
| 326 | 新增: > | |
| 327 | 新增: <Pencil size={14} /> | |
| 328 | 新增: </button> | |
| 329 | 新增: </div> | |
| 330 | 新增: ))} | |
| 331 | 新增: </div> | |
| 332 | 新增: {data && ( | |
| 333 | 新增: <footer> | |
| 334 | 新增: {visible.length} 个收藏<span>保存在此 Cage 环境</span> | |
| 335 | 新增: </footer> | |
| 336 | 新增: )} | |
| 337 | 新增: </section> | |
| 338 | 新增: </>, | |
| 339 | 新增: document.body, | |
| 340 | 新增: )} | |
| 341 | 新增: {editor && | |
| 342 | 新增: createPortal( | |
| 343 | 新增: <div className="favorite-editor" data-browser-dialog> | |
| 344 | 新增: <Modal | |
| 345 | 新增: title={ | |
| 346 | 新增: editor.kind === "folder" | |
| 347 | 新增: ? editor.id | |
| 348 | 新增: ? "重命名收藏夹" | |
| 349 | 新增: : "新建收藏夹" | |
| 350 | 新增: : editor.id | |
| 351 | 新增: ? "编辑收藏" | |
| 352 | 新增: : "添加收藏" | |
| 353 | 新增: } | |
| 354 | 新增: onClose={ | |
| 355 | 新增: saving | |
| 356 | 新增: ? undefined | |
| 357 | 新增: : () => { | |
| 358 | 新增: setEditor(null); | |
| 359 | 新增: setError(""); | |
| 360 | 新增: } | |
| 361 | 新增: } | |
| 362 | 新增: footer={ | |
| 363 | 新增: <> | |
| 364 | 新增: {editor.kind === "item" && editor.id && ( | |
| 365 | 新增: <button | |
| 366 | 新增: className="favorite-remove" | |
| 367 | 新增: disabled={saving} | |
| 368 | 新增: onClick={() => remove(editor.id)} | |
| 369 | 新增: > | |
| 370 | 新增: 删除收藏 | |
| 371 | 新增: </button> | |
| 372 | 新增: )} | |
| 373 | 新增: <button | |
| 374 | 新增: disabled={saving} | |
| 375 | 新增: onClick={() => { | |
| 376 | 新增: setEditor(null); | |
| 377 | 新增: setError(""); | |
| 378 | 新增: }} | |
| 379 | 新增: > | |
| 380 | 新增: 取消 | |
| 381 | 新增: </button> | |
| 382 | 新增: <button | |
| 383 | 新增: className="primary" | |
| 384 | 新增: type="submit" | |
| 385 | 新增: form="favorite-form" | |
| 386 | 新增: disabled={saving} | |
| 387 | 新增: > | |
| 388 | 新增: {saving ? "保存中…" : "保存"} | |
| 389 | 新增: </button> | |
| 390 | 新增: </> | |
| 391 | 新增: } | |
| 392 | 新增: > | |
| 393 | 新增: <form | |
| 394 | 新增: id="favorite-form" | |
| 395 | 新增: className="favorite-form" | |
| 396 | 新增: onSubmit={save} | |
| 397 | 新增: > | |
| 398 | 新增: <label> | |
| 399 | 新增: 名称 | |
| 400 | 新增: <input | |
| 401 | 新增: aria-label="收藏名称" | |
| 402 | 新增: required | |
| 403 | 新增: maxLength={250} | |
| 404 | 新增: value={editor.title} | |
| 405 | 新增: onChange={(event) => | |
| 406 | 新增: setEditor({ ...editor, title: event.target.value }) | |
| 407 | 新增: } | |
| 408 | 新增: /> | |
| 409 | 新增: </label> | |
| 410 | 新增: {editor.kind === "item" && ( | |
| 411 | 新增: <> | |
| 412 | 新增: <label> | |
| 413 | 新增: 网址 | |
| 414 | 新增: <input | |
| 415 | 新增: aria-label="收藏网址" | |
| 416 | 新增: type="url" | |
| 417 | 新增: required | |
| 418 | 新增: value={editor.url} | |
| 419 | 新增: onChange={(event) => | |
| 420 | 新增: setEditor({ ...editor, url: event.target.value }) | |
| 421 | 新增: } | |
| 422 | 新增: /> | |
| 423 | 新增: </label> | |
| 424 | 新增: <label> | |
| 425 | 新增: 收藏夹 | |
| 426 | 新增: <select | |
| 427 | 新增: aria-label="保存到收藏夹" | |
| 428 | 新增: value={editor.folder_id} | |
| 429 | 新增: disabled={Boolean(editor.newFolder)} | |
| 430 | 新增: onChange={(event) => | |
| 431 | 新增: setEditor({ | |
| 432 | 新增: ...editor, | |
| 433 | 新增: folder_id: event.target.value, | |
| 434 | 新增: }) | |
| 435 | 新增: } | |
| 436 | 新增: > | |
| 437 | 新增: <option value="">未分类</option> | |
| 438 | 新增: {data?.folders.map((item) => ( | |
| 439 | 新增: <option key={item.id} value={item.id}> | |
| 440 | 新增: {item.title} | |
| 441 | 新增: </option> | |
| 442 | 新增: ))} | |
| 443 | 新增: </select> | |
| 444 | 新增: </label> | |
| 445 | 新增: <label> | |
| 446 | 新增: 新建收藏夹(可选) | |
| 447 | 新增: <input | |
| 448 | 新增: aria-label="新收藏夹名称" | |
| 449 | 新增: maxLength={250} | |
| 450 | 新增: placeholder="填写名称后,将收藏保存到新文件夹" | |
| 451 | 新增: value={editor.newFolder || ""} | |
| 452 | 新增: onChange={(event) => | |
| 453 | 新增: setEditor({ | |
| 454 | 新增: ...editor, | |
| 455 | 新增: newFolder: event.target.value, | |
| 456 | 新增: }) | |
| 457 | 新增: } | |
| 458 | 新增: /> | |
| 459 | 新增: </label> | |
| 460 | 新增: </> | |
| 461 | 新增: )} | |
| 462 | 新增: {error && ( | |
| 463 | 新增: <p role="alert" className="favorites-error"> | |
| 464 | 新增: {error} | |
| 465 | 新增: </p> | |
| 466 | 新增: )} | |
| 467 | 新增: </form> | |
| 468 | 新增: </Modal> | |
| 469 | 新增: </div>, | |
| 470 | 新增: document.body, | |
| 471 | 新增: )} | |
| 472 | 新增: </> | |
| 473 | 新增: ); | |
| 474 | 新增:} | |
| @@ -0,0 +1,53 @@ | ||
| 1 | 新增:import React, { useEffect, useState } from "react"; | |
| 2 | 新增:import { api } from "./api"; | |
| 3 | 新增: | |
| 4 | 新增:export function EnvironmentVersions({ status, onConfirm }) { | |
| 5 | 新增: const [data, setData] = useState(null), [error, setError] = useState(""), [loading, setLoading] = useState(false), [starting, setStarting] = useState(false); | |
| 6 | 新增: const refresh = async () => { | |
| 7 | 新增: setLoading(true); | |
| 8 | 新增: try { setData(await api("/environment/versions")); setError(""); } | |
| 9 | 新增: catch (e) { setError(e.message); } | |
| 10 | 新增: finally { setLoading(false); } | |
| 11 | 新增: }; | |
| 12 | 新增: useEffect(() => { | |
| 13 | 新增: let live = true; | |
| 14 | 新增: setLoading(true); | |
| 15 | 新增: api("/environment/versions") | |
| 16 | 新增: .then((next) => { if (live) { setData(next); setError(""); } }) | |
| 17 | 新增: .catch((e) => { if (live) setError(e.message); }) | |
| 18 | 新增: .finally(() => { if (live) setLoading(false); }); | |
| 19 | 新增: return () => { live = false; }; | |
| 20 | 新增: }, [status.vm_running, status.job?.running]); | |
| 21 | 新增: const busy = Boolean(status.job?.running) || starting; | |
| 22 | 新增: const update = async (tools) => { | |
| 23 | 新增: if (!(await onConfirm({ | |
| 24 | 新增: title: tools ? "更新环境工具?" : "更新环境组件?", | |
| 25 | 新增: body: "请先保存浏览器和编辑器中的内容。浏览器、编辑器会短暂重启,编辑器内的终端可能结束;工作台终端、项目文件和登录状态会保留。", | |
| 26 | 新增: confirm: tools ? "更新工具" : "更新组件", | |
| 27 | 新增: }))) return; | |
| 28 | 新增: setStarting(true); setError(""); | |
| 29 | 新增: try { await api(tools ? "/environment/tools" : "/environment/update", {}); } | |
| 30 | 新增: catch (e) { setError(e.message); } | |
| 31 | 新增: finally { setStarting(false); } | |
| 32 | 新增: }; | |
| 33 | 新增: const componentLabels = { current: "已同步", update_required: "需要更新", stopped: "环境已停止", unknown: "暂时无法确认" }; | |
| 34 | 新增: const toolNames = { chromium: "浏览器", code_server: "文件编辑器", claude: "Claude Code", mise: "工具版本管理器", proxy: "代理核心" }; | |
| 35 | 新增: return ( | |
| 36 | 新增: <section className="environment-versions" aria-label="环境版本"> | |
| 37 | 新增: <h4>版本与组件</h4> | |
| 38 | 新增: <div className="setting-summary-row"><span>控制服务</span><strong>{data?.controller?.version || "—"}</strong></div> | |
| 39 | 新增: <div className="setting-summary-row"><span>环境组件</span><strong>{componentLabels[data?.components?.status] || (loading ? "正在读取…" : "暂时无法确认")}</strong></div> | |
| 40 | 新增: {data?.tools && <table className="environment-tool-table"> | |
| 41 | 新增: <thead><tr><th>工具</th><th>当前版本</th><th>受管版本</th></tr></thead> | |
| 42 | 新增: <tbody>{Object.entries(toolNames).map(([key, name]) => <tr key={key}><td>{name}</td><td>{data.tools[key]?.current || "—"}</td><td>{data.tools[key]?.required || "—"}</td></tr>)}</tbody> | |
| 43 | 新增: </table>} | |
| 44 | 新增: {(error || data?.error) && <p role="alert" className="error-message">{error || data.error}</p>} | |
| 45 | 新增: <div className="environment-version-actions"> | |
| 46 | 新增: <button disabled={loading || busy} onClick={refresh}>{loading ? "正在读取…" : "刷新版本"}</button> | |
| 47 | 新增: {data?.components?.update_required && <button className="primary" disabled={busy || !status.vm_running} onClick={() => update(false)}>更新环境组件</button>} | |
| 48 | 新增: <button disabled={busy || !data?.tools_update_allowed} onClick={() => update(true)}>更新环境工具</button> | |
| 49 | 新增: </div> | |
| 50 | 新增: <p className="field-help">组件更新保留虚拟磁盘与终端。工具更新需先启动环境、同步组件并通过网络检查;手动暂停外网时不会自动恢复连接。</p> | |
| 51 | 新增: </section> | |
| 52 | 新增: ); | |
| 53 | 新增:} | |
二进制文件,不显示改动。
| @@ -1,3 +1,4 @@ | ||
| 1 | 新增:import logo from "./logo.png"; | |
| 1 | 2 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | 3 | import { createRoot } from "react-dom/client"; |
| 3 | 4 | import { |
| @@ -26,6 +27,8 @@ import { AppearanceProvider } from "./appearance"; | ||
| 26 | 27 | import { EnvironmentShield } from "./environment-shield"; |
| 27 | 28 | import { WorkspaceSidebar } from "./workspace-sidebar"; |
| 28 | 29 | import { WorkspaceTabs } from "./workspace-tabs"; |
| 30 | 新增:import { BrowserFavorites } from "./browser-favorites"; | |
| 31 | 新增:import { BrowserDownloads, useDownloadNotifications } from "./browser-downloads"; | |
| 29 | 32 | import { ProjectDialog } from "./project-dialog"; |
| 30 | 33 | import { |
| 31 | 34 | readLocal, |
| @@ -37,11 +40,19 @@ import { SafetyPanel } from "./safety"; | ||
| 37 | 40 | import { networkState, isGuestLocalURL } from "./safety-state.mjs"; |
| 38 | 41 | import { needsProxySetup } from "./onboarding-state.mjs"; |
| 39 | 42 | import { HostGitPreparation } from "./host-git"; |
| 43 | 新增:import { NetworkLatency } from "./network-latency"; | |
| 44 | 新增:import { useWindowVisibility } from "./window-visibility"; | |
| 45 | 新增:import { AppUpdateButton, useAppUpdates } from "./app-updates"; | |
| 40 | 46 | import "./style.css"; |
| 41 | 47 | import "./appearance.css"; |
| 42 | 48 | import { stopAndExit } from "./quit"; |
| 43 | 49 | |
| 44 | 50 | function App() { |
| 51 | 新增: const appUpdates = useAppUpdates(); | |
| 52 | 新增: const [recoveringEditor, setRecoveringEditor] = useState(false); | |
| 53 | 新增: const windowVisible = useWindowVisibility(); | |
| 54 | 新增: const windowVisibleRef = useRef(windowVisible); | |
| 55 | 新增: windowVisibleRef.current = windowVisible; | |
| 45 | 56 | const [status, setStatus] = useState(null), |
| 46 | 57 | [settings, setSettings] = useState(null), |
| 47 | 58 | [proxy, setProxy] = useState(null), |
| @@ -76,6 +87,10 @@ function App() { | ||
| 76 | 87 | readyRef = useRef(false), |
| 77 | 88 | browserIds = useRef(new Set()), |
| 78 | 89 | initialized = useRef(false), |
| 90 | 新增: browserStreamReady = useRef(false), | |
| 91 | 新增: browserSnapshot = useRef({ tabs: [] }), | |
| 92 | 新增: refreshStatus = useRef(null), | |
| 93 | 新增: launchAcknowledged = useRef(false), | |
| 79 | 94 | lastJob = useRef(""), |
| 80 | 95 | quitAfterStop = useRef(null); |
| 81 | 96 | activeRef.current = active; |
| @@ -109,9 +124,10 @@ function App() { | ||
| 109 | 124 | ? "运行中" |
| 110 | 125 | : "离线可用" |
| 111 | 126 | : running |
| 112 | 删除: ? "浏览器待恢复" | |
| 127 | 新增: ? status?.environment_update_required ? "环境待更新" : "浏览器待恢复" | |
| 113 | 128 | : "已停止"; |
| 114 | 129 | const notify = (text) => setToast(text); |
| 130 | 新增: useDownloadNotifications(browser.downloads, notify); | |
| 115 | 131 | const refreshSettings = async () => { |
| 116 | 132 | const results = await Promise.allSettled([api("/settings"), api("/proxy")]); |
| 117 | 133 | if (results[0].status === "fulfilled") setSettings(results[0].value); |
| @@ -316,11 +332,17 @@ function App() { | ||
| 316 | 332 | }; |
| 317 | 333 | useEffect(() => { |
| 318 | 334 | let live = true, |
| 319 | 删除: timer; | |
| 335 | 新增: timer, | |
| 336 | 新增: polling = false; | |
| 320 | 337 | const poll = async () => { |
| 338 | 新增: if (!live || polling) return; | |
| 339 | 新增: clearTimeout(timer); | |
| 340 | 新增: polling = true; | |
| 341 | 新增: let jobRunning = false; | |
| 321 | 342 | try { |
| 322 | 343 | const next = await api("/status"); |
| 323 | 344 | if (!live) return; |
| 345 | 新增: jobRunning = next.job.running; | |
| 324 | 346 | setStatus(next); |
| 325 | 347 | setConnectionError(""); |
| 326 | 348 | if ( |
| @@ -333,11 +355,14 @@ function App() { | ||
| 333 | 355 | if (next.job.error) notify(next.job.error); |
| 334 | 356 | } |
| 335 | 357 | if (next.ready) { |
| 336 | 删除: const [b, t] = await Promise.all([ | |
| 337 | 删除: api("/browser/tabs"), | |
| 358 | 新增: const fetchBrowser = !browserStreamReady.current || !initialized.current; | |
| 359 | 新增: const [browserResult, t] = await Promise.all([ | |
| 360 | 新增: fetchBrowser ? api("/browser/tabs") : null, | |
| 338 | 361 | api("/terminals"), |
| 339 | 362 | ]); |
| 340 | 363 | if (!live) return; |
| 364 | 新增: const b = browserResult || browserSnapshot.current; | |
| 365 | 新增: browserSnapshot.current = b; | |
| 341 | 366 | setBrowser(b); |
| 342 | 367 | const all = [ |
| 343 | 368 | ...b.tabs, |
| @@ -371,8 +396,14 @@ function App() { | ||
| 371 | 396 | } |
| 372 | 397 | } catch (e) { |
| 373 | 398 | if (live) setConnectionError(e.message); |
| 399 | 新增: } finally { | |
| 400 | 新增: polling = false; | |
| 401 | 新增: if (live) | |
| 402 | 新增: timer = setTimeout( | |
| 403 | 新增: poll, | |
| 404 | 新增: jobRunning ? 1200 : windowVisibleRef.current ? 3000 : 15000, | |
| 405 | 新增: ); | |
| 374 | 406 | } |
| 375 | 删除: if (live) timer = setTimeout(poll, 1200); | |
| 376 | 407 | }; |
| 377 | 408 | (async () => { |
| 378 | 409 | try { |
| @@ -392,6 +423,7 @@ function App() { | ||
| 392 | 423 | } catch { |
| 393 | 424 | // Network settings remain available when the core cannot be read. |
| 394 | 425 | } |
| 426 | 新增: refreshStatus.current = poll; | |
| 395 | 427 | await poll(); |
| 396 | 428 | } catch (e) { |
| 397 | 429 | if (live) setFatal(e.message); |
| @@ -399,14 +431,31 @@ function App() { | ||
| 399 | 431 | })(); |
| 400 | 432 | return () => { |
| 401 | 433 | live = false; |
| 434 | 新增: refreshStatus.current = null; | |
| 402 | 435 | clearTimeout(timer); |
| 403 | 436 | }; |
| 404 | 437 | }, []); |
| 438 | 新增: useEffect(() => { | |
| 439 | 新增: if (windowVisible) refreshStatus.current?.(); | |
| 440 | 新增: }, [windowVisible]); | |
| 441 | 新增: useEffect(() => { | |
| 442 | 新增: if (!settings || !status || fatal || connectionError || launchAcknowledged.current || !nativeAvailable()) return; | |
| 443 | 新增: // Effects run after the workbench render commits. HTML navigation alone | |
| 444 | 新增: // cannot confirm a successful upgrade when session/API startup failed. | |
| 445 | 新增: let live = true; | |
| 446 | 新增: native("workbenchReady").then((accepted) => { | |
| 447 | 新增: if (live && accepted === true) launchAcknowledged.current = true; | |
| 448 | 新增: }).catch(() => {}); | |
| 449 | 新增: return () => { live = false; }; | |
| 450 | 新增: }, [settings, status, fatal, connectionError]); | |
| 405 | 451 | useEffect(() => { |
| 406 | 452 | if (!status?.ready) return; |
| 407 | 453 | const stream = new EventSource("/api/browser/events"); |
| 454 | 新增: stream.onopen = () => { browserStreamReady.current = true; }; | |
| 455 | 新增: stream.onerror = () => { browserStreamReady.current = false; }; | |
| 408 | 456 | stream.onmessage = (event) => { |
| 409 | 457 | const b = JSON.parse(event.data); |
| 458 | 新增: browserSnapshot.current = b; | |
| 410 | 459 | setBrowser((previous) => ({ ...previous, ...b })); |
| 411 | 460 | setTabs((previous) => { |
| 412 | 461 | const map = new Map(b.tabs.map((t) => [t.id, t])); |
| @@ -426,7 +475,10 @@ function App() { | ||
| 426 | 475 | setActive(b.active); |
| 427 | 476 | browserIds.current = new Set(b.tabs.map((t) => t.id)); |
| 428 | 477 | }; |
| 429 | 删除: return () => stream.close(); | |
| 478 | 新增: return () => { | |
| 479 | 新增: browserStreamReady.current = false; | |
| 480 | 新增: stream.close(); | |
| 481 | 新增: }; | |
| 430 | 482 | }, [status?.ready]); |
| 431 | 483 | useEffect(() => { |
| 432 | 484 | if (current && current.kind !== "terminal") |
| @@ -451,6 +503,14 @@ function App() { | ||
| 451 | 503 | const key = (event) => { |
| 452 | 504 | if (!event.metaKey) return; |
| 453 | 505 | const k = event.key.toLowerCase(); |
| 506 | 新增: if (document.querySelector("[data-browser-dialog]")) { | |
| 507 | 新增: if (k === "w") { | |
| 508 | 新增: event.preventDefault(); | |
| 509 | 新增: event.stopImmediatePropagation(); | |
| 510 | 新增: document.dispatchEvent(new Event("cage-close-modal")); | |
| 511 | 新增: } | |
| 512 | 新增: return; | |
| 513 | 新增: } | |
| 454 | 514 | if (dialog) { |
| 455 | 515 | if (k === "w") { |
| 456 | 516 | event.preventDefault(); |
| @@ -487,10 +547,15 @@ function App() { | ||
| 487 | 547 | if (k === "o") { |
| 488 | 548 | event.preventDefault(); |
| 489 | 549 | event.stopImmediatePropagation(); |
| 550 | 新增: if (event.shiftKey) { | |
| 551 | 新增: document.dispatchEvent(new Event("cage-show-favorites")); | |
| 552 | 新增: return; | |
| 553 | 新增: } | |
| 490 | 554 | if (!busy && running) setProjectDialog({ path: "" }); |
| 491 | 555 | return; |
| 492 | 556 | } |
| 493 | 557 | if (k === "t" && !event.shiftKey) handle = newPage; |
| 558 | 新增: if (k === "d") handle = () => document.dispatchEvent(new Event("cage-add-favorite")); | |
| 494 | 559 | if (k === "enter" && event.shiftKey) handle = newTerminalHere; |
| 495 | 560 | if (k === "l") |
| 496 | 561 | handle = () => { |
| @@ -571,6 +636,10 @@ function App() { | ||
| 571 | 636 | if (command === "newTerminal" && status?.vm_running) |
| 572 | 637 | await newTerminalHere(); |
| 573 | 638 | if (command === "closeTab") { |
| 639 | 新增: if (document.querySelector("[data-browser-dialog]")) { | |
| 640 | 新增: document.dispatchEvent(new Event("cage-close-modal")); | |
| 641 | 新增: return; | |
| 642 | 新增: } | |
| 574 | 643 | if (dialog) { |
| 575 | 644 | const resolve = dialog.resolve; |
| 576 | 645 | setDialog(null); |
| @@ -664,7 +733,14 @@ function App() { | ||
| 664 | 733 | { ...savedTabs, [tabLayoutKey]: next }, |
| 665 | 734 | setSavedTabs, |
| 666 | 735 | ); |
| 667 | 删除: const reorder = (from, to) => { | |
| 736 | 新增: const reorder = (from, to, scopeOrder) => { | |
| 737 | 新增: if (scopeOrder) { | |
| 738 | 新增: const ids = new Set(scopeOrder); | |
| 739 | 新增: let index = 0; | |
| 740 | 新增: const order = displayTabs.map((tab) => ids.has(tab.id) ? scopeOrder[index++] : tab.id); | |
| 741 | 新增: changeTabMetadata({ ...metadata, order }); | |
| 742 | 新增: return; | |
| 743 | 新增: } | |
| 668 | 744 | if (from === to) return; |
| 669 | 745 | const order = displayTabs.map((tab) => tab.id).filter((id) => id !== from); |
| 670 | 746 | order.splice(order.indexOf(to), 0, from); |
| @@ -802,6 +878,7 @@ function App() { | ||
| 802 | 878 | > |
| 803 | 879 | {!sidebarCollapsed && ( |
| 804 | 880 | <WorkspaceSidebar |
| 881 | 新增: updateAction={<AppUpdateButton updates={appUpdates} />} | |
| 805 | 882 | workspace={selectedProject || status.workspace} |
| 806 | 883 | defaultWorkspace={status.environment_directory} |
| 807 | 884 | projects={projects} |
| @@ -838,7 +915,7 @@ function App() { | ||
| 838 | 915 | <div className="browser-tab-bar"> |
| 839 | 916 | {sidebarCollapsed && ( |
| 840 | 917 | <button |
| 841 | 删除: className="icon-button" | |
| 918 | 新增: className="icon-button sidebar-expand" | |
| 842 | 919 | aria-label="展开侧栏" |
| 843 | 920 | onClick={() => |
| 844 | 921 | persist( |
| @@ -848,7 +925,8 @@ function App() { | ||
| 848 | 925 | ) |
| 849 | 926 | } |
| 850 | 927 | > |
| 851 | 删除: <PanelLeftOpen size={18} /> | |
| 928 | 新增: <img className="sidebar-expand-logo" src={logo} alt="" /> | |
| 929 | 新增: <PanelLeftOpen className="sidebar-expand-icon" size={18} /> | |
| 852 | 930 | </button> |
| 853 | 931 | )} |
| 854 | 932 | <WorkspaceTabs |
| @@ -879,7 +957,7 @@ function App() { | ||
| 879 | 957 | <div className="content-heading"> |
| 880 | 958 | {sidebarCollapsed && ( |
| 881 | 959 | <button |
| 882 | 删除: className="icon-button" | |
| 960 | 新增: className="icon-button sidebar-expand" | |
| 883 | 961 | aria-label="展开侧栏" |
| 884 | 962 | title="展开侧栏" |
| 885 | 963 | onClick={() => |
| @@ -890,7 +968,8 @@ function App() { | ||
| 890 | 968 | ) |
| 891 | 969 | } |
| 892 | 970 | > |
| 893 | 删除: <PanelLeftOpen size={18} /> | |
| 971 | 新增: <img className="sidebar-expand-logo" src={logo} alt="" /> | |
| 972 | 新增: <PanelLeftOpen className="sidebar-expand-icon" size={18} /> | |
| 894 | 973 | </button> |
| 895 | 974 | )} |
| 896 | 975 | <div className="content-breadcrumb"> |
| @@ -1003,6 +1082,15 @@ function App() { | ||
| 1003 | 1082 | <ArrowUpRight size={15} /> |
| 1004 | 1083 | </button> |
| 1005 | 1084 | </form> |
| 1085 | 新增: <BrowserFavorites current={current} ready={status.ready && !busy} onOpen={openBrowserPage} /> | |
| 1086 | 新增: <BrowserDownloads downloads={browser.downloads} ready={status.ready && !busy} onStatus={notify} /> | |
| 1087 | 新增: {current?.kind === "editor" && <button className="icon-button" aria-label="恢复编辑器" title="单独重启编辑器" disabled={!status.ready || busy || recoveringEditor} onClick={async () => { | |
| 1088 | 新增: if (!(await confirm({ title: "重启编辑器?", body: "请先保存文件。浏览器、终端和环境会继续运行。", confirm: "重启编辑器" }))) return; | |
| 1089 | 新增: setRecoveringEditor(true); | |
| 1090 | 新增: try { await api("/browser/editor-restart", { workspace: current.workspace || contentWorkspace }); notify("编辑器已恢复"); } | |
| 1091 | 新增: catch (error) { notify(error.message); } | |
| 1092 | 新增: finally { setRecoveringEditor(false); } | |
| 1093 | 新增: }}><RefreshCw size={15} className={recoveringEditor ? "spin" : ""} /></button>} | |
| 1006 | 1094 | <div className="clipboard-actions"> |
| 1007 | 1095 | <button |
| 1008 | 1096 | className="icon-button" |
| @@ -1085,6 +1173,12 @@ function App() { | ||
| 1085 | 1173 | </div> |
| 1086 | 1174 | )} |
| 1087 | 1175 | <main className="workspace"> |
| 1176 | 新增: {status.environment_update_required && !busy && ( | |
| 1177 | 新增: <div className="environment-update-banner" role="status"> | |
| 1178 | 新增: <span>{status.environment_update_error || "环境组件需要更新。请先保存编辑器中的文件。"}</span> | |
| 1179 | 新增: <button onClick={() => openSettings("project")}>查看并更新</button> | |
| 1180 | 新增: </div> | |
| 1181 | 新增: )} | |
| 1088 | 1182 | {(status.vm_running || terminal) && ( |
| 1089 | 1183 | <> |
| 1090 | 1184 | {status.ready ? ( |
| @@ -1092,6 +1186,7 @@ function App() { | ||
| 1092 | 1186 | ref={remote} |
| 1093 | 1187 | visible={Boolean(showRemote && !settingsOpen)} |
| 1094 | 1188 | keyboard={status.keyboard} |
| 1189 | 新增: tabId={current?.id} | |
| 1095 | 1190 | onStatus={notify} |
| 1096 | 1191 | onFallback={(text, message) => |
| 1097 | 1192 | setTransfer({ text, message }) |
| @@ -1317,6 +1412,7 @@ function App() { | ||
| 1317 | 1412 | )} |
| 1318 | 1413 | </main> |
| 1319 | 1414 | <footer className="status-bar"> |
| 1415 | 新增: {sidebarCollapsed && <AppUpdateButton updates={appUpdates} />} | |
| 1320 | 1416 | <button onClick={() => setSafetyOpen(true)} title="网络与隔离检查"> |
| 1321 | 1417 | <EnvironmentShield |
| 1322 | 1418 | size={14} |
| @@ -1340,6 +1436,13 @@ function App() { | ||
| 1340 | 1436 | {settings.timezone} |
| 1341 | 1437 | {settings.auto_timezone ? " · 自动" : ""} |
| 1342 | 1438 | </button> |
| 1439 | 新增: <span className="status-divider" /> | |
| 1440 | 新增: <NetworkLatency | |
| 1441 | 新增: key={`${proxy?.selected}:${proxy?.revision}:${running}:${busy}:${Boolean(connectionError)}`} | |
| 1442 | 新增: enabled={running && !busy && !connectionError} | |
| 1443 | 新增: revision={proxy?.revision} | |
| 1444 | 新增: selected={proxy?.selected} | |
| 1445 | 新增: /> | |
| 1343 | 1446 | <span className="status-spacer" /> |
| 1344 | 1447 | <span className="status-feedback" role="status"> |
| 1345 | 1448 | {toast || |
| @@ -0,0 +1,78 @@ | ||
| 1 | 新增:import React, { useEffect, useState } from "react"; | |
| 2 | 新增:import { Activity } from "lucide-react"; | |
| 3 | 新增:import { api } from "./api"; | |
| 4 | 新增: | |
| 5 | 新增:export function NetworkLatency({ enabled, revision, selected }) { | |
| 6 | 新增: const [sample, setSample] = useState(null), | |
| 7 | 新增: [retry, setRetry] = useState(0); | |
| 8 | 新增: useEffect(() => { | |
| 9 | 新增: if (!enabled) return; | |
| 10 | 新增: let cancelled = false, | |
| 11 | 新增: timer; | |
| 12 | 新增: const measure = async () => { | |
| 13 | 新增: try { | |
| 14 | 新增: const proxy = await api("/proxy"); | |
| 15 | 新增: if (cancelled) return; | |
| 16 | 新增: if (!proxy.active || !proxy.running || !proxy.selected) { | |
| 17 | 新增: setSample({ label: "延迟 —", detail: "当前代理未连接" }); | |
| 18 | 新增: } else { | |
| 19 | 新增: const result = await api("/proxy/delay", { node_id: proxy.selected }); | |
| 20 | 新增: if (cancelled) return; | |
| 21 | 新增: const current = await api("/proxy"); | |
| 22 | 新增: if (cancelled) return; | |
| 23 | 新增: if ( | |
| 24 | 新增: !current.active || | |
| 25 | 新增: !current.running || | |
| 26 | 新增: current.selected !== proxy.selected || | |
| 27 | 新增: current.revision !== proxy.revision | |
| 28 | 新增: ) { | |
| 29 | 新增: setSample(null); | |
| 30 | 新增: } else if (Number.isFinite(result.delay) && result.delay > 0) { | |
| 31 | 新增: setSample({ | |
| 32 | 新增: label: `${Math.round(result.delay)} ms`, | |
| 33 | 新增: detail: | |
| 34 | 新增: "当前节点到 www.gstatic.com 的 HTTP 延迟;每 30 秒更新,点击重新检测。节点连通性与环境外网放行分别检查。", | |
| 35 | 新增: }); | |
| 36 | 新增: } else { | |
| 37 | 新增: setSample({ | |
| 38 | 新增: label: "延迟不可用", | |
| 39 | 新增: detail: "当前节点测速未成功,点击重试", | |
| 40 | 新增: }); | |
| 41 | 新增: } | |
| 42 | 新增: } | |
| 43 | 新增: } catch { | |
| 44 | 新增: if (!cancelled) | |
| 45 | 新增: setSample({ | |
| 46 | 新增: label: "延迟不可用", | |
| 47 | 新增: detail: "无法测量当前节点延迟,点击重试", | |
| 48 | 新增: }); | |
| 49 | 新增: } finally { | |
| 50 | 新增: if (!cancelled) timer = setTimeout(measure, 30000); | |
| 51 | 新增: } | |
| 52 | 新增: }; | |
| 53 | 新增: measure(); | |
| 54 | 新增: return () => { | |
| 55 | 新增: cancelled = true; | |
| 56 | 新增: clearTimeout(timer); | |
| 57 | 新增: }; | |
| 58 | 新增: }, [enabled, revision, selected, retry]); | |
| 59 | 新增: return ( | |
| 60 | 新增: <button | |
| 61 | 新增: className="status-latency" | |
| 62 | 新增: aria-label={`网络延迟:${enabled ? sample?.label || "检测中" : "未连接"}`} | |
| 63 | 新增: title={ | |
| 64 | 新增: enabled | |
| 65 | 新增: ? sample?.detail || "正在检测当前节点的网络延迟" | |
| 66 | 新增: : "环境启动并连接代理后检测网络延迟" | |
| 67 | 新增: } | |
| 68 | 新增: disabled={!enabled} | |
| 69 | 新增: onClick={() => { | |
| 70 | 新增: setSample(null); | |
| 71 | 新增: setRetry((value) => value + 1); | |
| 72 | 新增: }} | |
| 73 | 新增: > | |
| 74 | 新增: <Activity size={12} /> | |
| 75 | 新增: <span>{enabled ? sample?.label || "测延迟…" : "延迟 —"}</span> | |
| 76 | 新增: </button> | |
| 77 | 新增: ); | |
| 78 | 新增:} | |
| @@ -6,7 +6,7 @@ import { readClipboard, writeClipboard, nativeAvailable } from "./api"; | ||
| 6 | 6 | export function installRemoteInput( |
| 7 | 7 | rfb, |
| 8 | 8 | container, |
| 9 | 删除: { mode, onStatus, onFallback, isActive }, | |
| 9 | 新增: { mode, onStatus, onFallback, isActive, insertText }, | |
| 10 | 10 | ) { |
| 11 | 11 | const listeners = [], |
| 12 | 12 | handled = new Set(), |
| @@ -16,12 +16,17 @@ export function installRemoteInput( | ||
| 16 | 16 | copyRequested = false, |
| 17 | 17 | copyTimer, |
| 18 | 18 | pending = 0, |
| 19 | 新增: composing = false, | |
| 19 | 20 | disposed = false; |
| 20 | 21 | const target = document.createElement("textarea"); |
| 21 | 删除: target.setAttribute("aria-label", "远程粘贴接收区"); | |
| 22 | 删除: target.style.cssText = | |
| 23 | 删除: "position:fixed;left:-10000px;top:0;width:1px;height:1px"; | |
| 24 | 删除: document.body.append(target); | |
| 22 | 新增: target.setAttribute("aria-label", "Cage 网页输入"); | |
| 23 | 新增: target.setAttribute("autocomplete", "off"); | |
| 24 | 新增: target.setAttribute("autocapitalize", "off"); | |
| 25 | 新增: target.spellcheck = false; | |
| 26 | 新增: target.className = "remote-text-input"; | |
| 27 | 新增: target.style.cssText = "position:fixed;left:0;top:0"; | |
| 28 | 新增: container.append(target); | |
| 29 | 新增: rfb.cageSetKeyboardTarget(target); | |
| 25 | 30 | const on = (object, type, fn, options) => { |
| 26 | 31 | object.addEventListener(type, fn, options); |
| 27 | 32 | listeners.push(() => object.removeEventListener(type, fn, options)); |
| @@ -30,6 +35,51 @@ export function installRemoteInput( | ||
| 30 | 35 | isActive() && |
| 31 | 36 | (container.contains(document.activeElement) || |
| 32 | 37 | document.activeElement === target); |
| 38 | 新增: const position = (x, y) => { | |
| 39 | 新增: if (composing) return; | |
| 40 | 新增: target.style.left = `${Math.max(0, Math.min(x, window.innerWidth - 280))}px`; | |
| 41 | 新增: target.style.top = `${Math.max(0, Math.min(y, window.innerHeight - 36))}px`; | |
| 42 | 新增: }; | |
| 43 | 新增: const bounds = container.getBoundingClientRect(); | |
| 44 | 新增: position(bounds.left + 12, bounds.top + 12); | |
| 45 | 新增: on( | |
| 46 | 新增: container, | |
| 47 | 新增: "pointerdown", | |
| 48 | 新增: (event) => position(event.clientX, event.clientY), | |
| 49 | 新增: true, | |
| 50 | 新增: ); | |
| 51 | 新增: const commit = (text) => { | |
| 52 | 新增: if (disposed || !isActive() || !text) return; | |
| 53 | 新增: // X0tigervnc cannot map arbitrary Unicode to its finite X11 keycode pool. | |
| 54 | 新增: // The browser inserts committed text directly, without clipboard mutation. | |
| 55 | 新增: insertText(text).catch(() => { | |
| 56 | 新增: if (!disposed) onStatus("文字输入未完成,请重新连接画面后重试"); | |
| 57 | 新增: }); | |
| 58 | 新增: }; | |
| 59 | 新增: const resetComposition = () => { | |
| 60 | 新增: composing = false; | |
| 61 | 新增: target.value = ""; | |
| 62 | 新增: }; | |
| 63 | 新增: on(target, "compositionstart", () => { | |
| 64 | 新增: composing = true; | |
| 65 | 新增: }); | |
| 66 | 新增: on(target, "compositionend", (event) => { | |
| 67 | 新增: if (composing) commit(event.data || ""); | |
| 68 | 新增: resetComposition(); | |
| 69 | 新增: }); | |
| 70 | 新增: on(target, "input", (event) => { | |
| 71 | 新增: if (composing || event.isComposing) return; | |
| 72 | 新增: // WebKit may deliver the final input after compositionend. That text has | |
| 73 | 新增: // already been sent. Input without composition covers emoji and dictation. | |
| 74 | 新增: if ( | |
| 75 | 新增: !["insertFromComposition", "insertCompositionText"].includes( | |
| 76 | 新增: event.inputType, | |
| 77 | 新增: ) | |
| 78 | 新增: ) | |
| 79 | 新增: commit(target.value); | |
| 80 | 新增: target.value = ""; | |
| 81 | 新增: }); | |
| 82 | 新增: on(target, "blur", resetComposition); | |
| 33 | 83 | const say = (text) => { |
| 34 | 84 | if (!disposed) onStatus(text); |
| 35 | 85 | }; |
| @@ -96,6 +146,17 @@ export function installRemoteInput( | ||
| 96 | 146 | "keydown", |
| 97 | 147 | (event) => { |
| 98 | 148 | if (!focused()) return; |
| 149 | 新增: if ( | |
| 150 | 新增: composing || | |
| 151 | 新增: event.isComposing || | |
| 152 | 新增: event.keyCode === 229 || | |
| 153 | 新增: ["Process", "Dead"].includes(event.key) | |
| 154 | 新增: ) { | |
| 155 | 新增: // Leave the default action to the host IME; noVNC must not cancel it | |
| 156 | 新增: // or send candidate navigation/confirmation keys into the guest. | |
| 157 | 新增: event.stopImmediatePropagation(); | |
| 158 | 新增: return; | |
| 159 | 新增: } | |
| 99 | 160 | const code = getKeycode(event), |
| 100 | 161 | mapping = mode() === "mac", |
| 101 | 162 | malformedCommandLetter = |
| @@ -181,6 +242,8 @@ export function installRemoteInput( | ||
| 181 | 242 | "keyup", |
| 182 | 243 | (event) => { |
| 183 | 244 | const code = getKeycode(event); |
| 245 | 新增: // noVNC ignores releases for keys it never sent. Let keyup through so a | |
| 246 | 新增: // modifier pressed before composition can still be released normally. | |
| 184 | 247 | physical.delete(code); |
| 185 | 248 | if (remote.has(code)) { |
| 186 | 249 | rfb.sendKey(remote.get(code), code, false); |
| @@ -215,6 +278,7 @@ export function installRemoteInput( | ||
| 215 | 278 | paste, |
| 216 | 279 | text: () => lastText, |
| 217 | 280 | edit(action) { |
| 281 | 新增: if (composing) return false; | |
| 218 | 282 | if (action === "copy") copy(); |
| 219 | 283 | else if (action === "cut") copy("x"); |
| 220 | 284 | else if (action === "paste") void readAndPaste(); |
| @@ -235,6 +299,7 @@ export function installRemoteInput( | ||
| 235 | 299 | clearTimeout(copyTimer); |
| 236 | 300 | release(); |
| 237 | 301 | listeners.forEach((remove) => remove()); |
| 302 | 新增: rfb.cageSetKeyboardTarget(null); | |
| 238 | 303 | target.remove(); |
| 239 | 304 | }, |
| 240 | 305 | }; |
| @@ -15,24 +15,33 @@ function fixture(native = false) { | ||
| 15 | 15 | local = {}, |
| 16 | 16 | keys = [], |
| 17 | 17 | pastes = [], |
| 18 | 新增: texts = [], | |
| 18 | 19 | writes = [], |
| 19 | 20 | statuses = []; |
| 20 | 21 | let reads = 0, |
| 21 | 22 | mode = "mac"; |
| 22 | 23 | doc.activeElement = canvas; |
| 23 | 24 | doc.body = { append() {} }; |
| 24 | 删除: doc.createElement = () => ({ | |
| 25 | 新增: const target = Object.assign(new EventTarget(), { | |
| 26 | 新增: value: "", | |
| 25 | 27 | style: {}, |
| 28 | 新增: classList: { add() {}, remove() {} }, | |
| 26 | 29 | setAttribute() {}, |
| 27 | 30 | focus() { |
| 28 | 31 | doc.activeElement = this; |
| 29 | 32 | }, |
| 30 | 33 | remove() {}, |
| 31 | 34 | }); |
| 35 | 新增: doc.createElement = () => target; | |
| 36 | 新增: win.innerWidth = 1280; | |
| 37 | 新增: win.innerHeight = 800; | |
| 32 | 38 | const rfb = new EventTarget(); |
| 39 | 新增: rfb.cageSetKeyboardTarget = (element) => { | |
| 40 | 新增: rfb.target = element; | |
| 41 | 新增: }; | |
| 33 | 42 | rfb.sendKey = (...args) => keys.push(args); |
| 34 | 43 | rfb.focus = () => { |
| 35 | 删除: doc.activeElement = canvas; | |
| 44 | 新增: doc.activeElement = rfb.target || canvas; | |
| 36 | 45 | }; |
| 37 | 46 | rfb.cagePasteText = (text) => { |
| 38 | 47 | pastes.push(text); |
| @@ -57,16 +66,27 @@ function fixture(native = false) { | ||
| 57 | 66 | getKeysym: (e) => |
| 58 | 67 | ({ Shift: 0xffe1, Control: 0xffe3, Alt: 0xffe9, Meta: 0xffeb })[e.key] ?? |
| 59 | 68 | (e.key.length === 1 ? e.key.codePointAt(0) : null), |
| 69 | 新增: Keysyms: { | |
| 70 | 新增: lookup: (codepoint) => | |
| 71 | 新增: codepoint <= 255 ? codepoint : 0x01000000 | codepoint, | |
| 72 | 新增: }, | |
| 60 | 73 | }; |
| 61 | 74 | const install = vm.runInNewContext(source + "\ninstallRemoteInput;", context); |
| 62 | 75 | const controller = install( |
| 63 | 76 | rfb, |
| 64 | 删除: { contains: (element) => element === canvas }, | |
| 77 | 新增: Object.assign(new EventTarget(), { | |
| 78 | 新增: contains: (element) => element === canvas || element === target, | |
| 79 | 新增: append() {}, | |
| 80 | 新增: getBoundingClientRect: () => ({ left: 0, top: 0 }), | |
| 81 | 新增: }), | |
| 65 | 82 | { |
| 66 | 83 | mode: () => mode, |
| 67 | 84 | onStatus: (t) => statuses.push(t), |
| 68 | 85 | onFallback() {}, |
| 69 | 86 | isActive: () => true, |
| 87 | 新增: insertText: async (text) => { | |
| 88 | 新增: texts.push(text); | |
| 89 | 新增: }, | |
| 70 | 90 | }, |
| 71 | 91 | ); |
| 72 | 92 | const key = (type, key, code, extra = {}) => { |
| @@ -89,11 +109,13 @@ function fixture(native = false) { | ||
| 89 | 109 | rfb, |
| 90 | 110 | keys, |
| 91 | 111 | pastes, |
| 112 | 新增: texts, | |
| 92 | 113 | writes, |
| 93 | 114 | statuses, |
| 94 | 115 | controller, |
| 95 | 116 | key, |
| 96 | 117 | local, |
| 118 | 新增: target, | |
| 97 | 119 | setMode: (value) => { |
| 98 | 120 | mode = value; |
| 99 | 121 | }, |
| @@ -133,6 +155,85 @@ test("Mac find and redo preserve the Linux Ctrl/Shift chord", () => { | ||
| 133 | 155 | f.controller.dispose(); |
| 134 | 156 | } |
| 135 | 157 | }); |
| 158 | 新增: | |
| 159 | 新增:function inputEvent(f, type, properties = {}) { | |
| 160 | 新增: const event = new Event(type, { cancelable: true }); | |
| 161 | 新增: Object.assign(event, properties); | |
| 162 | 新增: f.target.dispatchEvent(event); | |
| 163 | 新增: return event; | |
| 164 | 新增:} | |
| 165 | 新增: | |
| 166 | 新增:test("host IME receives composition keys and sends only committed Unicode in order", () => { | |
| 167 | 新增: const f = fixture(); | |
| 168 | 新增: try { | |
| 169 | 新增: f.rfb.focus(); | |
| 170 | 新增: assert.equal(f.doc.activeElement, f.target); | |
| 171 | 新增: assert.equal( | |
| 172 | 新增: f.key("keydown", "Process", "KeyN", { keyCode: 229 }).defaultPrevented, | |
| 173 | 新增: false, | |
| 174 | 新增: ); | |
| 175 | 新增: inputEvent(f, "compositionstart"); | |
| 176 | 新增: f.target.value = "nihao"; | |
| 177 | 新增: inputEvent(f, "input", { | |
| 178 | 新增: data: "nihao", | |
| 179 | 新增: isComposing: true, | |
| 180 | 新增: inputType: "insertCompositionText", | |
| 181 | 新增: }); | |
| 182 | 新增: assert.equal( | |
| 183 | 新增: f.key("keydown", " ", "Space", { isComposing: true }).defaultPrevented, | |
| 184 | 新增: false, | |
| 185 | 新增: ); | |
| 186 | 新增: assert.deepEqual(f.keys, []); | |
| 187 | 新增: inputEvent(f, "compositionend", { data: "你好🙂" }); | |
| 188 | 新增: // Safari sends a final input after compositionend; Chromium sends it before. | |
| 189 | 新增: f.target.value = "你好🙂"; | |
| 190 | 新增: inputEvent(f, "input", { | |
| 191 | 新增: data: "你好🙂", | |
| 192 | 新增: inputType: "insertFromComposition", | |
| 193 | 新增: }); | |
| 194 | 新增: assert.deepEqual(f.keys, []); | |
| 195 | 新增: assert.equal(f.target.value, ""); | |
| 196 | 新增: assert.deepEqual(f.texts, ["你好🙂"]); | |
| 197 | 新增: assert.equal(f.reads(), 0); | |
| 198 | 新增: inputEvent(f, "compositionstart"); | |
| 199 | 新增: inputEvent(f, "compositionend", { data: "你好" }); | |
| 200 | 新增: assert.equal( | |
| 201 | 新增: f.texts.length, | |
| 202 | 新增: 2, | |
| 203 | 新增: "identical consecutive commits are not deduplicated", | |
| 204 | 新增: ); | |
| 205 | 新增: } finally { | |
| 206 | 新增: f.controller.dispose(); | |
| 207 | 新增: } | |
| 208 | 新增: assert.equal(f.rfb.target, null); | |
| 209 | 新增:}); | |
| 210 | 新增: | |
| 211 | 新增:test("cancelled and disconnected compositions do not insert text", () => { | |
| 212 | 新增: const f = fixture(); | |
| 213 | 新增: f.rfb.focus(); | |
| 214 | 新增: inputEvent(f, "compositionstart"); | |
| 215 | 新增: inputEvent(f, "compositionend", { data: "" }); | |
| 216 | 新增: assert.deepEqual(f.keys, []); | |
| 217 | 新增: inputEvent(f, "compositionstart"); | |
| 218 | 新增: f.controller.dispose(); | |
| 219 | 新增: inputEvent(f, "compositionend", { data: "迟到的文本" }); | |
| 220 | 新增: assert.deepEqual(f.keys, []); | |
| 221 | 新增: assert.deepEqual(f.texts, []); | |
| 222 | 新增:}); | |
| 223 | 新增: | |
| 224 | 新增:test("text input without a composition supports emoji and clears the host buffer", () => { | |
| 225 | 新增: const f = fixture(); | |
| 226 | 新增: try { | |
| 227 | 新增: f.rfb.focus(); | |
| 228 | 新增: f.target.value = "🙂"; | |
| 229 | 新增: inputEvent(f, "input", { data: "🙂", inputType: "insertText" }); | |
| 230 | 新增: assert.deepEqual(f.keys, []); | |
| 231 | 新增: assert.deepEqual(f.texts, ["🙂"]); | |
| 232 | 新增: assert.equal(f.target.value, ""); | |
| 233 | 新增: } finally { | |
| 234 | 新增: f.controller.dispose(); | |
| 235 | 新增: } | |
| 236 | 新增:}); | |
| 136 | 237 | test("local fields and native keyboard mode do not acquire mapped shortcuts", () => { |
| 137 | 238 | const f = fixture(); |
| 138 | 239 | try { |
| @@ -16,6 +16,7 @@ import { AppearanceSettings } from "./appearance-settings"; | ||
| 16 | 16 | import { ProxySettings } from "./proxy-settings"; |
| 17 | 17 | import { ExitPolicyFields } from "./exit-policy"; |
| 18 | 18 | import { canonicalExitPolicy } from "./safety-state.mjs"; |
| 19 | 新增:import { EnvironmentVersions } from "./environment-versions"; | |
| 19 | 20 | const sections = [ |
| 20 | 21 | ["keyboard", "通用", SlidersHorizontal], |
| 21 | 22 | ["appearance", "外观", Palette], |
| @@ -526,6 +527,7 @@ export function SettingsPanel({ | ||
| 526 | 527 | <p className="footnote"> |
| 527 | 528 | 切换项目只改变新终端和文件编辑器的起始位置;已有终端、网页和登录态会保留。 |
| 528 | 529 | </p> |
| 530 | 新增: <EnvironmentVersions status={status} onConfirm={onConfirm} /> | |
| 529 | 531 | {status.can_restore && ( |
| 530 | 532 | <button |
| 531 | 533 | className="text-button" |
| @@ -488,11 +488,55 @@ button.large { | ||
| 488 | 488 | width: 100% !important; |
| 489 | 489 | height: 100% !important; |
| 490 | 490 | } |
| 491 | 新增:.remote-text-input { | |
| 492 | 新增: width: 1px; | |
| 493 | 新增: height: 24px; | |
| 494 | 新增: min-height: 0; | |
| 495 | 新增: padding: 0; | |
| 496 | 新增: border: 0; | |
| 497 | 新增: opacity: 0; | |
| 498 | 新增: pointer-events: none; | |
| 499 | 新增: resize: none; | |
| 500 | 新增: font: 16px/24px system-ui; | |
| 501 | 新增:} | |
| 491 | 502 | .concealed { |
| 492 | 503 | visibility: hidden; |
| 493 | 504 | pointer-events: none; |
| 494 | 505 | z-index: -1; |
| 495 | 506 | } |
| 507 | 新增:.sidebar-footer-actions { | |
| 508 | 新增: display: flex; | |
| 509 | 新增: align-items: center; | |
| 510 | 新增: gap: 6px; | |
| 511 | 新增:} | |
| 512 | 新增:.sidebar-footer-actions > .sidebar-link { flex: 1; min-width: 0; } | |
| 513 | 新增:.app-update-button { position: relative; flex: 0 0 auto; } | |
| 514 | 新增:.app-update-button.available { color: var(--accent, #267455); } | |
| 515 | 新增:.update-available-dot { | |
| 516 | 新增: position: absolute; | |
| 517 | 新增: width: 5px; | |
| 518 | 新增: height: 5px; | |
| 519 | 新增: border-radius: 50%; | |
| 520 | 新增: background: currentColor; | |
| 521 | 新增: right: 4px; | |
| 522 | 新增: top: 4px; | |
| 523 | 新增:} | |
| 524 | 新增:.app-update-details { min-width: min(340px, 65vw); padding: 18px 24px 24px; } | |
| 525 | 新增:.app-update-details dl { display: grid; grid-template-columns: auto 1fr; gap: 8px 20px; } | |
| 526 | 新增:.app-update-details dt { color: var(--muted); } | |
| 527 | 新增:.app-update-details dd { margin: 0; } | |
| 528 | 新增:.app-update-details progress { width: 100%; accent-color: var(--accent, #267455); } | |
| 529 | 新增:.browser-download-list { min-width: min(400px, 70vw); max-height: 55vh; overflow: auto; padding: 4px 24px 20px; } | |
| 530 | 新增:.browser-download-item { padding: 12px 0; border-bottom: 1px solid var(--border, #dedede); overflow-wrap: anywhere; } | |
| 531 | 新增:.browser-download-item p { margin: 5px 0; font-size: 12px; color: var(--muted); } | |
| 532 | 新增:.browser-download-item .download-path { user-select: text; } | |
| 533 | 新增:.environment-versions { margin-top: 28px; } | |
| 534 | 新增:.environment-versions .setting-summary-row { display: flex; flex-direction: row; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 0; } | |
| 535 | 新增:.environment-versions .setting-summary-row strong { margin: 0; } | |
| 536 | 新增:.environment-tool-table { width: 100%; border-collapse: collapse; font-size: 12px; margin: 12px 0; } | |
| 537 | 新增:.environment-tool-table th, .environment-tool-table td { padding: 8px 4px; text-align: left; overflow-wrap: anywhere; border-bottom: 1px solid var(--border, #dedede); } | |
| 538 | 新增:.environment-version-actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 14px 0; } | |
| 539 | 新增:.environment-update-banner { position: absolute; z-index: 8; top: 8px; left: 16px; right: 16px; padding: 10px 14px; display: flex; align-items: center; gap: 12px; justify-content: space-between; background: var(--surface, #fff); border: 1px solid var(--border, #dedede); border-radius: 8px; font-size: 13px; } | |
| 496 | 540 | .terminal-view { |
| 497 | 541 | padding: 18px 20px 13px; |
| 498 | 542 | } |
| @@ -579,6 +623,11 @@ button.large { | ||
| 579 | 623 | .status-spacer { |
| 580 | 624 | flex: 1; |
| 581 | 625 | } |
| 626 | 新增:.status-latency { | |
| 627 | 新增: flex-shrink: 0; | |
| 628 | 新增: font-variant-numeric: tabular-nums; | |
| 629 | 新增: white-space: nowrap; | |
| 630 | 新增:} | |
| 582 | 631 | .status-feedback { |
| 583 | 632 | max-width: 48vw; |
| 584 | 633 | overflow: hidden; |
| @@ -1953,25 +2002,30 @@ svg { | ||
| 1953 | 2002 | align-items: center; |
| 1954 | 2003 | gap: 4px; |
| 1955 | 2004 | min-width: 0; |
| 1956 | 删除: padding: 8px 12px 0; | |
| 2005 | 新增: padding: 4px 12px; | |
| 1957 | 2006 | height: 48px; |
| 1958 | 2007 | background: var(--chrome); |
| 1959 | 2008 | } |
| 1960 | 2009 | .browser-tabs { |
| 2010 | 新增: position: relative; | |
| 1961 | 2011 | display: flex; |
| 2012 | 新增: flex: 1; | |
| 1962 | 2013 | gap: 4px; |
| 1963 | 2014 | min-width: 0; |
| 1964 | 删除: overflow-x: auto; | |
| 1965 | 删除: scrollbar-width: thin; | |
| 2015 | 新增: overflow: clip; | |
| 1966 | 2016 | align-self: stretch; |
| 1967 | 2017 | } |
| 1968 | 2018 | .browser-tab { |
| 1969 | 2019 | display: flex; |
| 1970 | 2020 | align-items: center; |
| 1971 | 删除: flex: 0 0 220px; | |
| 1972 | 删除: min-width: 120px; | |
| 1973 | 删除: max-width: 240px; | |
| 1974 | 删除: border-radius: 8px 8px 0 0; | |
| 2021 | 新增: flex: none; | |
| 2022 | 新增: min-width: 0; | |
| 2023 | 新增: position: relative; | |
| 2024 | 新增: border-radius: 8px; | |
| 2025 | 新增: overflow: hidden; | |
| 2026 | 新增: user-select: none; | |
| 2027 | 新增: touch-action: none; | |
| 2028 | 新增: transition: width 160ms ease, transform 160ms ease, background 120ms ease; | |
| 1975 | 2029 | color: var(--muted); |
| 1976 | 2030 | } |
| 1977 | 2031 | .browser-tab:hover { |
| @@ -1984,7 +2038,7 @@ svg { | ||
| 1984 | 2038 | .browser-tab > [role="tab"] { |
| 1985 | 2039 | background: transparent; |
| 1986 | 2040 | border: 0; |
| 1987 | 删除: border-radius: 8px 0 0 0; | |
| 2041 | 新增: border-radius: 8px; | |
| 1988 | 2042 | flex: 1; |
| 1989 | 2043 | min-width: 0; |
| 1990 | 2044 | height: 100%; |
| @@ -1995,6 +2049,7 @@ svg { | ||
| 1995 | 2049 | font-size: 0.9286rem; |
| 1996 | 2050 | } |
| 1997 | 2051 | .browser-tab > [role="tab"] > span { |
| 2052 | 新增: min-width: 0; | |
| 1998 | 2053 | white-space: nowrap; |
| 1999 | 2054 | overflow: hidden; |
| 2000 | 2055 | text-overflow: ellipsis; |
| @@ -2009,3 +2064,92 @@ svg { | ||
| 2009 | 2064 | .browser-tab-bar > .icon-button { |
| 2010 | 2065 | flex-shrink: 0; |
| 2011 | 2066 | } |
| 2067 | 新增:.browser-tabs.is-dragging .browser-tab { transition: transform 160ms ease; } | |
| 2068 | 新增:.browser-tabs .browser-tab.dragging { | |
| 2069 | 新增: transition: none; | |
| 2070 | 新增: z-index: 2; | |
| 2071 | 新增: background: var(--selected); | |
| 2072 | 新增: box-shadow: 0 2px 4px #0003; | |
| 2073 | 新增: cursor: grabbing; | |
| 2074 | 新增:} | |
| 2075 | 新增:.browser-tab.dragging > [role="tab"] { cursor: grabbing; } | |
| 2076 | 新增:.browser-tab > [role="tab"]:active { transform: none; } | |
| 2077 | 新增:.browser-tab.compact:not(.active) .tab-close { display: none; } | |
| 2078 | 新增:.browser-tab.compact > [role="tab"] { padding-inline: 8px; gap: 4px; } | |
| 2079 | 新增:.browser-tab.tiny > [role="tab"] { padding-inline: 4px; } | |
| 2080 | 新增:.browser-tab.tiny:not(.active) > [role="tab"] > span, | |
| 2081 | 新增:.browser-tab.tiny .tab-pin { display: none; } | |
| 2082 | 新增:.browser-tab.tiny.active .tab-close { display: none; } | |
| 2083 | 新增:.browser-tab.sliver > [role="tab"] { padding-inline: 0; justify-content: center; } | |
| 2084 | 新增:.browser-tab.sliver > [role="tab"] > svg { display: none; } | |
| 2085 | 新增:.browser-tab.sliver > [role="tab"]::after { content: ""; height: 14px; width: 2px; background: var(--muted); border-radius: 2px; opacity: .5; } | |
| 2086 | 新增:.browser-new-tab { order: 1; } | |
| 2087 | 新增:.browser-all-tabs { position: relative; order: 2; } | |
| 2088 | 新增:.all-tabs-menu { right: 0; top: 36px; width: min(360px, calc(100vw - 32px)); } | |
| 2089 | 新增:.all-tabs-menu input { width: 100%; margin-bottom: 8px; } | |
| 2090 | 新增:.all-tabs-results { max-height: min(440px, 65vh); overflow-y: auto; } | |
| 2091 | 新增:.all-tabs-results button { width: 100%; } | |
| 2092 | 新增:.all-tabs-results button > span:first-of-type { overflow: hidden; text-overflow: ellipsis; flex: 1; } | |
| 2093 | 新增:.current-tab-marker { font-size: 0.8571rem; color: var(--muted); } | |
| 2094 | 新增:@media (prefers-reduced-motion: reduce) { .browser-tab, .browser-tabs.is-dragging .browser-tab { transition: none; } } | |
| 2095 | 新增:[data-reduced-motion="true"] .browser-tab { transition: none; } | |
| 2096 | 新增:.favorites-actions { display: flex; align-items: center; gap: 4px; } | |
| 2097 | 新增:.favorite-star.saved { color: var(--accent); } | |
| 2098 | 新增:.favorites-dismiss { position: fixed; inset: 0; z-index: 35; } | |
| 2099 | 新增:.favorites-panel { | |
| 2100 | 新增: position: fixed; z-index: 36; right: 16px; top: 104px; | |
| 2101 | 新增: width: min(380px, calc(100vw - 32px)); max-height: calc(100vh - 160px); | |
| 2102 | 新增: display: flex; flex-direction: column; border: 1px solid var(--line); | |
| 2103 | 新增: border-radius: 12px; background: var(--paper); box-shadow: 0 8px 32px #0002; | |
| 2104 | 新增: padding: 16px; gap: 12px; | |
| 2105 | 新增:} | |
| 2106 | 新增:.favorites-panel header { display: flex; align-items: center; gap: 8px; } | |
| 2107 | 新增:.favorites-panel h2 { margin: 0; flex: 1; font-size: 1.1429rem; font-weight: 600; color: var(--strong); } | |
| 2108 | 新增:.favorites-search { display: flex; align-items: center; gap: 8px; background: var(--chrome); padding: 0 8px; border-radius: 6px; } | |
| 2109 | 新增:.favorites-search input { width: 100%; min-width: 0; background: transparent; border: none; } | |
| 2110 | 新增:.favorites-search input, .favorite-form input, .favorite-form select, .favorites-folder-select select, .all-tabs-menu input { | |
| 2111 | 新增: min-height: 34px; padding: 7px 8px; border: 1px solid var(--line); border-radius: 6px; | |
| 2112 | 新增: background: var(--input); color: var(--ink); font: inherit; | |
| 2113 | 新增:} | |
| 2114 | 新增:.favorites-search input { border: none; background: transparent; padding-inline: 0; } | |
| 2115 | 新增:.favorite-form { overflow-y: auto; } | |
| 2116 | 新增:.favorites-folder-select { display: flex; gap: 4px; align-items: center; } | |
| 2117 | 新增:.favorites-folder-select select { flex: 1; min-width: 0; } | |
| 2118 | 新增:.favorites-list { overflow-y: auto; min-height: 96px; } | |
| 2119 | 新增:.favorite-row { display: flex; align-items: center; border-radius: 6px; } | |
| 2120 | 新增:.favorite-row:hover { background: var(--hover); } | |
| 2121 | 新增:.favorite-link { border: none; background: transparent; flex: 1; min-width: 0; padding: 8px; text-align: left; gap: 12px; } | |
| 2122 | 新增:.favorite-link > span { flex: 1; min-width: 0; display: grid; gap: 4px; } | |
| 2123 | 新增:.favorite-link strong, .favorite-link small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } | |
| 2124 | 新增:.favorite-link strong { font-weight: 500; color: var(--strong); } | |
| 2125 | 新增:.favorite-link small { font-size: 0.8571rem; color: var(--muted); } | |
| 2126 | 新增:.favorites-panel footer { display: flex; justify-content: space-between; gap: 8px; color: var(--muted); font-size: 0.8571rem; } | |
| 2127 | 新增:.favorites-empty { padding: 24px 8px; text-align: center; color: var(--muted); } | |
| 2128 | 新增:.favorites-empty p { color: var(--strong); margin: 12px 0 8px; } | |
| 2129 | 新增:.favorites-empty span { font-size: 0.9286rem; } | |
| 2130 | 新增:.favorite-form { display: grid; gap: 16px; padding: 20px 24px; } | |
| 2131 | 新增:.favorite-form label { display: grid; gap: 8px; } | |
| 2132 | 新增:.favorite-form input, .favorite-form select { width: 100%; min-width: 0; } | |
| 2133 | 新增:.favorites-error { color: var(--danger); white-space: normal; } | |
| 2134 | 新增:.favorites-error button { margin-top: 8px; } | |
| 2135 | 新增:.favorite-remove { margin-right: auto; } | |
| 2136 | 新增:.favorite-editor .modal-scrim { z-index: 40; } | |
| 2137 | 新增: | |
| 2138 | 新增:.brand-logo, | |
| 2139 | 新增:.sidebar-expand-logo { | |
| 2140 | 新增: width: 22px; | |
| 2141 | 新增: height: 22px; | |
| 2142 | 新增: object-fit: contain; | |
| 2143 | 新增: border-radius: 4px; | |
| 2144 | 新增:} | |
| 2145 | 新增:.sidebar-expand-icon { | |
| 2146 | 新增: display: none; | |
| 2147 | 新增:} | |
| 2148 | 新增:.sidebar-expand:hover .sidebar-expand-logo, | |
| 2149 | 新增:.sidebar-expand:focus-visible .sidebar-expand-logo { | |
| 2150 | 新增: display: none; | |
| 2151 | 新增:} | |
| 2152 | 新增:.sidebar-expand:hover .sidebar-expand-icon, | |
| 2153 | 新增:.sidebar-expand:focus-visible .sidebar-expand-icon { | |
| 2154 | 新增: display: block; | |
| 2155 | 新增:} | |
| @@ -12,18 +12,21 @@ import { FitAddon } from "@xterm/addon-fit"; | ||
| 12 | 12 | import RFB from "../.generated/novnc/core/rfb.js"; |
| 13 | 13 | import { api, readClipboard, writeClipboard } from "./api"; |
| 14 | 14 | import { installRemoteInput } from "./remote-input"; |
| 15 | 新增:import { useWindowVisibility } from "./window-visibility"; | |
| 15 | 16 | import { RefreshCw, Clipboard, ArrowUpRight } from "lucide-react"; |
| 16 | 17 | import "@xterm/xterm/css/xterm.css"; |
| 17 | 18 | |
| 18 | 19 | export const RemoteView = forwardRef(function RemoteView( |
| 19 | 删除: { visible, keyboard, onStatus, onFallback }, | |
| 20 | 新增: { visible, keyboard, tabId, onStatus, onFallback }, | |
| 20 | 21 | ref, |
| 21 | 22 | ) { |
| 23 | 新增: const windowVisible = useWindowVisibility(); | |
| 24 | 新增: const screenVisible = visible && windowVisible; | |
| 22 | 25 | const box = useRef(), |
| 23 | 26 | rfb = useRef(), |
| 24 | 27 | input = useRef(), |
| 25 | 28 | current = useRef({ visible, keyboard, onStatus, onFallback }); |
| 26 | 删除: current.current = { visible, keyboard, onStatus, onFallback }; | |
| 29 | 新增: current.current = { visible: screenVisible, keyboard, tabId, onStatus, onFallback }; | |
| 27 | 30 | const failures = useRef(0); |
| 28 | 31 | const [connection, setConnection] = useState("connecting"), |
| 29 | 32 | [attempt, setAttempt] = useState(0); |
| @@ -40,6 +43,7 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 40 | 43 | onFallback(input.current?.text() || "", "可在此使用本机复制、粘贴。"), |
| 41 | 44 | })); |
| 42 | 45 | useEffect(() => { |
| 46 | 新增: if (!screenVisible) return; | |
| 43 | 47 | let disposed = false, |
| 44 | 48 | client, |
| 45 | 49 | resizeObserver, |
| @@ -76,6 +80,7 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 76 | 80 | const resize = () => { |
| 77 | 81 | clearTimeout(resizeTimer); |
| 78 | 82 | resizeTimer = setTimeout(() => { |
| 83 | 新增: if (disposed) return; | |
| 79 | 84 | const { width, height } = box.current.getBoundingClientRect(); |
| 80 | 85 | if (width >= 320 && height >= 240) |
| 81 | 86 | api("/browser/resize", { |
| @@ -90,6 +95,14 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 90 | 95 | resizeObserver.observe(box.current); |
| 91 | 96 | resize(); |
| 92 | 97 | input.current = installRemoteInput(client, box.current, { |
| 98 | 新增: insertText: (text) => { | |
| 99 | 新增: const id = current.current.tabId; | |
| 100 | 新增: return client.cageRunInput(() => { | |
| 101 | 新增: if (disposed || !current.current.visible || current.current.tabId !== id) | |
| 102 | 新增: throw new Error("Input target changed"); | |
| 103 | 新增: return api("/browser/insert-text", { id, text }); | |
| 104 | 新增: }); | |
| 105 | 新增: }, | |
| 93 | 106 | mode: () => current.current.keyboard, |
| 94 | 107 | isActive: () => current.current.visible, |
| 95 | 108 | onStatus: (t) => current.current.onStatus(t), |
| @@ -98,6 +111,7 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 98 | 111 | if (current.current.visible) client.focus(); |
| 99 | 112 | }); |
| 100 | 113 | client.addEventListener("disconnect", () => { |
| 114 | 新增: if (disposed) return; | |
| 101 | 115 | input.current?.dispose(); |
| 102 | 116 | input.current = null; |
| 103 | 117 | retry(); |
| @@ -119,13 +133,13 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 119 | 133 | client?.disconnect(); |
| 120 | 134 | rfb.current = null; |
| 121 | 135 | }; |
| 122 | 删除: }, [attempt]); | |
| 136 | 新增: }, [attempt, screenVisible]); | |
| 123 | 137 | useEffect(() => { |
| 124 | 删除: if (visible && connection === "connected") { | |
| 138 | 新增: if (screenVisible && connection === "connected") { | |
| 125 | 139 | const t = setTimeout(() => rfb.current?.focus(), 80); |
| 126 | 140 | return () => clearTimeout(t); |
| 127 | 141 | } |
| 128 | 删除: }, [visible, connection]); | |
| 142 | 新增: }, [screenVisible, connection]); | |
| 129 | 143 | return ( |
| 130 | 144 | <div className={`remote-view ${visible ? "" : "concealed"}`}> |
| 131 | 145 | <div className="remote-canvas" ref={box} /> |
| @@ -0,0 +1,17 @@ | ||
| 1 | 新增:import { useSyncExternalStore } from "react"; | |
| 2 | 新增: | |
| 3 | 新增:const visible = () => | |
| 4 | 新增: document.visibilityState !== "hidden" && window.cageWindowVisible !== false; | |
| 5 | 新增: | |
| 6 | 新增:function subscribe(notify) { | |
| 7 | 新增: document.addEventListener("visibilitychange", notify); | |
| 8 | 新增: window.addEventListener("cage-window-visibility", notify); | |
| 9 | 新增: return () => { | |
| 10 | 新增: document.removeEventListener("visibilitychange", notify); | |
| 11 | 新增: window.removeEventListener("cage-window-visibility", notify); | |
| 12 | 新增: }; | |
| 13 | 新增:} | |
| 14 | 新增: | |
| 15 | 新增:export function useWindowVisibility() { | |
| 16 | 新增: return useSyncExternalStore(subscribe, visible); | |
| 17 | 新增:} | |
| @@ -11,6 +11,7 @@ import { | ||
| 11 | 11 | Settings2, |
| 12 | 12 | } from "lucide-react"; |
| 13 | 13 | import { EnvironmentShield } from "./environment-shield"; |
| 14 | 新增:import logo from "./logo.png"; | |
| 14 | 15 | import { projectName } from "./workspace-state.mjs"; |
| 15 | 16 | import { WorkspaceTabs } from "./workspace-tabs"; |
| 16 | 17 | |
| @@ -41,6 +42,7 @@ export function WorkspaceSidebar({ | ||
| 41 | 42 | onSettings, |
| 42 | 43 | onSafety, |
| 43 | 44 | onCollapse, |
| 45 | 新增: updateAction, | |
| 44 | 46 | }) { |
| 45 | 47 | const [collapsed, setCollapsed] = useState({}); |
| 46 | 48 | const activeWorkspace = tabs.find((tab) => tab.id === active)?.workspace; |
| @@ -53,7 +55,7 @@ export function WorkspaceSidebar({ | ||
| 53 | 55 | <aside className="workspace-sidebar" aria-label="项目与终端"> |
| 54 | 56 | <div className="sidebar-top"> |
| 55 | 57 | <span className="sidebar-brand"> |
| 56 | 删除: <EnvironmentShield size={21} healthy={healthy} /> | |
| 58 | 新增: <img className="brand-logo" src={logo} alt="" /> | |
| 57 | 59 | Cage |
| 58 | 60 | </span> |
| 59 | 61 | <button |
| @@ -207,10 +209,13 @@ export function WorkspaceSidebar({ | ||
| 207 | 209 | <span>{healthy ? "环境运行正常" : runtimeLabel}</span> |
| 208 | 210 | <EnvironmentShield size={17} healthy={healthy} /> |
| 209 | 211 | </button> |
| 210 | 删除: <button className="sidebar-link" onClick={onSettings}> | |
| 211 | 删除: <Settings2 size={17} /> | |
| 212 | 删除: 设置<kbd>⌘,</kbd> | |
| 213 | 删除: </button> | |
| 212 | 新增: <div className="sidebar-footer-actions"> | |
| 213 | 新增: <button className="sidebar-link" onClick={onSettings}> | |
| 214 | 新增: <Settings2 size={17} /> | |
| 215 | 新增: 设置<kbd>⌘,</kbd> | |
| 216 | 新增: </button> | |
| 217 | 新增: {updateAction} | |
| 218 | 新增: </div> | |
| 214 | 219 | </div> |
| 215 | 220 | </aside> |
| 216 | 221 | ); |
| @@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from "react"; | ||
| 2 | 2 | import { createPortal } from "react-dom"; |
| 3 | 3 | import { |
| 4 | 4 | FileCode2, |
| 5 | 新增: ChevronDown, | |
| 5 | 6 | Globe2, |
| 6 | 7 | MoreHorizontal, |
| 7 | 8 | Pin, |
| @@ -37,8 +38,136 @@ export function WorkspaceTabs({ | ||
| 37 | 38 | }) { |
| 38 | 39 | const [menu, setMenu] = useState(null); |
| 39 | 40 | const [dragged, setDragged] = useState(null); |
| 41 | 新增: const [drag, setDrag] = useState(null); | |
| 42 | 新增: const [allOpen, setAllOpen] = useState(false); | |
| 43 | 新增: const [query, setQuery] = useState(""); | |
| 44 | 新增: const [width, setWidth] = useState(0); | |
| 45 | 新增: const pointer = useRef(null); | |
| 46 | 新增: const suppressClick = useRef(false); | |
| 40 | 47 | const trigger = useRef(); |
| 41 | 48 | const list = useRef(); |
| 49 | 新增: useEffect(() => { | |
| 50 | 新增: if (!horizontal || !list.current) return; | |
| 51 | 新增: const observer = new ResizeObserver(([entry]) => | |
| 52 | 新增: setWidth(entry.contentRect.width), | |
| 53 | 新增: ); | |
| 54 | 新增: observer.observe(list.current); | |
| 55 | 新增: return () => observer.disconnect(); | |
| 56 | 新增: }, [horizontal]); | |
| 57 | 新增: const gap = tabs.length > 20 ? 1 : 4; | |
| 58 | 新增: const available = Math.max(0, width - gap * Math.max(0, tabs.length - 1)); | |
| 59 | 新增: const regularWidth = Math.min(220, available / Math.max(1, tabs.length)); | |
| 60 | 新增: const activeWidth = | |
| 61 | 新增: tabs.length > 1 && tabs.some((tab) => tab.id === active) | |
| 62 | 新增: ? Math.min(220, Math.max(regularWidth, Math.min(160, available * 0.4))) | |
| 63 | 新增: : regularWidth; | |
| 64 | 新增: const otherWidth = Math.max( | |
| 65 | 新增: 0, | |
| 66 | 新增: (available - activeWidth) / Math.max(1, tabs.length - 1), | |
| 67 | 新增: ); | |
| 68 | 新增: const tabWidth = (id) => | |
| 69 | 新增: id === active ? activeWidth : Math.min(220, otherWidth); | |
| 70 | 新增: const matchingTabs = tabs.filter((tab) => | |
| 71 | 新增: `${tabName(tab, saved)} ${tab.url || ""}` | |
| 72 | 新增: .toLowerCase() | |
| 73 | 新增: .includes(query.toLowerCase()), | |
| 74 | 新增: ); | |
| 75 | 新增: const finishDrag = (commit) => { | |
| 76 | 新增: const current = pointer.current; | |
| 77 | 新增: pointer.current = null; | |
| 78 | 新增: setDrag(null); | |
| 79 | 新增: if (current?.moved) { | |
| 80 | 新增: suppressClick.current = true; | |
| 81 | 新增: if (commit) onReorder(current.id, null, current.order); | |
| 82 | 新增: } | |
| 83 | 新增: }; | |
| 84 | 新增: useEffect(() => { | |
| 85 | 新增: if (!drag) return; | |
| 86 | 新增: const cancel = (event) => { | |
| 87 | 新增: if (event.key !== "Escape") return; | |
| 88 | 新增: event.preventDefault(); | |
| 89 | 新增: event.stopImmediatePropagation(); | |
| 90 | 新增: finishDrag(false); | |
| 91 | 新增: }; | |
| 92 | 新增: document.addEventListener("keydown", cancel, true); | |
| 93 | 新增: return () => document.removeEventListener("keydown", cancel, true); | |
| 94 | 新增: }, [Boolean(drag)]); | |
| 95 | 新增: const startDrag = (event, tab) => { | |
| 96 | 新增: if ( | |
| 97 | 新增: !horizontal || | |
| 98 | 新增: busy || | |
| 99 | 新增: !ready || | |
| 100 | 新增: event.button !== 0 || | |
| 101 | 新增: event.target.closest(".tab-close") | |
| 102 | 新增: ) | |
| 103 | 新增: return; | |
| 104 | 新增: suppressClick.current = false; | |
| 105 | 新增: const items = [...list.current.children].map((node) => ({ | |
| 106 | 新增: id: node.dataset.tabId, | |
| 107 | 新增: left: node.offsetLeft, | |
| 108 | 新增: width: node.getBoundingClientRect().width, | |
| 109 | 新增: })); | |
| 110 | 新增: const group = items.filter( | |
| 111 | 新增: (item) => | |
| 112 | 新增: Boolean(saved[item.id]?.pinned) === Boolean(saved[tab.id]?.pinned), | |
| 113 | 新增: ); | |
| 114 | 新增: pointer.current = { | |
| 115 | 新增: id: tab.id, | |
| 116 | 新增: startX: event.clientX, | |
| 117 | 新增: items, | |
| 118 | 新增: group, | |
| 119 | 新增: order: items.map((item) => item.id), | |
| 120 | 新增: moved: false, | |
| 121 | 新增: }; | |
| 122 | 新增: }; | |
| 123 | 新增: const moveDrag = (event) => { | |
| 124 | 新增: const current = pointer.current; | |
| 125 | 新增: if (!current) return; | |
| 126 | 新增: if (event.buttons === 0) { | |
| 127 | 新增: finishDrag(false); | |
| 128 | 新增: return; | |
| 129 | 新增: } | |
| 130 | 新增: const item = current.items.find((item) => item.id === current.id); | |
| 131 | 新增: let dx = event.clientX - current.startX; | |
| 132 | 新增: if (!current.moved && Math.abs(dx) < 5) return; | |
| 133 | 新增: if (!current.moved) event.currentTarget.setPointerCapture(event.pointerId); | |
| 134 | 新增: current.moved = true; | |
| 135 | 新增: dx = Math.max( | |
| 136 | 新增: current.group[0].left - item.left, | |
| 137 | 新增: Math.min( | |
| 138 | 新增: dx, | |
| 139 | 新增: current.group.at(-1).left + | |
| 140 | 新增: current.group.at(-1).width - | |
| 141 | 新增: item.left - | |
| 142 | 新增: item.width, | |
| 143 | 新增: ), | |
| 144 | 新增: ); | |
| 145 | 新增: const center = item.left + item.width / 2 + dx; | |
| 146 | 新增: const rest = current.group.filter((other) => other.id !== item.id); | |
| 147 | 新增: const target = rest.filter( | |
| 148 | 新增: (other) => center > other.left + other.width / 2, | |
| 149 | 新增: ).length; | |
| 150 | 新增: const groupOrder = rest.map((other) => other.id); | |
| 151 | 新增: groupOrder.splice(target, 0, item.id); | |
| 152 | 新增: let at = 0; | |
| 153 | 新增: current.order = current.items.map((other) => | |
| 154 | 新增: current.group.includes(other) ? groupOrder[at++] : other.id, | |
| 155 | 新增: ); | |
| 156 | 新增: let left = current.items[0].left; | |
| 157 | 新增: const offsets = {}; | |
| 158 | 新增: for (const id of current.order) { | |
| 159 | 新增: const original = current.items.find((other) => other.id === id); | |
| 160 | 新增: offsets[id] = id === item.id ? dx : left - original.left; | |
| 161 | 新增: left += original.width + gap; | |
| 162 | 新增: } | |
| 163 | 新增: setDrag({ | |
| 164 | 新增: id: item.id, | |
| 165 | 新增: offsets, | |
| 166 | 新增: widths: Object.fromEntries( | |
| 167 | 新增: current.items.map((item) => [item.id, item.width]), | |
| 168 | 新增: ), | |
| 169 | 新增: }); | |
| 170 | 新增: }; | |
| 42 | 171 | const showMenu = (tab, event) => { |
| 43 | 172 | event.preventDefault(); |
| 44 | 173 | trigger.current = event.currentTarget; |
| @@ -50,22 +179,24 @@ export function WorkspaceTabs({ | ||
| 50 | 179 | }); |
| 51 | 180 | }; |
| 52 | 181 | useEffect(() => { |
| 182 | 新增: if (horizontal) return; | |
| 53 | 183 | list.current |
| 54 | 184 | ?.querySelector('[aria-selected="true"]') |
| 55 | 185 | ?.scrollIntoView({ block: "nearest", inline: "nearest" }); |
| 56 | 删除: }, [active]); | |
| 186 | 新增: }, [active, horizontal]); | |
| 57 | 187 | useEffect(() => { |
| 58 | 删除: if (!menu) return; | |
| 188 | 新增: if (!menu && !allOpen) return; | |
| 59 | 189 | const dismiss = (event) => { |
| 60 | 190 | if (event.key === "Escape") { |
| 61 | 191 | event.stopPropagation(); |
| 62 | 192 | setMenu(null); |
| 193 | 新增: setAllOpen(false); | |
| 63 | 194 | trigger.current?.focus(); |
| 64 | 195 | } |
| 65 | 196 | }; |
| 66 | 197 | document.addEventListener("keydown", dismiss); |
| 67 | 198 | return () => document.removeEventListener("keydown", dismiss); |
| 68 | 删除: }, [menu]); | |
| 199 | 新增: }, [menu, allOpen]); | |
| 69 | 200 | return ( |
| 70 | 201 | <> |
| 71 | 202 | <div |
| @@ -73,15 +204,53 @@ export function WorkspaceTabs({ | ||
| 73 | 204 | role="tablist" |
| 74 | 205 | aria-label={label} |
| 75 | 206 | aria-orientation={horizontal ? "horizontal" : "vertical"} |
| 76 | 删除: className={horizontal ? "browser-tabs" : "sidebar-tabs"} | |
| 207 | 新增: className={ | |
| 208 | 新增: horizontal | |
| 209 | 新增: ? `browser-tabs ${drag ? "is-dragging" : ""}` | |
| 210 | 新增: : "sidebar-tabs" | |
| 211 | 新增: } | |
| 212 | 新增: style={ | |
| 213 | 新增: horizontal | |
| 214 | 新增: ? { | |
| 215 | 新增: gap, | |
| 216 | 新增: width: tabs.length * 220 + gap * Math.max(0, tabs.length - 1), | |
| 217 | 新增: flex: "0 1 auto", | |
| 218 | 新增: } | |
| 219 | 新增: : undefined | |
| 220 | 新增: } | |
| 77 | 221 | > |
| 78 | 222 | {tabs.map((tab, index) => { |
| 79 | 223 | const title = tabName(tab, saved); |
| 80 | 224 | return ( |
| 81 | 225 | <div |
| 82 | 226 | key={tab.id} |
| 83 | 删除: className={`${horizontal ? "browser-tab" : "sidebar-tab"} ${tab.id === active ? "active" : ""} ${tab.closed ? "ended" : ""}`} | |
| 84 | 删除: draggable={!busy} | |
| 227 | 新增: data-tab-id={tab.id} | |
| 228 | 新增: className={`${horizontal ? "browser-tab" : "sidebar-tab"} ${tab.id === active ? "active" : ""} ${tab.closed ? "ended" : ""} ${drag?.id === tab.id ? "dragging" : ""} ${horizontal && tabWidth(tab.id) < 96 ? "compact" : ""} ${horizontal && tabWidth(tab.id) < 40 ? "tiny" : ""} ${horizontal && tabWidth(tab.id) < 24 ? "sliver" : ""}`} | |
| 229 | 新增: style={ | |
| 230 | 新增: horizontal | |
| 231 | 新增: ? { | |
| 232 | 新增: width: drag?.widths[tab.id] ?? tabWidth(tab.id), | |
| 233 | 新增: transform: drag | |
| 234 | 新增: ? `translateX(${drag.offsets[tab.id] || 0}px)` | |
| 235 | 新增: : undefined, | |
| 236 | 新增: } | |
| 237 | 新增: : undefined | |
| 238 | 新增: } | |
| 239 | 新增: onPointerDown={(event) => startDrag(event, tab)} | |
| 240 | 新增: onPointerMove={moveDrag} | |
| 241 | 新增: onPointerUp={() => finishDrag(true)} | |
| 242 | 新增: onPointerCancel={() => finishDrag(false)} | |
| 243 | 新增: onLostPointerCapture={() => { | |
| 244 | 新增: if (pointer.current) finishDrag(false); | |
| 245 | 新增: }} | |
| 246 | 新增: onClickCapture={(event) => { | |
| 247 | 新增: if (suppressClick.current) { | |
| 248 | 新增: event.preventDefault(); | |
| 249 | 新增: event.stopPropagation(); | |
| 250 | 新增: suppressClick.current = false; | |
| 251 | 新增: } | |
| 252 | 新增: }} | |
| 253 | 新增: draggable={!horizontal && !busy} | |
| 85 | 254 | onDragStart={(event) => { |
| 86 | 255 | setDragged(tab.id); |
| 87 | 256 | event.dataTransfer.setData("text/plain", tab.id); |
| @@ -99,6 +268,7 @@ export function WorkspaceTabs({ | ||
| 99 | 268 | > |
| 100 | 269 | <button |
| 101 | 270 | role="tab" |
| 271 | 新增: aria-label={title} | |
| 102 | 272 | aria-selected={tab.id === active} |
| 103 | 273 | tabIndex={ |
| 104 | 274 | tab.id === active || |
| @@ -159,6 +329,62 @@ export function WorkspaceTabs({ | ||
| 159 | 329 | ); |
| 160 | 330 | })} |
| 161 | 331 | </div> |
| 332 | 新增: {horizontal && ( | |
| 333 | 新增: <div className="browser-all-tabs"> | |
| 334 | 新增: <button | |
| 335 | 新增: className="icon-button" | |
| 336 | 新增: aria-label="搜索标签页" | |
| 337 | 新增: title="搜索标签页" | |
| 338 | 新增: aria-expanded={allOpen} | |
| 339 | 新增: onClick={(event) => { | |
| 340 | 新增: trigger.current = event.currentTarget; | |
| 341 | 新增: setAllOpen(!allOpen); | |
| 342 | 新增: setQuery(""); | |
| 343 | 新增: }} | |
| 344 | 新增: > | |
| 345 | 新增: <ChevronDown size={16} /> | |
| 346 | 新增: </button> | |
| 347 | 新增: {allOpen && ( | |
| 348 | 新增: <> | |
| 349 | 新增: <div className="menu-dismiss" onClick={() => setAllOpen(false)} /> | |
| 350 | 新增: <div | |
| 351 | 新增: className="menu all-tabs-menu" | |
| 352 | 新增: role="dialog" | |
| 353 | 新增: aria-label="搜索标签页" | |
| 354 | 新增: > | |
| 355 | 新增: <input | |
| 356 | 新增: autoFocus | |
| 357 | 新增: aria-label="搜索已打开的标签页" | |
| 358 | 新增: placeholder="搜索标签页" | |
| 359 | 新增: value={query} | |
| 360 | 新增: onChange={(event) => setQuery(event.target.value)} | |
| 361 | 新增: /> | |
| 362 | 新增: <div className="all-tabs-results"> | |
| 363 | 新增: {matchingTabs.length === 0 && ( | |
| 364 | 新增: <p className="favorites-empty">没有匹配的标签页</p> | |
| 365 | 新增: )} | |
| 366 | 新增: {matchingTabs.map((tab) => ( | |
| 367 | 新增: <button | |
| 368 | 新增: key={tab.id} | |
| 369 | 新增: title={tab.url} | |
| 370 | 新增: onClick={() => { | |
| 371 | 新增: setAllOpen(false); | |
| 372 | 新增: onSelect(tab.id); | |
| 373 | 新增: }} | |
| 374 | 新增: > | |
| 375 | 新增: <TabIcon kind={tab.kind} /> | |
| 376 | 新增: <span>{tabName(tab, saved)}</span> | |
| 377 | 新增: {tab.id === active && ( | |
| 378 | 新增: <span className="current-tab-marker">当前</span> | |
| 379 | 新增: )} | |
| 380 | 新增: </button> | |
| 381 | 新增: ))} | |
| 382 | 新增: </div> | |
| 383 | 新增: </div> | |
| 384 | 新增: </> | |
| 385 | 新增: )} | |
| 386 | 新增: </div> | |
| 387 | 新增: )} | |
| 162 | 388 | {menu && |
| 163 | 389 | createPortal( |
| 164 | 390 | <> |
| @@ -3,4 +3,4 @@ | ||
| 3 | 3 | Upstream: https://github.com/novnc/noVNC/tree/v1.6.0 |
| 4 | 4 | Release archive SHA-256: 5066103959ef4e9b10f37e5a148627360dd8414e4cf8a7db92bdbd022e728aaa |
| 5 | 5 | |
| 6 | 删除:Only core, vendor and license files are retained. This source is obtained from the official release, never copied from a mutable guest. The build copies it into `.generated/novnc` and applies `internal/cage/novnc-patch.py`, the same clipboard/fence patch used by the legacy VM viewer. Modified RFB code retains its MPL-2.0 header; the complete modification source is shipped in this repository. | |
| 6 | 新增:Only core, vendor and license files are retained. This source is obtained from the official release, never copied from a mutable guest. The build copies it into `.generated/novnc` and applies `internal/cage/novnc-patch.py`, the same patch used by the legacy VM viewer. The patch serializes clipboard transfers and lets the workbench attach an editable keyboard target for host IME composition. Legacy viewers retain their canvas keyboard target. Modified RFB code retains its MPL-2.0 header; the complete modification source is shipped in this repository. | |
| @@ -1,6 +0,0 @@ | ||
| 1 | 删除:{ | |
| 2 | 删除: "project_id": "appgprj_6ae60643abd0819183bcdf597934e97c", | |
| 3 | 删除: "static": { | |
| 4 | 删除: "directory": "dist" | |
| 5 | 删除: } | |
| 6 | 删除:} | |
| @@ -1,16 +1,24 @@ | ||
| 1 | 1 | # Cage 项目主页 |
| 2 | 2 | |
| 3 | 删除:面向首次使用者的中文介绍、安装入口、三步开始和使用边界。页面采用暖白底与陶土橙强调色,使用实际工作台渲染的演示截图。 | |
| 3 | 新增:主页地址为 <https://lee-xeo.github.io/Claude-Cage/>,面向首次使用者介绍产品、公开安装包、开始使用步骤与使用边界。 | |
| 4 | 新增: | |
| 5 | 新增:在本目录执行: | |
| 4 | 6 | |
| 5 | 7 | ```sh |
| 6 | 8 | npm ci |
| 7 | 删除:npm run dev # http://localhost:4822 | |
| 9 | 新增:npm run dev # http://localhost:4822/Claude-Cage/ | |
| 8 | 10 | npm run check |
| 9 | 11 | npm run build # dist/ |
| 10 | 12 | ``` |
| 11 | 13 | |
| 12 | 删除:当前页面位于 `src/pages/index.astro`,样式位于 `src/styles/cage.css`,产品截图在 `public/`。版本与下载地址需和根目录 `VERSION`、GitHub Release 保持一致。App 的签名、公证状态只能根据实际发布证据填写。 | |
| 14 | 新增:默认中文入口与其他语言路由位于 `src/pages/`,共用 `src/components/CageHome.astro`。`src/i18n/cage.ts` 从根目录对应 README 提取正文,`src/i18n/languages.ts` 定义下拉框中的 15 种语言及界面短文案。样式位于 `src/styles/cage.css`,工作台截图位于 `public/`,README 共用素材位于根目录 `assets/`。`astro.config.mjs` 的 `site` 和 `base` 分别指定站点域名与项目子路径;内部链接、图片和重定向使用 `import.meta.env.BASE_URL`。自定义部署可通过 `SITE_URL` 和 `SITE_BASE` 覆盖。 | |
| 15 | 新增: | |
| 16 | 新增:下载信息来自 `src/data/release.json`,表示可公开下载的版本,可以低于根目录 `VERSION` 所标记的开发版本。从仓库根目录运行 `node www/scripts/sync-release.mjs`,即可从匿名 GitHub API 刷新公开版本,并核对附件与校验清单。普通本地构建使用已保存的数据,不要求联网。 | |
| 17 | 新增: | |
| 18 | 新增:GitHub Actions 在 `main` 的网站文件变化、Release 发布或编辑、手动运行时重新构建并部署 GitHub Pages;PR 只检查。Release 事件会先下载实际安装包与对应 Mihomo 源码,验证摘要、Developer ID 签名、Apple 公证和 Gatekeeper,失败时不会部署这一轮网站。发布操作见[公开发行与主页部署](../docs/public-releases.md)。 | |
| 19 | 新增: | |
| 20 | 新增:根目录 README 是维护者确认产品措辞的来源。README 修改触发主页重新构建;发布工作流只刷新下载版本并读取现有译文,不自动生成翻译。中文主页为 `/`,其他语言使用 `/<语言代码>/`,语言范围与根目录 README 导航一致,不提供英语。下拉框切换独立 URL;阿拉伯语、波斯语、普什图语、达里语使用从右向左布局。网页正文直接复用对应 README 译文,结构调整时构建会提示维护者同步映射。 | |
| 13 | 21 | |
| 14 | 删除:私有阶段主页通过 Sites 以仅所有者可见的方式预览,身份记录在 `.openai/hosting.json`。安装包存放于私有 GitHub Release,访问者仍需仓库权限;网站不保存或转发 GitHub 令牌。GitHub Actions 只构建静态产物,不自动公开 Pages。 | |
| 22 | 新增:GitHub Pages 是当前主页的发布目标,部署配置由仓库工作流维护。 | |
| 15 | 23 | |
| 16 | 删除:公开发布前需确认仓库、Release 和网站的访问范围,并更新正式域名。`SITE_URL` 可覆盖构建时站点地址。保留的上游组件不作为 Cage 页面入口。 | |
| 24 | 新增:`public/install.sh` 仍被上游 `release.sh` 与安装器测试使用,保留用于 agent-vm 兼容流程,不作为 Cage 安装入口。 | |
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import { defineConfig } from 'astro/config'; |
| 2 | 2 | export default defineConfig({ |
| 3 | 删除: site: process.env.SITE_URL || 'https://claude-cage.aedanheryford981685.chatgpt.site', | |
| 3 | 新增: site: process.env.SITE_URL || 'https://lee-xeo.github.io', | |
| 4 | 新增: base: process.env.SITE_BASE || '/Claude-Cage', | |
| 4 | 5 | trailingSlash: 'always', |
| 5 | 6 | server: { port: 4822 }, |
| 6 | 7 | build: { inlineStylesheets: 'auto' }, |
| @@ -1,22 +1,19 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "claude-cage-website", |
| 3 | 删除: "version": "0.1.0", | |
| 3 | 新增: "version": "0.1.0-alpha.1", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "claude-cage-website", |
| 9 | 删除: "version": "0.1.0", | |
| 9 | 新增: "version": "0.1.0-alpha.1", | |
| 10 | 10 | "license": "MIT", |
| 11 | 11 | "dependencies": { |
| 12 | 删除: "@astrojs/sitemap": "^3.7.4", | |
| 13 | 12 | "@fontsource-variable/inter": "^5.3.0", |
| 14 | 删除: "@fontsource-variable/jetbrains-mono": "^5.3.0", | |
| 15 | 13 | "astro": "^7.3.3" |
| 16 | 14 | }, |
| 17 | 15 | "devDependencies": { |
| 18 | 16 | "@astrojs/check": "^0.9.10", |
| 19 | 删除: "sharp": "^0.35.4", | |
| 20 | 17 | "typescript": "^6.0.3" |
| 21 | 18 | } |
| 22 | 19 | }, |
| @@ -357,16 +354,6 @@ | ||
| 357 | 354 | "node": ">=22.12.0" |
| 358 | 355 | } |
| 359 | 356 | }, |
| 360 | 删除: "node_modules/@astrojs/sitemap": { | |
| 361 | 删除: "version": "3.7.4", | |
| 362 | 删除: "resolved": "https://registry.npmjs.org/@astrojs/sitemap/-/sitemap-3.7.4.tgz", | |
| 363 | 删除: "integrity": "sha512-LbKNC24bdUWcQf/pThB6qLlSqHojxGjZDURIzFocY8rlWnAn2t74nnhnK6S5x0NHriHoAduLEpVjRykmeGiVvA==", | |
| 364 | 删除: "license": "MIT", | |
| 365 | 删除: "dependencies": { | |
| 366 | 删除: "sitemap": "^9.0.0", | |
| 367 | 删除: "zod": "^4.3.6" | |
| 368 | 删除: } | |
| 369 | 删除: }, | |
| 370 | 357 | "node_modules/@astrojs/telemetry": { |
| 371 | 358 | "version": "3.3.3", |
| 372 | 359 | "resolved": "https://registry.npmjs.org/@astrojs/telemetry/-/telemetry-3.3.3.tgz", |
| @@ -1149,21 +1136,12 @@ | ||
| 1149 | 1136 | "url": "https://github.com/sponsors/ayuhito" |
| 1150 | 1137 | } |
| 1151 | 1138 | }, |
| 1152 | 删除: "node_modules/@fontsource-variable/jetbrains-mono": { | |
| 1153 | 删除: "version": "5.3.0", | |
| 1154 | 删除: "resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz", | |
| 1155 | 删除: "integrity": "sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==", | |
| 1156 | 删除: "license": "OFL-1.1", | |
| 1157 | 删除: "funding": { | |
| 1158 | 删除: "url": "https://github.com/sponsors/ayuhito" | |
| 1159 | 删除: } | |
| 1160 | 删除: }, | |
| 1161 | 1139 | "node_modules/@img/colour": { |
| 1162 | 1140 | "version": "1.1.0", |
| 1163 | 1141 | "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", |
| 1164 | 1142 | "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", |
| 1165 | 删除: "devOptional": true, | |
| 1166 | 1143 | "license": "MIT", |
| 1144 | 新增: "optional": true, | |
| 1167 | 1145 | "engines": { |
| 1168 | 1146 | "node": ">=18" |
| 1169 | 1147 | } |
| @@ -1175,7 +1153,6 @@ | ||
| 1175 | 1153 | "cpu": [ |
| 1176 | 1154 | "arm64" |
| 1177 | 1155 | ], |
| 1178 | 删除: "dev": true, | |
| 1179 | 1156 | "license": "Apache-2.0", |
| 1180 | 1157 | "optional": true, |
| 1181 | 1158 | "os": [ |
| @@ -1198,7 +1175,6 @@ | ||
| 1198 | 1175 | "cpu": [ |
| 1199 | 1176 | "x64" |
| 1200 | 1177 | ], |
| 1201 | 删除: "dev": true, | |
| 1202 | 1178 | "license": "Apache-2.0", |
| 1203 | 1179 | "optional": true, |
| 1204 | 1180 | "os": [ |
| @@ -1218,7 +1194,6 @@ | ||
| 1218 | 1194 | "version": "0.35.5", |
| 1219 | 1195 | "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", |
| 1220 | 1196 | "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", |
| 1221 | 删除: "dev": true, | |
| 1222 | 1197 | "license": "Apache-2.0", |
| 1223 | 1198 | "optional": true, |
| 1224 | 1199 | "os": [ |
| @@ -1241,7 +1216,6 @@ | ||
| 1241 | 1216 | "cpu": [ |
| 1242 | 1217 | "arm64" |
| 1243 | 1218 | ], |
| 1244 | 删除: "dev": true, | |
| 1245 | 1219 | "license": "LGPL-3.0-or-later", |
| 1246 | 1220 | "optional": true, |
| 1247 | 1221 | "os": [ |
| @@ -1258,7 +1232,6 @@ | ||
| 1258 | 1232 | "cpu": [ |
| 1259 | 1233 | "x64" |
| 1260 | 1234 | ], |
| 1261 | 删除: "dev": true, | |
| 1262 | 1235 | "license": "LGPL-3.0-or-later", |
| 1263 | 1236 | "optional": true, |
| 1264 | 1237 | "os": [ |
| @@ -1275,7 +1248,6 @@ | ||
| 1275 | 1248 | "cpu": [ |
| 1276 | 1249 | "arm" |
| 1277 | 1250 | ], |
| 1278 | 删除: "dev": true, | |
| 1279 | 1251 | "license": "LGPL-3.0-or-later", |
| 1280 | 1252 | "optional": true, |
| 1281 | 1253 | "os": [ |
| @@ -1292,7 +1264,6 @@ | ||
| 1292 | 1264 | "cpu": [ |
| 1293 | 1265 | "arm64" |
| 1294 | 1266 | ], |
| 1295 | 删除: "dev": true, | |
| 1296 | 1267 | "license": "LGPL-3.0-or-later", |
| 1297 | 1268 | "optional": true, |
| 1298 | 1269 | "os": [ |
| @@ -1309,7 +1280,6 @@ | ||
| 1309 | 1280 | "cpu": [ |
| 1310 | 1281 | "ppc64" |
| 1311 | 1282 | ], |
| 1312 | 删除: "dev": true, | |
| 1313 | 1283 | "license": "LGPL-3.0-or-later", |
| 1314 | 1284 | "optional": true, |
| 1315 | 1285 | "os": [ |
| @@ -1326,7 +1296,6 @@ | ||
| 1326 | 1296 | "cpu": [ |
| 1327 | 1297 | "riscv64" |
| 1328 | 1298 | ], |
| 1329 | 删除: "dev": true, | |
| 1330 | 1299 | "license": "LGPL-3.0-or-later", |
| 1331 | 1300 | "optional": true, |
| 1332 | 1301 | "os": [ |
| @@ -1343,7 +1312,6 @@ | ||
| 1343 | 1312 | "cpu": [ |
| 1344 | 1313 | "s390x" |
| 1345 | 1314 | ], |
| 1346 | 删除: "dev": true, | |
| 1347 | 1315 | "license": "LGPL-3.0-or-later", |
| 1348 | 1316 | "optional": true, |
| 1349 | 1317 | "os": [ |
| @@ -1360,7 +1328,6 @@ | ||
| 1360 | 1328 | "cpu": [ |
| 1361 | 1329 | "x64" |
| 1362 | 1330 | ], |
| 1363 | 删除: "dev": true, | |
| 1364 | 1331 | "license": "LGPL-3.0-or-later", |
| 1365 | 1332 | "optional": true, |
| 1366 | 1333 | "os": [ |
| @@ -1377,7 +1344,6 @@ | ||
| 1377 | 1344 | "cpu": [ |
| 1378 | 1345 | "arm64" |
| 1379 | 1346 | ], |
| 1380 | 删除: "dev": true, | |
| 1381 | 1347 | "license": "LGPL-3.0-or-later", |
| 1382 | 1348 | "optional": true, |
| 1383 | 1349 | "os": [ |
| @@ -1394,7 +1360,6 @@ | ||
| 1394 | 1360 | "cpu": [ |
| 1395 | 1361 | "x64" |
| 1396 | 1362 | ], |
| 1397 | 删除: "dev": true, | |
| 1398 | 1363 | "license": "LGPL-3.0-or-later", |
| 1399 | 1364 | "optional": true, |
| 1400 | 1365 | "os": [ |
| @@ -1411,7 +1376,6 @@ | ||
| 1411 | 1376 | "cpu": [ |
| 1412 | 1377 | "arm" |
| 1413 | 1378 | ], |
| 1414 | 删除: "dev": true, | |
| 1415 | 1379 | "license": "Apache-2.0", |
| 1416 | 1380 | "optional": true, |
| 1417 | 1381 | "os": [ |
| @@ -1434,7 +1398,6 @@ | ||
| 1434 | 1398 | "cpu": [ |
| 1435 | 1399 | "arm64" |
| 1436 | 1400 | ], |
| 1437 | 删除: "dev": true, | |
| 1438 | 1401 | "license": "Apache-2.0", |
| 1439 | 1402 | "optional": true, |
| 1440 | 1403 | "os": [ |
| @@ -1457,7 +1420,6 @@ | ||
| 1457 | 1420 | "cpu": [ |
| 1458 | 1421 | "ppc64" |
| 1459 | 1422 | ], |
| 1460 | 删除: "dev": true, | |
| 1461 | 1423 | "license": "Apache-2.0", |
| 1462 | 1424 | "optional": true, |
| 1463 | 1425 | "os": [ |
| @@ -1480,7 +1442,6 @@ | ||
| 1480 | 1442 | "cpu": [ |
| 1481 | 1443 | "riscv64" |
| 1482 | 1444 | ], |
| 1483 | 删除: "dev": true, | |
| 1484 | 1445 | "license": "Apache-2.0", |
| 1485 | 1446 | "optional": true, |
| 1486 | 1447 | "os": [ |
| @@ -1503,7 +1464,6 @@ | ||
| 1503 | 1464 | "cpu": [ |
| 1504 | 1465 | "s390x" |
| 1505 | 1466 | ], |
| 1506 | 删除: "dev": true, | |
| 1507 | 1467 | "license": "Apache-2.0", |
| 1508 | 1468 | "optional": true, |
| 1509 | 1469 | "os": [ |
| @@ -1526,7 +1486,6 @@ | ||
| 1526 | 1486 | "cpu": [ |
| 1527 | 1487 | "x64" |
| 1528 | 1488 | ], |
| 1529 | 删除: "dev": true, | |
| 1530 | 1489 | "license": "Apache-2.0", |
| 1531 | 1490 | "optional": true, |
| 1532 | 1491 | "os": [ |
| @@ -1549,7 +1508,6 @@ | ||
| 1549 | 1508 | "cpu": [ |
| 1550 | 1509 | "arm64" |
| 1551 | 1510 | ], |
| 1552 | 删除: "dev": true, | |
| 1553 | 1511 | "license": "Apache-2.0", |
| 1554 | 1512 | "optional": true, |
| 1555 | 1513 | "os": [ |
| @@ -1572,7 +1530,6 @@ | ||
| 1572 | 1530 | "cpu": [ |
| 1573 | 1531 | "x64" |
| 1574 | 1532 | ], |
| 1575 | 删除: "dev": true, | |
| 1576 | 1533 | "license": "Apache-2.0", |
| 1577 | 1534 | "optional": true, |
| 1578 | 1535 | "os": [ |
| @@ -1592,7 +1549,6 @@ | ||
| 1592 | 1549 | "version": "0.35.5", |
| 1593 | 1550 | "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", |
| 1594 | 1551 | "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", |
| 1595 | 删除: "dev": true, | |
| 1596 | 1552 | "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", |
| 1597 | 1553 | "optional": true, |
| 1598 | 1554 | "dependencies": { |
| @@ -1612,7 +1568,6 @@ | ||
| 1612 | 1568 | "cpu": [ |
| 1613 | 1569 | "wasm32" |
| 1614 | 1570 | ], |
| 1615 | 删除: "dev": true, | |
| 1616 | 1571 | "license": "Apache-2.0", |
| 1617 | 1572 | "optional": true, |
| 1618 | 1573 | "dependencies": { |
| @@ -1632,7 +1587,6 @@ | ||
| 1632 | 1587 | "cpu": [ |
| 1633 | 1588 | "arm64" |
| 1634 | 1589 | ], |
| 1635 | 删除: "dev": true, | |
| 1636 | 1590 | "license": "Apache-2.0 AND LGPL-3.0-or-later", |
| 1637 | 1591 | "optional": true, |
| 1638 | 1592 | "os": [ |
| @@ -1652,7 +1606,6 @@ | ||
| 1652 | 1606 | "cpu": [ |
| 1653 | 1607 | "ia32" |
| 1654 | 1608 | ], |
| 1655 | 删除: "dev": true, | |
| 1656 | 1609 | "license": "Apache-2.0 AND LGPL-3.0-or-later", |
| 1657 | 1610 | "optional": true, |
| 1658 | 1611 | "os": [ |
| @@ -1672,7 +1625,6 @@ | ||
| 1672 | 1625 | "cpu": [ |
| 1673 | 1626 | "x64" |
| 1674 | 1627 | ], |
| 1675 | 删除: "dev": true, | |
| 1676 | 1628 | "license": "Apache-2.0 AND LGPL-3.0-or-later", |
| 1677 | 1629 | "optional": true, |
| 1678 | 1630 | "os": [ |
| @@ -2125,24 +2077,6 @@ | ||
| 2125 | 2077 | "@types/unist": "*" |
| 2126 | 2078 | } |
| 2127 | 2079 | }, |
| 2128 | 删除: "node_modules/@types/node": { | |
| 2129 | 删除: "version": "24.13.6", | |
| 2130 | 删除: "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.6.tgz", | |
| 2131 | 删除: "integrity": "sha512-SGrw/h3KPFshy3OE6ZL53LMBG5vGQQ8/gIpiqz/kRZhPJ7HgwCEs8LBuNtWLa8dvGZVpSF7+Bf+c11HUrCb/yg==", | |
| 2132 | 删除: "license": "MIT", | |
| 2133 | 删除: "dependencies": { | |
| 2134 | 删除: "undici-types": "~7.18.0" | |
| 2135 | 删除: } | |
| 2136 | 删除: }, | |
| 2137 | 删除: "node_modules/@types/sax": { | |
| 2138 | 删除: "version": "1.2.7", | |
| 2139 | 删除: "resolved": "https://registry.npmjs.org/@types/sax/-/sax-1.2.7.tgz", | |
| 2140 | 删除: "integrity": "sha512-rO73L89PJxeYM3s3pPPjiPgVVcymqU490g0YO5n5By0k2Erzj6tay/4lr1CHAAU4JyOWd1rpQ8bCf6cZfHU96A==", | |
| 2141 | 删除: "license": "MIT", | |
| 2142 | 删除: "dependencies": { | |
| 2143 | 删除: "@types/node": "*" | |
| 2144 | 删除: } | |
| 2145 | 删除: }, | |
| 2146 | 2080 | "node_modules/@types/unist": { |
| 2147 | 2081 | "version": "3.0.3", |
| 2148 | 2082 | "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", |
| @@ -2365,12 +2299,6 @@ | ||
| 2365 | 2299 | "url": "https://github.com/sponsors/jonschlinkert" |
| 2366 | 2300 | } |
| 2367 | 2301 | }, |
| 2368 | 删除: "node_modules/arg": { | |
| 2369 | 删除: "version": "5.0.2", | |
| 2370 | 删除: "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", | |
| 2371 | 删除: "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", | |
| 2372 | 删除: "license": "MIT" | |
| 2373 | 删除: }, | |
| 2374 | 2302 | "node_modules/argparse": { |
| 2375 | 2303 | "version": "2.0.1", |
| 2376 | 2304 | "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", |
| @@ -4120,8 +4048,8 @@ | ||
| 4120 | 4048 | "version": "0.35.5", |
| 4121 | 4049 | "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", |
| 4122 | 4050 | "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", |
| 4123 | 删除: "devOptional": true, | |
| 4124 | 4051 | "license": "Apache-2.0", |
| 4052 | 新增: "optional": true, | |
| 4125 | 4053 | "dependencies": { |
| 4126 | 4054 | "@img/colour": "^1.1.0", |
| 4127 | 4055 | "detect-libc": "^2.1.2", |
| @@ -4191,25 +4119,6 @@ | ||
| 4191 | 4119 | "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", |
| 4192 | 4120 | "license": "MIT" |
| 4193 | 4121 | }, |
| 4194 | 删除: "node_modules/sitemap": { | |
| 4195 | 删除: "version": "9.0.1", | |
| 4196 | 删除: "resolved": "https://registry.npmjs.org/sitemap/-/sitemap-9.0.1.tgz", | |
| 4197 | 删除: "integrity": "sha512-S6hzjGJSG3d6if0YoF5kTyeRJvia6FSTBroE5fQ0bu1QNxyJqhhinfUsXi9fH3MgtXODWvwo2BDyQSnhPQ88uQ==", | |
| 4198 | 删除: "license": "MIT", | |
| 4199 | 删除: "dependencies": { | |
| 4200 | 删除: "@types/node": "^24.9.2", | |
| 4201 | 删除: "@types/sax": "^1.2.1", | |
| 4202 | 删除: "arg": "^5.0.0", | |
| 4203 | 删除: "sax": "^1.4.1" | |
| 4204 | 删除: }, | |
| 4205 | 删除: "bin": { | |
| 4206 | 删除: "sitemap": "dist/esm/cli.js" | |
| 4207 | 删除: }, | |
| 4208 | 删除: "engines": { | |
| 4209 | 删除: "node": ">=20.19.5", | |
| 4210 | 删除: "npm": ">=10.8.2" | |
| 4211 | 删除: } | |
| 4212 | 删除: }, | |
| 4213 | 4122 | "node_modules/smol-toml": { |
| 4214 | 4123 | "version": "1.9.1", |
| 4215 | 4124 | "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz", |
| @@ -4438,12 +4347,6 @@ | ||
| 4438 | 4347 | "node": ">=22.19.0" |
| 4439 | 4348 | } |
| 4440 | 4349 | }, |
| 4441 | 删除: "node_modules/undici-types": { | |
| 4442 | 删除: "version": "7.18.2", | |
| 4443 | 删除: "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", | |
| 4444 | 删除: "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", | |
| 4445 | 删除: "license": "MIT" | |
| 4446 | 删除: }, | |
| 4447 | 4350 | "node_modules/unified": { |
| 4448 | 4351 | "version": "11.0.5", |
| 4449 | 4352 | "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "claude-cage-website", |
| 3 | 3 | "type": "module", |
| 4 | 删除: "version": "0.1.0", | |
| 4 | 新增: "version": "0.1.0-alpha.1", | |
| 5 | 5 | "private": true, |
| 6 | 6 | "description": "Claude Cage project website and macOS downloads", |
| 7 | 7 | "license": "MIT", |
| @@ -10,23 +10,17 @@ | ||
| 10 | 10 | "start": "astro dev", |
| 11 | 11 | "build": "astro build", |
| 12 | 12 | "preview": "astro preview", |
| 13 | 删除: "check": "astro check", | |
| 14 | 删除: "og": "node scripts/build-og.mjs", | |
| 15 | 删除: "favicon": "node scripts/build-favicon.mjs" | |
| 13 | 新增: "check": "astro check" | |
| 16 | 14 | }, |
| 17 | 15 | "dependencies": { |
| 18 | 删除: "@astrojs/sitemap": "^3.7.4", | |
| 19 | 16 | "@fontsource-variable/inter": "^5.3.0", |
| 20 | 删除: "@fontsource-variable/jetbrains-mono": "^5.3.0", | |
| 21 | 17 | "astro": "^7.3.3" |
| 22 | 18 | }, |
| 23 | 19 | "devDependencies": { |
| 24 | 20 | "@astrojs/check": "^0.9.10", |
| 25 | 删除: "sharp": "^0.35.4", | |
| 26 | 21 | "typescript": "^6.0.3" |
| 27 | 22 | }, |
| 28 | 23 | "allowScripts": { |
| 29 | 删除: "[email protected]": true, | |
| 30 | 删除: "[email protected]": true | |
| 24 | 新增: "[email protected]": true | |
| 31 | 25 | } |
| 32 | 26 | } |
二进制文件,不显示改动。
二进制文件,不显示改动。
| @@ -1,5 +0,0 @@ | ||
| 1 | 删除:<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="agent-vm"> | |
| 2 | 删除: <rect width="32" height="32" rx="7" fill="#191713"/> | |
| 3 | 删除: <rect x="5.5" y="5.5" width="21" height="21" rx="4.5" fill="none" stroke="#7d766b" stroke-width="1.6"/> | |
| 4 | 删除: <rect x="11" y="11" width="10" height="10" rx="2.2" fill="#d2772a"/> | |
| 5 | 删除:</svg> | |
二进制文件,不显示改动。
二进制文件,不显示改动。
二进制文件,不显示改动。
| @@ -1,2 +1,2 @@ | ||
| 1 | 1 | User-agent: * |
| 2 | 删除:Disallow: / | |
| 2 | 新增:Allow: / | |
二进制文件,不显示改动。
| @@ -1,29 +0,0 @@ | ||
| 1 | 删除:/** | |
| 2 | 删除: * Renders the PNG icons from public/favicon.svg: favicon.png for browsers | |
| 3 | 删除: * without SVG favicons, apple-touch-icon.png for iOS home screens. | |
| 4 | 删除: * | |
| 5 | 删除: * Run with `npm run favicon` after changing the SVG. The PNGs are committed, | |
| 6 | 删除: * like og.png. | |
| 7 | 删除: */ | |
| 8 | 删除: | |
| 9 | 删除:import { dirname, resolve } from 'node:path'; | |
| 10 | 删除:import { fileURLToPath } from 'node:url'; | |
| 11 | 删除:import sharp from 'sharp'; | |
| 12 | 删除: | |
| 13 | 删除:const here = dirname(fileURLToPath(import.meta.url)); | |
| 14 | 删除:const pub = resolve(here, '../public'); | |
| 15 | 删除:const svg = resolve(pub, 'favicon.svg'); | |
| 16 | 删除: | |
| 17 | 删除:// Sizes match the `sizes` attributes in Base.astro. | |
| 18 | 删除:async function render(name, size, flatten) { | |
| 19 | 删除: // Rasterized at 8x the target, then scaled down. The SVG's viewBox is 32px. | |
| 20 | 删除: let img = sharp(svg, { density: (72 * 8 * size) / 32 }).resize(size, size); | |
| 21 | 删除: if (flatten) img = img.flatten({ background: flatten }); | |
| 22 | 删除: await img.png({ compressionLevel: 9 }).toFile(resolve(pub, name)); | |
| 23 | 删除: console.log(`wrote ${resolve(pub, name)}`); | |
| 24 | 删除:} | |
| 25 | 删除: | |
| 26 | 删除:await render('favicon.png', 32); | |
| 27 | 删除:// iOS fills transparency with black and rounds the corners itself: the | |
| 28 | 删除:// background goes to the edges instead. | |
| 29 | 删除:await render('apple-touch-icon.png', 180, '#191713'); | |
| @@ -1,82 +0,0 @@ | ||
| 1 | 删除:/** | |
| 2 | 删除: * Renders public/og.png from an inline SVG. | |
| 3 | 删除: * | |
| 4 | 删除: * Run with `npm run og` after changing the wording. The PNG is committed, so a | |
| 5 | 删除: * normal `npm run build` (and the CI deploy) never needs sharp or a font stack | |
| 6 | 删除: * on the machine doing the build. | |
| 7 | 删除: */ | |
| 8 | 删除: | |
| 9 | 删除:import { mkdir } from 'node:fs/promises'; | |
| 10 | 删除:import { dirname, resolve } from 'node:path'; | |
| 11 | 删除:import { fileURLToPath } from 'node:url'; | |
| 12 | 删除:import sharp from 'sharp'; | |
| 13 | 删除: | |
| 14 | 删除:const here = dirname(fileURLToPath(import.meta.url)); | |
| 15 | 删除:const out = resolve(here, '../public/og.png'); | |
| 16 | 删除: | |
| 17 | 删除:const W = 1200; | |
| 18 | 删除:const H = 630; | |
| 19 | 删除:const GRID = 60; | |
| 20 | 删除: | |
| 21 | 删除:const gridLines = []; | |
| 22 | 删除:for (let x = GRID; x < W; x += GRID) { | |
| 23 | 删除: gridLines.push(`<line x1="${x}" y1="0" x2="${x}" y2="${H}" />`); | |
| 24 | 删除:} | |
| 25 | 删除:for (let y = GRID; y < H; y += GRID) { | |
| 26 | 删除: gridLines.push(`<line x1="0" y1="${y}" x2="${W}" y2="${y}" />`); | |
| 27 | 删除:} | |
| 28 | 删除: | |
| 29 | 删除:// The SVG renderer behind sharp does not map the generic `sans-serif` keyword | |
| 30 | 删除:// to a real family, so both stacks name actual faces and end on the keyword. | |
| 31 | 删除:// macOS hits Helvetica, a Linux CI box hits Liberation. | |
| 32 | 删除:const SANS = 'Inter, Helvetica Neue, Helvetica, Liberation Sans, Arial, sans-serif'; | |
| 33 | 删除:const MONO = 'JetBrains Mono, SF Mono, Menlo, DejaVu Sans Mono, Liberation Mono, monospace'; | |
| 34 | 删除: | |
| 35 | 删除:const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}"> | |
| 36 | 删除: <defs> | |
| 37 | 删除: <linearGradient id="fade" x1="0" y1="0" x2="0" y2="1"> | |
| 38 | 删除: <stop offset="0" stop-color="#ffffff" stop-opacity="0.05" /> | |
| 39 | 删除: <stop offset="1" stop-color="#ffffff" stop-opacity="0" /> | |
| 40 | 删除: </linearGradient> | |
| 41 | 删除: </defs> | |
| 42 | 删除: | |
| 43 | 删除: <rect width="${W}" height="${H}" fill="#131210" /> | |
| 44 | 删除: <g stroke="#ffffff" stroke-opacity="0.035" stroke-width="1"> | |
| 45 | 删除: ${gridLines.join('\n ')} | |
| 46 | 删除: </g> | |
| 47 | 删除: <rect width="${W}" height="${H}" fill="url(#fade)" /> | |
| 48 | 删除: | |
| 49 | 删除: <g transform="translate(96 96)"> | |
| 50 | 删除: <rect x="0" y="0" width="56" height="56" rx="13" fill="none" stroke="#8a8275" stroke-width="3" /> | |
| 51 | 删除: <rect x="17" y="17" width="22" height="22" rx="5" fill="#e08c3e" /> | |
| 52 | 删除: <text x="78" y="39" font-family="${MONO}" font-size="34" font-weight="700" fill="#f1ece2"> | |
| 53 | 删除: agent-vm | |
| 54 | 删除: </text> | |
| 55 | 删除: </g> | |
| 56 | 删除: | |
| 57 | 删除: <text x="96" y="310" font-family="${SANS}" font-size="66" font-weight="700" fill="#f1ece2"> | |
| 58 | 删除: Give agents a machine | |
| 59 | 删除: </text> | |
| 60 | 删除: <text x="96" y="388" font-family="${SANS}" font-size="66" font-weight="700" fill="#f1ece2"> | |
| 61 | 删除: they can wreck. | |
| 62 | 删除: <tspan fill="#e08c3e"> Keep yours.</tspan> | |
| 63 | 删除: </text> | |
| 64 | 删除: | |
| 65 | 删除: <text x="96" y="462" font-family="${SANS}" font-size="29" fill="#b8afa1"> | |
| 66 | 删除: Sandboxed Linux VMs for AI coding agents. One per project. | |
| 67 | 删除: </text> | |
| 68 | 删除: | |
| 69 | 删除: <line x1="96" y1="524" x2="${W - 96}" y2="524" stroke="#2c2823" stroke-width="2" /> | |
| 70 | 删除: | |
| 71 | 删除: <text x="96" y="568" font-family="${MONO}" font-size="24" fill="#8a8275"> | |
| 72 | 删除: www.agent-vm.org | |
| 73 | 删除: </text> | |
| 74 | 删除: <text x="${W - 96}" y="568" text-anchor="end" font-family="${MONO}" font-size="24" fill="#8a8275"> | |
| 75 | 删除: MIT · macOS + Linux · built on Lima | |
| 76 | 删除: </text> | |
| 77 | 删除:</svg>`; | |
| 78 | 删除: | |
| 79 | 删除:await mkdir(dirname(out), { recursive: true }); | |
| 80 | 删除:await sharp(Buffer.from(svg)).png({ compressionLevel: 9 }).toFile(out); | |
| 81 | 删除: | |
| 82 | 删除:console.log(`wrote ${out}`); | |
| @@ -0,0 +1,31 @@ | ||
| 1 | 新增:// Check emitted pages, not just the locale configuration: catch missing routes, | |
| 2 | 新增:// broken project subpaths and languages drifting away from the README menu. | |
| 3 | 新增:import assert from 'node:assert/strict'; | |
| 4 | 新增:import fs from 'node:fs'; | |
| 5 | 新增:import path from 'node:path'; | |
| 6 | 新增:import { fileURLToPath } from 'node:url'; | |
| 7 | 新增:const root = fileURLToPath(new URL('../../', import.meta.url)); | |
| 8 | 新增:const readme = fs.readFileSync(path.join(root,'README.md'),'utf8'); | |
| 9 | 新增:const menu = readme.split('\n').find(line => line.includes('(README.md)') && line.includes('(README.')); | |
| 10 | 新增:assert.ok(menu, 'README language navigation is missing'); | |
| 11 | 新增:const codes = [...menu.matchAll(/\]\(README(?:\.([\w-]+))?\.md\)/g)].map(m => m[1] || 'zh'); | |
| 12 | 新增:// README.md has no dot before the base name's extension in the optional group. | |
| 13 | 新增:assert.equal(codes[0], 'zh'); | |
| 14 | 新增:assert.ok(!codes.includes('en')); | |
| 15 | 新增:const dist = path.join(root,'www/dist'); | |
| 16 | 新增:for (const code of codes) { | |
| 17 | 新增: const html = fs.readFileSync(path.join(dist,code === 'zh' ? '' : code,'index.html'),'utf8'); | |
| 18 | 新增: const options = [...html.matchAll(/<option\b[^>]*value="([^"]+)"/g)].map(m=>m[1]); | |
| 19 | 新增: assert.equal(options.length,codes.length, `${code}: language dropdown missing options`); | |
| 20 | 新增: assert.ok(!options.some(url=>url.endsWith('/en/')), `${code}: unexpected English route`); | |
| 21 | 新增: assert.ok(html.includes('id="site-language"'), `${code}: missing language selector`); | |
| 22 | 新增: assert.ok(html.includes(`dir="${['ar','fa','ps','prs'].includes(code)?'rtl':'ltr'}"`), `${code}: incorrect reading direction`); | |
| 23 | 新增: for (const match of html.matchAll(/(?:src|href)="(\/Claude-Cage\/[^"#]+)"/g)) { | |
| 24 | 新增: const relative = decodeURIComponent(match[1].slice('/Claude-Cage/'.length)); | |
| 25 | 新增: const target = path.join(dist,relative.endsWith('/') ? relative+'index.html' : relative); | |
| 26 | 新增: assert.ok(fs.existsSync(target), `${code}: broken local asset or link ${match[1]}`); | |
| 27 | 新增: } | |
| 28 | 新增: assert.ok(!html.includes('/Users/'), `${code}: local developer path leaked`); | |
| 29 | 新增:} | |
| 30 | 新增:assert.ok(!fs.existsSync(path.join(dist,'en/index.html')), 'Old English page still present'); | |
| 31 | 新增:console.log(`Verified ${codes.length} README languages, dropdowns, directions and local assets.`); | |
| @@ -0,0 +1,113 @@ | ||
| 1 | 新增:// Use anonymous public endpoints: a maintainer token must not hide download failures. | |
| 2 | 新增:import { createHash } from 'node:crypto'; | |
| 3 | 新增:import { createWriteStream } from 'node:fs'; | |
| 4 | 新增:import { mkdir, writeFile, rm } from 'node:fs/promises'; | |
| 5 | 新增:import { dirname, join, resolve } from 'node:path'; | |
| 6 | 新增:import { pathToFileURL } from 'node:url'; | |
| 7 | 新增:import { Readable, Transform } from 'node:stream'; | |
| 8 | 新增:import { pipeline } from 'node:stream/promises'; | |
| 9 | 新增:import { parseArgs } from 'node:util'; | |
| 10 | 新增: | |
| 11 | 新增:const repository = 'Lee-xeo/Claude-Cage'; | |
| 12 | 新增:const repoURL = `https://github.com/${repository}`; | |
| 13 | 新增:const apiURL = `https://api.github.com/repos/${repository}/releases`; | |
| 14 | 新增: | |
| 15 | 新增:async function request(url) { | |
| 16 | 新增: const response = await fetch(url, { | |
| 17 | 新增: headers: { 'User-Agent': 'Cage-Release-Verification', Accept: url.startsWith(apiURL) ? 'application/vnd.github+json' : 'application/octet-stream' }, | |
| 18 | 新增: signal: AbortSignal.timeout(180_000), | |
| 19 | 新增: }); | |
| 20 | 新增: if (!response.ok) throw new Error(`Public download failed: HTTP ${response.status} (${new URL(url).pathname})`); | |
| 21 | 新增: return response; | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:export function releaseAssets(release) { | |
| 25 | 新增: if (release.draft || !/^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(release.tag_name)) { | |
| 26 | 新增: throw new Error('Expected a published Cage version tag'); | |
| 27 | 新增: } | |
| 28 | 新增: const version = release.tag_name.slice(1); | |
| 29 | 新增: const names = [`Cage-${version}-macos-arm64.dmg`, 'SHA256SUMS']; | |
| 30 | 新增: const assets = names.map(name => release.assets.find(asset => asset.name === name)); | |
| 31 | 新增: const source = release.assets.find(asset => /^mihomo-v[\d.]+-source\.tar\.gz$/.test(asset.name)); | |
| 32 | 新增: assets.push(source); | |
| 33 | 新增: for (const asset of assets) { | |
| 34 | 新增: if (!asset || asset.state !== 'uploaded' || !Number.isSafeInteger(asset.size) || asset.size <= 0 || asset.size > 512 * 1024 * 1024) { | |
| 35 | 新增: throw new Error(`Release ${release.tag_name} is missing a complete DMG, checksum file, or Mihomo source`); | |
| 36 | 新增: } | |
| 37 | 新增: if (asset.browser_download_url !== `${repoURL}/releases/download/${release.tag_name}/${asset.name}`) { | |
| 38 | 新增: throw new Error('Release asset is outside the expected repository and tag'); | |
| 39 | 新增: } | |
| 40 | 新增: } | |
| 41 | 新增: if (assets[1].size > 64 * 1024) throw new Error('Checksum file is too large'); | |
| 42 | 新增: return { version, archive: assets[0], checksums: assets[1], source }; | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:export function checksumFor(text, asset) { | |
| 46 | 新增: const entries = text.split(/\r?\n/).map(line => line.trim().split(/\s+/)) | |
| 47 | 新增: .filter(fields => fields.length === 2 && fields[1].replace(/^\*/, '') === asset.name); | |
| 48 | 新增: if (entries.length !== 1 || !/^[a-f0-9]{64}$/i.test(entries[0][0])) throw new Error(`Missing or duplicate SHA-256 for ${asset.name}`); | |
| 49 | 新增: const digest = entries[0][0].toLowerCase(); | |
| 50 | 新增: if (asset.digest && asset.digest.toLowerCase() !== `sha256:${digest}`) throw new Error(`GitHub digest disagrees with SHA256SUMS for ${asset.name}`); | |
| 51 | 新增: return digest; | |
| 52 | 新增:} | |
| 53 | 新增: | |
| 54 | 新增:async function download(asset, digest, directory) { | |
| 55 | 新增: await mkdir(directory, { recursive: true }); | |
| 56 | 新增: const path = join(directory, asset.name); | |
| 57 | 新增: const response = await request(asset.browser_download_url); | |
| 58 | 新增: const hash = createHash('sha256'); | |
| 59 | 新增: let size = 0; | |
| 60 | 新增: try { | |
| 61 | 新增: await pipeline(Readable.fromWeb(response.body), new Transform({ | |
| 62 | 新增: transform(chunk, encoding, callback) { | |
| 63 | 新增: size += chunk.length; | |
| 64 | 新增: if (size > asset.size) return callback(new Error('Release asset exceeds its declared size')); | |
| 65 | 新增: hash.update(chunk); | |
| 66 | 新增: callback(null, chunk); | |
| 67 | 新增: }, | |
| 68 | 新增: }), createWriteStream(`${path}.part`, { flags: 'wx' })); | |
| 69 | 新增: if (size !== asset.size || hash.digest('hex') !== digest) throw new Error(`Downloaded bytes do not match SHA256SUMS: ${asset.name}`); | |
| 70 | 新增: const { rename } = await import('node:fs/promises'); | |
| 71 | 新增: await rename(`${path}.part`, path); | |
| 72 | 新增: } finally { | |
| 73 | 新增: await rm(`${path}.part`, { force: true }); | |
| 74 | 新增: } | |
| 75 | 新增: console.log(`Verified public download: ${asset.name} (${size} bytes)`); | |
| 76 | 新增:} | |
| 77 | 新增: | |
| 78 | 新增:async function main() { | |
| 79 | 新增: const { values } = parseArgs({ options: { | |
| 80 | 新增: tag: { type: 'string' }, output: { type: 'string', default: 'www/src/data/release.json' }, | |
| 81 | 新增: 'archive-directory': { type: 'string' }, | |
| 82 | 新增: } }); | |
| 83 | 新增: let release; | |
| 84 | 新增: if (values.tag) { | |
| 85 | 新增: release = await (await request(`${apiURL}/tags/${encodeURIComponent(values.tag)}`)).json(); | |
| 86 | 新增: } else { | |
| 87 | 新增: const releases = await (await request(`${apiURL}?per_page=100`)).json(); | |
| 88 | 新增: // GitHub orders by creation time. Show the first complete public Cage release. | |
| 89 | 新增: release = releases.find(item => { | |
| 90 | 新增: try { releaseAssets(item); return true; } catch { return false; } | |
| 91 | 新增: }); | |
| 92 | 新增: if (!release) throw new Error('No complete public Cage release is available'); | |
| 93 | 新增: } | |
| 94 | 新增: const { version, archive, checksums, source } = releaseAssets(release); | |
| 95 | 新增: const response = await request(checksums.browser_download_url); | |
| 96 | 新增: const text = await response.text(); | |
| 97 | 新增: if (Buffer.byteLength(text) !== checksums.size) throw new Error('Checksum file size differs from GitHub metadata'); | |
| 98 | 新增: const digest = checksumFor(text, archive); | |
| 99 | 新增: const sourceDigest = checksumFor(text, source); | |
| 100 | 新增: if (values['archive-directory']) { | |
| 101 | 新增: await download(archive, digest, values['archive-directory']); | |
| 102 | 新增: await download(source, sourceDigest, values['archive-directory']); | |
| 103 | 新增: await writeFile(join(values['archive-directory'], 'SHA256SUMS'), text); | |
| 104 | 新增: } | |
| 105 | 新增: const output = resolve(values.output); | |
| 106 | 新增: await mkdir(dirname(output), { recursive: true }); | |
| 107 | 新增: await writeFile(output, `${JSON.stringify({ version, releaseURL: `${repoURL}/releases/tag/v${version}`, downloadURL: archive.browser_download_url }, null, 2)}\n`); | |
| 108 | 新增: console.log(`Website download: Cage ${version}`); | |
| 109 | 新增:} | |
| 110 | 新增: | |
| 111 | 新增:if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { | |
| 112 | 新增: main().catch(error => { console.error(error.message); process.exitCode = 1; }); | |
| 113 | 新增:} | |
| @@ -0,0 +1,32 @@ | ||
| 1 | 新增:import assert from 'node:assert/strict'; | |
| 2 | 新增:import { test } from 'node:test'; | |
| 3 | 新增:import { releaseAssets, checksumFor } from './sync-release.mjs'; | |
| 4 | 新增: | |
| 5 | 新增:const hash = 'a'.repeat(64); | |
| 6 | 新增:function fixture() { | |
| 7 | 新增: return { tag_name: 'v0.2.0-alpha.10', draft: false, assets: | |
| 8 | 新增: ['Cage-0.2.0-alpha.10-macos-arm64.dmg', 'SHA256SUMS', 'mihomo-v1.19.33-source.tar.gz'].map(name => ({ | |
| 9 | 新增: name, state: 'uploaded', size: 100, digest: `sha256:${hash}`, | |
| 10 | 新增: browser_download_url: `https://github.com/Lee-xeo/Claude-Cage/releases/download/v0.2.0-alpha.10/${name}`, | |
| 11 | 新增: })), | |
| 12 | 新增: }; | |
| 13 | 新增:} | |
| 14 | 新增:test('accept complete Alpha release; reject drafts, incomplete uploads and cross-version assets', () => { | |
| 15 | 新增: assert.equal(releaseAssets(fixture()).version, '0.2.0-alpha.10'); | |
| 16 | 新增: for (const mutate of [ | |
| 17 | 新增: r => { r.draft = true; }, r => { r.assets.pop(); }, | |
| 18 | 新增: r => { r.assets[0].state = 'new'; }, r => { r.assets[0].size = 0; }, | |
| 19 | 新增: r => { r.assets[0].browser_download_url = r.assets[0].browser_download_url.replace('/v0.2.0-alpha.10/', '/v0.1.0/'); }, | |
| 20 | 新增: ]) { | |
| 21 | 新增: const release = fixture(); mutate(release); | |
| 22 | 新增: assert.throws(() => releaseAssets(release)); | |
| 23 | 新增: } | |
| 24 | 新增:}); | |
| 25 | 新增:test('checksum must uniquely match the archive and GitHub digest', () => { | |
| 26 | 新增: const archive = fixture().assets[0]; | |
| 27 | 新增: const line = `${hash} ${archive.name}\n`; | |
| 28 | 新增: assert.equal(checksumFor(line, archive), hash); | |
| 29 | 新增: for (const text of ['', line + line, `${'b'.repeat(64)} ${archive.name}`, `${hash} another.dmg`]) { | |
| 30 | 新增: assert.throws(() => checksumFor(text, archive)); | |
| 31 | 新增: } | |
| 32 | 新增:}); | |
| @@ -1,479 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import CodeBlock from './CodeBlock.astro'; | |
| 3 | 删除:import { inline } from '../lib/inline'; | |
| 4 | 删除:import Heading from './Heading.astro'; | |
| 5 | 删除:import { slug } from '../lib/slug'; | |
| 6 | 删除:import { en } from '../i18n/en'; | |
| 7 | 删除:import { t, type Locale } from '../i18n'; | |
| 8 | 删除: | |
| 9 | 删除:interface Props { | |
| 10 | 删除: locale: Locale; | |
| 11 | 删除:} | |
| 12 | 删除: | |
| 13 | 删除:const { locale } = Astro.props; | |
| 14 | 删除:const d = t(locale); | |
| 15 | 删除:const dg = d.architecture.diagram; | |
| 16 | 删除:--- | |
| 17 | 删除: | |
| 18 | 删除:<section class="section" id="architecture"> | |
| 19 | 删除: <div class="container"> | |
| 20 | 删除: <div class="section-head"> | |
| 21 | 删除: <p class="eyebrow">{d.architecture.eyebrow}</p> | |
| 22 | 删除: <Heading as="h2" id="architecture" own={false} locale={locale}>{d.architecture.title}</Heading> | |
| 23 | 删除: <p class="lede" set:html={inline(d.architecture.lede)} /> | |
| 24 | 删除: </div> | |
| 25 | 删除: | |
| 26 | 删除: <ol class="arch__steps"> | |
| 27 | 删除: { | |
| 28 | 删除: d.architecture.steps.map((step, index) => ( | |
| 29 | 删除: <li class="arch__step"> | |
| 30 | 删除: <span class="arch__step-n" aria-hidden="true"> | |
| 31 | 删除: {step.n} | |
| 32 | 删除: </span> | |
| 33 | 删除: <Heading as="h3" id={slug(en.architecture.steps[index]!.title)} locale={locale} class="arch__step-title">{step.title}</Heading> | |
| 34 | 删除: <p class="prose arch__step-body" set:html={inline(step.body)} /> | |
| 35 | 删除: </li> | |
| 36 | 删除: )) | |
| 37 | 删除: } | |
| 38 | 删除: </ol> | |
| 39 | 删除: | |
| 40 | 删除: <div class="arch__diagram"> | |
| 41 | 删除: <div class="arch__panel arch__panel--host"> | |
| 42 | 删除: <div class="arch__panel-head"> | |
| 43 | 删除: <h3 class="arch__panel-title">{dg.hostTitle}</h3> | |
| 44 | 删除: <span class="arch__panel-note">{dg.hostNote}</span> | |
| 45 | 删除: </div> | |
| 46 | 删除: <ul class="arch__items"> | |
| 47 | 删除: {dg.hostItems.map((item) => <li class="arch__item arch__item--locked">{item}</li>)} | |
| 48 | 删除: </ul> | |
| 49 | 删除: </div> | |
| 50 | 删除: | |
| 51 | 删除: <div class="arch__boundary"> | |
| 52 | 删除: <span class="arch__boundary-label">{dg.boundaryLabel}</span> | |
| 53 | 删除: </div> | |
| 54 | 删除: | |
| 55 | 删除: <div class="arch__panel arch__panel--vm"> | |
| 56 | 删除: <div class="arch__panel-head"> | |
| 57 | 删除: <h3 class="arch__panel-title">{dg.vmTitle}</h3> | |
| 58 | 删除: <span class="arch__panel-note arch__panel-note--safe">{dg.vmNote}</span> | |
| 59 | 删除: </div> | |
| 60 | 删除: <ul class="arch__items"> | |
| 61 | 删除: {dg.vmItems.map((item) => <li class="arch__item">{item}</li>)} | |
| 62 | 删除: </ul> | |
| 63 | 删除: </div> | |
| 64 | 删除: | |
| 65 | 删除: {/* Spans both columns on purpose: the project directory is the one | |
| 66 | 删除: thing that exists on both sides of the boundary at once. */} | |
| 67 | 删除: <div class="arch__shared"> | |
| 68 | 删除: <div class="arch__shared-stems" aria-hidden="true"> | |
| 69 | 删除: <span class="arch__stem"></span> | |
| 70 | 删除: <span class="arch__stem"></span> | |
| 71 | 删除: </div> | |
| 72 | 删除: <div class="arch__shared-box"> | |
| 73 | 删除: <div class="arch__panel-head"> | |
| 74 | 删除: <h3 class="arch__shared-title">{dg.sharedTitle}</h3> | |
| 75 | 删除: <span class="arch__shared-label">{dg.sharedLabel}</span> | |
| 76 | 删除: </div> | |
| 77 | 删除: <p class="prose arch__shared-body" set:html={inline(dg.sharedBody)} /> | |
| 78 | 删除: </div> | |
| 79 | 删除: </div> | |
| 80 | 删除: </div> | |
| 81 | 删除: | |
| 82 | 删除: <p class="prose arch__isolation" set:html={inline(d.architecture.isolationNote)} /> | |
| 83 | 删除: | |
| 84 | 删除: <div class="arch__tables"> | |
| 85 | 删除: <div class="arch__table-block"> | |
| 86 | 删除: <Heading as="h3" id={slug(en.architecture.contentsTitle)} locale={locale} class="arch__sub">{d.architecture.contentsTitle}</Heading> | |
| 87 | 删除: <p class="prose arch__sub-body" set:html={inline(d.architecture.contentsLede)} /> | |
| 88 | 删除: <div class="table-wrap"> | |
| 89 | 删除: <table> | |
| 90 | 删除: <thead> | |
| 91 | 删除: <tr> | |
| 92 | 删除: {d.architecture.contentsHeaders.map((header) => <th scope="col">{header}</th>)} | |
| 93 | 删除: </tr> | |
| 94 | 删除: </thead> | |
| 95 | 删除: <tbody> | |
| 96 | 删除: { | |
| 97 | 删除: d.architecture.contents.map(([category, packages, name, standard]) => ( | |
| 98 | 删除: <tr> | |
| 99 | 删除: <td>{category}</td> | |
| 100 | 删除: <td class="arch__packages">{packages}</td> | |
| 101 | 删除: <td class="arch__name">{name}</td> | |
| 102 | 删除: <td class="arch__flag">{standard}</td> | |
| 103 | 删除: </tr> | |
| 104 | 删除: )) | |
| 105 | 删除: } | |
| 106 | 删除: </tbody> | |
| 107 | 删除: </table> | |
| 108 | 删除: </div> | |
| 109 | 删除: <CodeBlock locale={locale} code={d.architecture.contentsCode} /> | |
| 110 | 删除: <p class="prose arch__sub-note" set:html={inline(d.architecture.contentsNote)} /> | |
| 111 | 删除: </div> | |
| 112 | 删除: | |
| 113 | 删除: <div class="arch__table-block"> | |
| 114 | 删除: <Heading as="h3" id={slug(en.architecture.dockerTitle)} locale={locale} class="arch__sub">{d.architecture.dockerTitle}</Heading> | |
| 115 | 删除: <p class="prose arch__sub-body" set:html={inline(d.architecture.dockerLede)} /> | |
| 116 | 删除: <div class="table-wrap"> | |
| 117 | 删除: <table class="arch__compare"> | |
| 118 | 删除: <thead> | |
| 119 | 删除: <tr> | |
| 120 | 删除: { | |
| 121 | 删除: d.architecture.dockerHeaders.map((header, index) => ( | |
| 122 | 删除: <th scope="col" class:list={[index === 3 && 'arch__col-win']}> | |
| 123 | 删除: {header} | |
| 124 | 删除: </th> | |
| 125 | 删除: )) | |
| 126 | 删除: } | |
| 127 | 删除: </tr> | |
| 128 | 删除: </thead> | |
| 129 | 删除: <tbody> | |
| 130 | 删除: { | |
| 131 | 删除: d.architecture.docker.map((row) => ( | |
| 132 | 删除: <tr> | |
| 133 | 删除: <th scope="row">{row[0]}</th> | |
| 134 | 删除: <td set:html={inline(row[1] ?? '')} /> | |
| 135 | 删除: <td set:html={inline(row[2] ?? '')} /> | |
| 136 | 删除: <td class="arch__col-win" set:html={inline(row[3] ?? '')} /> | |
| 137 | 删除: </tr> | |
| 138 | 删除: )) | |
| 139 | 删除: } | |
| 140 | 删除: </tbody> | |
| 141 | 删除: </table> | |
| 142 | 删除: </div> | |
| 143 | 删除: <p class="prose arch__sub-note" set:html={inline(d.architecture.dockerNote)} /> | |
| 144 | 删除: </div> | |
| 145 | 删除: </div> | |
| 146 | 删除: </div> | |
| 147 | 删除:</section> | |
| 148 | 删除: | |
| 149 | 删除:<style> | |
| 150 | 删除: .arch__steps { | |
| 151 | 删除: display: grid; | |
| 152 | 删除: grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr)); | |
| 153 | 删除: gap: 0; | |
| 154 | 删除: list-style: none; | |
| 155 | 删除: border-top: 1px solid var(--line); | |
| 156 | 删除: margin-bottom: clamp(2.75rem, 5.5vw, 4.5rem); | |
| 157 | 删除: } | |
| 158 | 删除: | |
| 159 | 删除: .arch__step { | |
| 160 | 删除: padding: 1.6rem clamp(1rem, 2vw, 1.75rem) 1.75rem; | |
| 161 | 删除: border-left: 1px solid var(--line); | |
| 162 | 删除: } | |
| 163 | 删除: | |
| 164 | 删除: .arch__step:first-child { | |
| 165 | 删除: padding-left: 0; | |
| 166 | 删除: border-left: 0; | |
| 167 | 删除: } | |
| 168 | 删除: | |
| 169 | 删除: .arch__step-n { | |
| 170 | 删除: display: block; | |
| 171 | 删除: font-family: var(--font-mono); | |
| 172 | 删除: font-size: 0.72rem; | |
| 173 | 删除: letter-spacing: 0.12em; | |
| 174 | 删除: color: var(--accent); | |
| 175 | 删除: margin-bottom: 0.8rem; | |
| 176 | 删除: } | |
| 177 | 删除: | |
| 178 | 删除: .arch__step-title { | |
| 179 | 删除: font-size: 0.98rem; | |
| 180 | 删除: margin-bottom: 0.45rem; | |
| 181 | 删除: } | |
| 182 | 删除: | |
| 183 | 删除: .arch__step-body { | |
| 184 | 删除: font-size: 0.89rem; | |
| 185 | 删除: } | |
| 186 | 删除: | |
| 187 | 删除: /* Diagram ----------------------------------------------------------------- */ | |
| 188 | 删除: | |
| 189 | 删除: .arch__diagram { | |
| 190 | 删除: --diagram-gap: clamp(1rem, 2.5vw, 2rem); | |
| 191 | 删除: display: grid; | |
| 192 | 删除: grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); | |
| 193 | 删除: gap: var(--diagram-gap); | |
| 194 | 删除: align-items: stretch; | |
| 195 | 删除: padding: clamp(1.5rem, 3vw, 2.5rem); | |
| 196 | 删除: border: 1px solid var(--line); | |
| 197 | 删除: border-radius: var(--radius-lg); | |
| 198 | 删除: background: var(--surface); | |
| 199 | 删除: } | |
| 200 | 删除: | |
| 201 | 删除: .arch__panel { | |
| 202 | 删除: display: grid; | |
| 203 | 删除: align-content: start; | |
| 204 | 删除: gap: 1.1rem; | |
| 205 | 删除: padding: clamp(1.1rem, 2vw, 1.5rem); | |
| 206 | 删除: border: 1px solid var(--line); | |
| 207 | 删除: border-radius: var(--radius); | |
| 208 | 删除: background: var(--surface-2); | |
| 209 | 删除: } | |
| 210 | 删除: | |
| 211 | 删除: .arch__panel--vm { | |
| 212 | 删除: border-color: var(--safe-line); | |
| 213 | 删除: background: var(--safe-wash); | |
| 214 | 删除: } | |
| 215 | 删除: | |
| 216 | 删除: .arch__panel-head { | |
| 217 | 删除: display: flex; | |
| 218 | 删除: flex-wrap: wrap; | |
| 219 | 删除: align-items: baseline; | |
| 220 | 删除: justify-content: space-between; | |
| 221 | 删除: gap: 0.5rem; | |
| 222 | 删除: } | |
| 223 | 删除: | |
| 224 | 删除: .arch__panel-title { | |
| 225 | 删除: font-size: 1rem; | |
| 226 | 删除: } | |
| 227 | 删除: | |
| 228 | 删除: .arch__panel-note { | |
| 229 | 删除: font-family: var(--font-mono); | |
| 230 | 删除: font-size: 0.68rem; | |
| 231 | 删除: letter-spacing: 0.08em; | |
| 232 | 删除: text-transform: uppercase; | |
| 233 | 删除: color: var(--ink-3); | |
| 234 | 删除: } | |
| 235 | 删除: | |
| 236 | 删除: .arch__panel-note--safe { | |
| 237 | 删除: color: var(--safe); | |
| 238 | 删除: } | |
| 239 | 删除: | |
| 240 | 删除: .arch__items { | |
| 241 | 删除: display: grid; | |
| 242 | 删除: gap: 0.4rem; | |
| 243 | 删除: list-style: none; | |
| 244 | 删除: } | |
| 245 | 删除: | |
| 246 | 删除: .arch__item { | |
| 247 | 删除: position: relative; | |
| 248 | 删除: padding-left: 1.15rem; | |
| 249 | 删除: font-size: 0.89rem; | |
| 250 | 删除: color: var(--ink-2); | |
| 251 | 删除: } | |
| 252 | 删除: | |
| 253 | 删除: .arch__item::before { | |
| 254 | 删除: content: ''; | |
| 255 | 删除: position: absolute; | |
| 256 | 删除: left: 0; | |
| 257 | 删除: top: 0.62em; | |
| 258 | 删除: width: 0.4rem; | |
| 259 | 删除: height: 0.4rem; | |
| 260 | 删除: border-radius: 50%; | |
| 261 | 删除: background: var(--safe); | |
| 262 | 删除: } | |
| 263 | 删除: | |
| 264 | 删除: .arch__item--locked::before { | |
| 265 | 删除: background: var(--ink-4); | |
| 266 | 删除: } | |
| 267 | 删除: | |
| 268 | 删除: .arch__boundary { | |
| 269 | 删除: position: relative; | |
| 270 | 删除: display: grid; | |
| 271 | 删除: place-items: center; | |
| 272 | 删除: min-width: 2.5rem; | |
| 273 | 删除: } | |
| 274 | 删除: | |
| 275 | 删除: .arch__boundary::before { | |
| 276 | 删除: content: ''; | |
| 277 | 删除: position: absolute; | |
| 278 | 删除: top: 0; | |
| 279 | 删除: bottom: 0; | |
| 280 | 删除: left: 50%; | |
| 281 | 删除: width: 0; | |
| 282 | 删除: border-left: 2px dashed var(--line-strong); | |
| 283 | 删除: } | |
| 284 | 删除: | |
| 285 | 删除: .arch__boundary-label { | |
| 286 | 删除: position: relative; | |
| 287 | 删除: padding: 0.5rem 0.25rem; | |
| 288 | 删除: background: var(--surface); | |
| 289 | 删除: font-family: var(--font-mono); | |
| 290 | 删除: font-size: 0.65rem; | |
| 291 | 删除: letter-spacing: 0.14em; | |
| 292 | 删除: text-transform: uppercase; | |
| 293 | 删除: color: var(--ink-3); | |
| 294 | 删除: writing-mode: vertical-rl; | |
| 295 | 删除: text-orientation: mixed; | |
| 296 | 删除: } | |
| 297 | 删除: | |
| 298 | 删除: /* The shared band sits under both panels and grows a stem up into each, | |
| 299 | 删除: so the project directory reads as one thing touching both sides. */ | |
| 300 | 删除: .arch__shared { | |
| 301 | 删除: grid-column: 1 / -1; | |
| 302 | 删除: /* Cancel the row gap so the stems start at the panels' bottom edge | |
| 303 | 删除: instead of floating below it. */ | |
| 304 | 删除: margin-top: calc(-1 * var(--diagram-gap)); | |
| 305 | 删除: } | |
| 306 | 删除: | |
| 307 | 删除: .arch__shared-stems { | |
| 308 | 删除: display: grid; | |
| 309 | 删除: grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); | |
| 310 | 删除: gap: var(--diagram-gap); | |
| 311 | 删除: height: calc(var(--diagram-gap) + 1.4rem); | |
| 312 | 删除: } | |
| 313 | 删除: | |
| 314 | 删除: .arch__stem { | |
| 315 | 删除: justify-self: center; | |
| 316 | 删除: width: 0; | |
| 317 | 删除: height: 100%; | |
| 318 | 删除: border-left: 2px solid var(--accent); | |
| 319 | 删除: } | |
| 320 | 删除: | |
| 321 | 删除: /* The middle track is the hypervisor boundary column: nothing crosses it | |
| 322 | 删除: here, the two stems flank it. */ | |
| 323 | 删除: .arch__stem:nth-child(2) { | |
| 324 | 删除: grid-column: 3; | |
| 325 | 删除: } | |
| 326 | 删除: | |
| 327 | 删除: .arch__shared-box { | |
| 328 | 删除: display: grid; | |
| 329 | 删除: gap: 0.65rem; | |
| 330 | 删除: padding: clamp(1.1rem, 2vw, 1.5rem); | |
| 331 | 删除: border: 1px solid var(--accent-line); | |
| 332 | 删除: border-radius: var(--radius); | |
| 333 | 删除: background: var(--accent-wash); | |
| 334 | 删除: } | |
| 335 | 删除: | |
| 336 | 删除: .arch__shared-title { | |
| 337 | 删除: font-family: var(--font-mono); | |
| 338 | 删除: font-size: 0.92rem; | |
| 339 | 删除: color: var(--accent); | |
| 340 | 删除: } | |
| 341 | 删除: | |
| 342 | 删除: .arch__shared-label { | |
| 343 | 删除: font-family: var(--font-mono); | |
| 344 | 删除: font-size: 0.68rem; | |
| 345 | 删除: letter-spacing: 0.08em; | |
| 346 | 删除: text-transform: uppercase; | |
| 347 | 删除: color: var(--accent); | |
| 348 | 删除: } | |
| 349 | 删除: | |
| 350 | 删除: .arch__shared-body { | |
| 351 | 删除: font-size: 0.88rem; | |
| 352 | 删除: } | |
| 353 | 删除: | |
| 354 | 删除: .arch__isolation { | |
| 355 | 删除: max-width: 48rem; | |
| 356 | 删除: margin-top: 1.5rem; | |
| 357 | 删除: font-size: 0.92rem; | |
| 358 | 删除: } | |
| 359 | 删除: | |
| 360 | 删除: /* Tables ------------------------------------------------------------------ */ | |
| 361 | 删除: | |
| 362 | 删除: .arch__tables { | |
| 363 | 删除: display: grid; | |
| 364 | 删除: gap: clamp(2.5rem, 5vw, 4rem); | |
| 365 | 删除: margin-top: clamp(2.75rem, 5.5vw, 4.5rem); | |
| 366 | 删除: } | |
| 367 | 删除: | |
| 368 | 删除: .arch__table-block { | |
| 369 | 删除: display: grid; | |
| 370 | 删除: gap: 1rem; | |
| 371 | 删除: align-content: start; | |
| 372 | 删除: min-width: 0; | |
| 373 | 删除: } | |
| 374 | 删除: | |
| 375 | 删除: .arch__sub { | |
| 376 | 删除: font-size: 1.05rem; | |
| 377 | 删除: } | |
| 378 | 删除: | |
| 379 | 删除: .arch__sub-body { | |
| 380 | 删除: font-size: 0.93rem; | |
| 381 | 删除: margin-top: -0.35rem; | |
| 382 | 删除: max-width: 48rem; | |
| 383 | 删除: } | |
| 384 | 删除: | |
| 385 | 删除: .arch__sub-note { | |
| 386 | 删除: font-size: 0.88rem; | |
| 387 | 删除: max-width: 48rem; | |
| 388 | 删除: } | |
| 389 | 删除: | |
| 390 | 删除: .arch__packages { | |
| 391 | 删除: font-size: 0.84rem; | |
| 392 | 删除: } | |
| 393 | 删除: | |
| 394 | 删除: .arch__name { | |
| 395 | 删除: font-family: var(--font-mono); | |
| 396 | 删除: font-size: 0.79rem; | |
| 397 | 删除: color: var(--accent); | |
| 398 | 删除: } | |
| 399 | 删除: | |
| 400 | 删除: .arch__flag { | |
| 401 | 删除: font-variant-caps: all-small-caps; | |
| 402 | 删除: letter-spacing: 0.06em; | |
| 403 | 删除: color: var(--ink-3); | |
| 404 | 删除: } | |
| 405 | 删除: | |
| 406 | 删除: .arch__compare th[scope='row'] { | |
| 407 | 删除: padding: 0.72rem 1rem; | |
| 408 | 删除: text-align: left; | |
| 409 | 删除: font-weight: 500; | |
| 410 | 删除: color: var(--ink); | |
| 411 | 删除: border-bottom: 1px solid var(--line); | |
| 412 | 删除: vertical-align: top; | |
| 413 | 删除: } | |
| 414 | 删除: | |
| 415 | 删除: .arch__compare tbody tr:last-child th[scope='row'] { | |
| 416 | 删除: border-bottom: 0; | |
| 417 | 删除: } | |
| 418 | 删除: | |
| 419 | 删除: /* Marks our own column, nothing more. A green "we win" tint on a table of | |
| 420 | 删除: plain facts reads as a scorecard and costs the table its credibility. */ | |
| 421 | 删除: .arch__col-win { | |
| 422 | 删除: background: var(--surface-2); | |
| 423 | 删除: color: var(--ink); | |
| 424 | 删除: font-weight: 500; | |
| 425 | 删除: } | |
| 426 | 删除: | |
| 427 | 删除: thead .arch__col-win { | |
| 428 | 删除: color: var(--ink-2); | |
| 429 | 删除: } | |
| 430 | 删除: | |
| 431 | 删除: @media (max-width: 62rem) { | |
| 432 | 删除: .arch__steps { | |
| 433 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 434 | 删除: } | |
| 435 | 删除: | |
| 436 | 删除: .arch__step { | |
| 437 | 删除: padding: 1.35rem 0; | |
| 438 | 删除: border-left: 0; | |
| 439 | 删除: border-bottom: 1px solid var(--line); | |
| 440 | 删除: } | |
| 441 | 删除: | |
| 442 | 删除: .arch__step:last-child { | |
| 443 | 删除: border-bottom: 0; | |
| 444 | 删除: } | |
| 445 | 删除: | |
| 446 | 删除: .arch__diagram { | |
| 447 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 448 | 删除: } | |
| 449 | 删除: | |
| 450 | 删除: .arch__boundary { | |
| 451 | 删除: min-height: 3.5rem; | |
| 452 | 删除: } | |
| 453 | 删除: | |
| 454 | 删除: .arch__boundary::before { | |
| 455 | 删除: top: 50%; | |
| 456 | 删除: bottom: auto; | |
| 457 | 删除: left: 0; | |
| 458 | 删除: right: 0; | |
| 459 | 删除: width: auto; | |
| 460 | 删除: border-left: 0; | |
| 461 | 删除: border-top: 2px dashed var(--line-strong); | |
| 462 | 删除: } | |
| 463 | 删除: | |
| 464 | 删除: .arch__boundary-label { | |
| 465 | 删除: writing-mode: horizontal-tb; | |
| 466 | 删除: padding: 0.25rem 0.75rem; | |
| 467 | 删除: } | |
| 468 | 删除: | |
| 469 | 删除: /* One column: the two stems would point at nothing. */ | |
| 470 | 删除: .arch__shared-stems { | |
| 471 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 472 | 删除: height: 1rem; | |
| 473 | 删除: } | |
| 474 | 删除: | |
| 475 | 删除: .arch__stem:nth-child(2) { | |
| 476 | 删除: display: none; | |
| 477 | 删除: } | |
| 478 | 删除: } | |
| 479 | 删除:</style> | |
| @@ -0,0 +1,62 @@ | ||
| 1 | 新增:--- | |
| 2 | 新增:import '@fontsource-variable/inter'; | |
| 3 | 新增:import '../styles/cage.css'; | |
| 4 | 新增:import { cageCopy, languages, type CageLocale } from '../i18n/cage'; | |
| 5 | 新增:import published from '../data/release.json'; | |
| 6 | 新增:import art from '../../../assets/claude-cage-character.png'; | |
| 7 | 新增:import checks from '../../../assets/network-checks.png'; | |
| 8 | 新增:import communityCheck from '../../../assets/community-browser-check.png'; | |
| 9 | 新增:import qr from '../../../assets/community-qq.png'; | |
| 10 | 新增:interface Props { locale: CageLocale } | |
| 11 | 新增:const { locale } = Astro.props; | |
| 12 | 新增:const c = cageCopy[locale]; | |
| 13 | 新增:const base = import.meta.env.BASE_URL; | |
| 14 | 新增:const repo = 'https://github.com/Lee-xeo/Claude-Cage'; | |
| 15 | 新增:const pathFor = (code: CageLocale) => `${base}${code === 'zh' ? '' : `${code}/`}`; | |
| 16 | 新增:const canonical = new URL(pathFor(locale), Astro.site); | |
| 17 | 新增:--- | |
| 18 | 新增:<!doctype html> | |
| 19 | 新增:<html lang={c.lang} dir={c.dir}> | |
| 20 | 新增:<head> | |
| 21 | 新增: <meta charset="UTF-8" /> | |
| 22 | 新增: <meta name="viewport" content="width=device-width, initial-scale=1" /> | |
| 23 | 新增: <meta name="description" content={c.description} /> | |
| 24 | 新增: <meta name="theme-color" content="#faf8f4" /> | |
| 25 | 新增: <title>{c.title}</title> | |
| 26 | 新增: <link rel="canonical" href={canonical} /> | |
| 27 | 新增: {languages.map(l => <link rel="alternate" hreflang={l.lang} href={new URL(pathFor(l.code), Astro.site)} />)} | |
| 28 | 新增: <link rel="alternate" hreflang="x-default" href={new URL(base, Astro.site)} /> | |
| 29 | 新增: <link rel="icon" href={`${base}cage-icon.png`} /> | |
| 30 | 新增: <meta property="og:type" content="website" /><meta property="og:site_name" content="Claude Cage" /> | |
| 31 | 新增: <meta property="og:title" content={c.title} /><meta property="og:description" content={c.description} /> | |
| 32 | 新增: <meta property="og:url" content={canonical} /><meta property="og:image" content={new URL(art.src, Astro.site)} /> | |
| 33 | 新增:</head> | |
| 34 | 新增:<body> | |
| 35 | 新增: <header class="nav wrap"> | |
| 36 | 新增: <a class="brand" href={pathFor(locale)} aria-label={c.home}><img src={`${base}cage-icon.png`} width="40" height="40" alt="" /><span>Claude Cage</span></a> | |
| 37 | 新增: <nav><a href="#how">{c.start}</a><a href={repo}>GitHub ↗</a><a class="nav-download" href="#download">{c.downloadLabel} ↓</a></nav> | |
| 38 | 新增: </header> | |
| 39 | 新增: <div class="language-switch wrap"><label for="site-language">{c.languageLabel}</label><select id="site-language" aria-label={c.languageLabel}>{languages.map(l => <option value={pathFor(l.code)} selected={l.code === locale} lang={l.lang}>{l.name}</option>)}</select></div> | |
| 40 | 新增: <main id="main"> | |
| 41 | 新增: <section class="story-hero wrap"> | |
| 42 | 新增: <div class="story-copy"><span class="eyebrow"><span class="seed"></span>CLAUDE CAGE · v{published.version}</span><h1>{c.hero}{c.heroAccent && <><br /><em>{c.heroAccent}</em></>}</h1><p class="tagline">{c.tagline}</p><p class="hero-intro">{c.intro}</p><a class="button" href="#download">{c.downloadLabel} ↓</a><span class="requirements" dir="ltr">{c.requirements} · v{published.version}</span></div> | |
| 43 | 新增: <figure class="character"><img src={art.src} width={art.width} height={art.height} alt={c.artAlt} fetchpriority="high" /></figure> | |
| 44 | 新增: </section> | |
| 45 | 新增: <section class="manifesto wrap"><h2>{c.why}</h2><p>{c.whyText}</p><ul class="key-features">{c.keyFeatures.map(text => <li>{text}</li>)}</ul><p class="small-note">{c.whyNote}</p></section> | |
| 46 | 新增: <section class="tools wrap" aria-labelledby="tools-title"><div class="section-intro"><h2 id="tools-title">{c.featureTitle}</h2></div><div class="tool-list">{c.features.map(([title,text],i) => <article><span class="tool-icon" aria-hidden="true">{['>_','↔','◎','↗'][i]}</span><div><h3>{title}</h3><p>{text}</p></div></article>)}</div></section> | |
| 47 | 新增: <div class="wrap"><figure class="product"><div class="window-bar" dir="ltr"><span class="window-dots" aria-hidden="true">● ● ●</span><span>Claude Cage · v{published.version}</span><span class="window-label">macOS</span></div><img src={`${base}workbench.jpg`} width="1230" height="692" alt={c.workbench} loading="lazy" /><figcaption>{c.workbench}</figcaption></figure></div> | |
| 48 | 新增: <section class="evidence wrap"><h2>{c.evidenceTitle}</h2><div class="evidence-grid"><figure><a href={checks.src}><img src={checks.src} width={checks.width} height={checks.height} alt={c.checksLabel} loading="lazy" /></a><figcaption>{c.checksLabel}</figcaption></figure><figure><a href={communityCheck.src}><img src={communityCheck.src} width={communityCheck.width} height={communityCheck.height} alt={c.communityCheckLabel} loading="lazy" /></a><figcaption>{c.communityCheckLabel}</figcaption></figure></div><p class="small-note">{c.evidenceNote}</p></section> | |
| 49 | 新增: <section id="how" class="start-section"><div class="wrap"><div class="quick-start"><h2>{c.quickTitle}</h2><p>{c.quickText}</p><pre><code>{c.prompt}</code></pre><p class="small-note">{c.quickNote}</p></div><div class="section-heading"><h2 class="steps-title">{c.stepsTitle}</h2></div><div class="steps">{c.steps.map(([title,text],i)=><article><span class="step-number" dir="ltr">0{i+1}</span><h3>{title}</h3><p>{text}</p></article>)}</div><details class="first-look"><summary>{c.firstLookLabel}<span aria-hidden="true">+</span></summary><img src={`${base}first-run.jpg`} width="1230" height="692" alt={c.firstLookLabel} loading="lazy" /></details></div></section> | |
| 50 | 新增: <section id="boundaries" class="boundaries wrap"><h2>{c.boundaryTitle}</h2><div class="boundary-list">{c.boundaries.map(([title,text])=><article><span aria-hidden="true">↔</span><div>{title && <h3>{title}</h3>}<p>{text}</p></div></article>)}</div></section> | |
| 51 | 新增: <section id="download" class="download-section wrap"><div class="download-box"><img src={`${base}cage-icon.png`} width="84" height="84" alt="" /><span class="eyebrow">CLAUDE CAGE · ALPHA</span><h2>{c.downloadTitle}</h2><p>{c.downloadText}</p><a class="button" href={published.downloadURL}>{c.downloadLabel} ↗</a><div class="download-meta" dir="ltr"><span>v{published.version}</span><span>Apple Silicon</span><span>macOS 14+</span></div><p class="access-note">{c.downloadNote}</p><p class="access-note update-note">{c.updateNote}</p><a class="text-link" href={published.releaseURL}>{c.releaseNotesLabel} ↗</a></div></section> | |
| 52 | 新增: <section class="community wrap"><div><h2>{c.communityTitle}</h2><p>{c.communityText}</p><div class="community-links"><a class="text-link" href={`${repo}/issues`}>{c.issuesLabel} ↗</a><a class="text-link" href={repo}>GitHub ↗</a></div></div><figure><a href={qr.src}><img src={qr.src} width={qr.width} height={qr.height} alt={c.group} loading="lazy" /></a><figcaption dir="ltr">{c.group}</figcaption></figure></section> | |
| 53 | 新增: <section class="faq wrap"><h2>{c.docsTitle}</h2><ul class="doc-links">{c.docs.map(doc => <li><a class="text-link" href={doc.href}>{doc.label} ↗</a><p>{doc.title}</p></li>)}</ul></section> | |
| 54 | 新增: <section class="license wrap"><h2>{c.licenseTitle}</h2><p>{c.licenseText}</p></section> | |
| 55 | 新增: </main> | |
| 56 | 新增: <footer class="wrap"><a class="brand" href={pathFor(locale)}><img src={`${base}cage-icon.png`} width="28" height="28" alt="" />Claude Cage</a><div><a href={repo}>GitHub ↗</a><a href={`${repo}/blob/main/${locale === 'zh' ? 'README.md' : `README.${locale}.md`}`}>README ↗</a></div><small>{c.independent}</small></footer> | |
| 57 | 新增: <script> | |
| 58 | 新增: const language = document.querySelector<HTMLSelectElement>('#site-language'); | |
| 59 | 新增: language?.addEventListener('change', () => { window.location.assign(language.value); }); | |
| 60 | 新增: </script> | |
| 61 | 新增:</body> | |
| 62 | 新增:</html> | |
| @@ -1,215 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import { highlightShell } from '../lib/shell-highlight'; | |
| 3 | 删除:import { escapeHtml } from '../lib/inline'; | |
| 4 | 删除:import { t, type Locale } from '../i18n'; | |
| 5 | 删除: | |
| 6 | 删除:interface Props { | |
| 7 | 删除: code: string; | |
| 8 | 删除: locale: Locale; | |
| 9 | 删除: title?: string; | |
| 10 | 删除: /** Render a `$` gutter before each non-comment, non-blank line. */ | |
| 11 | 删除: prompt?: boolean; | |
| 12 | 删除: class?: string; | |
| 13 | 删除:} | |
| 14 | 删除: | |
| 15 | 删除:const { code, locale, title, prompt = false, class: className } = Astro.props; | |
| 16 | 删除:const d = t(locale); | |
| 17 | 删除: | |
| 18 | 删除:// Built as a string rather than as markup: inside a <pre>, the indentation of | |
| 19 | 删除:// the template would land in the output as real whitespace. | |
| 20 | 删除:const html = highlightShell(code) | |
| 21 | 删除: .map((tokens) => { | |
| 22 | 删除: const bare = tokens.length === 0 || tokens[0]!.kind === 'comment'; | |
| 23 | 删除: const gutter = prompt | |
| 24 | 删除: ? `<span class="code__prompt" aria-hidden="true">${bare ? ' ' : '$'}</span>` | |
| 25 | 删除: : ''; | |
| 26 | 删除: const body = tokens | |
| 27 | 删除: .map((token) => `<span class="tk tk--${token.kind}">${escapeHtml(token.text)}</span>`) | |
| 28 | 删除: .join(''); | |
| 29 | 删除: return `<span class="code__line">${gutter}${body}</span>`; | |
| 30 | 删除: }) | |
| 31 | 删除: .join('\n'); | |
| 32 | 删除:--- | |
| 33 | 删除: | |
| 34 | 删除:<figure class:list={['code', className]}> | |
| 35 | 删除: { | |
| 36 | 删除: title && ( | |
| 37 | 删除: <figcaption class="code__bar"> | |
| 38 | 删除: <span class="code__title">{title}</span> | |
| 39 | 删除: </figcaption> | |
| 40 | 删除: ) | |
| 41 | 删除: } | |
| 42 | 删除: <div class="code__body"> | |
| 43 | 删除: <pre class="code__pre"><code set:html={html} /></pre> | |
| 44 | 删除: <button | |
| 45 | 删除: type="button" | |
| 46 | 删除: class="code__copy" | |
| 47 | 删除: data-copy | |
| 48 | 删除: data-copied-label={d.ui.copied} | |
| 49 | 删除: data-failed-label={d.ui.copyFailed} | |
| 50 | 删除: data-idle-label={d.ui.copy} | |
| 51 | 删除: aria-label={d.ui.copyLabel} | |
| 52 | 删除: > | |
| 53 | 删除: <span data-copy-text>{d.ui.copy}</span> | |
| 54 | 删除: </button> | |
| 55 | 删除: </div> | |
| 56 | 删除:</figure> | |
| 57 | 删除: | |
| 58 | 删除:<style> | |
| 59 | 删除: .code { | |
| 60 | 删除: margin: 0; | |
| 61 | 删除: border: 1px solid var(--code-line); | |
| 62 | 删除: border-radius: var(--radius-lg); | |
| 63 | 删除: background: var(--code-bg); | |
| 64 | 删除: overflow: hidden; | |
| 65 | 删除: } | |
| 66 | 删除: | |
| 67 | 删除: .code__bar { | |
| 68 | 删除: display: flex; | |
| 69 | 删除: align-items: center; | |
| 70 | 删除: gap: 0.5rem; | |
| 71 | 删除: padding: 0.5rem 0.9rem; | |
| 72 | 删除: border-bottom: 1px solid var(--code-line); | |
| 73 | 删除: background: color-mix(in srgb, var(--code-bg) 82%, #fff 18%); | |
| 74 | 删除: } | |
| 75 | 删除: | |
| 76 | 删除: .code__title { | |
| 77 | 删除: font-family: var(--font-mono); | |
| 78 | 删除: font-size: 0.7rem; | |
| 79 | 删除: letter-spacing: 0.1em; | |
| 80 | 删除: text-transform: uppercase; | |
| 81 | 删除: color: var(--code-ink-2); | |
| 82 | 删除: } | |
| 83 | 删除: | |
| 84 | 删除: .code__body { | |
| 85 | 删除: position: relative; | |
| 86 | 删除: } | |
| 87 | 删除: | |
| 88 | 删除: .code__pre { | |
| 89 | 删除: margin: 0; | |
| 90 | 删除: padding: 1rem 1.1rem; | |
| 91 | 删除: overflow-x: auto; | |
| 92 | 删除: font-size: 0.815rem; | |
| 93 | 删除: line-height: 1.75; | |
| 94 | 删除: color: var(--code-ink); | |
| 95 | 删除: tab-size: 2; | |
| 96 | 删除: } | |
| 97 | 删除: | |
| 98 | 删除: .code__pre :global(.code__prompt) { | |
| 99 | 删除: display: inline-block; | |
| 100 | 删除: width: 1.15rem; | |
| 101 | 删除: color: var(--code-ink-2); | |
| 102 | 删除: user-select: none; | |
| 103 | 删除: } | |
| 104 | 删除: | |
| 105 | 删除: .code__pre :global(.tk--command) { | |
| 106 | 删除: color: #eaa963; | |
| 107 | 删除: } | |
| 108 | 删除: .code__pre :global(.tk--flag) { | |
| 109 | 删除: color: #86b8d8; | |
| 110 | 删除: } | |
| 111 | 删除: .code__pre :global(.tk--string) { | |
| 112 | 删除: color: #9dc08b; | |
| 113 | 删除: } | |
| 114 | 删除: .code__pre :global(.tk--variable) { | |
| 115 | 删除: color: #cba6d8; | |
| 116 | 删除: } | |
| 117 | 删除: .code__pre :global(.tk--comment) { | |
| 118 | 删除: color: var(--code-ink-2); | |
| 119 | 删除: font-style: italic; | |
| 120 | 删除: } | |
| 121 | 删除: | |
| 122 | 删除: .code__copy { | |
| 123 | 删除: position: absolute; | |
| 124 | 删除: top: 0.55rem; | |
| 125 | 删除: right: 0.55rem; | |
| 126 | 删除: padding: 0.28rem 0.6rem; | |
| 127 | 删除: border: 1px solid var(--code-line); | |
| 128 | 删除: border-radius: 5px; | |
| 129 | 删除: background: var(--surface); | |
| 130 | 删除: color: var(--code-ink-2); | |
| 131 | 删除: font-family: var(--font-mono); | |
| 132 | 删除: font-size: 0.68rem; | |
| 133 | 删除: letter-spacing: 0.06em; | |
| 134 | 删除: text-transform: uppercase; | |
| 135 | 删除: cursor: pointer; | |
| 136 | 删除: opacity: 0; | |
| 137 | 删除: transition: opacity 0.14s ease, color 0.14s ease, border-color 0.14s ease; | |
| 138 | 删除: } | |
| 139 | 删除: | |
| 140 | 删除: .code:hover .code__copy, | |
| 141 | 删除: .code__copy:focus-visible { | |
| 142 | 删除: opacity: 1; | |
| 143 | 删除: } | |
| 144 | 删除: | |
| 145 | 删除: .code__copy:hover { | |
| 146 | 删除: color: var(--code-ink); | |
| 147 | 删除: border-color: var(--code-ink-2); | |
| 148 | 删除: } | |
| 149 | 删除: | |
| 150 | 删除: .code__copy[data-state='done'] { | |
| 151 | 删除: opacity: 1; | |
| 152 | 删除: color: #9dc08b; | |
| 153 | 删除: border-color: #9dc08b; | |
| 154 | 删除: } | |
| 155 | 删除: | |
| 156 | 删除: .code__copy[data-state='failed'] { | |
| 157 | 删除: opacity: 1; | |
| 158 | 删除: color: #e08c6b; | |
| 159 | 删除: border-color: #e08c6b; | |
| 160 | 删除: } | |
| 161 | 删除: | |
| 162 | 删除: /* Coarse pointers never hover, so the button has to stay visible, and the | |
| 163 | 删除: code starts below it instead of under it. */ | |
| 164 | 删除: @media (hover: none) { | |
| 165 | 删除: .code__copy { | |
| 166 | 删除: opacity: 1; | |
| 167 | 删除: } | |
| 168 | 删除: | |
| 169 | 删除: .code__pre { | |
| 170 | 删除: padding-top: 2.6rem; | |
| 171 | 删除: } | |
| 172 | 删除: } | |
| 173 | 删除:</style> | |
| 174 | 删除: | |
| 175 | 删除:<script> | |
| 176 | 删除: // One delegated listener rather than one per block: the page has a lot of | |
| 177 | 删除: // them, and they are all identical. | |
| 178 | 删除: document.addEventListener('click', async (event) => { | |
| 179 | 删除: const target = event.target; | |
| 180 | 删除: if (!(target instanceof Element)) return; | |
| 181 | 删除: const button = target.closest<HTMLButtonElement>('[data-copy]'); | |
| 182 | 删除: if (!button) return; | |
| 183 | 删除: | |
| 184 | 删除: const pre = button.parentElement?.querySelector('pre'); | |
| 185 | 删除: if (!pre) return; | |
| 186 | 删除: | |
| 187 | 删除: const label = button.querySelector<HTMLElement>('[data-copy-text]'); | |
| 188 | 删除: // Reading the token spans rather than the line's textContent keeps the `$` | |
| 189 | 删除: // gutter out: it is an aria-hidden decoration, and pasting it would break | |
| 190 | 删除: // every command. | |
| 191 | 删除: const text = Array.from(pre.querySelectorAll('.code__line')) | |
| 192 | 删除: .map((line) => | |
| 193 | 删除: Array.from(line.querySelectorAll('.tk')) | |
| 194 | 删除: .map((tk) => tk.textContent ?? '') | |
| 195 | 删除: .join(''), | |
| 196 | 删除: ) | |
| 197 | 删除: .join('\n'); | |
| 198 | 删除: | |
| 199 | 删除: const settle = (state: 'done' | 'failed', message: string) => { | |
| 200 | 删除: button.setAttribute('data-state', state); | |
| 201 | 删除: if (label) label.textContent = message; | |
| 202 | 删除: window.setTimeout(() => { | |
| 203 | 删除: button.removeAttribute('data-state'); | |
| 204 | 删除: if (label) label.textContent = button.dataset.idleLabel ?? 'Copy'; | |
| 205 | 删除: }, 1800); | |
| 206 | 删除: }; | |
| 207 | 删除: | |
| 208 | 删除: try { | |
| 209 | 删除: await navigator.clipboard.writeText(text); | |
| 210 | 删除: settle('done', button.dataset.copiedLabel ?? 'Copied'); | |
| 211 | 删除: } catch { | |
| 212 | 删除: settle('failed', button.dataset.failedLabel ?? 'Copy failed'); | |
| 213 | 删除: } | |
| 214 | 删除: }); | |
| 215 | 删除:</script> | |
| @@ -1,219 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import CodeBlock from './CodeBlock.astro'; | |
| 3 | 删除:import { inline } from '../lib/inline'; | |
| 4 | 删除:import Heading from './Heading.astro'; | |
| 5 | 删除:import { slug } from '../lib/slug'; | |
| 6 | 删除:import { en } from '../i18n/en'; | |
| 7 | 删除:import { t, type Locale } from '../i18n'; | |
| 8 | 删除: | |
| 9 | 删除:interface Props { | |
| 10 | 删除: locale: Locale; | |
| 11 | 删除:} | |
| 12 | 删除: | |
| 13 | 删除:const { locale } = Astro.props; | |
| 14 | 删除:const d = t(locale); | |
| 15 | 删除:--- | |
| 16 | 删除: | |
| 17 | 删除:<section class="section contribute" id="contribute"> | |
| 18 | 删除: <div class="container"> | |
| 19 | 删除: <div class="section-head"> | |
| 20 | 删除: <p class="eyebrow">{d.contribute.eyebrow}</p> | |
| 21 | 删除: <Heading as="h2" id="contribute" own={false} locale={locale}>{d.contribute.title}</Heading> | |
| 22 | 删除: <p class="lede" set:html={inline(d.contribute.lede)} /> | |
| 23 | 删除: </div> | |
| 24 | 删除: | |
| 25 | 删除: <div class="contribute__grid"> | |
| 26 | 删除: <div class="contribute__col"> | |
| 27 | 删除: <Heading as="h3" id={slug(en.contribute.testsTitle)} locale={locale} class="contribute__sub">{d.contribute.testsTitle}</Heading> | |
| 28 | 删除: <p class="prose contribute__body" set:html={inline(d.contribute.testsBody)} /> | |
| 29 | 删除: <ul class="contribute__rules contribute__tests"> | |
| 30 | 删除: { | |
| 31 | 删除: d.contribute.testsList.map((item) => ( | |
| 32 | 删除: <li class="contribute__rule"> | |
| 33 | 删除: <span class="prose" set:html={inline(item)} /> | |
| 34 | 删除: </li> | |
| 35 | 删除: )) | |
| 36 | 删除: } | |
| 37 | 删除: </ul> | |
| 38 | 删除: <CodeBlock locale={locale} code={d.contribute.testsCode} prompt /> | |
| 39 | 删除: | |
| 40 | 删除: <Heading as="h3" id={slug(en.contribute.shellsTitle)} locale={locale} class="contribute__sub contribute__sub--spaced">{d.contribute.shellsTitle}</Heading> | |
| 41 | 删除: <p class="prose contribute__body" set:html={inline(d.contribute.shellsBody)} /> | |
| 42 | 删除: <CodeBlock locale={locale} code={d.contribute.shellsCode} /> | |
| 43 | 删除: </div> | |
| 44 | 删除: | |
| 45 | 删除: <div class="contribute__col"> | |
| 46 | 删除: <Heading as="h3" id={slug(en.contribute.structureTitle)} locale={locale} class="contribute__sub">{d.contribute.structureTitle}</Heading> | |
| 47 | 删除: <div class="table-wrap"> | |
| 48 | 删除: <table class="table--code"> | |
| 49 | 删除: <thead> | |
| 50 | 删除: <tr> | |
| 51 | 删除: {d.contribute.structureHeaders.map((header) => <th scope="col">{header}</th>)} | |
| 52 | 删除: </tr> | |
| 53 | 删除: </thead> | |
| 54 | 删除: <tbody> | |
| 55 | 删除: { | |
| 56 | 删除: d.contribute.structure.map(([file, description]) => ( | |
| 57 | 删除: <tr> | |
| 58 | 删除: <td>{file}</td> | |
| 59 | 删除: <td>{description}</td> | |
| 60 | 删除: </tr> | |
| 61 | 删除: )) | |
| 62 | 删除: } | |
| 63 | 删除: </tbody> | |
| 64 | 删除: </table> | |
| 65 | 删除: </div> | |
| 66 | 删除: | |
| 67 | 删除: <Heading as="h3" id={slug(en.contribute.guidelinesTitle)} locale={locale} class="contribute__sub contribute__sub--spaced">{d.contribute.guidelinesTitle}</Heading> | |
| 68 | 删除: <ul class="contribute__rules"> | |
| 69 | 删除: { | |
| 70 | 删除: d.contribute.guidelines.map((rule) => ( | |
| 71 | 删除: <li class="contribute__rule"> | |
| 72 | 删除: <span class="prose" set:html={inline(rule)} /> | |
| 73 | 删除: </li> | |
| 74 | 删除: )) | |
| 75 | 删除: } | |
| 76 | 删除: </ul> | |
| 77 | 删除: </div> | |
| 78 | 删除: </div> | |
| 79 | 删除: | |
| 80 | 删除: <div class="contribute__links"> | |
| 81 | 删除: <a class="contribute__link" href={d.contribute.issuesHref} rel="noopener" target="_blank"> | |
| 82 | 删除: <span class="contribute__link-label">{d.contribute.issuesLabel}</span> | |
| 83 | 删除: <span class="contribute__link-arrow" aria-hidden="true">→</span> | |
| 84 | 删除: </a> | |
| 85 | 删除: <a class="contribute__link" href={d.contribute.prHref} rel="noopener" target="_blank"> | |
| 86 | 删除: <span class="contribute__link-label">{d.contribute.prLabel}</span> | |
| 87 | 删除: <span class="contribute__link-arrow" aria-hidden="true">→</span> | |
| 88 | 删除: </a> | |
| 89 | 删除: <a class="contribute__link" href={d.contribute.repoHref} rel="noopener" target="_blank"> | |
| 90 | 删除: <span class="contribute__link-label">{d.contribute.repoLabel}</span> | |
| 91 | 删除: <span class="contribute__link-arrow" aria-hidden="true">→</span> | |
| 92 | 删除: </a> | |
| 93 | 删除: <a class="contribute__link" href={d.contribute.chatHref} rel="noopener" target="_blank"> | |
| 94 | 删除: <span class="contribute__link-label">{d.contribute.chatLabel}</span> | |
| 95 | 删除: <span class="contribute__link-arrow" aria-hidden="true">→</span> | |
| 96 | 删除: </a> | |
| 97 | 删除: </div> | |
| 98 | 删除: </div> | |
| 99 | 删除:</section> | |
| 100 | 删除: | |
| 101 | 删除:<style> | |
| 102 | 删除: .contribute { | |
| 103 | 删除: background: var(--paper-sunk); | |
| 104 | 删除: } | |
| 105 | 删除: | |
| 106 | 删除: .contribute__grid { | |
| 107 | 删除: display: grid; | |
| 108 | 删除: grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); | |
| 109 | 删除: gap: clamp(1.75rem, 4vw, 3.25rem); | |
| 110 | 删除: align-items: start; | |
| 111 | 删除: } | |
| 112 | 删除: | |
| 113 | 删除: .contribute__col { | |
| 114 | 删除: display: grid; | |
| 115 | 删除: align-content: start; | |
| 116 | 删除: min-width: 0; | |
| 117 | 删除: } | |
| 118 | 删除: | |
| 119 | 删除: .contribute__sub { | |
| 120 | 删除: font-size: 1.05rem; | |
| 121 | 删除: margin-bottom: 0.65rem; | |
| 122 | 删除: } | |
| 123 | 删除: | |
| 124 | 删除: .contribute__sub--spaced { | |
| 125 | 删除: margin-top: 2.25rem; | |
| 126 | 删除: } | |
| 127 | 删除: | |
| 128 | 删除: .contribute__body { | |
| 129 | 删除: font-size: 0.92rem; | |
| 130 | 删除: margin-bottom: 1rem; | |
| 131 | 删除: max-width: 44rem; | |
| 132 | 删除: } | |
| 133 | 删除: | |
| 134 | 删除: .contribute__rules { | |
| 135 | 删除: display: grid; | |
| 136 | 删除: gap: 0.75rem; | |
| 137 | 删除: list-style: none; | |
| 138 | 删除: } | |
| 139 | 删除: | |
| 140 | 删除: .contribute__tests { | |
| 141 | 删除: margin-bottom: 1rem; | |
| 142 | 删除: } | |
| 143 | 删除: | |
| 144 | 删除: .contribute__rule { | |
| 145 | 删除: position: relative; | |
| 146 | 删除: padding-left: 1.4rem; | |
| 147 | 删除: font-size: 0.92rem; | |
| 148 | 删除: } | |
| 149 | 删除: | |
| 150 | 删除: .contribute__rule::before { | |
| 151 | 删除: content: ''; | |
| 152 | 删除: position: absolute; | |
| 153 | 删除: left: 0; | |
| 154 | 删除: top: 0.62em; | |
| 155 | 删除: width: 0.45rem; | |
| 156 | 删除: height: 0.45rem; | |
| 157 | 删除: border: 1px solid var(--accent); | |
| 158 | 删除: border-radius: 1px; | |
| 159 | 删除: transform: rotate(45deg); | |
| 160 | 删除: } | |
| 161 | 删除: | |
| 162 | 删除: .contribute__links { | |
| 163 | 删除: display: grid; | |
| 164 | 删除: grid-template-columns: repeat(4, minmax(0, 1fr)); | |
| 165 | 删除: gap: 1px; | |
| 166 | 删除: margin-top: clamp(2.5rem, 5vw, 4rem); | |
| 167 | 删除: background: var(--line); | |
| 168 | 删除: border: 1px solid var(--line); | |
| 169 | 删除: border-radius: var(--radius-lg); | |
| 170 | 删除: overflow: hidden; | |
| 171 | 删除: } | |
| 172 | 删除: | |
| 173 | 删除: .contribute__link { | |
| 174 | 删除: display: flex; | |
| 175 | 删除: align-items: center; | |
| 176 | 删除: justify-content: space-between; | |
| 177 | 删除: gap: 1rem; | |
| 178 | 删除: padding: 1.15rem 1.35rem; | |
| 179 | 删除: background: var(--surface); | |
| 180 | 删除: color: var(--ink); | |
| 181 | 删除: text-decoration: none; | |
| 182 | 删除: font-weight: 540; | |
| 183 | 删除: font-size: 0.95rem; | |
| 184 | 删除: transition: background-color 0.14s ease, color 0.14s ease; | |
| 185 | 删除: } | |
| 186 | 删除: | |
| 187 | 删除: .contribute__link:hover { | |
| 188 | 删除: background: var(--accent-wash); | |
| 189 | 删除: color: var(--accent); | |
| 190 | 删除: } | |
| 191 | 删除: | |
| 192 | 删除: .contribute__link-arrow { | |
| 193 | 删除: font-family: var(--font-mono); | |
| 194 | 删除: color: var(--ink-4); | |
| 195 | 删除: transition: transform 0.14s ease, color 0.14s ease; | |
| 196 | 删除: } | |
| 197 | 删除: | |
| 198 | 删除: .contribute__link:hover .contribute__link-arrow { | |
| 199 | 删除: color: var(--accent); | |
| 200 | 删除: transform: translateX(3px); | |
| 201 | 删除: } | |
| 202 | 删除: | |
| 203 | 删除: @media (max-width: 62rem) { | |
| 204 | 删除: .contribute__grid { | |
| 205 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 206 | 删除: gap: 2.5rem; | |
| 207 | 删除: } | |
| 208 | 删除: | |
| 209 | 删除: .contribute__links { | |
| 210 | 删除: grid-template-columns: repeat(2, minmax(0, 1fr)); | |
| 211 | 删除: } | |
| 212 | 删除: } | |
| 213 | 删除: | |
| 214 | 删除: @media (max-width: 36rem) { | |
| 215 | 删除: .contribute__links { | |
| 216 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 217 | 删除: } | |
| 218 | 删除: } | |
| 219 | 删除:</style> | |
| @@ -1,156 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import { inline } from '../lib/inline'; | |
| 3 | 删除:import Heading from './Heading.astro'; | |
| 4 | 删除:import { t, type Locale } from '../i18n'; | |
| 5 | 删除: | |
| 6 | 删除:interface Props { | |
| 7 | 删除: locale: Locale; | |
| 8 | 删除:} | |
| 9 | 删除: | |
| 10 | 删除:const { locale } = Astro.props; | |
| 11 | 删除:const d = t(locale); | |
| 12 | 删除:--- | |
| 13 | 删除: | |
| 14 | 删除:<section class="section" id="credits"> | |
| 15 | 删除: <div class="container"> | |
| 16 | 删除: <div class="section-head"> | |
| 17 | 删除: <p class="eyebrow">{d.credits.eyebrow}</p> | |
| 18 | 删除: <Heading as="h2" id="credits" own={false} locale={locale}>{d.credits.title}</Heading> | |
| 19 | 删除: <p class="lede" set:html={inline(d.credits.lede)} /> | |
| 20 | 删除: </div> | |
| 21 | 删除: | |
| 22 | 删除: <div class="credits__groups"> | |
| 23 | 删除: { | |
| 24 | 删除: d.credits.groups.map((group) => ( | |
| 25 | 删除: <section class="credits__group"> | |
| 26 | 删除: <h3 class="credits__group-title">{group.title}</h3> | |
| 27 | 删除: <ul class="credits__list"> | |
| 28 | 删除: {group.items.map((item) => ( | |
| 29 | 删除: <li class="credits__item"> | |
| 30 | 删除: <a class="credits__name" href={item.href} rel="noopener" target="_blank"> | |
| 31 | 删除: {item.name} | |
| 32 | 删除: </a> | |
| 33 | 删除: <span class="credits__note">{item.note}</span> | |
| 34 | 删除: </li> | |
| 35 | 删除: ))} | |
| 36 | 删除: </ul> | |
| 37 | 删除: </section> | |
| 38 | 删除: )) | |
| 39 | 删除: } | |
| 40 | 删除: </div> | |
| 41 | 删除: | |
| 42 | 删除: <div class="credits__meta"> | |
| 43 | 删除: <div class="credits__meta-block"> | |
| 44 | 删除: <h3 class="credits__meta-title">{d.credits.authorTitle}</h3> | |
| 45 | 删除: <p class="prose"> | |
| 46 | 删除: {d.credits.authorBody} | |
| 47 | 删除: </p> | |
| 48 | 删除: <a class="credits__handle" href={d.credits.authorHref} rel="noopener" target="_blank"> | |
| 49 | 删除: @{d.credits.authorName} | |
| 50 | 删除: </a> | |
| 51 | 删除: </div> | |
| 52 | 删除: | |
| 53 | 删除: <div class="credits__meta-block"> | |
| 54 | 删除: <h3 class="credits__meta-title">{d.credits.licenseTitle}</h3> | |
| 55 | 删除: <p class="prose">{d.credits.licenseBody}</p> | |
| 56 | 删除: <a class="credits__handle" href={d.credits.licenseHref} rel="noopener" target="_blank"> | |
| 57 | 删除: LICENSE | |
| 58 | 删除: </a> | |
| 59 | 删除: </div> | |
| 60 | 删除: </div> | |
| 61 | 删除: </div> | |
| 62 | 删除:</section> | |
| 63 | 删除: | |
| 64 | 删除:<style> | |
| 65 | 删除: .credits__groups { | |
| 66 | 删除: display: grid; | |
| 67 | 删除: grid-template-columns: repeat(auto-fit, minmax(min(100%, 17rem), 1fr)); | |
| 68 | 删除: gap: clamp(1.75rem, 4vw, 3rem); | |
| 69 | 删除: } | |
| 70 | 删除: | |
| 71 | 删除: .credits__group-title { | |
| 72 | 删除: font-family: var(--font-mono); | |
| 73 | 删除: font-size: 0.72rem; | |
| 74 | 删除: font-weight: 500; | |
| 75 | 删除: letter-spacing: 0.12em; | |
| 76 | 删除: text-transform: uppercase; | |
| 77 | 删除: color: var(--ink-3); | |
| 78 | 删除: padding-bottom: 0.75rem; | |
| 79 | 删除: margin-bottom: 1.1rem; | |
| 80 | 删除: border-bottom: 1px solid var(--line); | |
| 81 | 删除: } | |
| 82 | 删除: | |
| 83 | 删除: .credits__list { | |
| 84 | 删除: display: grid; | |
| 85 | 删除: gap: 1rem; | |
| 86 | 删除: list-style: none; | |
| 87 | 删除: } | |
| 88 | 删除: | |
| 89 | 删除: .credits__item { | |
| 90 | 删除: display: grid; | |
| 91 | 删除: gap: 0.15rem; | |
| 92 | 删除: } | |
| 93 | 删除: | |
| 94 | 删除: .credits__name { | |
| 95 | 删除: font-size: 0.97rem; | |
| 96 | 删除: font-weight: 560; | |
| 97 | 删除: color: var(--ink); | |
| 98 | 删除: text-decoration: none; | |
| 99 | 删除: justify-self: start; | |
| 100 | 删除: border-bottom: 1px solid var(--line-strong); | |
| 101 | 删除: } | |
| 102 | 删除: | |
| 103 | 删除: .credits__name:hover { | |
| 104 | 删除: color: var(--accent); | |
| 105 | 删除: border-bottom-color: var(--accent); | |
| 106 | 删除: } | |
| 107 | 删除: | |
| 108 | 删除: .credits__note { | |
| 109 | 删除: font-size: 0.87rem; | |
| 110 | 删除: color: var(--ink-3); | |
| 111 | 删除: } | |
| 112 | 删除: | |
| 113 | 删除: .credits__meta { | |
| 114 | 删除: display: grid; | |
| 115 | 删除: grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr)); | |
| 116 | 删除: gap: clamp(1.25rem, 3vw, 2.5rem); | |
| 117 | 删除: margin-top: clamp(2.5rem, 5vw, 4rem); | |
| 118 | 删除: padding-top: clamp(2rem, 4vw, 3rem); | |
| 119 | 删除: border-top: 1px solid var(--line); | |
| 120 | 删除: } | |
| 121 | 删除: | |
| 122 | 删除: .credits__meta-block { | |
| 123 | 删除: display: grid; | |
| 124 | 删除: gap: 0.5rem; | |
| 125 | 删除: align-content: start; | |
| 126 | 删除: } | |
| 127 | 删除: | |
| 128 | 删除: .credits__meta-title { | |
| 129 | 删除: font-family: var(--font-mono); | |
| 130 | 删除: font-size: 0.72rem; | |
| 131 | 删除: font-weight: 500; | |
| 132 | 删除: letter-spacing: 0.12em; | |
| 133 | 删除: text-transform: uppercase; | |
| 134 | 删除: color: var(--ink-3); | |
| 135 | 删除: } | |
| 136 | 删除: | |
| 137 | 删除: .credits__meta-block .prose { | |
| 138 | 删除: font-size: 0.93rem; | |
| 139 | 删除: } | |
| 140 | 删除: | |
| 141 | 删除: .credits__handle { | |
| 142 | 删除: justify-self: start; | |
| 143 | 删除: font-family: var(--font-mono); | |
| 144 | 删除: font-size: 0.83rem; | |
| 145 | 删除: text-decoration: none; | |
| 146 | 删除: padding: 0.28rem 0.6rem; | |
| 147 | 删除: border: 1px solid var(--line-strong); | |
| 148 | 删除: border-radius: var(--radius); | |
| 149 | 删除: color: var(--ink-2); | |
| 150 | 删除: } | |
| 151 | 删除: | |
| 152 | 删除: .credits__handle:hover { | |
| 153 | 删除: border-color: var(--accent); | |
| 154 | 删除: color: var(--accent); | |
| 155 | 删除: } | |
| 156 | 删除:</style> | |
| @@ -1,104 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:// Groups of topics, each with paragraphs, an optional list and an optional | |
| 3 | 删除:// code sample. Used by Architecture and Security. | |
| 4 | 删除:import CodeBlock from './CodeBlock.astro'; | |
| 5 | 删除:import { inline } from '../lib/inline'; | |
| 6 | 删除:import Heading from './Heading.astro'; | |
| 7 | 删除:import { slug } from '../lib/slug'; | |
| 8 | 删除:import type { Locale } from '../i18n'; | |
| 9 | 删除: | |
| 10 | 删除:interface Topic { | |
| 11 | 删除: title: string; | |
| 12 | 删除: paras: string[]; | |
| 13 | 删除: list: string[]; | |
| 14 | 删除: code: string; | |
| 15 | 删除:} | |
| 16 | 删除: | |
| 17 | 删除:interface Group { | |
| 18 | 删除: id?: string; | |
| 19 | 删除: title: string; | |
| 20 | 删除: topics: Topic[]; | |
| 21 | 删除:} | |
| 22 | 删除: | |
| 23 | 删除:interface Props { | |
| 24 | 删除: locale: Locale; | |
| 25 | 删除: groups: Group[]; | |
| 26 | 删除: // The English groups: anchors come from their titles, so links work in | |
| 27 | 删除: // every language. | |
| 28 | 删除: source: Group[]; | |
| 29 | 删除:} | |
| 30 | 删除: | |
| 31 | 删除:const { locale, groups, source } = Astro.props; | |
| 32 | 删除:--- | |
| 33 | 删除: | |
| 34 | 删除:{ | |
| 35 | 删除: groups.map((group, g) => ( | |
| 36 | 删除: <div class="docs__group"> | |
| 37 | 删除: <Heading as="h3" id={source[g]!.id ?? slug(source[g]!.title)} locale={locale} class="docs__group-title">{group.title}</Heading> | |
| 38 | 删除: <div class="docs__topics"> | |
| 39 | 删除: {group.topics.map((topic, i) => ( | |
| 40 | 删除: <article class="docs__topic"> | |
| 41 | 删除: <Heading as="h4" id={slug(source[g]!.topics[i]!.title)} locale={locale} class="docs__topic-title">{topic.title}</Heading> | |
| 42 | 删除: {topic.paras.map((para) => <p class="prose docs__p" set:html={inline(para)} />)} | |
| 43 | 删除: {topic.list.length > 0 && ( | |
| 44 | 删除: <ul class="docs__list"> | |
| 45 | 删除: {topic.list.map((item) => <li class="prose docs__p" set:html={inline(item)} />)} | |
| 46 | 删除: </ul> | |
| 47 | 删除: )} | |
| 48 | 删除: {topic.code && <CodeBlock locale={locale} code={topic.code} />} | |
| 49 | 删除: </article> | |
| 50 | 删除: ))} | |
| 51 | 删除: </div> | |
| 52 | 删除: </div> | |
| 53 | 删除: )) | |
| 54 | 删除:} | |
| 55 | 删除: | |
| 56 | 删除:<style> | |
| 57 | 删除: .docs__group { | |
| 58 | 删除: display: grid; | |
| 59 | 删除: gap: 1rem; | |
| 60 | 删除: margin-top: clamp(2rem, 4vw, 3rem); | |
| 61 | 删除: } | |
| 62 | 删除: | |
| 63 | 删除: .docs__group-title { | |
| 64 | 删除: font-size: 1.15rem; | |
| 65 | 删除: } | |
| 66 | 删除: | |
| 67 | 删除: .docs__topics { | |
| 68 | 删除: display: grid; | |
| 69 | 删除: grid-template-columns: repeat(auto-fit, minmax(min(100%, 28rem), 1fr)); | |
| 70 | 删除: gap: 1px; | |
| 71 | 删除: background: var(--line); | |
| 72 | 删除: border: 1px solid var(--line); | |
| 73 | 删除: border-radius: var(--radius-lg); | |
| 74 | 删除: overflow: hidden; | |
| 75 | 删除: } | |
| 76 | 删除: | |
| 77 | 删除: .docs__topic { | |
| 78 | 删除: display: grid; | |
| 79 | 删除: align-content: start; | |
| 80 | 删除: min-width: 0; | |
| 81 | 删除: gap: 0.75rem; | |
| 82 | 删除: padding: clamp(1.25rem, 2.4vw, 1.75rem); | |
| 83 | 删除: background: var(--surface); | |
| 84 | 删除: } | |
| 85 | 删除: | |
| 86 | 删除: /* An odd count would otherwise leave a hole in the last row. */ | |
| 87 | 删除: .docs__topic:last-child:nth-child(odd) { | |
| 88 | 删除: grid-column: 1 / -1; | |
| 89 | 删除: } | |
| 90 | 删除: | |
| 91 | 删除: .docs__topic-title { | |
| 92 | 删除: font-size: 1.02rem; | |
| 93 | 删除: } | |
| 94 | 删除: | |
| 95 | 删除: .docs__p { | |
| 96 | 删除: font-size: 0.91rem; | |
| 97 | 删除: } | |
| 98 | 删除: | |
| 99 | 删除: .docs__list { | |
| 100 | 删除: display: grid; | |
| 101 | 删除: gap: 0.5rem; | |
| 102 | 删除: padding-left: 1.1rem; | |
| 103 | 删除: } | |
| 104 | 删除:</style> | |
| @@ -1,27 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:// The Security section: groups of topics, see DocGroups. | |
| 3 | 删除:import DocGroups from './DocGroups.astro'; | |
| 4 | 删除:import { inline } from '../lib/inline'; | |
| 5 | 删除:import Heading from './Heading.astro'; | |
| 6 | 删除:import { en } from '../i18n/en'; | |
| 7 | 删除:import { t, type Locale } from '../i18n'; | |
| 8 | 删除: | |
| 9 | 删除:interface Props { | |
| 10 | 删除: locale: Locale; | |
| 11 | 删除:} | |
| 12 | 删除: | |
| 13 | 删除:const { locale } = Astro.props; | |
| 14 | 删除:const d = t(locale).security; | |
| 15 | 删除:--- | |
| 16 | 删除: | |
| 17 | 删除:<section class="section docs" id="security"> | |
| 18 | 删除: <div class="container"> | |
| 19 | 删除: <div class="section-head"> | |
| 20 | 删除: <p class="eyebrow">{d.eyebrow}</p> | |
| 21 | 删除: <Heading as="h2" id="security" own={false} locale={locale}>{d.title}</Heading> | |
| 22 | 删除: <p class="lede" set:html={inline(d.lede)} /> | |
| 23 | 删除: </div> | |
| 24 | 删除: | |
| 25 | 删除: <DocGroups locale={locale} groups={d.groups} source={en.security.groups} /> | |
| 26 | 删除: </div> | |
| 27 | 删除:</section> | |
| @@ -1,101 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import { t, localeHref, otherLocales, type Locale } from '../i18n'; | |
| 3 | 删除: | |
| 4 | 删除:interface Props { | |
| 5 | 删除: locale: Locale; | |
| 6 | 删除:} | |
| 7 | 删除: | |
| 8 | 删除:const { locale } = Astro.props; | |
| 9 | 删除:const d = t(locale); | |
| 10 | 删除:--- | |
| 11 | 删除: | |
| 12 | 删除:<footer class="footer"> | |
| 13 | 删除: <div class="container footer__inner"> | |
| 14 | 删除: <div class="footer__brand"> | |
| 15 | 删除: <span class="footer__name">agent-vm</span> | |
| 16 | 删除: <p class="footer__tagline">{d.footer.tagline}</p> | |
| 17 | 删除: </div> | |
| 18 | 删除: | |
| 19 | 删除: <div class="footer__meta"> | |
| 20 | 删除: <a class="footer__link" href="https://github.com/sylvinus/agent-vm" rel="noopener" target="_blank"> | |
| 21 | 删除: {d.nav.github} | |
| 22 | 删除: </a> | |
| 23 | 删除: <a class="footer__link" href={d.contribute.chatHref} rel="noopener" target="_blank"> | |
| 24 | 删除: Matrix | |
| 25 | 删除: </a> | |
| 26 | 删除: <a | |
| 27 | 删除: class="footer__link" | |
| 28 | 删除: href="https://github.com/sylvinus/agent-vm/blob/main/LICENSE" | |
| 29 | 删除: rel="noopener" | |
| 30 | 删除: target="_blank" | |
| 31 | 删除: > | |
| 32 | 删除: {d.footer.license} | |
| 33 | 删除: </a> | |
| 34 | 删除: { | |
| 35 | 删除: otherLocales(locale).map((other) => ( | |
| 36 | 删除: <a class="footer__link" href={localeHref(other)} hreflang={other} lang={other}> | |
| 37 | 删除: {t(other).meta.label} | |
| 38 | 删除: </a> | |
| 39 | 删除: )) | |
| 40 | 删除: } | |
| 41 | 删除: <a class="footer__link" href="#main">{d.footer.backToTop}</a> | |
| 42 | 删除: </div> | |
| 43 | 删除: </div> | |
| 44 | 删除:</footer> | |
| 45 | 删除: | |
| 46 | 删除:<style> | |
| 47 | 删除: .footer { | |
| 48 | 删除: border-top: 1px solid var(--line); | |
| 49 | 删除: background: var(--paper-sunk); | |
| 50 | 删除: padding-block: clamp(2.5rem, 5vw, 3.5rem); | |
| 51 | 删除: } | |
| 52 | 删除: | |
| 53 | 删除: .footer__inner { | |
| 54 | 删除: display: grid; | |
| 55 | 删除: grid-template-columns: minmax(0, 1fr) auto; | |
| 56 | 删除: gap: 1.5rem clamp(1.5rem, 4vw, 3rem); | |
| 57 | 删除: align-items: start; | |
| 58 | 删除: } | |
| 59 | 删除: | |
| 60 | 删除: .footer__name { | |
| 61 | 删除: font-family: var(--font-mono); | |
| 62 | 删除: font-size: 0.95rem; | |
| 63 | 删除: font-weight: 600; | |
| 64 | 删除: color: var(--ink); | |
| 65 | 删除: } | |
| 66 | 删除: | |
| 67 | 删除: .footer__tagline { | |
| 68 | 删除: margin-top: 0.4rem; | |
| 69 | 删除: max-width: 30rem; | |
| 70 | 删除: font-size: 0.89rem; | |
| 71 | 删除: color: var(--ink-3); | |
| 72 | 删除: text-wrap: pretty; | |
| 73 | 删除: } | |
| 74 | 删除: | |
| 75 | 删除: .footer__meta { | |
| 76 | 删除: display: flex; | |
| 77 | 删除: flex-wrap: wrap; | |
| 78 | 删除: gap: 0.4rem 1.25rem; | |
| 79 | 删除: justify-content: flex-end; | |
| 80 | 删除: } | |
| 81 | 删除: | |
| 82 | 删除: .footer__link { | |
| 83 | 删除: font-size: 0.87rem; | |
| 84 | 删除: color: var(--ink-2); | |
| 85 | 删除: text-decoration: none; | |
| 86 | 删除: } | |
| 87 | 删除: | |
| 88 | 删除: .footer__link:hover { | |
| 89 | 删除: color: var(--accent); | |
| 90 | 删除: } | |
| 91 | 删除: | |
| 92 | 删除: @media (max-width: 48rem) { | |
| 93 | 删除: .footer__inner { | |
| 94 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 95 | 删除: } | |
| 96 | 删除: | |
| 97 | 删除: .footer__meta { | |
| 98 | 删除: justify-content: flex-start; | |
| 99 | 删除: } | |
| 100 | 删除: } | |
| 101 | 删除:</style> | |
| @@ -1,109 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:// A heading with a link to itself, shown on hover. Clicking it follows the | |
| 3 | 删除:// link, as any anchor, and copies the full URL. | |
| 4 | 删除:// | |
| 5 | 删除:// `id` is the anchor. With `own` false the heading does not carry it: a | |
| 6 | 删除:// section title, whose <section> already has the id. | |
| 7 | 删除:import { t, type Locale } from '../i18n'; | |
| 8 | 删除: | |
| 9 | 删除:interface Props { | |
| 10 | 删除: as: 'h2' | 'h3' | 'h4'; | |
| 11 | 删除: id: string; | |
| 12 | 删除: locale: Locale; | |
| 13 | 删除: own?: boolean; | |
| 14 | 删除: class?: string; | |
| 15 | 删除: [key: string]: unknown; | |
| 16 | 删除:} | |
| 17 | 删除: | |
| 18 | 删除:// `...rest` carries the caller's scoped-style attribute, so the class it | |
| 19 | 删除:// passes keeps its styles. | |
| 20 | 删除:const { as: Tag, id, locale, own = true, class: className, ...rest } = Astro.props; | |
| 21 | 删除:const d = t(locale); | |
| 22 | 删除:--- | |
| 23 | 删除: | |
| 24 | 删除:<Tag id={own ? id : undefined} class:list={['anchored', className]} {...rest}> | |
| 25 | 删除: <slot /><a | |
| 26 | 删除: class="anchored__link" | |
| 27 | 删除: href={`#${id}`} | |
| 28 | 删除: data-anchor | |
| 29 | 删除: aria-label={d.ui.anchorLabel} | |
| 30 | 删除: data-copied-label={d.ui.linkCopied} | |
| 31 | 删除: ><svg viewBox="0 0 16 16" aria-hidden="true" focusable="false" | |
| 32 | 删除: ><path | |
| 33 | 删除: d="M6.9 9.1a3 3 0 0 0 4.2 0l2.2-2.2a3 3 0 0 0-4.2-4.2l-.9.9M9.1 6.9a3 3 0 0 0-4.2 0L2.7 9.1a3 3 0 0 0 4.2 4.2l.9-.9" | |
| 34 | 删除: ></path></svg | |
| 35 | 删除: ></a | |
| 36 | 删除: > | |
| 37 | 删除:</Tag> | |
| 38 | 删除: | |
| 39 | 删除:<style> | |
| 40 | 删除: .anchored__link { | |
| 41 | 删除: position: relative; | |
| 42 | 删除: display: inline-flex; | |
| 43 | 删除: align-items: center; | |
| 44 | 删除: margin-left: 0.4em; | |
| 45 | 删除: vertical-align: middle; | |
| 46 | 删除: color: var(--ink-4); | |
| 47 | 删除: text-decoration: none; | |
| 48 | 删除: opacity: 0; | |
| 49 | 删除: transition: opacity 0.14s ease, color 0.14s ease; | |
| 50 | 删除: } | |
| 51 | 删除: | |
| 52 | 删除: .anchored__link svg { | |
| 53 | 删除: width: 0.8em; | |
| 54 | 删除: height: 0.8em; | |
| 55 | 删除: fill: none; | |
| 56 | 删除: stroke: currentColor; | |
| 57 | 删除: stroke-width: 1.6; | |
| 58 | 删除: stroke-linecap: round; | |
| 59 | 删除: } | |
| 60 | 删除: | |
| 61 | 删除: .anchored:hover .anchored__link, | |
| 62 | 删除: .anchored__link:focus-visible { | |
| 63 | 删除: opacity: 1; | |
| 64 | 删除: } | |
| 65 | 删除: | |
| 66 | 删除: .anchored__link:hover { | |
| 67 | 删除: color: var(--accent); | |
| 68 | 删除: } | |
| 69 | 删除: | |
| 70 | 删除: .anchored__link[data-state='done'] { | |
| 71 | 删除: opacity: 1; | |
| 72 | 删除: color: var(--safe); | |
| 73 | 删除: } | |
| 74 | 删除: | |
| 75 | 删除: .anchored__link[data-state='done']::after { | |
| 76 | 删除: content: attr(data-copied-label); | |
| 77 | 删除: position: absolute; | |
| 78 | 删除: left: calc(100% + 0.4rem); | |
| 79 | 删除: white-space: nowrap; | |
| 80 | 删除: font-family: var(--font-mono); | |
| 81 | 删除: font-size: 0.68rem; | |
| 82 | 删除: font-weight: 400; | |
| 83 | 删除: letter-spacing: 0.06em; | |
| 84 | 删除: text-transform: uppercase; | |
| 85 | 删除: } | |
| 86 | 删除: | |
| 87 | 删除: /* Coarse pointers never hover: keep the link findable. */ | |
| 88 | 删除: @media (hover: none) { | |
| 89 | 删除: .anchored__link { | |
| 90 | 删除: opacity: 0.45; | |
| 91 | 删除: } | |
| 92 | 删除: } | |
| 93 | 删除:</style> | |
| 94 | 删除: | |
| 95 | 删除:<script> | |
| 96 | 删除: // One listener for every heading on the page. The link is followed as | |
| 97 | 删除: // usual; this only adds the copy. | |
| 98 | 删除: document.addEventListener('click', (event) => { | |
| 99 | 删除: const link = (event.target as Element | null)?.closest<HTMLAnchorElement>('[data-anchor]'); | |
| 100 | 删除: if (!link || !navigator.clipboard) return; | |
| 101 | 删除: navigator.clipboard.writeText(link.href).then( | |
| 102 | 删除: () => { | |
| 103 | 删除: link.dataset.state = 'done'; | |
| 104 | 删除: window.setTimeout(() => delete link.dataset.state, 1600); | |
| 105 | 删除: }, | |
| 106 | 删除: () => {}, | |
| 107 | 删除: ); | |
| 108 | 删除: }); | |
| 109 | 删除:</script> | |
| @@ -1,331 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import InstallTabs from './InstallTabs.astro'; | |
| 3 | 删除:import { inline } from '../lib/inline'; | |
| 4 | 删除:import { t, type Locale } from '../i18n'; | |
| 5 | 删除: | |
| 6 | 删除:interface Props { | |
| 7 | 删除: locale: Locale; | |
| 8 | 删除:} | |
| 9 | 删除: | |
| 10 | 删除:const { locale } = Astro.props; | |
| 11 | 删除:const d = t(locale); | |
| 12 | 删除: | |
| 13 | 删除:// Illustrative session, with no real path or host. The output lines follow | |
| 14 | 删除:// what agent-vm prints for a VM that exists but is stopped, trimmed to what | |
| 15 | 删除:// makes the point: not every line has to be there. | |
| 16 | 删除:const session: Array<{ kind: 'cmd' | 'out' | 'ok' | 'dim' | 'gap'; text: string }> = [ | |
| 17 | 删除: { kind: 'cmd', text: 'cd ~/work/acme-api' }, | |
| 18 | 删除: { kind: 'cmd', text: 'agent-vm run cat ~/.ssh/id_ed25519' }, | |
| 19 | 删除: { kind: 'out', text: "Starting VM 'agent-vm-acme-api-8f3c1d20'..." }, | |
| 20 | 删除: { kind: 'out', text: ' Resources: CPUs: 1, Memory: 3 GiB, Disk: 10 GiB' }, | |
| 21 | 删除: { kind: 'ok', text: 'cat: /Users/you/.ssh/id_ed25519: No such file or directory' }, | |
| 22 | 删除: { kind: 'gap', text: '' }, | |
| 23 | 删除: { kind: 'cmd', text: 'agent-vm opencode' }, | |
| 24 | 删除: { kind: 'out', text: ' Resources: CPUs: 1, Memory: 3 GiB, Disk: 10 GiB' }, | |
| 25 | 删除: { kind: 'dim', text: '# OpenCode starts here, with --auto' }, | |
| 26 | 删除:]; | |
| 27 | 删除:--- | |
| 28 | 删除: | |
| 29 | 删除:<section class="hero"> | |
| 30 | 删除: <div class="hero__grid" aria-hidden="true"></div> | |
| 31 | 删除: | |
| 32 | 删除: <div class="container hero__inner"> | |
| 33 | 删除: <div class="hero__copy"> | |
| 34 | 删除: <h1 class="hero__title"> | |
| 35 | 删除: {d.hero.title} | |
| 36 | 删除: <span class="hero__accent">{d.hero.titleAccent}</span> | |
| 37 | 删除: </h1> | |
| 38 | 删除: | |
| 39 | 删除: <p class="lede hero__lede">{d.hero.lede}</p> | |
| 40 | 删除: | |
| 41 | 删除: <div class="hero__install"> | |
| 42 | 删除: <p class="hero__install-label">{d.hero.installLabel}</p> | |
| 43 | 删除: {/* The curl installer offers to run setup itself. */} | |
| 44 | 删除: <InstallTabs | |
| 45 | 删除: locale={locale} | |
| 46 | 删除: id="hero-install" | |
| 47 | 删除: then={{ brew: 'agent-vm setup', git: 'agent-vm setup' }} | |
| 48 | 删除: /> | |
| 49 | 删除: </div> | |
| 50 | 删除: | |
| 51 | 删除: <div class="hero__ctas"> | |
| 52 | 删除: <a class="btn btn--primary" href="#install">{d.hero.ctaPrimary}</a> | |
| 53 | 删除: <a class="btn btn--ghost" href="#architecture">{d.hero.ctaSecondary}</a> | |
| 54 | 删除: </div> | |
| 55 | 删除: | |
| 56 | 删除: <p class="hero__meta">{d.hero.meta}</p> | |
| 57 | 删除: </div> | |
| 58 | 删除: | |
| 59 | 删除: <div class="hero__demo"> | |
| 60 | 删除: <div class="term"> | |
| 61 | 删除: <div class="term__bar"> | |
| 62 | 删除: <span class="term__dots" aria-hidden="true"> | |
| 63 | 删除: <i></i><i></i><i></i> | |
| 64 | 删除: </span> | |
| 65 | 删除: </div> | |
| 66 | 删除: <div class="term__body"> | |
| 67 | 删除: { | |
| 68 | 删除: session.map((line) => ( | |
| 69 | 删除: <div class:list={['term__line', `term__line--${line.kind}`]}> | |
| 70 | 删除: {line.kind === 'cmd' && ( | |
| 71 | 删除: <span class="term__prompt" aria-hidden="true"> | |
| 72 | 删除: $ | |
| 73 | 删除: </span> | |
| 74 | 删除: )} | |
| 75 | 删除: <span class="term__text">{line.text}</span> | |
| 76 | 删除: </div> | |
| 77 | 删除: )) | |
| 78 | 删除: } | |
| 79 | 删除: </div> | |
| 80 | 删除: </div> | |
| 81 | 删除: <p class="hero__caption">{d.hero.terminalCaption}</p> | |
| 82 | 删除: </div> | |
| 83 | 删除: </div> | |
| 84 | 删除: | |
| 85 | 删除: <div class="container"> | |
| 86 | 删除: <ul class="hero__points"> | |
| 87 | 删除: { | |
| 88 | 删除: d.hero.points.map((point) => ( | |
| 89 | 删除: <li class="hero__point"> | |
| 90 | 删除: <h2 class="hero__point-title" set:html={inline(point.title)} /> | |
| 91 | 删除: <p class="hero__point-body" set:html={inline(point.body)} /> | |
| 92 | 删除: </li> | |
| 93 | 删除: )) | |
| 94 | 删除: } | |
| 95 | 删除: </ul> | |
| 96 | 删除: </div> | |
| 97 | 删除:</section> | |
| 98 | 删除: | |
| 99 | 删除:<style> | |
| 100 | 删除: .hero { | |
| 101 | 删除: position: relative; | |
| 102 | 删除: padding-top: clamp(3rem, 7vw, 5.5rem); | |
| 103 | 删除: padding-bottom: clamp(2.5rem, 5vw, 4rem); | |
| 104 | 删除: overflow: hidden; | |
| 105 | 删除: } | |
| 106 | 删除: | |
| 107 | 删除: /* A faint engineering grid, fading out downward. Decoration only. */ | |
| 108 | 删除: .hero__grid { | |
| 109 | 删除: position: absolute; | |
| 110 | 删除: inset: 0; | |
| 111 | 删除: background-image: linear-gradient(to right, var(--line) 1px, transparent 1px), | |
| 112 | 删除: linear-gradient(to bottom, var(--line) 1px, transparent 1px); | |
| 113 | 删除: background-size: 3.5rem 3.5rem; | |
| 114 | 删除: mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), transparent 72%); | |
| 115 | 删除: -webkit-mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), transparent 72%); | |
| 116 | 删除: pointer-events: none; | |
| 117 | 删除: } | |
| 118 | 删除: | |
| 119 | 删除: .hero__inner { | |
| 120 | 删除: position: relative; | |
| 121 | 删除: display: grid; | |
| 122 | 删除: grid-template-columns: minmax(0, 1.05fr) minmax(0, 0.95fr); | |
| 123 | 删除: gap: clamp(2rem, 5vw, 4.5rem); | |
| 124 | 删除: align-items: start; | |
| 125 | 删除: } | |
| 126 | 删除: | |
| 127 | 删除: .hero__title { | |
| 128 | 删除: margin-bottom: 1.5rem; | |
| 129 | 删除: } | |
| 130 | 删除: | |
| 131 | 删除: .hero__meta { | |
| 132 | 删除: margin-top: 1.5rem; | |
| 133 | 删除: font-family: var(--font-mono); | |
| 134 | 删除: font-size: 0.72rem; | |
| 135 | 删除: letter-spacing: 0.1em; | |
| 136 | 删除: text-transform: uppercase; | |
| 137 | 删除: color: var(--ink-4); | |
| 138 | 删除: } | |
| 139 | 删除: | |
| 140 | 删除: .hero__accent { | |
| 141 | 删除: display: block; | |
| 142 | 删除: color: var(--accent); | |
| 143 | 删除: } | |
| 144 | 删除: | |
| 145 | 删除: .hero__lede { | |
| 146 | 删除: max-width: 38rem; | |
| 147 | 删除: margin-bottom: 2.25rem; | |
| 148 | 删除: } | |
| 149 | 删除: | |
| 150 | 删除: .hero__install { | |
| 151 | 删除: margin-bottom: 1.5rem; | |
| 152 | 删除: } | |
| 153 | 删除: | |
| 154 | 删除: .hero__install-label { | |
| 155 | 删除: margin-bottom: 0.6rem; | |
| 156 | 删除: font-family: var(--font-mono); | |
| 157 | 删除: font-size: 0.7rem; | |
| 158 | 删除: letter-spacing: 0.12em; | |
| 159 | 删除: text-transform: uppercase; | |
| 160 | 删除: color: var(--ink-3); | |
| 161 | 删除: } | |
| 162 | 删除: | |
| 163 | 删除: .hero__ctas { | |
| 164 | 删除: display: flex; | |
| 165 | 删除: flex-wrap: wrap; | |
| 166 | 删除: gap: 0.7rem; | |
| 167 | 删除: } | |
| 168 | 删除: | |
| 169 | 删除: /* Terminal ---------------------------------------------------------------- */ | |
| 170 | 删除: | |
| 171 | 删除: .hero__copy, | |
| 172 | 删除: .hero__demo { | |
| 173 | 删除: min-width: 0; | |
| 174 | 删除: } | |
| 175 | 删除: | |
| 176 | 删除: .hero__demo { | |
| 177 | 删除: position: relative; | |
| 178 | 删除: padding-top: 2.5rem; | |
| 179 | 删除: } | |
| 180 | 删除: | |
| 181 | 删除: .term { | |
| 182 | 删除: border: 1px solid var(--code-line); | |
| 183 | 删除: border-radius: var(--radius-lg); | |
| 184 | 删除: background: var(--code-bg); | |
| 185 | 删除: overflow: hidden; | |
| 186 | 删除: } | |
| 187 | 删除: | |
| 188 | 删除: .term__bar { | |
| 189 | 删除: display: flex; | |
| 190 | 删除: align-items: center; | |
| 191 | 删除: padding: 0.6rem 0.9rem; | |
| 192 | 删除: border-bottom: 1px solid var(--code-line); | |
| 193 | 删除: background: color-mix(in srgb, var(--code-bg) 82%, #fff 18%); | |
| 194 | 删除: } | |
| 195 | 删除: | |
| 196 | 删除: .term__dots { | |
| 197 | 删除: display: inline-flex; | |
| 198 | 删除: gap: 0.35rem; | |
| 199 | 删除: } | |
| 200 | 删除: | |
| 201 | 删除: .term__dots i { | |
| 202 | 删除: width: 0.55rem; | |
| 203 | 删除: height: 0.55rem; | |
| 204 | 删除: border-radius: 50%; | |
| 205 | 删除: background: var(--code-line); | |
| 206 | 删除: } | |
| 207 | 删除: | |
| 208 | 删除: .term__body { | |
| 209 | 删除: padding: 1.1rem 1.15rem 1.4rem; | |
| 210 | 删除: font-family: var(--font-mono); | |
| 211 | 删除: font-size: 0.79rem; | |
| 212 | 删除: line-height: 1.85; | |
| 213 | 删除: color: var(--code-ink); | |
| 214 | 删除: overflow-x: auto; | |
| 215 | 删除: } | |
| 216 | 删除: | |
| 217 | 删除: .term__line { | |
| 218 | 删除: display: flex; | |
| 219 | 删除: gap: 0.55rem; | |
| 220 | 删除: white-space: pre; | |
| 221 | 删除: } | |
| 222 | 删除: | |
| 223 | 删除: .term__line--gap { | |
| 224 | 删除: height: 0.7rem; | |
| 225 | 删除: } | |
| 226 | 删除: | |
| 227 | 删除: .term__prompt { | |
| 228 | 删除: color: #eaa963; | |
| 229 | 删除: user-select: none; | |
| 230 | 删除: } | |
| 231 | 删除: | |
| 232 | 删除: .term__line--out .term__text { | |
| 233 | 删除: color: var(--code-ink-2); | |
| 234 | 删除: } | |
| 235 | 删除: | |
| 236 | 删除: .term__line--dim .term__text { | |
| 237 | 删除: color: #6f6a60; | |
| 238 | 删除: font-style: italic; | |
| 239 | 删除: } | |
| 240 | 删除: | |
| 241 | 删除: .term__line--ok .term__text { | |
| 242 | 删除: color: #9dc08b; | |
| 243 | 删除: } | |
| 244 | 删除: | |
| 245 | 删除: .hero__caption { | |
| 246 | 删除: margin-top: 0.9rem; | |
| 247 | 删除: font-size: 0.82rem; | |
| 248 | 删除: color: var(--ink-3); | |
| 249 | 删除: } | |
| 250 | 删除: | |
| 251 | 删除: /* Points ------------------------------------------------------------------ */ | |
| 252 | 删除: | |
| 253 | 删除: .hero__points { | |
| 254 | 删除: position: relative; | |
| 255 | 删除: display: grid; | |
| 256 | 删除: grid-template-columns: repeat(4, minmax(0, 1fr)); | |
| 257 | 删除: gap: 0; | |
| 258 | 删除: margin-top: clamp(3rem, 6vw, 5rem); | |
| 259 | 删除: list-style: none; | |
| 260 | 删除: border-top: 1px solid var(--line); | |
| 261 | 删除: } | |
| 262 | 删除: | |
| 263 | 删除: .hero__point { | |
| 264 | 删除: padding: 1.6rem clamp(1rem, 2vw, 1.75rem) 0; | |
| 265 | 删除: border-left: 1px solid var(--line); | |
| 266 | 删除: } | |
| 267 | 删除: | |
| 268 | 删除: .hero__point:first-child { | |
| 269 | 删除: padding-left: 0; | |
| 270 | 删除: border-left: 0; | |
| 271 | 删除: } | |
| 272 | 删除: | |
| 273 | 删除: .hero__point-title { | |
| 274 | 删除: font-size: 0.95rem; | |
| 275 | 删除: font-weight: 600; | |
| 276 | 删除: letter-spacing: -0.01em; | |
| 277 | 删除: margin-bottom: 0.4rem; | |
| 278 | 删除: } | |
| 279 | 删除: | |
| 280 | 删除: .hero__point-body { | |
| 281 | 删除: font-size: 0.9rem; | |
| 282 | 删除: color: var(--ink-2); | |
| 283 | 删除: text-wrap: pretty; | |
| 284 | 删除: } | |
| 285 | 删除: | |
| 286 | 删除: /* Four columns only while they stay readable; two, then one. */ | |
| 287 | 删除: @media (max-width: 72rem) { | |
| 288 | 删除: .hero__points { | |
| 289 | 删除: grid-template-columns: repeat(2, minmax(0, 1fr)); | |
| 290 | 删除: } | |
| 291 | 删除: | |
| 292 | 删除: .hero__point:nth-child(odd) { | |
| 293 | 删除: padding-left: 0; | |
| 294 | 删除: border-left: 0; | |
| 295 | 删除: } | |
| 296 | 删除: | |
| 297 | 删除: .hero__point:nth-child(n + 3) { | |
| 298 | 删除: padding-top: 1.6rem; | |
| 299 | 删除: border-top: 1px solid var(--line); | |
| 300 | 删除: } | |
| 301 | 删除: } | |
| 302 | 删除: | |
| 303 | 删除: @media (max-width: 62rem) { | |
| 304 | 删除: .hero__inner { | |
| 305 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 306 | 删除: } | |
| 307 | 删除: | |
| 308 | 删除: .hero__demo { | |
| 309 | 删除: padding-top: 0; | |
| 310 | 删除: } | |
| 311 | 删除: | |
| 312 | 删除: .hero__points { | |
| 313 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 314 | 删除: } | |
| 315 | 删除: | |
| 316 | 删除: .hero__point { | |
| 317 | 删除: padding: 1.25rem 0; | |
| 318 | 删除: border-left: 0; | |
| 319 | 删除: border-top: 0; | |
| 320 | 删除: border-bottom: 1px solid var(--line); | |
| 321 | 删除: } | |
| 322 | 删除: | |
| 323 | 删除: .hero__point:first-child { | |
| 324 | 删除: padding-top: 1.25rem; | |
| 325 | 删除: } | |
| 326 | 删除: | |
| 327 | 删除: .hero__point:last-child { | |
| 328 | 删除: border-bottom: 0; | |
| 329 | 删除: } | |
| 330 | 删除: } | |
| 331 | 删除:</style> | |
| @@ -1,179 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import CodeBlock from './CodeBlock.astro'; | |
| 3 | 删除:import InstallTabs from './InstallTabs.astro'; | |
| 4 | 删除:import { inline } from '../lib/inline'; | |
| 5 | 删除:import Heading from './Heading.astro'; | |
| 6 | 删除:import { slug } from '../lib/slug'; | |
| 7 | 删除:import { en } from '../i18n/en'; | |
| 8 | 删除:import { t, type Locale } from '../i18n'; | |
| 9 | 删除: | |
| 10 | 删除:interface Props { | |
| 11 | 删除: locale: Locale; | |
| 12 | 删除:} | |
| 13 | 删除: | |
| 14 | 删除:const { locale } = Astro.props; | |
| 15 | 删除:const d = t(locale); | |
| 16 | 删除:--- | |
| 17 | 删除: | |
| 18 | 删除:<section class="section" id="install"> | |
| 19 | 删除: <div class="container"> | |
| 20 | 删除: <div class="section-head"> | |
| 21 | 删除: <p class="eyebrow">{d.install.eyebrow}</p> | |
| 22 | 删除: <Heading as="h2" id="install" own={false} locale={locale}>{d.install.title}</Heading> | |
| 23 | 删除: <p class="lede" set:html={inline(d.install.lede)} /> | |
| 24 | 删除: </div> | |
| 25 | 删除: | |
| 26 | 删除: <div class="install__layout"> | |
| 27 | 删除: <aside class="install__prereq card card--sunk"> | |
| 28 | 删除: <h3 class="install__prereq-title">{d.install.prerequisitesTitle}</h3> | |
| 29 | 删除: <ul class="install__prereq-list"> | |
| 30 | 删除: { | |
| 31 | 删除: d.install.prerequisites.map((item) => ( | |
| 32 | 删除: <li class="install__prereq-item"> | |
| 33 | 删除: <span class="install__prereq-name"> | |
| 34 | 删除: {item.href ? ( | |
| 35 | 删除: <a href={item.href} rel="noopener noreferrer" target="_blank"> | |
| 36 | 删除: {item.name} | |
| 37 | 删除: </a> | |
| 38 | 删除: ) : ( | |
| 39 | 删除: item.name | |
| 40 | 删除: )} | |
| 41 | 删除: </span> | |
| 42 | 删除: <span class="install__prereq-note" set:html={inline(item.note)} /> | |
| 43 | 删除: </li> | |
| 44 | 删除: )) | |
| 45 | 删除: } | |
| 46 | 删除: </ul> | |
| 47 | 删除: </aside> | |
| 48 | 删除: | |
| 49 | 删除: <ol class="install__steps"> | |
| 50 | 删除: <li class="install__step"> | |
| 51 | 删除: <div class="install__step-head"> | |
| 52 | 删除: <span class="install__step-n" aria-hidden="true">01</span> | |
| 53 | 删除: <div> | |
| 54 | 删除: <Heading as="h3" id={slug(en.install.methodsTitle)} locale={locale} class="install__step-title">{d.install.methodsTitle}</Heading> | |
| 55 | 删除: <p class="prose install__step-body" set:html={inline(d.install.methodsBody)} /> | |
| 56 | 删除: </div> | |
| 57 | 删除: </div> | |
| 58 | 删除: <InstallTabs locale={locale} id="install-methods" notes /> | |
| 59 | 删除: </li> | |
| 60 | 删除: { | |
| 61 | 删除: d.install.steps.map((step, index) => ( | |
| 62 | 删除: <li class="install__step"> | |
| 63 | 删除: <div class="install__step-head"> | |
| 64 | 删除: <span class="install__step-n" aria-hidden="true"> | |
| 65 | 删除: {String(index + 2).padStart(2, '0')} | |
| 66 | 删除: </span> | |
| 67 | 删除: <div> | |
| 68 | 删除: <Heading as="h3" id={slug(en.install.steps[index]!.title)} locale={locale} class="install__step-title">{step.title}</Heading> | |
| 69 | 删除: <p class="prose install__step-body" set:html={inline(step.body)} /> | |
| 70 | 删除: </div> | |
| 71 | 删除: </div> | |
| 72 | 删除: <CodeBlock locale={locale} code={step.code} prompt /> | |
| 73 | 删除: </li> | |
| 74 | 删除: )) | |
| 75 | 删除: } | |
| 76 | 删除: </ol> | |
| 77 | 删除: </div> | |
| 78 | 删除: </div> | |
| 79 | 删除:</section> | |
| 80 | 删除: | |
| 81 | 删除:<style> | |
| 82 | 删除: .install__layout { | |
| 83 | 删除: display: grid; | |
| 84 | 删除: grid-template-columns: minmax(0, 0.62fr) minmax(0, 1.38fr); | |
| 85 | 删除: gap: clamp(1.5rem, 3.5vw, 3rem); | |
| 86 | 删除: align-items: start; | |
| 87 | 删除: } | |
| 88 | 删除: | |
| 89 | 删除: .install__prereq { | |
| 90 | 删除: position: sticky; | |
| 91 | 删除: top: calc(var(--nav-h) + 2rem); | |
| 92 | 删除: } | |
| 93 | 删除: | |
| 94 | 删除: .install__prereq-title { | |
| 95 | 删除: font-size: 0.72rem; | |
| 96 | 删除: font-family: var(--font-mono); | |
| 97 | 删除: letter-spacing: 0.12em; | |
| 98 | 删除: text-transform: uppercase; | |
| 99 | 删除: color: var(--ink-3); | |
| 100 | 删除: font-weight: 500; | |
| 101 | 删除: margin-bottom: 1.1rem; | |
| 102 | 删除: } | |
| 103 | 删除: | |
| 104 | 删除: .install__prereq-list { | |
| 105 | 删除: list-style: none; | |
| 106 | 删除: display: grid; | |
| 107 | 删除: gap: 1.05rem; | |
| 108 | 删除: } | |
| 109 | 删除: | |
| 110 | 删除: .install__prereq-item { | |
| 111 | 删除: display: grid; | |
| 112 | 删除: gap: 0.2rem; | |
| 113 | 删除: padding-left: 0.9rem; | |
| 114 | 删除: border-left: 2px solid var(--accent-line); | |
| 115 | 删除: } | |
| 116 | 删除: | |
| 117 | 删除: .install__prereq-name { | |
| 118 | 删除: font-size: 0.95rem; | |
| 119 | 删除: font-weight: 560; | |
| 120 | 删除: color: var(--ink); | |
| 121 | 删除: } | |
| 122 | 删除: | |
| 123 | 删除: .install__prereq-note { | |
| 124 | 删除: font-size: 0.86rem; | |
| 125 | 删除: color: var(--ink-3); | |
| 126 | 删除: } | |
| 127 | 删除: | |
| 128 | 删除: .install__steps { | |
| 129 | 删除: list-style: none; | |
| 130 | 删除: display: grid; | |
| 131 | 删除: gap: clamp(1.75rem, 3vw, 2.5rem); | |
| 132 | 删除: min-width: 0; | |
| 133 | 删除: } | |
| 134 | 删除: | |
| 135 | 删除: .install__step { | |
| 136 | 删除: display: grid; | |
| 137 | 删除: gap: 1rem; | |
| 138 | 删除: min-width: 0; | |
| 139 | 删除: } | |
| 140 | 删除: | |
| 141 | 删除: .install__step-head { | |
| 142 | 删除: display: flex; | |
| 143 | 删除: gap: 1rem; | |
| 144 | 删除: align-items: start; | |
| 145 | 删除: } | |
| 146 | 删除: | |
| 147 | 删除: .install__step-n { | |
| 148 | 删除: flex: none; | |
| 149 | 删除: width: 2.1rem; | |
| 150 | 删除: height: 2.1rem; | |
| 151 | 删除: display: grid; | |
| 152 | 删除: place-items: center; | |
| 153 | 删除: border: 1px solid var(--line-strong); | |
| 154 | 删除: border-radius: 50%; | |
| 155 | 删除: font-family: var(--font-mono); | |
| 156 | 删除: font-size: 0.74rem; | |
| 157 | 删除: color: var(--accent); | |
| 158 | 删除: background: var(--surface); | |
| 159 | 删除: } | |
| 160 | 删除: | |
| 161 | 删除: .install__step-title { | |
| 162 | 删除: margin-bottom: 0.3rem; | |
| 163 | 删除: } | |
| 164 | 删除: | |
| 165 | 删除: .install__step-body { | |
| 166 | 删除: font-size: 0.94rem; | |
| 167 | 删除: max-width: 44rem; | |
| 168 | 删除: } | |
| 169 | 删除: | |
| 170 | 删除: @media (max-width: 62rem) { | |
| 171 | 删除: .install__layout { | |
| 172 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 173 | 删除: } | |
| 174 | 删除: | |
| 175 | 删除: .install__prereq { | |
| 176 | 删除: position: static; | |
| 177 | 删除: } | |
| 178 | 删除: } | |
| 179 | 删除:</style> | |
| @@ -1,171 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import CodeBlock from './CodeBlock.astro'; | |
| 3 | 删除:import { inline } from '../lib/inline'; | |
| 4 | 删除:import { t, type Locale } from '../i18n'; | |
| 5 | 删除: | |
| 6 | 删除:interface Props { | |
| 7 | 删除: locale: Locale; | |
| 8 | 删除: /** Keeps ids unique: the hero and the install section both have one. */ | |
| 9 | 删除: id: string; | |
| 10 | 删除: /** Command appended to a method's code, by method id. */ | |
| 11 | 删除: then?: Record<string, string>; | |
| 12 | 删除: /** Show each method's note under its code. */ | |
| 13 | 删除: notes?: boolean; | |
| 14 | 删除:} | |
| 15 | 删除: | |
| 16 | 删除:const { locale, id, then = {}, notes = false } = Astro.props; | |
| 17 | 删除:const d = t(locale); | |
| 18 | 删除:const methods = d.install.methods; | |
| 19 | 删除:--- | |
| 20 | 删除: | |
| 21 | 删除:<div class="tabs" data-tabs> | |
| 22 | 删除: <div class="tabs__list" role="tablist" aria-label={d.install.methodsLabel}> | |
| 23 | 删除: { | |
| 24 | 删除: methods.map((method, index) => ( | |
| 25 | 删除: <button | |
| 26 | 删除: type="button" | |
| 27 | 删除: class="tabs__tab" | |
| 28 | 删除: role="tab" | |
| 29 | 删除: id={`${id}-tab-${method.id}`} | |
| 30 | 删除: aria-controls={`${id}-panel-${method.id}`} | |
| 31 | 删除: aria-selected={index === 0 ? 'true' : 'false'} | |
| 32 | 删除: tabindex={index === 0 ? 0 : -1} | |
| 33 | 删除: data-tab={method.id} | |
| 34 | 删除: > | |
| 35 | 删除: {method.label} | |
| 36 | 删除: </button> | |
| 37 | 删除: )) | |
| 38 | 删除: } | |
| 39 | 删除: </div> | |
| 40 | 删除: { | |
| 41 | 删除: methods.map((method, index) => ( | |
| 42 | 删除: <div | |
| 43 | 删除: class="tabs__panel" | |
| 44 | 删除: role="tabpanel" | |
| 45 | 删除: id={`${id}-panel-${method.id}`} | |
| 46 | 删除: aria-labelledby={`${id}-tab-${method.id}`} | |
| 47 | 删除: data-panel={method.id} | |
| 48 | 删除: hidden={index !== 0} | |
| 49 | 删除: > | |
| 50 | 删除: <CodeBlock locale={locale} prompt code={then[method.id] ? `${method.code}\n${then[method.id]}` : method.code} /> | |
| 51 | 删除: {notes && <p class="prose tabs__note" set:html={inline(method.note)} />} | |
| 52 | 删除: </div> | |
| 53 | 删除: )) | |
| 54 | 删除: } | |
| 55 | 删除:</div> | |
| 56 | 删除: | |
| 57 | 删除:<style> | |
| 58 | 删除: .tabs { | |
| 59 | 删除: display: grid; | |
| 60 | 删除: gap: 0.6rem; | |
| 61 | 删除: min-width: 0; | |
| 62 | 删除: } | |
| 63 | 删除: | |
| 64 | 删除: .tabs__list { | |
| 65 | 删除: display: flex; | |
| 66 | 删除: flex-wrap: wrap; | |
| 67 | 删除: gap: 0.35rem; | |
| 68 | 删除: } | |
| 69 | 删除: | |
| 70 | 删除: .tabs__tab { | |
| 71 | 删除: padding: 0.3rem 0.75rem; | |
| 72 | 删除: border: 1px solid var(--line); | |
| 73 | 删除: border-radius: 999px; | |
| 74 | 删除: background: transparent; | |
| 75 | 删除: color: var(--ink-3); | |
| 76 | 删除: font-family: var(--font-mono); | |
| 77 | 删除: font-size: 0.74rem; | |
| 78 | 删除: letter-spacing: 0.02em; | |
| 79 | 删除: cursor: pointer; | |
| 80 | 删除: transition: color 0.14s ease, border-color 0.14s ease, background 0.14s ease; | |
| 81 | 删除: } | |
| 82 | 删除: | |
| 83 | 删除: .tabs__tab:hover { | |
| 84 | 删除: color: var(--ink); | |
| 85 | 删除: border-color: var(--line-strong); | |
| 86 | 删除: } | |
| 87 | 删除: | |
| 88 | 删除: .tabs__tab[aria-selected='true'] { | |
| 89 | 删除: color: var(--accent); | |
| 90 | 删除: border-color: var(--accent-line); | |
| 91 | 删除: background: var(--accent-wash); | |
| 92 | 删除: } | |
| 93 | 删除: | |
| 94 | 删除: .tabs__tab:focus-visible { | |
| 95 | 删除: outline: 2px solid var(--accent); | |
| 96 | 删除: outline-offset: 2px; | |
| 97 | 删除: } | |
| 98 | 删除: | |
| 99 | 删除: .tabs__panel { | |
| 100 | 删除: display: grid; | |
| 101 | 删除: gap: 0.75rem; | |
| 102 | 删除: min-width: 0; | |
| 103 | 删除: } | |
| 104 | 删除: | |
| 105 | 删除: .tabs__panel[hidden] { | |
| 106 | 删除: display: none; | |
| 107 | 删除: } | |
| 108 | 删除: | |
| 109 | 删除: .tabs__note { | |
| 110 | 删除: font-size: 0.9rem; | |
| 111 | 删除: max-width: 44rem; | |
| 112 | 删除: } | |
| 113 | 删除:</style> | |
| 114 | 删除: | |
| 115 | 删除:<script> | |
| 116 | 删除: // Every tab set on the page shows the same method, and the choice is kept | |
| 117 | 删除: // for the next visit. | |
| 118 | 删除: const KEY = 'agent-vm:install-method'; | |
| 119 | 删除: | |
| 120 | 删除: function select(method: string, focus?: HTMLElement) { | |
| 121 | 删除: const tabs = document.querySelectorAll<HTMLElement>('[data-tabs] [data-tab]'); | |
| 122 | 删除: if (![...tabs].some((tab) => tab.dataset.tab === method)) return; | |
| 123 | 删除: for (const tab of tabs) { | |
| 124 | 删除: const on = tab.dataset.tab === method; | |
| 125 | 删除: tab.setAttribute('aria-selected', on ? 'true' : 'false'); | |
| 126 | 删除: tab.tabIndex = on ? 0 : -1; | |
| 127 | 删除: } | |
| 128 | 删除: for (const panel of document.querySelectorAll<HTMLElement>('[data-tabs] [data-panel]')) { | |
| 129 | 删除: panel.hidden = panel.dataset.panel !== method; | |
| 130 | 删除: } | |
| 131 | 删除: focus?.focus(); | |
| 132 | 删除: } | |
| 133 | 删除: | |
| 134 | 删除: function remember(method: string) { | |
| 135 | 删除: try { | |
| 136 | 删除: localStorage.setItem(KEY, method); | |
| 137 | 删除: } catch {} | |
| 138 | 删除: } | |
| 139 | 删除: | |
| 140 | 删除: try { | |
| 141 | 删除: const saved = localStorage.getItem(KEY); | |
| 142 | 删除: if (saved) select(saved); | |
| 143 | 删除: } catch {} | |
| 144 | 删除: | |
| 145 | 删除: document.addEventListener('click', (event) => { | |
| 146 | 删除: const tab = (event.target as Element | null)?.closest<HTMLElement>('[data-tabs] [data-tab]'); | |
| 147 | 删除: if (!tab?.dataset.tab) return; | |
| 148 | 删除: select(tab.dataset.tab); | |
| 149 | 删除: remember(tab.dataset.tab); | |
| 150 | 删除: }); | |
| 151 | 删除: | |
| 152 | 删除: // Arrow keys, Home and End move between tabs and select as they go. | |
| 153 | 删除: document.addEventListener('keydown', (event) => { | |
| 154 | 删除: const tab = (event.target as Element | null)?.closest<HTMLElement>('[data-tabs] [data-tab]'); | |
| 155 | 删除: const list = tab?.parentElement; | |
| 156 | 删除: if (!tab || !list) return; | |
| 157 | 删除: const tabs = [...list.querySelectorAll<HTMLElement>('[data-tab]')]; | |
| 158 | 删除: const at = tabs.indexOf(tab); | |
| 159 | 删除: const moves: Record<string, HTMLElement | undefined> = { | |
| 160 | 删除: ArrowRight: tabs[(at + 1) % tabs.length], | |
| 161 | 删除: ArrowLeft: tabs[(at - 1 + tabs.length) % tabs.length], | |
| 162 | 删除: Home: tabs[0], | |
| 163 | 删除: End: tabs[tabs.length - 1], | |
| 164 | 删除: }; | |
| 165 | 删除: const next = moves[event.key]; | |
| 166 | 删除: if (!next?.dataset.tab) return; | |
| 167 | 删除: event.preventDefault(); | |
| 168 | 删除: select(next.dataset.tab, next); | |
| 169 | 删除: remember(next.dataset.tab); | |
| 170 | 删除: }); | |
| 171 | 删除:</script> | |
| @@ -1,28 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import Hero from './Hero.astro'; | |
| 3 | 删除:import Threat from './Threat.astro'; | |
| 4 | 删除:import Install from './Install.astro'; | |
| 5 | 删除:import Usage from './Usage.astro'; | |
| 6 | 删除:import Reference from './Reference.astro'; | |
| 7 | 删除:import Docs from './Docs.astro'; | |
| 8 | 删除:import Architecture from './Architecture.astro'; | |
| 9 | 删除:import Contribute from './Contribute.astro'; | |
| 10 | 删除:import Credits from './Credits.astro'; | |
| 11 | 删除:import type { Locale } from '../i18n'; | |
| 12 | 删除: | |
| 13 | 删除:interface Props { | |
| 14 | 删除: locale: Locale; | |
| 15 | 删除:} | |
| 16 | 删除: | |
| 17 | 删除:const { locale } = Astro.props; | |
| 18 | 删除:--- | |
| 19 | 删除: | |
| 20 | 删除:<Hero locale={locale} /> | |
| 21 | 删除:<Threat locale={locale} /> | |
| 22 | 删除:<Install locale={locale} /> | |
| 23 | 删除:<Usage locale={locale} /> | |
| 24 | 删除:<Architecture locale={locale} /> | |
| 25 | 删除:<Docs locale={locale} /> | |
| 26 | 删除:<Reference locale={locale} /> | |
| 27 | 删除:<Contribute locale={locale} /> | |
| 28 | 删除:<Credits locale={locale} /> | |
| @@ -1,325 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import { t, localeHref, otherLocales, type Locale } from '../i18n'; | |
| 3 | 删除: | |
| 4 | 删除:interface Props { | |
| 5 | 删除: locale: Locale; | |
| 6 | 删除:} | |
| 7 | 删除: | |
| 8 | 删除:const { locale } = Astro.props; | |
| 9 | 删除:const d = t(locale); | |
| 10 | 删除: | |
| 11 | 删除:// Prefixed with the locale root rather than left as bare fragments: on the 404 | |
| 12 | 删除:// page, where none of these sections exist, a bare `#install` goes nowhere. | |
| 13 | 删除:// On the landing page itself the browser still treats these as same-document | |
| 14 | 删除:// fragment navigations, so the smooth scroll is unaffected. | |
| 15 | 删除:const home = localeHref(locale); | |
| 16 | 删除:const links = [ | |
| 17 | 删除: { href: `${home}#install`, label: d.nav.sections.install }, | |
| 18 | 删除: { href: `${home}#usage`, label: d.nav.sections.usage }, | |
| 19 | 删除: { href: `${home}#architecture`, label: d.nav.sections.architecture }, | |
| 20 | 删除: { href: `${home}#security`, label: d.nav.sections.security }, | |
| 21 | 删除: { href: `${home}#reference`, label: d.nav.sections.reference }, | |
| 22 | 删除: { href: `${home}#contribute`, label: d.nav.sections.contribute }, | |
| 23 | 删除: { href: `${home}#credits`, label: d.nav.sections.credits }, | |
| 24 | 删除:]; | |
| 25 | 删除:--- | |
| 26 | 删除: | |
| 27 | 删除:<header class="nav"> | |
| 28 | 删除: <div class="nav__inner container"> | |
| 29 | 删除: <a class="nav__brand" href={localeHref(locale)}> | |
| 30 | 删除: <svg class="nav__mark" viewBox="0 0 24 24" aria-hidden="true" focusable="false"> | |
| 31 | 删除: <rect x="1.25" y="1.25" width="21.5" height="21.5" rx="4.5" /> | |
| 32 | 删除: <rect class="nav__mark-inner" x="6.75" y="6.75" width="10.5" height="10.5" rx="2" /> | |
| 33 | 删除: </svg> | |
| 34 | 删除: <span class="nav__name">agent-vm</span> | |
| 35 | 删除: </a> | |
| 36 | 删除: | |
| 37 | 删除: <button | |
| 38 | 删除: type="button" | |
| 39 | 删除: class="nav__burger" | |
| 40 | 删除: data-nav-toggle | |
| 41 | 删除: aria-expanded="false" | |
| 42 | 删除: aria-controls="nav-panel" | |
| 43 | 删除: > | |
| 44 | 删除: <span class="visually-hidden">{d.nav.menu}</span> | |
| 45 | 删除: <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"> | |
| 46 | 删除: <path class="nav__burger-lines" d="M4 7h16M4 12h16M4 17h16" /> | |
| 47 | 删除: <path class="nav__burger-close" d="M6 6l12 12M18 6L6 18" /> | |
| 48 | 删除: </svg> | |
| 49 | 删除: </button> | |
| 50 | 删除: | |
| 51 | 删除: <div class="nav__panel" id="nav-panel" data-nav-panel> | |
| 52 | 删除: <nav class="nav__links" aria-label={d.nav.menu}> | |
| 53 | 删除: { | |
| 54 | 删除: links.map((link) => ( | |
| 55 | 删除: <a class="nav__link" href={link.href} data-nav-link> | |
| 56 | 删除: {link.label} | |
| 57 | 删除: </a> | |
| 58 | 删除: )) | |
| 59 | 删除: } | |
| 60 | 删除: </nav> | |
| 61 | 删除: | |
| 62 | 删除: <div class="nav__tools"> | |
| 63 | 删除: <div class="nav__langs" role="group" aria-label={d.nav.language}> | |
| 64 | 删除: <span class="nav__lang nav__lang--current" aria-current="true"> | |
| 65 | 删除: {locale.toUpperCase()} | |
| 66 | 删除: </span> | |
| 67 | 删除: { | |
| 68 | 删除: otherLocales(locale).map((other) => ( | |
| 69 | 删除: <a class="nav__lang" href={localeHref(other)} hreflang={other} lang={other}> | |
| 70 | 删除: {other.toUpperCase()} | |
| 71 | 删除: </a> | |
| 72 | 删除: )) | |
| 73 | 删除: } | |
| 74 | 删除: </div> | |
| 75 | 删除: | |
| 76 | 删除: <a | |
| 77 | 删除: class="nav__icon" | |
| 78 | 删除: href="https://github.com/sylvinus/agent-vm" | |
| 79 | 删除: rel="noopener" | |
| 80 | 删除: target="_blank" | |
| 81 | 删除: > | |
| 82 | 删除: <span class="visually-hidden">{d.nav.github}</span> | |
| 83 | 删除: <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" class="nav__gh"> | |
| 84 | 删除: <path | |
| 85 | 删除: d="M12 1.8a10.2 10.2 0 0 0-3.23 19.88c.51.1.7-.22.7-.49v-1.9c-2.84.62-3.44-1.2-3.44-1.2-.47-1.18-1.14-1.5-1.14-1.5-.93-.63.07-.62.07-.62 1.03.07 1.57 1.06 1.57 1.06.91 1.57 2.4 1.12 2.99.86.09-.66.36-1.12.65-1.37-2.27-.26-4.65-1.13-4.65-5.04 0-1.12.4-2.03 1.05-2.74-.1-.26-.45-1.3.1-2.7 0 0 .86-.28 2.8 1.05a9.7 9.7 0 0 1 5.1 0c1.94-1.33 2.8-1.05 2.8-1.05.55 1.4.2 2.44.1 2.7.65.71 1.05 1.62 1.05 2.74 0 3.92-2.39 4.78-4.66 5.03.37.32.7.94.7 1.9v2.81c0 .27.18.59.7.49A10.2 10.2 0 0 0 12 1.8z" | |
| 86 | 删除: /> | |
| 87 | 删除: </svg> | |
| 88 | 删除: </a> | |
| 89 | 删除: </div> | |
| 90 | 删除: </div> | |
| 91 | 删除: </div> | |
| 92 | 删除:</header> | |
| 93 | 删除: | |
| 94 | 删除:<style> | |
| 95 | 删除: .nav { | |
| 96 | 删除: position: sticky; | |
| 97 | 删除: top: 0; | |
| 98 | 删除: z-index: 50; | |
| 99 | 删除: background: color-mix(in srgb, var(--paper) 88%, transparent); | |
| 100 | 删除: backdrop-filter: saturate(160%) blur(12px); | |
| 101 | 删除: border-bottom: 1px solid var(--line); | |
| 102 | 删除: } | |
| 103 | 删除: | |
| 104 | 删除: .nav__inner { | |
| 105 | 删除: display: flex; | |
| 106 | 删除: align-items: center; | |
| 107 | 删除: gap: 1rem; | |
| 108 | 删除: min-height: var(--nav-h); | |
| 109 | 删除: } | |
| 110 | 删除: | |
| 111 | 删除: .nav__brand { | |
| 112 | 删除: display: inline-flex; | |
| 113 | 删除: align-items: center; | |
| 114 | 删除: gap: 0.55rem; | |
| 115 | 删除: margin-right: auto; | |
| 116 | 删除: color: var(--ink); | |
| 117 | 删除: text-decoration: none; | |
| 118 | 删除: font-weight: 600; | |
| 119 | 删除: letter-spacing: -0.015em; | |
| 120 | 删除: } | |
| 121 | 删除: | |
| 122 | 删除: .nav__mark { | |
| 123 | 删除: width: 1.35rem; | |
| 124 | 删除: height: 1.35rem; | |
| 125 | 删除: fill: none; | |
| 126 | 删除: stroke: var(--ink); | |
| 127 | 删除: stroke-width: 1.5; | |
| 128 | 删除: } | |
| 129 | 删除: | |
| 130 | 删除: .nav__mark-inner { | |
| 131 | 删除: fill: var(--accent); | |
| 132 | 删除: stroke: none; | |
| 133 | 删除: } | |
| 134 | 删除: | |
| 135 | 删除: .nav__name { | |
| 136 | 删除: font-family: var(--font-mono); | |
| 137 | 删除: font-size: 0.95rem; | |
| 138 | 删除: } | |
| 139 | 删除: | |
| 140 | 删除: .nav__burger { | |
| 141 | 删除: display: none; | |
| 142 | 删除: align-items: center; | |
| 143 | 删除: justify-content: center; | |
| 144 | 删除: width: 2.25rem; | |
| 145 | 删除: height: 2.25rem; | |
| 146 | 删除: padding: 0; | |
| 147 | 删除: border: 1px solid var(--line); | |
| 148 | 删除: border-radius: var(--radius); | |
| 149 | 删除: background: transparent; | |
| 150 | 删除: color: var(--ink); | |
| 151 | 删除: cursor: pointer; | |
| 152 | 删除: } | |
| 153 | 删除: | |
| 154 | 删除: .nav__burger svg { | |
| 155 | 删除: width: 1.1rem; | |
| 156 | 删除: height: 1.1rem; | |
| 157 | 删除: fill: none; | |
| 158 | 删除: stroke: currentColor; | |
| 159 | 删除: stroke-width: 1.6; | |
| 160 | 删除: stroke-linecap: round; | |
| 161 | 删除: } | |
| 162 | 删除: | |
| 163 | 删除: .nav__burger-close, | |
| 164 | 删除: .nav__burger[aria-expanded='true'] .nav__burger-lines { | |
| 165 | 删除: display: none; | |
| 166 | 删除: } | |
| 167 | 删除: | |
| 168 | 删除: .nav__burger[aria-expanded='true'] .nav__burger-close { | |
| 169 | 删除: display: inline; | |
| 170 | 删除: } | |
| 171 | 删除: | |
| 172 | 删除: .nav__panel { | |
| 173 | 删除: display: flex; | |
| 174 | 删除: align-items: center; | |
| 175 | 删除: gap: clamp(1rem, 2.5vw, 2rem); | |
| 176 | 删除: } | |
| 177 | 删除: | |
| 178 | 删除: .nav__links { | |
| 179 | 删除: display: flex; | |
| 180 | 删除: align-items: center; | |
| 181 | 删除: gap: clamp(0.85rem, 1.8vw, 1.6rem); | |
| 182 | 删除: } | |
| 183 | 删除: | |
| 184 | 删除: .nav__link { | |
| 185 | 删除: position: relative; | |
| 186 | 删除: padding-block: 0.3rem; | |
| 187 | 删除: color: var(--ink-2); | |
| 188 | 删除: font-size: 0.875rem; | |
| 189 | 删除: font-weight: 500; | |
| 190 | 删除: text-decoration: none; | |
| 191 | 删除: white-space: nowrap; | |
| 192 | 删除: } | |
| 193 | 删除: | |
| 194 | 删除: .nav__link:hover { | |
| 195 | 删除: color: var(--ink); | |
| 196 | 删除: } | |
| 197 | 删除: | |
| 198 | 删除: .nav__link[data-current] { | |
| 199 | 删除: color: var(--ink); | |
| 200 | 删除: } | |
| 201 | 删除: | |
| 202 | 删除: .nav__link[data-current]::after { | |
| 203 | 删除: content: ''; | |
| 204 | 删除: position: absolute; | |
| 205 | 删除: left: 0; | |
| 206 | 删除: right: 0; | |
| 207 | 删除: bottom: -0.15rem; | |
| 208 | 删除: height: 1.5px; | |
| 209 | 删除: background: var(--accent); | |
| 210 | 删除: border-radius: 2px; | |
| 211 | 删除: } | |
| 212 | 删除: | |
| 213 | 删除: .nav__tools { | |
| 214 | 删除: display: flex; | |
| 215 | 删除: align-items: center; | |
| 216 | 删除: gap: 0.5rem; | |
| 217 | 删除: } | |
| 218 | 删除: | |
| 219 | 删除: .nav__langs { | |
| 220 | 删除: display: inline-flex; | |
| 221 | 删除: align-items: center; | |
| 222 | 删除: border: 1px solid var(--line); | |
| 223 | 删除: border-radius: var(--radius); | |
| 224 | 删除: overflow: hidden; | |
| 225 | 删除: } | |
| 226 | 删除: | |
| 227 | 删除: .nav__lang { | |
| 228 | 删除: padding: 0.3rem 0.5rem; | |
| 229 | 删除: font-family: var(--font-mono); | |
| 230 | 删除: font-size: 0.7rem; | |
| 231 | 删除: font-weight: 500; | |
| 232 | 删除: letter-spacing: 0.06em; | |
| 233 | 删除: color: var(--ink-3); | |
| 234 | 删除: text-decoration: none; | |
| 235 | 删除: background: transparent; | |
| 236 | 删除: } | |
| 237 | 删除: | |
| 238 | 删除: .nav__lang:hover { | |
| 239 | 删除: color: var(--ink); | |
| 240 | 删除: background: var(--surface-2); | |
| 241 | 删除: } | |
| 242 | 删除: | |
| 243 | 删除: .nav__lang--current { | |
| 244 | 删除: background: var(--ink); | |
| 245 | 删除: color: var(--paper); | |
| 246 | 删除: } | |
| 247 | 删除: | |
| 248 | 删除: .nav__lang--current:hover { | |
| 249 | 删除: background: var(--ink); | |
| 250 | 删除: color: var(--paper); | |
| 251 | 删除: } | |
| 252 | 删除: | |
| 253 | 删除: .nav__icon { | |
| 254 | 删除: display: inline-flex; | |
| 255 | 删除: align-items: center; | |
| 256 | 删除: justify-content: center; | |
| 257 | 删除: width: 2rem; | |
| 258 | 删除: height: 2rem; | |
| 259 | 删除: padding: 0; | |
| 260 | 删除: border: 1px solid var(--line); | |
| 261 | 删除: border-radius: var(--radius); | |
| 262 | 删除: background: transparent; | |
| 263 | 删除: color: var(--ink-2); | |
| 264 | 删除: cursor: pointer; | |
| 265 | 删除: } | |
| 266 | 删除: | |
| 267 | 删除: .nav__icon:hover { | |
| 268 | 删除: color: var(--ink); | |
| 269 | 删除: background: var(--surface-2); | |
| 270 | 删除: } | |
| 271 | 删除: | |
| 272 | 删除: .nav__icon svg { | |
| 273 | 删除: width: 1.05rem; | |
| 274 | 删除: height: 1.05rem; | |
| 275 | 删除: } | |
| 276 | 删除: | |
| 277 | 删除: .nav__gh { | |
| 278 | 删除: fill: currentColor; | |
| 279 | 删除: stroke: none; | |
| 280 | 删除: } | |
| 281 | 删除: | |
| 282 | 删除: @media (max-width: 62rem) { | |
| 283 | 删除: .nav__burger { | |
| 284 | 删除: display: inline-flex; | |
| 285 | 删除: } | |
| 286 | 删除: | |
| 287 | 删除: .nav__panel { | |
| 288 | 删除: display: none; | |
| 289 | 删除: position: absolute; | |
| 290 | 删除: left: 0; | |
| 291 | 删除: right: 0; | |
| 292 | 删除: top: 100%; | |
| 293 | 删除: flex-direction: column; | |
| 294 | 删除: align-items: stretch; | |
| 295 | 删除: gap: 0.25rem; | |
| 296 | 删除: padding: 1rem var(--gutter) 1.25rem; | |
| 297 | 删除: background: var(--paper); | |
| 298 | 删除: border-bottom: 1px solid var(--line); | |
| 299 | 删除: } | |
| 300 | 删除: | |
| 301 | 删除: .nav__panel[data-open] { | |
| 302 | 删除: display: flex; | |
| 303 | 删除: } | |
| 304 | 删除: | |
| 305 | 删除: .nav__links { | |
| 306 | 删除: flex-direction: column; | |
| 307 | 删除: align-items: stretch; | |
| 308 | 删除: gap: 0; | |
| 309 | 删除: } | |
| 310 | 删除: | |
| 311 | 删除: .nav__link { | |
| 312 | 删除: padding-block: 0.7rem; | |
| 313 | 删除: border-bottom: 1px solid var(--line); | |
| 314 | 删除: font-size: 1rem; | |
| 315 | 删除: } | |
| 316 | 删除: | |
| 317 | 删除: .nav__link[data-current]::after { | |
| 318 | 删除: display: none; | |
| 319 | 删除: } | |
| 320 | 删除: | |
| 321 | 删除: .nav__tools { | |
| 322 | 删除: padding-top: 0.9rem; | |
| 323 | 删除: } | |
| 324 | 删除: } | |
| 325 | 删除:</style> | |
| @@ -1,251 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import CodeBlock from './CodeBlock.astro'; | |
| 3 | 删除:import DocGroups from './DocGroups.astro'; | |
| 4 | 删除:import { inline } from '../lib/inline'; | |
| 5 | 删除:import Heading from './Heading.astro'; | |
| 6 | 删除:import { slug } from '../lib/slug'; | |
| 7 | 删除:import { en } from '../i18n/en'; | |
| 8 | 删除:import { t, type Locale } from '../i18n'; | |
| 9 | 删除: | |
| 10 | 删除:interface Props { | |
| 11 | 删除: locale: Locale; | |
| 12 | 删除:} | |
| 13 | 删除: | |
| 14 | 删除:const { locale } = Astro.props; | |
| 15 | 删除:const d = t(locale).reference; | |
| 16 | 删除:--- | |
| 17 | 删除: | |
| 18 | 删除:<section class="section" id="reference"> | |
| 19 | 删除: <div class="container"> | |
| 20 | 删除: <div class="section-head"> | |
| 21 | 删除: <p class="eyebrow">{d.eyebrow}</p> | |
| 22 | 删除: <Heading as="h2" id="reference" own={false} locale={locale}>{d.title}</Heading> | |
| 23 | 删除: <p class="lede" set:html={inline(d.lede)} /> | |
| 24 | 删除: </div> | |
| 25 | 删除: | |
| 26 | 删除: <div class="ref__groups"> | |
| 27 | 删除: { | |
| 28 | 删除: d.commandGroups.map((group) => ( | |
| 29 | 删除: <div class="ref__group"> | |
| 30 | 删除: <h3 class="ref__group-title">{group.title}</h3> | |
| 31 | 删除: <div class="table-wrap"> | |
| 32 | 删除: <table class="ref__commands"> | |
| 33 | 删除: <tbody> | |
| 34 | 删除: {group.rows.map(([command, description]) => ( | |
| 35 | 删除: <tr> | |
| 36 | 删除: <th scope="row">{command}</th> | |
| 37 | 删除: <td set:html={inline(description ?? '')} /> | |
| 38 | 删除: </tr> | |
| 39 | 删除: ))} | |
| 40 | 删除: </tbody> | |
| 41 | 删除: </table> | |
| 42 | 删除: </div> | |
| 43 | 删除: </div> | |
| 44 | 删除: )) | |
| 45 | 删除: } | |
| 46 | 删除: </div> | |
| 47 | 删除: | |
| 48 | 删除: <div class="ref__block"> | |
| 49 | 删除: <Heading as="h3" id={slug(en.reference.optionsTitle)} locale={locale} class="ref__sub">{d.optionsTitle}</Heading> | |
| 50 | 删除: <p class="prose ref__note" set:html={inline(d.optionsNote)} /> | |
| 51 | 删除: <div class="table-wrap"> | |
| 52 | 删除: <table class="table--code table--grid"> | |
| 53 | 删除: <thead> | |
| 54 | 删除: <tr>{d.optionsHeaders.map((header) => <th scope="col">{header}</th>)}</tr> | |
| 55 | 删除: </thead> | |
| 56 | 删除: <tbody> | |
| 57 | 删除: { | |
| 58 | 删除: d.options.map(([flag, description, fallback]) => ( | |
| 59 | 删除: <tr> | |
| 60 | 删除: <td>{flag}</td> | |
| 61 | 删除: <td set:html={inline(description ?? '')} /> | |
| 62 | 删除: <td class="ref__default">{fallback}</td> | |
| 63 | 删除: </tr> | |
| 64 | 删除: )) | |
| 65 | 删除: } | |
| 66 | 删除: </tbody> | |
| 67 | 删除: </table> | |
| 68 | 删除: </div> | |
| 69 | 删除: </div> | |
| 70 | 删除: | |
| 71 | 删除: <div class="ref__block"> | |
| 72 | 删除: <Heading as="h3" id={slug(en.reference.envTitle)} locale={locale} class="ref__sub">{d.envTitle}</Heading> | |
| 73 | 删除: <p class="prose ref__note" set:html={inline(d.envNote)} /> | |
| 74 | 删除: <div class="table-wrap"> | |
| 75 | 删除: <table class="table--code table--grid"> | |
| 76 | 删除: <thead> | |
| 77 | 删除: <tr>{d.envHeaders.map((header) => <th scope="col">{header}</th>)}</tr> | |
| 78 | 删除: </thead> | |
| 79 | 删除: <tbody> | |
| 80 | 删除: { | |
| 81 | 删除: d.env.map(([name, description, fallback]) => ( | |
| 82 | 删除: <tr> | |
| 83 | 删除: <td>{name}</td> | |
| 84 | 删除: <td set:html={inline(description ?? '')} /> | |
| 85 | 删除: <td class="ref__default">{fallback}</td> | |
| 86 | 删除: </tr> | |
| 87 | 删除: )) | |
| 88 | 删除: } | |
| 89 | 删除: </tbody> | |
| 90 | 删除: </table> | |
| 91 | 删除: </div> | |
| 92 | 删除: </div> | |
| 93 | 删除: | |
| 94 | 删除: <div class="ref__block ref__split"> | |
| 95 | 删除: <div class="ref__col"> | |
| 96 | 删除: <Heading as="h3" id={slug(en.reference.customTitle)} locale={locale} class="ref__sub">{d.customTitle}</Heading> | |
| 97 | 删除: <p class="prose ref__note" set:html={inline(d.customLede)} /> | |
| 98 | 删除: <div class="table-wrap"> | |
| 99 | 删除: <table class="table--code ref__files"> | |
| 100 | 删除: <thead> | |
| 101 | 删除: <tr>{d.customTable.headers.map((header) => <th scope="col">{header}</th>)}</tr> | |
| 102 | 删除: </thead> | |
| 103 | 删除: <tbody> | |
| 104 | 删除: { | |
| 105 | 删除: d.customTable.rows.map((row) => ( | |
| 106 | 删除: <tr> | |
| 107 | 删除: {row.map((cell, index) => | |
| 108 | 删除: index === 0 ? ( | |
| 109 | 删除: <th scope="row"> | |
| 110 | 删除: <code>{cell}</code> | |
| 111 | 删除: </th> | |
| 112 | 删除: ) : ( | |
| 113 | 删除: <td>{cell}</td> | |
| 114 | 删除: ), | |
| 115 | 删除: )} | |
| 116 | 删除: </tr> | |
| 117 | 删除: )) | |
| 118 | 删除: } | |
| 119 | 删除: </tbody> | |
| 120 | 删除: </table> | |
| 121 | 删除: </div> | |
| 122 | 删除: | |
| 123 | 删除: <Heading as="h4" id={slug(en.reference.volumesTitle)} locale={locale} class="ref__sub">{d.volumesTitle}</Heading> | |
| 124 | 删除: <p class="prose ref__note" set:html={inline(d.volumesBody)} /> | |
| 125 | 删除: <CodeBlock locale={locale} code={d.volumesCode} /> | |
| 126 | 删除: <p class="prose ref__note" set:html={inline(d.volumesNote)} /> | |
| 127 | 删除: </div> | |
| 128 | 删除: | |
| 129 | 删除: <div class="ref__col"> | |
| 130 | 删除: <Heading as="h3" id="node" locale={locale} class="ref__sub">{d.nodeTitle}</Heading> | |
| 131 | 删除: <p class="prose ref__note" set:html={inline(d.nodeBody)} /> | |
| 132 | 删除: <CodeBlock locale={locale} code={d.nodeCode} /> | |
| 133 | 删除: <p class="prose ref__note" set:html={inline(d.nodeNote)} /> | |
| 134 | 删除: </div> | |
| 135 | 删除: </div> | |
| 136 | 删除: | |
| 137 | 删除: <div class="ref__block ref__split"> | |
| 138 | 删除: <div class="ref__col"> | |
| 139 | 删除: <Heading as="h3" id={slug(en.reference.scriptsTitle)} locale={locale} class="ref__sub">{d.scriptsTitle}</Heading> | |
| 140 | 删除: {d.scriptsParas.map((para) => <p class="prose ref__note" set:html={inline(para)} />)} | |
| 141 | 删除: </div> | |
| 142 | 删除: <div class="ref__col"> | |
| 143 | 删除: <CodeBlock locale={locale} code={d.scriptsCode} /> | |
| 144 | 删除: </div> | |
| 145 | 删除: </div> | |
| 146 | 删除: | |
| 147 | 删除: <DocGroups locale={locale} groups={d.groups} source={en.reference.groups} /> | |
| 148 | 删除: </div> | |
| 149 | 删除:</section> | |
| 150 | 删除: | |
| 151 | 删除:<style> | |
| 152 | 删除: .ref__groups { | |
| 153 | 删除: display: grid; | |
| 154 | 删除: grid-template-columns: repeat(auto-fit, minmax(min(100%, 24rem), 1fr)); | |
| 155 | 删除: gap: clamp(1.5rem, 3vw, 2.5rem); | |
| 156 | 删除: align-items: start; | |
| 157 | 删除: } | |
| 158 | 删除: | |
| 159 | 删除: .ref__group { | |
| 160 | 删除: display: grid; | |
| 161 | 删除: align-content: start; | |
| 162 | 删除: min-width: 0; | |
| 163 | 删除: } | |
| 164 | 删除: | |
| 165 | 删除: .ref__group-title { | |
| 166 | 删除: margin-bottom: 0.75rem; | |
| 167 | 删除: font-family: var(--font-mono); | |
| 168 | 删除: font-size: 0.72rem; | |
| 169 | 删除: font-weight: 500; | |
| 170 | 删除: letter-spacing: 0.12em; | |
| 171 | 删除: text-transform: uppercase; | |
| 172 | 删除: color: var(--ink-3); | |
| 173 | 删除: } | |
| 174 | 删除: | |
| 175 | 删除: /* No thead on the command tables: the group title names the block, and a | |
| 176 | 删除: repeated "Command / What it does" row on five tables is noise. */ | |
| 177 | 删除: .ref__commands th[scope='row'] { | |
| 178 | 删除: padding: 0.72rem 1rem; | |
| 179 | 删除: border-bottom: 1px solid var(--line); | |
| 180 | 删除: text-align: left; | |
| 181 | 删除: vertical-align: top; | |
| 182 | 删除: font-family: var(--font-mono); | |
| 183 | 删除: font-size: 0.83rem; | |
| 184 | 删除: font-weight: 450; | |
| 185 | 删除: white-space: nowrap; | |
| 186 | 删除: color: var(--accent); | |
| 187 | 删除: } | |
| 188 | 删除: | |
| 189 | 删除: .ref__commands tbody tr:last-child th[scope='row'] { | |
| 190 | 删除: border-bottom: 0; | |
| 191 | 删除: } | |
| 192 | 删除: | |
| 193 | 删除: .ref__block { | |
| 194 | 删除: display: grid; | |
| 195 | 删除: gap: 1rem; | |
| 196 | 删除: align-content: start; | |
| 197 | 删除: min-width: 0; | |
| 198 | 删除: margin-top: clamp(2.5rem, 5vw, 4rem); | |
| 199 | 删除: } | |
| 200 | 删除: | |
| 201 | 删除: .ref__split { | |
| 202 | 删除: grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); | |
| 203 | 删除: gap: clamp(1.75rem, 4vw, 3.25rem); | |
| 204 | 删除: align-items: start; | |
| 205 | 删除: } | |
| 206 | 删除: | |
| 207 | 删除: .ref__col { | |
| 208 | 删除: display: grid; | |
| 209 | 删除: gap: 1rem; | |
| 210 | 删除: min-width: 0; | |
| 211 | 删除: } | |
| 212 | 删除: | |
| 213 | 删除: .ref__sub { | |
| 214 | 删除: font-size: 1.05rem; | |
| 215 | 删除: } | |
| 216 | 删除: | |
| 217 | 删除: .ref__note { | |
| 218 | 删除: font-size: 0.9rem; | |
| 219 | 删除: } | |
| 220 | 删除: | |
| 221 | 删除: .ref__files th[scope='row'] { | |
| 222 | 删除: padding: 0.72rem 1rem; | |
| 223 | 删除: border-bottom: 1px solid var(--line); | |
| 224 | 删除: text-align: left; | |
| 225 | 删除: font-weight: 500; | |
| 226 | 删除: vertical-align: top; | |
| 227 | 删除: } | |
| 228 | 删除: | |
| 229 | 删除: .ref__files tbody tr:last-child th[scope='row'] { | |
| 230 | 删除: border-bottom: 0; | |
| 231 | 删除: } | |
| 232 | 删除: | |
| 233 | 删除: .ref__files th[scope='row'] code { | |
| 234 | 删除: font-size: 0.8rem; | |
| 235 | 删除: color: var(--accent); | |
| 236 | 删除: white-space: nowrap; | |
| 237 | 删除: } | |
| 238 | 删除: | |
| 239 | 删除: .ref__default { | |
| 240 | 删除: font-family: var(--font-mono); | |
| 241 | 删除: font-size: 0.78rem; | |
| 242 | 删除: color: var(--ink-3); | |
| 243 | 删除: white-space: nowrap; | |
| 244 | 删除: } | |
| 245 | 删除: | |
| 246 | 删除: @media (max-width: 62rem) { | |
| 247 | 删除: .ref__split { | |
| 248 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 249 | 删除: } | |
| 250 | 删除: } | |
| 251 | 删除:</style> | |
| @@ -1,133 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import { inline } from '../lib/inline'; | |
| 3 | 删除:import Heading from './Heading.astro'; | |
| 4 | 删除:import { t, type Locale } from '../i18n'; | |
| 5 | 删除: | |
| 6 | 删除:interface Props { | |
| 7 | 删除: locale: Locale; | |
| 8 | 删除:} | |
| 9 | 删除: | |
| 10 | 删除:const { locale } = Astro.props; | |
| 11 | 删除:const d = t(locale); | |
| 12 | 删除:--- | |
| 13 | 删除: | |
| 14 | 删除:<section class="section threat" id="why"> | |
| 15 | 删除: <div class="container threat__inner"> | |
| 16 | 删除: <div class="threat__head"> | |
| 17 | 删除: <p class="eyebrow">{d.threat.eyebrow}</p> | |
| 18 | 删除: <Heading as="h2" id="why" own={false} locale={locale} class="threat__title">{d.threat.title}</Heading> | |
| 19 | 删除: <p class="lede threat__lede" set:html={inline(d.threat.lede)} /> | |
| 20 | 删除: </div> | |
| 21 | 删除: | |
| 22 | 删除: <div class="threat__body"> | |
| 23 | 删除: <ol class="threat__reasons"> | |
| 24 | 删除: { | |
| 25 | 删除: d.threat.reasons.map((reason, index) => ( | |
| 26 | 删除: <li class="threat__reason"> | |
| 27 | 删除: <span class="threat__reason-n" aria-hidden="true"> | |
| 28 | 删除: {String(index + 1).padStart(2, '0')} | |
| 29 | 删除: </span> | |
| 30 | 删除: <div class="threat__reason-text"> | |
| 31 | 删除: <h3 class="threat__reason-title">{reason.title}</h3> | |
| 32 | 删除: <p class="prose threat__p" set:html={inline(reason.body)} /> | |
| 33 | 删除: </div> | |
| 34 | 删除: </li> | |
| 35 | 删除: )) | |
| 36 | 删除: } | |
| 37 | 删除: </ol> | |
| 38 | 删除: | |
| 39 | 删除: <div class="note note--accent threat__note"> | |
| 40 | 删除: <p class="prose" set:html={inline(d.threat.closing)} /> | |
| 41 | 删除: </div> | |
| 42 | 删除: </div> | |
| 43 | 删除: </div> | |
| 44 | 删除:</section> | |
| 45 | 删除: | |
| 46 | 删除:<style> | |
| 47 | 删除: .threat { | |
| 48 | 删除: background: var(--paper-sunk); | |
| 49 | 删除: } | |
| 50 | 删除: | |
| 51 | 删除: .threat__inner { | |
| 52 | 删除: display: grid; | |
| 53 | 删除: grid-template-columns: minmax(0, 0.8fr) minmax(0, 1.2fr); | |
| 54 | 删除: gap: clamp(2rem, 5vw, 4.5rem); | |
| 55 | 删除: align-items: start; | |
| 56 | 删除: } | |
| 57 | 删除: | |
| 58 | 删除: .threat__head { | |
| 59 | 删除: position: sticky; | |
| 60 | 删除: top: calc(var(--nav-h) + 2.5rem); | |
| 61 | 删除: display: grid; | |
| 62 | 删除: gap: 1.15rem; | |
| 63 | 删除: } | |
| 64 | 删除: | |
| 65 | 删除: .threat__title { | |
| 66 | 删除: font-size: clamp(1.8rem, 3.2vw, 2.6rem); | |
| 67 | 删除: } | |
| 68 | 删除: | |
| 69 | 删除: .threat__lede { | |
| 70 | 删除: font-size: 1rem; | |
| 71 | 删除: } | |
| 72 | 删除: | |
| 73 | 删除: .threat__body { | |
| 74 | 删除: display: grid; | |
| 75 | 删除: gap: 1.75rem; | |
| 76 | 删除: max-width: 44rem; | |
| 77 | 删除: } | |
| 78 | 删除: | |
| 79 | 删除: .threat__reasons { | |
| 80 | 删除: display: grid; | |
| 81 | 删除: gap: 1.75rem; | |
| 82 | 删除: list-style: none; | |
| 83 | 删除: } | |
| 84 | 删除: | |
| 85 | 删除: .threat__reason { | |
| 86 | 删除: display: flex; | |
| 87 | 删除: gap: 1rem; | |
| 88 | 删除: align-items: start; | |
| 89 | 删除: } | |
| 90 | 删除: | |
| 91 | 删除: .threat__reason-n { | |
| 92 | 删除: flex: none; | |
| 93 | 删除: width: 2.1rem; | |
| 94 | 删除: height: 2.1rem; | |
| 95 | 删除: display: grid; | |
| 96 | 删除: place-items: center; | |
| 97 | 删除: border: 1px solid var(--line-strong); | |
| 98 | 删除: border-radius: 50%; | |
| 99 | 删除: font-family: var(--font-mono); | |
| 100 | 删除: font-size: 0.74rem; | |
| 101 | 删除: color: var(--danger); | |
| 102 | 删除: background: var(--surface); | |
| 103 | 删除: } | |
| 104 | 删除: | |
| 105 | 删除: .threat__reason-text { | |
| 106 | 删除: min-width: 0; | |
| 107 | 删除: } | |
| 108 | 删除: | |
| 109 | 删除: .threat__reason-title { | |
| 110 | 删除: font-size: 1.02rem; | |
| 111 | 删除: margin-bottom: 0.4rem; | |
| 112 | 删除: } | |
| 113 | 删除: | |
| 114 | 删除: .threat__p { | |
| 115 | 删除: font-size: 0.97rem; | |
| 116 | 删除: line-height: 1.7; | |
| 117 | 删除: } | |
| 118 | 删除: | |
| 119 | 删除: .threat__note .prose { | |
| 120 | 删除: font-size: 0.97rem; | |
| 121 | 删除: line-height: 1.7; | |
| 122 | 删除: } | |
| 123 | 删除: | |
| 124 | 删除: @media (max-width: 62rem) { | |
| 125 | 删除: .threat__inner { | |
| 126 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 127 | 删除: } | |
| 128 | 删除: | |
| 129 | 删除: .threat__head { | |
| 130 | 删除: position: static; | |
| 131 | 删除: } | |
| 132 | 删除: } | |
| 133 | 删除:</style> | |
| @@ -1,125 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import CodeBlock from './CodeBlock.astro'; | |
| 3 | 删除:import { inline } from '../lib/inline'; | |
| 4 | 删除:import Heading from './Heading.astro'; | |
| 5 | 删除:import { slug } from '../lib/slug'; | |
| 6 | 删除:import { en } from '../i18n/en'; | |
| 7 | 删除:import { t, type Locale } from '../i18n'; | |
| 8 | 删除: | |
| 9 | 删除:interface Props { | |
| 10 | 删除: locale: Locale; | |
| 11 | 删除:} | |
| 12 | 删除: | |
| 13 | 删除:const { locale } = Astro.props; | |
| 14 | 删除:const d = t(locale); | |
| 15 | 删除:--- | |
| 16 | 删除: | |
| 17 | 删除:<section class="section" id="usage"> | |
| 18 | 删除: <div class="container"> | |
| 19 | 删除: <div class="section-head"> | |
| 20 | 删除: <p class="eyebrow">{d.usage.eyebrow}</p> | |
| 21 | 删除: <Heading as="h2" id="usage" own={false} locale={locale}>{d.usage.title}</Heading> | |
| 22 | 删除: <p class="lede" set:html={inline(d.usage.lede)} /> | |
| 23 | 删除: </div> | |
| 24 | 删除: | |
| 25 | 删除: <div class="usage__cards"> | |
| 26 | 删除: { | |
| 27 | 删除: d.usage.cards.map((card, index) => ( | |
| 28 | 删除: <article class="usage__card"> | |
| 29 | 删除: <Heading as="h3" id={slug(en.usage.cards[index]!.title)} locale={locale} class="usage__card-title">{card.title}</Heading> | |
| 30 | 删除: <p class="prose usage__card-body" set:html={inline(card.body)} /> | |
| 31 | 删除: <CodeBlock locale={locale} code={card.code} class="usage__card-code" /> | |
| 32 | 删除: </article> | |
| 33 | 删除: )) | |
| 34 | 删除: } | |
| 35 | 删除: </div> | |
| 36 | 删除: | |
| 37 | 删除: <div class="usage__split"> | |
| 38 | 删除: <div class="usage__git"> | |
| 39 | 删除: <Heading as="h3" id={slug(en.usage.gitTitle)} locale={locale} class="usage__sub">{d.usage.gitTitle}</Heading> | |
| 40 | 删除: <p class="prose usage__sub-body" set:html={inline(d.usage.gitBody)} /> | |
| 41 | 删除: <CodeBlock locale={locale} code={d.usage.gitCode} /> | |
| 42 | 删除: </div> | |
| 43 | 删除: | |
| 44 | 删除: <div class="usage__git"> | |
| 45 | 删除: <p class="prose usage__note" set:html={inline(d.usage.gitNote)} /> | |
| 46 | 删除: </div> | |
| 47 | 删除: </div> | |
| 48 | 删除: </div> | |
| 49 | 删除:</section> | |
| 50 | 删除: | |
| 51 | 删除:<style> | |
| 52 | 删除: .usage__cards { | |
| 53 | 删除: display: grid; | |
| 54 | 删除: /* 28rem so two columns fit the container: at three, the trailing `#` | |
| 55 | 删除: comments in the samples get clipped and need sideways scrolling. */ | |
| 56 | 删除: grid-template-columns: repeat(auto-fit, minmax(min(100%, 28rem), 1fr)); | |
| 57 | 删除: gap: 1px; | |
| 58 | 删除: background: var(--line); | |
| 59 | 删除: border: 1px solid var(--line); | |
| 60 | 删除: border-radius: var(--radius-lg); | |
| 61 | 删除: overflow: hidden; | |
| 62 | 删除: } | |
| 63 | 删除: | |
| 64 | 删除: .usage__card { | |
| 65 | 删除: display: grid; | |
| 66 | 删除: align-content: start; | |
| 67 | 删除: /* Without this a grid item keeps min-width:auto and a wide code block | |
| 68 | 删除: pushes the card past its track, over the neighbouring column. */ | |
| 69 | 删除: min-width: 0; | |
| 70 | 删除: gap: 0.85rem; | |
| 71 | 删除: padding: clamp(1.25rem, 2.4vw, 1.75rem); | |
| 72 | 删除: background: var(--surface); | |
| 73 | 删除: } | |
| 74 | 删除: | |
| 75 | 删除: .usage__card-title { | |
| 76 | 删除: font-size: 1.02rem; | |
| 77 | 删除: } | |
| 78 | 删除: | |
| 79 | 删除: .usage__card-body { | |
| 80 | 删除: font-size: 0.91rem; | |
| 81 | 删除: } | |
| 82 | 删除: | |
| 83 | 删除: .usage__card-code { | |
| 84 | 删除: margin-top: 0.15rem; | |
| 85 | 删除: } | |
| 86 | 删除: | |
| 87 | 删除: /* An odd card count would otherwise leave a hole in the last row. */ | |
| 88 | 删除: .usage__card:last-child:nth-child(odd) { | |
| 89 | 删除: grid-column: 1 / -1; | |
| 90 | 删除: } | |
| 91 | 删除: | |
| 92 | 删除: .usage__split { | |
| 93 | 删除: display: grid; | |
| 94 | 删除: grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); | |
| 95 | 删除: gap: clamp(1.75rem, 4vw, 3.25rem); | |
| 96 | 删除: margin-top: clamp(2.5rem, 5vw, 4rem); | |
| 97 | 删除: align-items: start; | |
| 98 | 删除: } | |
| 99 | 删除: | |
| 100 | 删除: .usage__git { | |
| 101 | 删除: display: grid; | |
| 102 | 删除: gap: 1rem; | |
| 103 | 删除: align-content: start; | |
| 104 | 删除: min-width: 0; | |
| 105 | 删除: } | |
| 106 | 删除: | |
| 107 | 删除: .usage__sub { | |
| 108 | 删除: font-size: 1.05rem; | |
| 109 | 删除: } | |
| 110 | 删除: | |
| 111 | 删除: .usage__sub-body { | |
| 112 | 删除: font-size: 0.93rem; | |
| 113 | 删除: margin-top: -0.35rem; | |
| 114 | 删除: } | |
| 115 | 删除: | |
| 116 | 删除: .usage__note { | |
| 117 | 删除: font-size: 0.88rem; | |
| 118 | 删除: } | |
| 119 | 删除: | |
| 120 | 删除: @media (max-width: 62rem) { | |
| 121 | 删除: .usage__split { | |
| 122 | 删除: grid-template-columns: minmax(0, 1fr); | |
| 123 | 删除: } | |
| 124 | 删除: } | |
| 125 | 删除:</style> | |
| @@ -0,0 +1,5 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "version": "0.1.0-alpha.1", | |
| 3 | 新增: "releaseURL": "https://github.com/Lee-xeo/Claude-Cage/releases/tag/v0.1.0-alpha.1", | |
| 4 | 新增: "downloadURL": "https://github.com/Lee-xeo/Claude-Cage/releases/download/v0.1.0-alpha.1/Cage-0.1.0-alpha.1-macos-arm64.dmg" | |
| 5 | 新增:} | |
| @@ -0,0 +1,72 @@ | ||
| 1 | 新增:import { languages, type CageLocale } from './languages'; | |
| 2 | 新增:export { languages, type CageLocale } from './languages'; | |
| 3 | 新增:export const locales = languages.map(language => language.code); | |
| 4 | 新增:const readmes = import.meta.glob<string>('../../../README*.md', { query: '?raw', import: 'default', eager: true }); | |
| 5 | 新增: | |
| 6 | 新增:function plain(text: string) { | |
| 7 | 新增: return text.replace(/<img\b[^>]*>/g, '').replace(/!\[[^\]]*\]\([^)]*\)/g, '') | |
| 8 | 新增: .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1').replace(/<[^>]+>/g, '') | |
| 9 | 新增: .replace(/\*\*|`/g, '').trim(); | |
| 10 | 新增:} | |
| 11 | 新增:function paragraphs(text: string) { | |
| 12 | 新增: return text.replace(/```[\s\S]*?```/g, '').split(/\n\s*\n/) | |
| 13 | 新增: .filter(block => !/^\s*(?:[-#|]|\d+\.)/.test(block)) | |
| 14 | 新增: .map(plain).filter(Boolean); | |
| 15 | 新增:} | |
| 16 | 新增:function bullets(text: string) { | |
| 17 | 新增: return [...text.matchAll(/^- (.+)$/gm)].map(match => match[1]); | |
| 18 | 新增:} | |
| 19 | 新增:function pair(text: string): [string, string] { | |
| 20 | 新增: const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/); | |
| 21 | 新增: return bold ? [plain(bold[1]), plain(bold[2])] : ['', plain(text)]; | |
| 22 | 新增:} | |
| 23 | 新增:function readCopy(language: typeof languages[number]) { | |
| 24 | 新增: const file = language.code === 'zh' ? 'README.md' : `README.${language.code}.md`; | |
| 25 | 新增: const source = readmes[`../../../${file}`]; | |
| 26 | 新增: if (!source) throw new Error(`Missing website language source: ${file}`); | |
| 27 | 新增: const headings = [...source.matchAll(/^## (.+)$/gm)]; | |
| 28 | 新增: if (headings.length !== 9) throw new Error(`${file}: expected the nine shared README sections; update the website mapping when the document structure changes`); | |
| 29 | 新增: const sections = headings.map((heading, i) => ({ | |
| 30 | 新增: title: heading[1], body: source.slice(heading.index! + heading[0].length, headings[i + 1]?.index ?? source.length), | |
| 31 | 新增: })); | |
| 32 | 新增: const [reason, uses, quick, installation, steps, boundaries, contribution, license] = sections; | |
| 33 | 新增: const reasonParagraphs = paragraphs(reason.body); | |
| 34 | 新增: const installParagraphs = paragraphs(installation.body); | |
| 35 | 新增: const captions = [...reason.body.matchAll(/^\*\*(.+?)\*\*\s*$/gm)].map(match => plain(match[1])); | |
| 36 | 新增: const stepHeadings = [...steps.body.matchAll(/^### \d+\. (.+)$/gm)]; | |
| 37 | 新增: if (stepHeadings.length !== 3 || bullets(reason.body).length !== 4 || bullets(boundaries.body).length !== 4) { | |
| 38 | 新增: throw new Error(`${file}: README feature, setup or boundary structure has changed`); | |
| 39 | 新增: } | |
| 40 | 新增: const setup = stepHeadings.map((heading, i): [string,string] => [heading[1], plain(steps.body.slice(heading.index! + heading[0].length, stepHeadings[i+1]?.index ?? steps.body.length))]); | |
| 41 | 新增: const docs = [...contribution.body.matchAll(/^\|\s*([^|]+)\s*\|\s*\[([^\]]+)\]\(([^)]+)\)\s*\|/gm)].map(match => ({ | |
| 42 | 新增: title: plain(match[1]), label: match[2], href: match[3].startsWith('https://') ? match[3] : `https://github.com/Lee-xeo/Claude-Cage/blob/main/${match[3]}`, | |
| 43 | 新增: })); | |
| 44 | 新增: const slogan = source.slice(0, headings[0].index).match(/^\*\*(.+?)\*\*$/m)?.[1] || 'Claude Cage'; | |
| 45 | 新增: const isChinese = language.code === 'zh' || language.code === 'zh-TW'; | |
| 46 | 新增: const limit = plain(bullets(boundaries.body).at(-1)!); | |
| 47 | 新增: return { | |
| 48 | 新增: ...language, title: `Claude Cage — ${plain(slogan)}`, description: reasonParagraphs[1], | |
| 49 | 新增: home: 'Claude Cage', start: quick.title, boundary: boundaries.title, | |
| 50 | 新增: hero: isChinese ? '把 Claude 大小姐' : 'Claude Cage', | |
| 51 | 新增: heroAccent: language.code === 'zh' ? '关起来。' : language.code === 'zh-TW' ? '關起來。' : '', | |
| 52 | 新增: tagline: isChinese ? plain(slogan).split(/[,,]/).slice(1).join(',') : plain(slogan), | |
| 53 | 新增: intro: reasonParagraphs[1], requirements: 'Apple Silicon · macOS 14+', artAlt: 'Claude Cage', | |
| 54 | 新增: why: reason.title, whyText: reasonParagraphs[0], whyNote: limit, | |
| 55 | 新增: keyFeatures: bullets(reason.body).map(plain), | |
| 56 | 新增: featureTitle: uses.title, features: bullets(uses.body).map(pair), | |
| 57 | 新增: workbench: `${captions[1] || 'Claude Cage'} · hello-cage`, | |
| 58 | 新增: evidenceTitle: captions[0] || language.checksLabel, evidenceNote: limit, | |
| 59 | 新增: quickTitle: quick.title, quickText: paragraphs(quick.body)[0], | |
| 60 | 新增: prompt: quick.body.match(/```[^\n]*\n([\s\S]*?)```/)?.[1]?.trim() || '', | |
| 61 | 新增: quickNote: paragraphs(quick.body).slice(1).join('\n'), | |
| 62 | 新增: stepsTitle: steps.title, steps: setup, | |
| 63 | 新增: boundaryTitle: boundaries.title, boundaries: bullets(boundaries.body).map(pair), | |
| 64 | 新增: downloadTitle: installation.title, downloadText: installParagraphs[1], | |
| 65 | 新增: downloadNote: installParagraphs[0], updateNote: installParagraphs.at(-1) || '', | |
| 66 | 新增: communityTitle: contribution.title, communityText: paragraphs(contribution.body).at(-1) || '', | |
| 67 | 新增: group: 'QQ · 1134250870', docsTitle: contribution.title, docs, | |
| 68 | 新增: licenseTitle: license.title, licenseText: paragraphs(license.body).slice(0,-1).join('\n\n'), | |
| 69 | 新增: independent: paragraphs(license.body).at(-1) || '', | |
| 70 | 新增: }; | |
| 71 | 新增:} | |
| 72 | 新增:export const cageCopy = Object.fromEntries(languages.map(language => [language.code, readCopy(language)])) as Record<CageLocale, ReturnType<typeof readCopy>>; | |
| @@ -1,848 +0,0 @@ | ||
| 1 | 删除:// English copy. `fr.ts` mirrors this shape exactly, typed against it, so a | |
| 2 | 删除:// missing or renamed key is a build error rather than a silent fallback. | |
| 3 | 删除:// | |
| 4 | 删除:// Shell commands are not translated: they are the same on every machine. | |
| 5 | 删除:// Only prose, labels and descriptions live here. | |
| 6 | 删除:// | |
| 7 | 删除:// House style: say what the thing does. No slogans, no absolutes the code | |
| 8 | 删除:// cannot back up ("cannot escape", "nothing leaves"), no sentence whose job | |
| 9 | 删除:// is to sound good. | |
| 10 | 删除: | |
| 11 | 删除:export const en = { | |
| 12 | 删除: meta: { | |
| 13 | 删除: lang: 'en', | |
| 14 | 删除: label: 'English', | |
| 15 | 删除: title: 'agent-vm | a disposable Linux VM per project for AI coding agents', | |
| 16 | 删除: description: | |
| 17 | 删除: 'agent-vm gives every project its own Linux VM and runs the coding agent there with permissions bypassed. Your SSH keys, your browser sessions, the rest of your disk and your local network are out of its reach. One binary, Lima built in. MIT.', | |
| 18 | 删除: skipToContent: 'Skip to content', | |
| 19 | 删除: }, | |
| 20 | 删除: | |
| 21 | 删除: nav: { | |
| 22 | 删除: sections: { | |
| 23 | 删除: install: 'Install', | |
| 24 | 删除: usage: 'Usage', | |
| 25 | 删除: reference: 'Reference', | |
| 26 | 删除: architecture: 'Architecture', | |
| 27 | 删除: security: 'Security', | |
| 28 | 删除: contribute: 'Contribute', | |
| 29 | 删除: credits: 'Credits', | |
| 30 | 删除: }, | |
| 31 | 删除: github: 'GitHub', | |
| 32 | 删除: menu: 'Menu', | |
| 33 | 删除: language: 'Language', | |
| 34 | 删除: }, | |
| 35 | 删除: | |
| 36 | 删除: hero: { | |
| 37 | 删除: title: 'Give agents a machine they can wreck.', | |
| 38 | 删除: titleAccent: 'Keep yours.', | |
| 39 | 删除: lede: | |
| 40 | 删除: 'agent-vm runs AI coding agents with full permissions in a Linux VM, per project. Your SSH keys, your browser sessions, the rest of your disk and your local network are out of their reach.', | |
| 41 | 删除: installLabel: 'Get started', | |
| 42 | 删除: ctaPrimary: 'Install it', | |
| 43 | 删除: ctaSecondary: 'How it works', | |
| 44 | 删除: meta: 'MIT licensed · macOS, Linux, Windows (experimental) · Lima built in', | |
| 45 | 删除: terminalCaption: | |
| 46 | 删除: 'Only the project directory is mounted.', | |
| 47 | 删除: points: [ | |
| 48 | 删除: { | |
| 49 | 删除: title: 'One binary, [Lima](https://lima-vm.io/) built in', | |
| 50 | 删除: body: 'No Lima to install, no Node, no npm, no Docker Desktop on your machine: the toolchain lives in the VM. On Linux, the VMs need QEMU and access to KVM.', | |
| 51 | 删除: }, | |
| 52 | 删除: { | |
| 53 | 删除: title: 'A separate kernel, not a namespace', | |
| 54 | 删除: body: 'On Linux, escaping a container puts you on the host. Escaping a VM means getting through the hypervisor first.', | |
| 55 | 删除: }, | |
| 56 | 删除: { | |
| 57 | 删除: title: 'Ports are forwarded for you', | |
| 58 | 删除: body: 'A dev server started in the VM answers on localhost at the same port, with a notification, and no flag or config. A port a program of yours already uses is left to it.', | |
| 59 | 删除: }, | |
| 60 | 删除: { | |
| 61 | 删除: title: 'Batteries included, root for the rest', | |
| 62 | 删除: body: 'The base VM ships dev tools, Docker, headless Chromium and the agents, picked in a setup wizard. The agent is root in its VM: it installs whatever else it needs.', | |
| 63 | 删除: }, | |
| 64 | 删除: ], | |
| 65 | 删除: }, | |
| 66 | 删除: | |
| 67 | 删除: threat: { | |
| 68 | 删除: eyebrow: 'Why this exists', | |
| 69 | 删除: title: 'Why not just run the agent on your machine?', | |
| 70 | 删除: lede: | |
| 71 | 删除: 'Every agent has a flag that turns approvals off, and many people run them that way. When that happens in your home directory, three things can go wrong.', | |
| 72 | 删除: reasons: [ | |
| 73 | 删除: { | |
| 74 | 删除: title: 'Dependency installs run arbitrary code', | |
| 75 | 删除: body: 'npm ran every package’s install scripts by default until npm 12 (July 2026), pip still runs a source package’s build, Cargo its `build.rs`, and your tests then run whatever got installed. In 2025 the Shai-Hulud worm spread through thousands of npm packages that way: it collected npm tokens, GitHub PATs, SSH keys and cloud credentials, then republished itself using them.', | |
| 76 | 删除: }, | |
| 77 | 删除: { | |
| 78 | 删除: title: 'Approval prompts stop working', | |
| 79 | 删除: body: 'The alternative is approving each command by hand. After the first few dozen prompts the answer is reflexive, and the one that mattered gets the same yes as the rest. That is why the bypass flag exists, and why it gets used.', | |
| 80 | 删除: }, | |
| 81 | 删除: { | |
| 82 | 删除: title: 'The agent is not reliable either', | |
| 83 | 删除: body: 'No compromised package needed. Agents read issues, web pages and READMEs, and anything they read can try to give them instructions. They also make plain mistakes: the wrong path, a `git checkout .` over uncommitted work.', | |
| 84 | 删除: }, | |
| 85 | 删除: ], | |
| 86 | 删除: closing: | |
| 87 | 删除: 'A VM limits what a mistake or a compromised agent can reach to the project, the internet, and what you hand it, such as [its env file](#share-secrets-across-vms). Your machine and your local network stay out of reach: see [Security](#security).', | |
| 88 | 删除: }, | |
| 89 | 删除: | |
| 90 | 删除: install: { | |
| 91 | 删除: eyebrow: 'Install', | |
| 92 | 删除: title: 'Install, build a template, run an agent.', | |
| 93 | 删除: lede: | |
| 94 | 删除: 'agent-vm is one binary, with Lima built in and no daemon: each running VM is served by an agent-vm process of its own.', | |
| 95 | 删除: prerequisitesTitle: 'Prerequisites', | |
| 96 | 删除: prerequisites: [ | |
| 97 | 删除: { name: 'macOS, Linux or Windows', note: 'Windows is experimental.', href: '' }, | |
| 98 | 删除: { | |
| 99 | 删除: name: 'QEMU, on Linux and Windows', | |
| 100 | 删除: note: 'macOS needs nothing more. On Linux, KVM too: `agent-vm setup` says what is missing and how to install it. On Windows, QEMU 7.2 or later and the Windows Hypervisor Platform feature.', | |
| 101 | 删除: href: '', | |
| 102 | 删除: }, | |
| 103 | 删除: { | |
| 104 | 删除: name: 'An agent subscription or API key', | |
| 105 | 删除: note: 'Authentication happens inside the VM, per VM.', | |
| 106 | 删除: href: '', | |
| 107 | 删除: }, | |
| 108 | 删除: ], | |
| 109 | 删除: methodsTitle: 'Install the command', | |
| 110 | 删除: methodsBody: 'Pick one. Each puts `agent-vm` on your `PATH`; only the Linux packages need root.', | |
| 111 | 删除: methodsLabel: 'Install method', | |
| 112 | 删除: methods: [ | |
| 113 | 删除: { | |
| 114 | 删除: id: 'curl', | |
| 115 | 删除: label: 'curl', | |
| 116 | 删除: code: 'curl -fsSL https://www.agent-vm.org/install.sh | sh', | |
| 117 | 删除: note: 'Downloads the latest release’s build for your machine from GitHub, checks it against the release’s `SHA256SUMS`, unpacks it in `~/.local/share/agent-vm` and links `agent-vm` into `~/.local/bin`. It then offers to run step 2 right away. Run it again to update. `sh -s -- --version X.Y.Z` installs a given release, `sh -s -- --git` a clone of `main`.', | |
| 118 | 删除: }, | |
| 119 | 删除: { | |
| 120 | 删除: id: 'brew', | |
| 121 | 删除: label: 'Homebrew', | |
| 122 | 删除: code: 'brew install sylvinus/tap/agent-vm', | |
| 123 | 删除: note: 'macOS, or Linux with Homebrew. `brew upgrade agent-vm` updates it.', | |
| 124 | 删除: }, | |
| 125 | 删除: { | |
| 126 | 删除: id: 'linux', | |
| 127 | 删除: label: 'Linux package', | |
| 128 | 删除: code: 'sudo apt install ./agent-vm_X.Y.Z_amd64.deb\nsudo dnf install ./agent-vm-X.Y.Z-1.x86_64.rpm', | |
| 129 | 删除: note: 'Download the `.deb` or `.rpm` of your architecture (`amd64`, `arm64`; `x86_64`, `aarch64`) from the GitHub releases. It installs `agent-vm` in `/usr/bin` and recommends QEMU and ssh. Not in a package repository yet: install the new file to update.', | |
| 130 | 删除: }, | |
| 131 | 删除: { | |
| 132 | 删除: id: 'nix', | |
| 133 | 删除: label: 'Nix', | |
| 134 | 删除: code: 'nix run github:sylvinus/agent-vm\nnix profile install github:sylvinus/agent-vm', | |
| 135 | 删除: note: 'Linux, NixOS included. QEMU comes with it; ssh is the system’s. `nix profile upgrade agent-vm` updates it.', | |
| 136 | 删除: }, | |
| 137 | 删除: { | |
| 138 | 删除: id: 'git', | |
| 139 | 删除: label: 'git', | |
| 140 | 删除: code: 'git clone https://github.com/sylvinus/agent-vm.git\ncd agent-vm && ./agent-vm.sh install', | |
| 141 | 删除: note: 'Builds it, with Go (and on macOS the Xcode command line tools), then `install` symlinks `agent-vm` onto your `PATH`. After a `git pull`, run `./agent-vm.sh install` again to rebuild. It then offers to run step 2 right away.', | |
| 142 | 删除: }, | |
| 143 | 删除: { | |
| 144 | 删除: id: 'windows', | |
| 145 | 删除: label: 'Windows', | |
| 146 | 删除: code: '# in Git Bash (experimental)\nwinget install SoftwareFreedom.QEMU\ncurl -fsSL https://www.agent-vm.org/install.sh | sh', | |
| 147 | 删除: note: 'Experimental. Without Git Bash, download `agent-vm-X.Y.Z-windows-amd64.tar.gz` (or `-arm64`) from the GitHub releases, unpack it with `tar -xzf`, and run `agent-vm.exe install` in PowerShell. VMs also need the Windows Hypervisor Platform feature, which an administrator turns on once: see [Windows and WSL](#windows-and-wsl).', | |
| 148 | 删除: }, | |
| 149 | 删除: ], | |
| 150 | 删除: steps: [ | |
| 151 | 删除: { | |
| 152 | 删除: title: 'Build the base template', | |
| 153 | 删除: body: 'Run once. A wizard picks what goes in the template: Enter takes the default set (see [What is in the VM](#what-is-in-the-vm)). It builds a Debian 13 VM with it and keeps it, stopped, as the template.', | |
| 154 | 删除: code: 'agent-vm setup', | |
| 155 | 删除: }, | |
| 156 | 删除: { | |
| 157 | 删除: title: 'Run an agent in your project', | |
| 158 | 删除: body: 'Clones the template into a VM for this directory, mounts the directory and launches the agent with permissions already granted. A start may first stop on a security question: see [Protecting .git](#git).', | |
| 159 | 删除: code: 'cd your-project\nagent-vm opencode # or: agent-vm claude', | |
| 160 | 删除: }, | |
| 161 | 删除: ], | |
| 162 | 删除: }, | |
| 163 | 删除: | |
| 164 | 删除: | |
| 165 | 删除: usage: { | |
| 166 | 删除: eyebrow: 'Usage', | |
| 167 | 删除: title: 'Everyday commands.', | |
| 168 | 删除: lede: | |
| 169 | 删除: 'Run them from your project directory. The [Reference](#reference) lists every command, option and file.', | |
| 170 | 删除: cards: [ | |
| 171 | 删除: { | |
| 172 | 删除: title: 'Run an agent', | |
| 173 | 删除: body: 'Extra arguments are forwarded to the agent as-is, so anything its own CLI accepts works here.', | |
| 174 | 删除: code: 'agent-vm opencode # OpenCode\nagent-vm claude # Claude Code\nagent-vm codex # Codex CLI\nagent-vm vibe # Mistral Vibe\nagent-vm pi # Pi\n\nagent-vm claude -p "fix all lint errors"\nagent-vm opencode run "update the changelog"', | |
| 175 | 删除: }, | |
| 176 | 删除: { | |
| 177 | 删除: title: 'Reach the dev server', | |
| 178 | 删除: body: 'Every port opened in the VM is forwarded to the same port on your localhost, so a dev server opens in your browser as usual, and a notification says so. A port a program of yours already listens on is not taken: the notification says that too. Ports 32768-60999, which the VM hands out to programs asking for any free port, are not forwarded. Treat the forwarded ports as the agent’s.', | |
| 179 | 删除: code: 'agent-vm run npm run dev # then open localhost:5173\nagent-vm run docker compose up', | |
| 180 | 删除: }, | |
| 181 | 删除: { | |
| 182 | 删除: title: 'Get inside', | |
| 183 | 删除: body: 'A shell to poke around, or a single command when you already know what you want.', | |
| 184 | 删除: code: 'agent-vm shell # zsh in the VM\nagent-vm run npm install # one-off command\nagent-vm run --tty opencode # allocate a PTY for TUIs\nagent-vm sh -c "ls -la | grep config"\nagent-vm code # VS Code in the browser, if set up', | |
| 185 | 删除: }, | |
| 186 | 删除: { | |
| 187 | 删除: title: 'Manage the fleet', | |
| 188 | 删除: body: 'The current directory’s VM is marked with `>` in `list`. If a directory is renamed, `list` is the only way to find its VM again.', | |
| 189 | 删除: code: 'agent-vm list # every VM, the current one marked\nagent-vm stop # stop, keep the disk\nagent-vm rm # stop and delete\nagent-vm destroy-all # every VM, base template included\nagent-vm doctor # what is wrong, and what to run', | |
| 190 | 删除: }, | |
| 191 | 删除: { | |
| 192 | 删除: title: 'Tighten the session', | |
| 193 | 删除: body: '`--readonly` makes every host share read-only, `rw` volumes included, and the host enforces it: root in the VM cannot lift it. Packages still install on the VM’s own disk, but nothing lands in the project. `--scratch` mounts nothing of yours: the agent clones the code with a token from `agent-vm env`, pushes its work, and the VM is deleted at exit.', | |
| 194 | 删除: code: 'agent-vm --readonly shell # nothing on the host writable\nagent-vm --scratch claude # nothing mounted, gone at exit\nagent-vm --rm run npm test # destroy the VM on exit', | |
| 195 | 删除: }, | |
| 196 | 删除: { | |
| 197 | 删除: title: 'Resize on the fly', | |
| 198 | 删除: body: 'A new VM gets the template’s 10 GB of disk, 3 GB of memory (4 with code-server picked in the wizard) and 1 CPU. Pass another value and the VM is reconfigured, after asking if it is running. Disk only grows. CPU and memory are capped at half the host, per VM.', | |
| 199 | 删除: code: 'agent-vm --disk 50 opencode\nagent-vm --memory 16 --cpus 8 shell\nagent-vm --reset claude # re-clone from the base template', | |
| 200 | 删除: }, | |
| 201 | 删除: { | |
| 202 | 删除: title: 'Share secrets across VMs', | |
| 203 | 删除: body: '`KEY=value` lines in `~/.agent-vm/env`, pushed into every VM on each command. Everything in the VM can read them: use narrow tokens you can revoke. Edit with `env set`, since one bad quote in the file breaks all of it.', | |
| 204 | 删除: code: 'agent-vm env set GH_TOKEN # pasted unseen, not in history\nagent-vm env list # names only, never values\nagent-vm env has ANTHROPIC_API_KEY\n\n# scoped to this project only\nagent-vm project-env set SOME_PATH ./config', | |
| 205 | 删除: }, | |
| 206 | 删除: { | |
| 207 | 删除: title: 'Edit with the VM’s tools', | |
| 208 | 删除: body: 'For language servers, linters, the debugger and the VM’s packages, run the editor in the VM: `agent-vm code` serves VS Code (code-server) to a browser tab, the only part on your machine. Set it up with `code-server` or a `code-*` name ([What is in the VM](#what-is-in-the-vm)). The tab can still open links, and every VM can send your browser to it, hence a password and a host name per VM ([Network and ports](#network-and-ports)). Do not connect a desktop editor over SSH instead ([SSH from your machine](#ssh-from-your-machine)).', | |
| 209 | 删除: code: 'agent-vm setup --preinstall=default,code-claude # once\nagent-vm code # prints the address and the password\n # Ctrl-C stops the editor', | |
| 210 | 删除: }, | |
| 211 | 删除: ], | |
| 212 | 删除: gitTitle: 'Letting the agent commit', | |
| 213 | 删除: gitBody: | |
| 214 | 删除: 'git reads its identity from the environment, so the shared env file covers it with no `git config` inside the VM. All four variables are needed: git refuses to commit without a committer, not just an author.', | |
| 215 | 删除: gitCode: | |
| 216 | 删除: '# ~/.agent-vm/env\nGIT_AUTHOR_NAME=Your Name\[email protected]\nGIT_COMMITTER_NAME=Your Name\[email protected]', | |
| 217 | 删除: gitNote: | |
| 218 | 删除: 'These variables win over `git config`, in every repository of the VM: for per-repository identities, set `user.name` and `user.email` from a runtime script instead. `gh` picks up `GH_TOKEN` on its own, so `gh pr create` works with nothing else. Plain `git push` over HTTPS needs a credential helper: one `gh auth setup-git` line in your [runtime script](#customisation-files).', | |
| 219 | 删除: }, | |
| 220 | 删除: | |
| 221 | 删除: reference: { | |
| 222 | 删除: eyebrow: 'Reference', | |
| 223 | 删除: title: 'Every command, option and file.', | |
| 224 | 删除: lede: 'What the sections above leave out: the full command set, the configuration files and variables, and what a script can rely on.', | |
| 225 | 删除: commandGroups: [ | |
| 226 | 删除: { | |
| 227 | 删除: title: 'Run an agent', | |
| 228 | 删除: rows: [ | |
| 229 | 删除: ['opencode [args]', 'Run OpenCode with `--auto`.'], | |
| 230 | 删除: ['claude [args]', 'Run Claude Code with `--dangerously-skip-permissions`.'], | |
| 231 | 删除: ['codex [args]', 'Run Codex CLI with `--dangerously-bypass-approvals-and-sandbox`.'], | |
| 232 | 删除: ['vibe [args]', 'Run Mistral Vibe with `--agent auto-approve`.'], | |
| 233 | 删除: ['pi [args]', 'Run Pi, which has no permission prompts.'], | |
| 234 | 删除: ], | |
| 235 | 删除: }, | |
| 236 | 删除: { | |
| 237 | 删除: title: 'Get inside', | |
| 238 | 删除: rows: [ | |
| 239 | 删除: ['shell, sh', 'Open a zsh shell in the VM. `-c "…"` runs a one-shot command through a login shell.'], | |
| 240 | 删除: ['run <cmd> [args]', 'Run a command with no shell. `--tty` allocates a PTY for TUIs.'], | |
| 241 | 删除: ['code', 'Serve VS Code (code-server) from the VM at `http://<vm-name>.localhost:<port>/`, until Ctrl-C, for you to open in your browser. Its password is made in the VM on first use and printed with the address. Needs `code-server` or a `code-*` name at setup ([What is in the VM](#what-is-in-the-vm)).'], | |
| 242 | 删除: ], | |
| 243 | 删除: }, | |
| 244 | 删除: { | |
| 245 | 删除: title: 'Manage the fleet', | |
| 246 | 删除: rows: [ | |
| 247 | 删除: ['list, status', 'List all agent-vm VMs, the current directory’s marked with `>`, with the agent-vm version that built the base each was cloned from, and when.'], | |
| 248 | 删除: ['stop [vm-name]', 'Stop this directory’s VM, or the named one. The disk survives.'], | |
| 249 | 删除: ['rm [vm-name]', 'Stop and delete. A name from `list` reaches a VM whose directory is gone.'], | |
| 250 | 删除: ['destroy-all', 'Stop and delete every agent-vm VM, the base template included. `setup` rebuilds it.'], | |
| 251 | 删除: ['doctor', 'Check the host, the base template, your settings files and this directory, and say what to run. Changes nothing.'], | |
| 252 | 删除: ], | |
| 253 | 删除: }, | |
| 254 | 删除: { | |
| 255 | 删除: title: 'Set up and configure', | |
| 256 | 删除: rows: [ | |
| 257 | 删除: ['install', 'Put `agent-vm` on your `PATH`: a link to the binary that runs it, in `~/.local/bin`. The curl installer runs it for you.'], | |
| 258 | 删除: ['uninstall', 'Remove that link. VMs and `~/.agent-vm` stay.'], | |
| 259 | 删除: ['setup', 'Build the base template. `--preinstall=LIST` skips the wizard ([What is in the VM](#what-is-in-the-vm)); `--disk`, `--memory` and `--cpus` size it.'], | |
| 260 | 删除: ['env <sub>', '`set`, `get`, `has`, `unset`, `list` on the secrets shared by every VM.'], | |
| 261 | 删除: ['project-env <sub>', 'Same subcommands, scoped to this project. Wins over the shared file.'], | |
| 262 | 删除: ['help', 'Show the built-in help.'], | |
| 263 | 删除: ], | |
| 264 | 删除: }, | |
| 265 | 删除: { | |
| 266 | 删除: title: 'Ask, from a script', | |
| 267 | 删除: rows: [ | |
| 268 | 删除: ['version', 'Print the version. `--min X.Y.Z` checks it instead of printing it.'], | |
| 269 | 删除: ['info [dir]', 'Machine-readable state, one `key=value` per line.'], | |
| 270 | 删除: ['name [dir]', 'Print the VM name for a directory. Defaults to the working directory.'], | |
| 271 | 删除: ], | |
| 272 | 删除: }, | |
| 273 | 删除: ], | |
| 274 | 删除: optionsTitle: 'VM options', | |
| 275 | 删除: optionsNote: 'For `claude`, `opencode`, `codex`, `vibe`, `pi`, `shell`, `run` and `code`, placed before the command or right after its name. Anything later belongs to the command: in `agent-vm run docker run --rm x`, `--rm` is docker’s.', | |
| 276 | 删除: optionsHeaders: ['Flag', 'What it does', 'Default'], | |
| 277 | 删除: options: [ | |
| 278 | 删除: ['--disk GB', 'VM disk size. Can grow, never shrink.', 'the template’s (10)'], | |
| 279 | 删除: ['--memory GB', 'VM memory. Clamped to half the host, per VM.', 'the template’s (3, or 4 with code-server picked in the wizard)'], | |
| 280 | 删除: ['--cpus N', 'CPU count. Clamped to half the host, per VM.', 'the template’s (1)'], | |
| 281 | 删除: ['--ssh-port N', 'Fixed host port for the VM’s SSH, for tools that save it. `0` goes back to a new one on each start. Restarts a running VM, asked first.', 'a new one per start'], | |
| 282 | 删除: ['--reset', 'Destroy and re-clone the VM from the base template.', 'off'], | |
| 283 | 删除: ['--readonly', 'Every host share read-only, project and volumes. Restarts a running VM, asked first.', 'off'], | |
| 284 | 删除: ['--unsafe-writable-git', 'Leave every `.git` writable so the agent can commit, with a warning. See [Protecting .git](#git).', 'off'], | |
| 285 | 删除: ['--unsafe-disable-security-prompts', 'Go on where a start would stop on a security question (see [Protecting .git](#git)). The warnings are still printed. Same as `AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1`.', 'off'], | |
| 286 | 删除: ['--rm', 'Destroy the VM once the command exits.', 'off'], | |
| 287 | 删除: ['--scratch', 'A new VM with nothing of yours mounted, deleted when the command ends (asked first on a terminal). `~/.agent-vm/env` and `runtime.sh` go in, the project’s files do not. Several can run at once.', 'off'], | |
| 288 | 删除: ], | |
| 289 | 删除: envTitle: 'Environment variables', | |
| 290 | 删除: envNote: 'Read from your shell, never from a file of the project.', | |
| 291 | 删除: envHeaders: ['Variable', 'What it does', 'Default'], | |
| 292 | 删除: env: [ | |
| 293 | 删除: ['AGENT_VM_STATE_DIR', 'Moves `~/.agent-vm`, VMs included, for tests, CI or a second install, without moving `HOME`.', '~/.agent-vm'], | |
| 294 | 删除: ['AGENT_VM_LIMA_HOME', 'Where the VMs live. Not your own Lima’s home: agent-vm keeps its VMs apart.', '~/.agent-vm/lima'], | |
| 295 | 删除: ['AGENT_VM_PROJECT_ENV', 'The project’s env file, relative to the project or absolute.', '.agent-vm.env'], | |
| 296 | 删除: ['AGENT_VM_PROJECT_RUNTIME', 'The project’s runtime script, relative to the project or absolute. Outside the project, the host reads it.', '.agent-vm.runtime.sh'], | |
| 297 | 删除: ['AGENT_VM_HOST_SHARE', 'CPU and memory per VM are capped at the host’s divided by this. `1`: the whole host.', '2'], | |
| 298 | 删除: ['AGENT_VM_BIN_DIR', 'Where `install` links `agent-vm`.', '~/.local/bin'], | |
| 299 | 删除: ['AGENT_VM_SSHFS_CACHE', '`1`: sshfs caches the writable shares too, faster on many files (`git status`, `find`); the VM may then see a file as it was up to 20 seconds before, and write that back. Applies when a VM is next started.', 'unset'], | |
| 300 | 删除: ['AGENT_VM_NOTIFY', '`0`: no desktop notification when a port is forwarded, or left to a program of yours.', 'unset'], | |
| 301 | 删除: ['AGENT_VM_GUARDED_WRITES', '`deny`: refuse the VM’s writes to [guarded files](#guarded-files) without asking, for a machine with no one at the screen.', 'unset'], | |
| 302 | 删除: ['AGENT_VM_UNSAFE_OPEN_NETWORK', '`1`: no [network isolation](#network-and-ports): the VMs reach your machine and your local networks. Applies when a VM is next started.', 'unset'], | |
| 303 | 删除: ['AGENT_VM_UNSAFE_WRITABLE_GIT', '`1`: same as `--unsafe-writable-git`.', 'unset'], | |
| 304 | 删除: ['AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS', '`1`: same as `--unsafe-disable-security-prompts`.', 'unset'], | |
| 305 | 删除: ], | |
| 306 | 删除: customTitle: 'Customisation files', | |
| 307 | 删除: customLede: | |
| 308 | 删除: 'Eight optional files, none of them needed to get started. The per-user ones sit in `~/.agent-vm/`, the per-project ones in the project itself.', | |
| 309 | 删除: customTable: { | |
| 310 | 删除: headers: ['File', 'Scope', 'Runs when'], | |
| 311 | 删除: rows: [ | |
| 312 | 删除: ['~/.agent-vm/env', 'All VMs', 'Pushed in on every invocation'], | |
| 313 | 删除: ['~/.agent-vm/volumes', 'All VMs, or the projects an entry names', 'Mounted at VM creation'], | |
| 314 | 删除: ['~/.agent-vm/network', 'All VMs: what they may reach ([Network and ports](#network-and-ports))', 'Read when a VM starts'], | |
| 315 | 删除: ['~/.agent-vm/guarded', 'All VMs: files to ask about ([Guarded files](#guarded-files))', 'Read when a VM starts'], | |
| 316 | 删除: ['~/.agent-vm/setup.sh', 'Base template', 'Once, during agent-vm setup'], | |
| 317 | 删除: ['~/.agent-vm/runtime.sh', 'All VMs', 'Every command that enters a VM, first'], | |
| 318 | 删除: ['.agent-vm.runtime.sh', 'Single project', 'Every command that enters its VM, after the global one'], | |
| 319 | 删除: ['.agent-vm.env', 'Single project', 'Pushed in after the shared env, so it wins'], | |
| 320 | 删除: ], | |
| 321 | 删除: }, | |
| 322 | 删除: volumesTitle: 'Extra mounts: ~/.agent-vm/volumes', | |
| 323 | 删除: volumesBody: | |
| 324 | 删除: 'One `source[:destination][:mode][:project]` per line, `~` expanded on the left, `#` for comments. The mode is `ro` (default) or `rw`, and `rw` only works for directories. Without a destination, the path is mounted at the same place in the VM; a relative one is inside the project. The fourth field limits the entry to the projects it matches, `*` matching anything.', | |
| 325 | 删除: volumesCode: | |
| 326 | 删除: '# ~/.agent-vm/volumes\n~/.gitconfig # same path, read-only\n~/.cache/shared:/home/you.guest/.cache/shared:rw\n\n# only in ~/work/webapp, as its .claude, read-only\n~/.claude-vm/webapp:.claude:ro:~/work/webapp\n\n# every project under ~/work\n~/.cache/pip:/home/you.guest/.cache/pip:rw:~/work/*\n\n# same path, one project only\n~/datasets::ro:~/work/ml', | |
| 327 | 删除: volumesNote: | |
| 328 | 删除: 'The list lives on your side, not in the project: the agent writes the project, and could otherwise mount any host folder into its VM. A relative destination that leaves the project, through `..` or a symlink, is skipped. Changes apply to new VMs: `--reset` re-applies them.', | |
| 329 | 删除: nodeTitle: 'Node.js: node_modules in the VM', | |
| 330 | 删除: nodeBody: | |
| 331 | 删除: 'Hundreds of thousands of files are slow across the share, and native packages differ between macOS and Linux anyway. Mount a folder of the VM’s own disk over `node_modules` from the project’s [runtime script](#customisation-files), which runs on every command:', | |
| 332 | 删除: nodeCode: | |
| 333 | 删除: '#!/bin/bash\n# .agent-vm.runtime.sh\nset -e\nmkdir -p "$HOME/node_modules" node_modules\nmountpoint -q node_modules ||\n sudo mount --bind "$HOME/node_modules" node_modules', | |
| 334 | 删除: nodeNote: 'The host sees an empty `node_modules`, or keeps its own: install there too if your editor needs the packages. In a workspace, repeat the mount for a package with a large `node_modules` of its own. A dev server in the VM may need polling to see edits made on the host (Vite: `server.watch.usePolling`).', | |
| 335 | 删除: scriptsTitle: 'From a script', | |
| 336 | 删除: scriptsParas: [ | |
| 337 | 删除: 'Use these commands rather than parsing human-facing output or reading `~/.agent-vm`: VM names and state files are implementation details. None of them starts a VM.', | |
| 338 | 删除: '`version --min` exits `0` when recent enough, `1` when older, `2` on a malformed call; an engine predating `--min` ignores it and exits `0`. In `info`, booleans are `1` or `0`, `unknown` when undeterminable, and `base_exists=1` means the template is usable.', | |
| 339 | 删除: 'A start asks its questions only when stderr is a terminal: otherwise it stops there. `security_questions` in `info` names them beforehand (`hooks`, `git-config`, `bare-repo` or `none`), and `--unsafe-disable-security-prompts` accepts them once the user agreed.', | |
| 340 | 删除: ], | |
| 341 | 删除: scriptsCode: | |
| 342 | 删除: 'agent-vm version --min 0.2.0 || exit 1 # silent when OK\nagent-vm name [dir] # VM name for a directory\nagent-vm info [dir] # one key=value per line\n\n# info keys: version, template, state_dir,\n# project_env, dir, vm_name, base_exists,\n# vm_exists, vm_running, vm_stale,\n# ssh_host, ssh_config, git_protected,\n# security_questions', | |
| 343 | 删除: groups: [ | |
| 344 | 删除: { | |
| 345 | 删除: title: 'Install and update', | |
| 346 | 删除: topics: [ | |
| 347 | 删除: { | |
| 348 | 删除: title: 'Installer options', | |
| 349 | 删除: paras: [ | |
| 350 | 删除: 'Options go after `sh -s --`: `--version X.Y.Z`, `--git` for a clone of `main`, `--dir DIR` instead of `~/.local/share/agent-vm`. To read the installer first, download it, then run it with `sh`.', | |
| 351 | 删除: ], | |
| 352 | 删除: list: [], | |
| 353 | 删除: code: 'curl -fsSL https://www.agent-vm.org/install.sh |\n sh -s -- --dir ~/tools/agent-vm\n\n# read it first\ncurl -fsSLO https://www.agent-vm.org/install.sh\nsh install.sh', | |
| 354 | 删除: }, | |
| 355 | 删除: { | |
| 356 | 删除: title: 'Updating', | |
| 357 | 删除: paras: [ | |
| 358 | 删除: 'Run the curl installer again, `brew upgrade agent-vm`, or `git pull && ./agent-vm.sh install` in a clone. `agent-vm uninstall` removes the link; VMs and `~/.agent-vm` stay.', | |
| 359 | 删除: 'Running `setup` again rebuilds the template, not the VMs cloned from it: agent-vm warns about those, and `--reset` re-clones one. Its full log is in `~/.agent-vm/setup.log`.', | |
| 360 | 删除: ], | |
| 361 | 删除: list: [], | |
| 362 | 删除: code: '', | |
| 363 | 删除: }, | |
| 364 | 删除: { | |
| 365 | 删除: title: 'From 0.2', | |
| 366 | 删除: paras: [ | |
| 367 | 删除: 'Lima is built in: Homebrew’s Lima, or the Lima build 0.2 installed, can go, unless you use it for VMs of your own. agent-vm keeps its VMs in `~/.agent-vm/lima`, apart from yours, and names them without the `agent-vm-` prefix: `your-project-1a2b3c4d`, and `base` for the template.', | |
| 368 | 删除: 'The first command that needs the VMs offers to move 0.2’s from `~/.lima` (or `$LIMA_HOME`), stopping the running ones first: they keep their disks, shares and settings. Declined, it asks again next time; with no terminal to ask on, it moves them. `doctor` and `info` only look, and say when some are still to move.', | |
| 369 | 删除: 'To update, run the curl installer again, or `git pull && ./agent-vm.sh install` in a clone (Go needed): the link on your `PATH` then leads to the binary. Until then, 0.2’s link to `agent-vm.sh` keeps working (in a clone, after a `git pull`, it builds agent-vm first), and so does a shell rc line sourcing it, which `install` says can go. A VM from a base 0.1.0 built no longer starts: run `agent-vm setup`, then `--reset`.', | |
| 370 | 删除: ], | |
| 371 | 删除: list: [], | |
| 372 | 删除: code: '', | |
| 373 | 删除: }, | |
| 374 | 删除: { | |
| 375 | 删除: title: 'Windows and WSL', | |
| 376 | 删除: paras: [ | |
| 377 | 删除: 'On Windows, agent-vm runs natively, from PowerShell or Git Bash, with QEMU; it is experimental. Your folders are `C:/Users/you/project` to it, and `/c/Users/you/project` in the VM, as with 0.2. The volumes file takes `C:/x` or `C:\\x`, and 0.2’s `/c/x`.', | |
| 378 | 删除: 'VMs need the Windows Hypervisor Platform feature. It is off by default and only an administrator can turn it on, once, in Windows Features or with the command below, then a reboot. On a managed laptop, that is a request to IT. A start that fails for want of it says so.', | |
| 379 | 删除: 'WSL2 is Linux to agent-vm, and its VMs need KVM, which WSL2 has only with nested virtualization from the Windows host. WSL1 cannot run VMs.', | |
| 380 | 删除: ], | |
| 381 | 删除: list: [], | |
| 382 | 删除: code: '# in PowerShell as administrator, then reboot\nDISM /Online /Enable-Feature `\n /FeatureName:HypervisorPlatform /All', | |
| 383 | 删除: }, | |
| 384 | 删除: { | |
| 385 | 删除: title: 'Paths', | |
| 386 | 删除: paras: [ | |
| 387 | 删除: 'Paths with whitespace, quotes, backslashes, control characters, `{{` (Lima reads it as a template) or bytes that are not UTF-8 are refused. iCloud Drive paths have spaces: go through a symlink. A folder name too long for Lima’s socket paths is cut in the VM’s name, which keeps the hash of the whole path.', | |
| 388 | 删除: ], | |
| 389 | 删除: list: [], | |
| 390 | 删除: code: 'ln -s ~/Library/Mobile\\ Documents/com~apple~CloudDocs/Dev \\\n ~/Dev\ncd ~/Dev/your-project && agent-vm claude', | |
| 391 | 删除: }, | |
| 392 | 删除: { | |
| 393 | 删除: title: 'Ports and doctor', | |
| 394 | 删除: paras: [ | |
| 395 | 删除: 'A port set with `--ssh-port` stays until `--reset` or `rm`. `doctor` prints no secret, so its output can go into an issue as is.', | |
| 396 | 删除: ], | |
| 397 | 删除: list: [], | |
| 398 | 删除: code: '', | |
| 399 | 删除: }, | |
| 400 | 删除: ], | |
| 401 | 删除: }, | |
| 402 | 删除: { | |
| 403 | 删除: title: 'Agents and configuration', | |
| 404 | 删除: topics: [ | |
| 405 | 删除: { | |
| 406 | 删除: title: 'How each agent runs', | |
| 407 | 删除: paras: [ | |
| 408 | 删除: 'Claude Code also gets bypass mode from managed settings, since it drops the flag when it relaunches itself ([#72479](https://github.com/anthropics/claude-code/issues/72479)). For Pi, setup sets `defaultProjectTrust: "always"`.', | |
| 409 | 删除: 'Log in inside the VM (`claude login`, `gh auth login`): the login stays with that VM. Mounting your host credentials would hand them to everything in it.', | |
| 410 | 删除: 'A 24-bit colour terminal that does not set `COLORTERM` (Terminal.app on macOS 26) needs `export COLORTERM=truecolor`.', | |
| 411 | 删除: ], | |
| 412 | 删除: list: [], | |
| 413 | 删除: code: '', | |
| 414 | 删除: }, | |
| 415 | 删除: { | |
| 416 | 删除: title: 'MCP servers', | |
| 417 | 删除: paras: [ | |
| 418 | 删除: 'Playwright MCP uses the VM’s Chromium and downloads no browser. For another engine, edit its entry (drop `--executable-path`, add `--browser firefox`) and run `npx playwright install firefox`. Add your own servers to `mcpServers` in `~/.claude.json`, from `~/.agent-vm/setup.sh` or inside a VM.', | |
| 419 | 删除: ], | |
| 420 | 删除: list: [], | |
| 421 | 删除: code: '{\n "mcpServers": {\n "postgres": {\n "command": "npx",\n "args": [\n "-y",\n "@modelcontextprotocol/server-postgres",\n "postgresql://localhost:5432/mydb"\n ]\n }\n }\n}', | |
| 422 | 删除: }, | |
| 423 | 删除: { | |
| 424 | 删除: title: 'The env files', | |
| 425 | 删除: paras: [ | |
| 426 | 删除: 'agent-vm knows none of the names: `gh` reads `GH_TOKEN`, Claude Code `ANTHROPIC_API_KEY`, Codex `OPENAI_API_KEY`, Vibe `MISTRAL_API_KEY`. Edits need no `--reset`.', | |
| 427 | 删除: 'The project’s `.agent-vm.env` is pushed after the shared one and wins. It sits in a repository, so keep secrets out: `project-env set` prints the line that gitignores it.', | |
| 428 | 删除: '`get` and `has` read the file without running it, and exit `2` on a value that needs a shell. `set` without a value reads it unseen, out of your shell history.', | |
| 429 | 删除: ], | |
| 430 | 删除: list: [], | |
| 431 | 删除: code: '', | |
| 432 | 删除: }, | |
| 433 | 删除: { | |
| 434 | 删除: title: 'Extra mounts, in detail', | |
| 435 | 删除: paras: [ | |
| 436 | 删除: 'A destination is used as written, with no `~`: the VM home is `/home/<you>.guest` (`.linux` before Lima 2.1). A missing source is skipped with a warning.', | |
| 437 | 删除: 'A single file is hardlinked into `~/.agent-vm/file-mounts/<vm>/` and bind-mounted. Across filesystems it is copied, and host edits wait for the next start.', | |
| 438 | 删除: ], | |
| 439 | 删除: list: [], | |
| 440 | 删除: code: '# ~/.agent-vm/volumes: your Claude instructions and skills,\n# not the whole ~/.claude, which holds your login on Linux\n~/.claude/CLAUDE.md:/home/you.guest/.claude/CLAUDE.md\n~/.claude/skills:/home/you.guest/.claude/skills', | |
| 441 | 删除: }, | |
| 442 | 删除: { | |
| 443 | 删除: title: 'Setup and runtime scripts', | |
| 444 | 删除: paras: [ | |
| 445 | 删除: '`~/.agent-vm/setup.sh` runs once in the template, at the end of `setup`, under zsh with sudo. `~/.agent-vm/runtime.sh`, then the project’s `.agent-vm.runtime.sh`, run on every command that enters the VM, so both must be safe to re-run. [`runtime.example.sh`](https://github.com/sylvinus/agent-vm/blob/main/runtime.example.sh) covers git identity, `gh auth setup-git`, skills and MCP servers.', | |
| 446 | 删除: 'They are fed on standard input: give a command in them that reads it `</dev/null`. Keep private keys out, the agent can read what they set up.', | |
| 447 | 删除: ], | |
| 448 | 删除: list: [], | |
| 449 | 删除: code: '# .agent-vm.runtime.sh\nmise install\nnpm install\ndocker compose up -d', | |
| 450 | 删除: }, | |
| 451 | 删除: ], | |
| 452 | 删除: }, | |
| 453 | 删除: ], | |
| 454 | 删除: }, | |
| 455 | 删除: | |
| 456 | 删除: security: { | |
| 457 | 删除: eyebrow: 'Security', | |
| 458 | 删除: title: 'What crosses the boundary.', | |
| 459 | 删除: lede: 'The VM cannot leave its shares. What remains is what crosses them: the project folder, which the agent writes and your machine reads, the terminal, and the network.', | |
| 460 | 删除: groups: [ | |
| 461 | 删除: { | |
| 462 | 删除: id: 'git', | |
| 463 | 删除: title: 'Protecting .git', | |
| 464 | 删除: topics: [ | |
| 465 | 删除: { | |
| 466 | 删除: title: 'Why .git', | |
| 467 | 删除: paras: [ | |
| 468 | 删除: 'Git on your machine runs what a repository’s `.git/config` and hooks name: `core.fsmonitor` on every `git status`, hooks on commit. Your editor and prompt run `git status` on their own, so a VM able to write `.git` could run commands on your host within seconds, invisible in `git diff`.', | |
| 469 | 删除: 'Every `.git` and `.hg` in the shares is read-only for the VM, at any depth, enforced on your machine by the SFTP server built into agent-vm (Lima’s `sshfs.readonlyNames`, not merged upstream yet: [lima-vm/lima#5529](https://github.com/lima-vm/lima/issues/5529)). The agent reads the history but cannot commit. The shares use `reverse-sshfs`, slower on many files (see [Node.js](#node)), and without sshfs’s cache on the writable ones, so the VM never writes back a file as it was before you changed it: `AGENT_VM_SSHFS_CACHE=1` trades that for speed.', | |
| 470 | 删除: ], | |
| 471 | 删除: list: [], | |
| 472 | 删除: code: 'agent-vm doctor # where you stand\n\n# let the agent commit anyway\nagent-vm --unsafe-writable-git claude', | |
| 473 | 删除: }, | |
| 474 | 删除: { | |
| 475 | 删除: title: 'Beyond the name .git', | |
| 476 | 删除: paras: [ | |
| 477 | 删除: 'The folder a `core.hooksPath` points to in a share (`.husky` for husky) is read-only too, as is a link on the way to it, and the same goes for the repositories in your writable volumes. A folder holding git’s internals (`HEAD`, `objects/`, `refs/`, a `config`) is a repository under any name: setting `safe.bareRepository` to `explicit` in your global git config makes git ignore it, and one in a writable volume is read-only by its name. A config included from a share, a command or a hook git runs from one, or hooks at the top of a share, are the same kind of door.', | |
| 478 | 删除: 'Before a VM boots with writable shares, agent-vm stops on each of these it finds, and asks: Enter, or no terminal, aborts. `doctor` lists them. `--unsafe-writable-git` (or `AGENT_VM_UNSAFE_WRITABLE_GIT=1` in your shell, never read from the project) lets the agent commit and reopens that path to your host, with a warning on every run.', | |
| 479 | 删除: ], | |
| 480 | 删除: list: [], | |
| 481 | 删除: code: '', | |
| 482 | 删除: }, | |
| 483 | 删除: { | |
| 484 | 删除: title: 'Lima, built in', | |
| 485 | 删除: paras: [ | |
| 486 | 删除: 'agent-vm builds Lima, its SFTP server (sshocker and pkg/sftp) and its network stack (gvisor-tap-vsock) from their upstream sources, with [patches](https://github.com/sylvinus/agent-vm/blob/main/patches/README.md) kept small enough to be sent upstream: the read-only names, fixes to the SFTP server (an append that crashed the VM, writes applied out of order), network isolation, the port check. Each running VM is served by an agent-vm process, which is Lima’s host agent.', | |
| 487 | 删除: 'Every share is served by the built-in SFTP server, confined to its folder: agent-vm starts no VM whose config says otherwise, whatever set it. A `default.yaml` or `override.yaml` in `~/.agent-vm/lima/_config` would add to every VM’s config, so agent-vm starts no VM while one is there.', | |
| 488 | 删除: ], | |
| 489 | 删除: list: [], | |
| 490 | 删除: code: '', | |
| 491 | 删除: }, | |
| 492 | 删除: ], | |
| 493 | 删除: }, | |
| 494 | 删除: { | |
| 495 | 删除: title: 'What agent-vm does', | |
| 496 | 删除: topics: [ | |
| 497 | 删除: { | |
| 498 | 删除: title: 'Refused directories and files', | |
| 499 | 删除: paras: [ | |
| 500 | 删除: 'agent-vm will not share your home directory, `/`, its own directory, `~/.agent-vm`, your own Lima’s directory (`~/.lima`), or a directory containing one of them: `cd ~ && agent-vm shell` would hand the VM your dotfiles and SSH keys. `--unsafe-disable-security-prompts` lets it share its own directory, to work on agent-vm from a clone: the VM can then change the agent-vm your machine runs.', | |
| 501 | 删除: 'It never reads a file in the project by its path, since the VM can make it a symlink to any file of yours. Its own git calls in a project refuse a bare repository and run no `core.fsmonitor` or pager.', | |
| 502 | 删除: ], | |
| 503 | 删除: list: [], | |
| 504 | 删除: code: '', | |
| 505 | 删除: }, | |
| 506 | 删除: { | |
| 507 | 删除: title: '--readonly, in detail', | |
| 508 | 删除: paras: [ | |
| 509 | 删除: '`--readonly` covers every share, `rw` volumes included: a writable volume containing the project would be a second way in. The built-in SFTP server enforces it on your machine, and agent-vm checks each VM’s config before it boots, never the guest’s word.', | |
| 510 | 删除: 'A running VM in the other mode is restarted, asked first. Declined, or with no terminal, the command fails, so another session’s read-only VM is never made writable under it.', | |
| 511 | 删除: ], | |
| 512 | 删除: list: [], | |
| 513 | 删除: code: '', | |
| 514 | 删除: }, | |
| 515 | 删除: ], | |
| 516 | 删除: }, | |
| 517 | 删除: { | |
| 518 | 删除: title: 'What else on your machine reads the project', | |
| 519 | 删除: topics: [ | |
| 520 | 删除: { | |
| 521 | 删除: title: 'The rule', | |
| 522 | 删除: paras: [ | |
| 523 | 删除: 'Anything on your machine that reads the project and acts on what it finds can run what the agent wrote. agent-vm closes git’s doors (see [Protecting .git](#git)), but cannot lock the files your other tools read without stopping the agent from working.', | |
| 524 | 删除: 'So on your machine, open the project in your editor and use git in it; run everything else in the VM, with `agent-vm run`. The lists below are examples, not an inventory.', | |
| 525 | 删除: ], | |
| 526 | 删除: list: [ | |
| 527 | 删除: 'Nothing at all: what runs when you `cd` into the folder, your prompt redraws, your editor opens it. The most dangerous kind.', | |
| 528 | 删除: 'Something you do anyway: `git commit` runs hooks kept in the working tree, `docker compose up` mounts what the compose file names.', | |
| 529 | 删除: 'Running project code: `npm test`, `make`, a build. That is the agent’s code: run it in the VM.', | |
| 530 | 删除: ], | |
| 531 | 删除: code: '', | |
| 532 | 删除: }, | |
| 533 | 删除: { | |
| 534 | 删除: title: 'Guarded files', | |
| 535 | 删除: paras: [ | |
| 536 | 删除: 'For the first kind, agent-vm guards the files your machine runs on its own: when the VM writes, creates, renames or removes one, at any depth in the shares, a dialog asks you first. A yes holds until the VM stops; a no, for a minute, after which a retry asks again. Where no dialog can be shown (no desktop session), the write is refused and a notification says so; a dialog left unanswered for two minutes refuses it too. `AGENT_VM_GUARDED_WRITES=deny` refuses them all without asking.', | |
| 537 | 删除: 'Guarded by default: `.envrc` (direnv), `.vscode/tasks.json`, `.vscode/settings.json` and `.vscode/launch.json` (VS Code), `.pre-commit-config.yaml` (pre-commit), `lefthook.yml` and `.lefthook.yml` (lefthook), `mise.toml` and `.mise.toml` (mise). Files the agent edits as a matter of course, such as a `Makefile` or `package.json`, are not: add them in `~/.agent-vm/guarded`, one path per line, read when a VM starts. `!path` removes a default, and `*.ext` guards an extension. On a Windows host, `*.library-ms`, `*.searchConnector-ms`, `*.lnk`, `*.url`, `*.scf` and `desktop.ini` are guarded too: Explorer sends your NTLM hash to the server they name when it shows them. There is no dialog on Windows, so the VM’s writes to them are refused.', | |
| 538 | 删除: ], | |
| 539 | 删除: list: [], | |
| 540 | 删除: code: '# ~/.agent-vm/guarded\nMakefile # ask before the VM changes any Makefile\n.github/workflows/ci.yml\n!.vscode/settings.json # no longer asked', | |
| 541 | 删除: }, | |
| 542 | 删除: { | |
| 543 | 删除: title: 'Editors and agents', | |
| 544 | 删除: paras: [ | |
| 545 | 删除: 'A changed tracked file shows in `git diff`, a new one as untracked; one in an ignored path (`node_modules`, `.venv`, `target/`) shows nowhere.', | |
| 546 | 删除: ], | |
| 547 | 删除: list: [ | |
| 548 | 删除: 'VS Code: open agent-vm projects in Restricted Mode, and do not trust a parent folder. A trusted workspace runs project code through tasks and extensions: `eslint.config.js`, `vite.config.ts`, `build.rs`.', | |
| 549 | 删除: 'JetBrains IDEs: “Preview in Safe Mode”. A trusted project runs its Gradle or Maven scripts on import.', | |
| 550 | 删除: 'Vim: leave `exrc` off. Neovim and Emacs ask before running project config.', | |
| 551 | 删除: 'Agents on your machine run commands from `.claude/settings.json` hooks, `.mcp.json` or `.cursor/`: review those, and treat `CLAUDE.md` and `AGENTS.md` as the VM’s writing.', | |
| 552 | 删除: ], | |
| 553 | 删除: code: '', | |
| 554 | 删除: }, | |
| 555 | 删除: { | |
| 556 | 删除: title: 'SSH from your machine', | |
| 557 | 删除: paras: [ | |
| 558 | 删除: 'Do not connect VS Code Remote-SSH or open-remote-ssh to an agent VM. They run a server in the VM, which root in the VM controls, and the editor on your machine trusts it. Microsoft’s Remote-SSH page says so: “a compromised remote could use the VS Code Remote connection to execute code on your local machine”, and it is by design. Public write-ups show it opening a terminal on the host and running commands there. That removes the boundary agent-vm sets up, which is worse than opening the project in Restricted Mode. JetBrains Gateway does not say it is safer: its security model page says what the backend loads goes to your machine without asking, the backend opens links there (after a prompt), and decides which client version your machine downloads. For language servers and a debugger with the VM’s packages, use [`agent-vm code`](#edit-with-the-vm-s-tools).', | |
| 559 | 删除: 'For scripts, `scp` or `rsync`, `agent-vm info` prints the SSH alias as `ssh_host`. Put these lines at the top of `~/.ssh/config`: a `ForwardAgent yes` found before them would hand the VM your SSH keys. `lima-*` also matches the VMs of your own Lima, if you have one. `--ssh-port` pins the port for tools that save it.', | |
| 560 | 删除: ], | |
| 561 | 删除: list: [], | |
| 562 | 删除: code: '# top of ~/.ssh/config\nInclude ~/.agent-vm/lima/*/ssh.config\nHost lima-*\n ForwardAgent no\n ForwardX11 no\n\nagent-vm info | grep ^ssh_host # the alias to use\nagent-vm --ssh-port 2222 shell # a fixed port', | |
| 563 | 删除: }, | |
| 564 | 删除: { | |
| 565 | 删除: title: 'Shell, commands, hooks', | |
| 566 | 删除: paras: [], | |
| 567 | 删除: list: [ | |
| 568 | 删除: 'direnv only loads an `.envrc` you allowed, and a change revokes it; agent-vm also asks before the VM writes one ([Guarded files](#guarded-files)).', | |
| 569 | 删除: 'mise trusts a config by its path: a VM allowed to change a trusted `mise.toml` makes your shell run its hooks and set its env on the next `cd`, agent-vm’s `AGENT_VM_UNSAFE_*` variables included. agent-vm asks before that write; `mise settings set paranoid true` also ties trust to the content. A config under another name (`mise.local.toml`, `.mise/config.toml`) is guarded only once you list it.', | |
| 570 | 删除: '`npm run`, `make`, `./gradlew`, `pytest`, `node_modules/.bin`, an activated `.venv`: each runs files the agent can write. Run them in the VM.', | |
| 571 | 删除: '`docker compose up` on your machine can mount any folder of yours into a root container. Docker runs in the VM: use it there.', | |
| 572 | 删除: 'lefthook and pre-commit keep their commands in the working tree: agent-vm asks before the VM changes their config, but not the scripts it names. husky’s hooks call project scripts. Read them in the diff, or commit with `--no-verify`.', | |
| 573 | 删除: ], | |
| 574 | 删除: code: '', | |
| 575 | 删除: }, | |
| 576 | 删除: { | |
| 577 | 删除: title: 'File managers', | |
| 578 | 删除: paras: [], | |
| 579 | 删除: list: [ | |
| 580 | 删除: 'macOS: files written through the share carry no quarantine flag, so Gatekeeper does not check an `.app`, `.command` or `.pkg` left there. Do not open them from Finder.', | |
| 581 | 删除: 'Windows: Explorer can contact the server named in a `.library-ms`, `.searchConnector-ms`, `.lnk`, `.url`, `.scf` or `desktop.ini` it displays, and send your NTLM hash ([CVE-2025-24054](https://research.checkpoint.com/2025/cve-2025-24054-ntlm-exploit-in-the-wild/) for `.library-ms`, [CVE-2025-50154](https://nvd.nist.gov/vuln/detail/CVE-2025-50154) and [CVE-2025-59214](https://nvd.nist.gov/vuln/detail/CVE-2025-59214) for `.lnk`). Patches have been bypassed before. agent-vm refuses the VM’s writes to these files on Windows; keep Windows updated, outbound SMB (TCP 445) blocked and, where you can, [NTLM blocked on the SMB client](https://learn.microsoft.com/en-us/powershell/module/smbshare/set-smbclientconfiguration).', | |
| 582 | 删除: 'Linux: KDE’s Dolphin ran commands from a `.desktop` file in a folder it only displayed (CVE-2019-14744, fixed in KDE Frameworks 5.61).', | |
| 583 | 删除: ], | |
| 584 | 删除: code: '', | |
| 585 | 删除: }, | |
| 586 | 删除: ], | |
| 587 | 删除: }, | |
| 588 | 删除: { | |
| 589 | 删除: title: 'Terminal and network', | |
| 590 | 删除: topics: [ | |
| 591 | 删除: { | |
| 592 | 删除: title: 'Terminal escape sequences', | |
| 593 | 删除: paras: [ | |
| 594 | 删除: 'What the VM prints reaches your terminal unfiltered, and terminals act on escape sequences. agent-vm cannot filter them without breaking the agents’ full-screen interfaces.', | |
| 595 | 删除: ], | |
| 596 | 删除: list: [ | |
| 597 | 删除: 'Clipboard: OSC 52 lets a program set your clipboard, and in some terminals read it. Never allow reads, and check what you paste into a host shell.', | |
| 598 | 删除: 'Replies typed for you: a sequence sent just before exit can make the terminal type into your host shell. Some were real bugs (iTerm2 [CVE-2024-38396](https://www.sentinelone.com/vulnerability-database/cve-2024-38396/)): keep your terminal updated.', | |
| 599 | 删除: 'Features that act on your machine: iTerm2 file transfer and triggers, kitty remote control (keep it off), links whose text differs from their target.', | |
| 600 | 删除: 'Spoofing: the VM can print a fake host prompt after a fake exit. Check where you are before typing a secret.', | |
| 601 | 删除: ], | |
| 602 | 删除: code: '', | |
| 603 | 删除: }, | |
| 604 | 删除: { | |
| 605 | 删除: title: 'Network and ports', | |
| 606 | 删除: paras: [ | |
| 607 | 删除: 'A VM reaches the internet, not your machine: its loopback (where the other VMs’ ports are forwarded), its own addresses and your local networks (private, link-local and carrier-grade NAT ranges) are refused, on your machine, by the network stack agent-vm runs for each VM. Root in the VM cannot lift it.', | |
| 608 | 删除: 'There is no `~/.agent-vm/network` by default, and none is needed: without it, the VMs reach the whole internet and nothing of your machine or local networks. Write one to open holes, read when a VM starts, one line each: `allow` an address (`192.168.1.20`), an address and port (`192.168.1.20:5432`, `[fd00::5]:80`), a network (`10.8.0.0/16`), or a service on your machine’s loopback, `localhost:PORT` (`localhost` alone opens every port), which the VM reaches at `192.168.5.2`. An `allow` line covers TCP and UDP.', | |
| 609 | 删除: '`domain` lines restrict the internet itself: those domains and their subdomains (`domain github.com` covers `api.github.com`; `*.github.com` means the same) become the only names the VMs resolve, and an address is reachable once agent-vm’s DNS gave it for one of them. `allow` lines still apply. A line it cannot read stops the start, named; `doctor` checks the file. `AGENT_VM_UNSAFE_OPEN_NETWORK=1` in your shell turns isolation off.', | |
| 610 | 删除: 'Each port a VM listens on is forwarded to your `127.0.0.1`, and a notification says so, except 32768-60999: the guest gives those to programs asking for any free port (Chromium’s DevTools port, language servers), and they stay inside the VM. A port a program of yours listens on is left to it, with a notification too: on macOS, a VM listening first on 5432 would otherwise receive the connections, and passwords, meant for your local Postgres. On a free port, what you send goes to the VM: check the notification.', | |
| 611 | 删除: 'No VM reaches the editor of another one any more, but `agent-vm code` still gives each its own password, made in that VM, and its own host name, `<vm-name>.localhost`. A VM can serve a page on a forwarded port and send your browser to another VM’s host name on that port; browsers keep cookies per host name and not per port, so the browser hands it that editor’s cookie. The VM cannot use it against the editor itself, being refused your loopback, but stop `agent-vm code` (Ctrl-C) when you are not using it. Chrome and Firefox resolve `*.localhost` themselves; Safari may not, and then `127.0.0.1` in a private window kept for the editor does the same.', | |
| 612 | 删除: ], | |
| 613 | 删除: list: [], | |
| 614 | 删除: code: '# ~/.agent-vm/network\nallow localhost:11434 # Ollama on this machine, at 192.168.5.2:11434\nallow 192.168.1.20:5432 # a database on the local network\nallow 10.8.0.0/16 # a VPN\n\n# only these on the internet, subdomains included\ndomain github.com\ndomain npmjs.org', | |
| 615 | 删除: }, | |
| 616 | 删除: ], | |
| 617 | 删除: }, | |
| 618 | 删除: ], | |
| 619 | 删除: }, | |
| 620 | 删除: | |
| 621 | 删除: architecture: { | |
| 622 | 删除: eyebrow: 'Architecture', | |
| 623 | 删除: title: 'A template, then a clone per directory.', | |
| 624 | 删除: lede: | |
| 625 | 删除: 'Setup pays the provisioning cost once. Every project after that is a clone of a VM that already has the toolchain in it.', | |
| 626 | 删除: steps: [ | |
| 627 | 删除: { | |
| 628 | 删除: n: '01', | |
| 629 | 删除: title: 'setup builds the template', | |
| 630 | 删除: body: 'agent-vm creates a Debian 13 VM with the Lima built into it. `agent-vm.setup.sh` installs the dev tools, Docker, Chromium and the agents inside it, then the VM is stopped and kept as a base template.', | |
| 631 | 删除: }, | |
| 632 | 删除: { | |
| 633 | 删除: n: '02', | |
| 634 | 删除: title: 'The first run clones it', | |
| 635 | 删除: body: 'Running an agent in a directory clones the template into a persistent VM keyed to that path, mounts the working directory, and runs the [runtime scripts](#customisation-files): the per-user one first, the per-project one second.', | |
| 636 | 删除: }, | |
| 637 | 删除: { | |
| 638 | 删除: n: '03', | |
| 639 | 删除: title: 'The agent works unattended', | |
| 640 | 删除: body: 'It is launched with its own auto-approve flag. It reaches the internet, not your machine. The ports it opens inside the VM are forwarded to yours, so a dev server is reachable in your browser as usual.', | |
| 641 | 删除: }, | |
| 642 | 删除: { | |
| 643 | 删除: n: '04', | |
| 644 | 删除: title: 'The VM outlives the session', | |
| 645 | 删除: body: 'It persists after the agent exits. Any later command in the same directory reuses it, with its containers and its logins intact, until `rm` or `--rm`.', | |
| 646 | 删除: }, | |
| 647 | 删除: ], | |
| 648 | 删除: diagram: { | |
| 649 | 删除: hostTitle: 'Your machine', | |
| 650 | 删除: hostItems: ['SSH keys', 'API tokens', 'Browser sessions', 'git config', 'Everything else'], | |
| 651 | 删除: hostNote: 'Only agent-vm installed', | |
| 652 | 删除: boundaryLabel: 'Hypervisor boundary', | |
| 653 | 删除: vmTitle: 'The VM', | |
| 654 | 删除: vmItems: ['The agent', 'node, python, docker, ...', 'Headless Chromium, ...', 'Ports, forwarded out'], | |
| 655 | 删除: vmNote: 'Separate kernel', | |
| 656 | 删除: sharedLabel: 'Shared', | |
| 657 | 删除: sharedTitle: '~/work/your-project', | |
| 658 | 删除: sharedBody: | |
| 659 | 删除: 'Your project directory, mounted into the VM at the same path. Your editor and the agent work on the same files, so there is nothing to copy back. Read-write by default, read-only with `--readonly`. Anything else that crosses is something you chose: the env file, and extra mounts listed in `~/.agent-vm/volumes`.', | |
| 660 | 删除: }, | |
| 661 | 删除: isolationNote: | |
| 662 | 删除: 'Each VM authenticates on its own: `claude login` happens inside it. Credentials persist across restarts of that VM and are shared with neither the host nor any other VM. Each VM has its own network stack too, which reaches the internet and not your machine: see [Network and ports](#network-and-ports).', | |
| 663 | 删除: contentsTitle: 'What is in the VM', | |
| 664 | 删除: contentsLede: | |
| 665 | 删除: 'The setup wizard offers the default set: everything below except the rows marked no. Answer `n` to pick each item. `--preinstall` takes the names instead, comma-separated, plus `default`, `all` or `none`, and skips the wizard, as does a setup with no terminal.', | |
| 666 | 删除: contentsHeaders: ['Category', 'Packages', 'Name', 'Default'], | |
| 667 | 删除: contents: [ | |
| 668 | 删除: ['Core', 'git, curl, wget, jq, zsh, ca-certificates, sshfs, build-essential, pkgconf, patch, unzip, zip, ripgrep, fd-find, htop', 'always', 'yes'], | |
| 669 | 删除: ['Build libs', 'libssl-dev, libreadline-dev, zlib1g-dev, libyaml-dev, libffi-dev', 'always', 'yes'], | |
| 670 | 删除: ['Version manager', 'mise', 'always', 'yes'], | |
| 671 | 删除: ['Python', 'python3, pip, venv', 'python', 'yes'], | |
| 672 | 删除: ['Node.js', 'Node.js 24 LTS via NodeSource', 'node', 'yes'], | |
| 673 | 删除: ['Ruby', 'ruby-full', 'ruby', 'no'], | |
| 674 | 删除: ['Rust', 'rustup, stable toolchain', 'rust', 'no'], | |
| 675 | 删除: ['Go', 'golang-go', 'golang', 'no'], | |
| 676 | 删除: ['GitHub CLI', 'gh', 'gh', 'yes'], | |
| 677 | 删除: ['Browser', 'Chromium headless, xvfb', 'chromium', 'yes'], | |
| 678 | 删除: ['Containers', 'Docker Engine, Docker Compose', 'docker', 'yes'], | |
| 679 | 删除: ['AI agents', 'Claude Code, OpenCode, Codex CLI, Mistral Vibe', 'claude, opencode, codex, vibe', 'yes'], | |
| 680 | 删除: ['AI agents', 'Pi', 'pi', 'no'], | |
| 681 | 删除: ['MCP', 'Chrome DevTools MCP, wired into every installed agent but Pi (no MCP support)', 'mcp-chrome', 'yes'], | |
| 682 | 删除: ['MCP', 'Playwright MCP, reusing the same Chromium', 'mcp-playwright', 'no'], | |
| 683 | 删除: ['Editor', 'code-server (VS Code in the browser, for `agent-vm code`), dark theme, GitHub Copilot off, no telemetry', 'code-server', 'no'], | |
| 684 | 删除: ['Editor', 'The Claude Code, OpenCode, Codex or Mistral Vibe extension, each starting with no permission prompts, with code-server', 'code-claude, code-opencode, code-codex, code-vibe', 'no'], | |
| 685 | 删除: ], | |
| 686 | 删除: contentsCode: | |
| 687 | 删除: 'agent-vm setup --preinstall=default # no prompts\nagent-vm setup --preinstall=default,rust # plus Rust\nagent-vm setup --preinstall=python,docker,claude # minimal Claude setup\nagent-vm setup --preinstall=default,code-claude # plus the editor\nagent-vm setup --disk 50 --memory 16 --cpus 8 # a bigger template', | |
| 688 | 删除: contentsNote: | |
| 689 | 删除: '`codex` and `pi` pull in `node`, and so does `mcp-chrome` with `chromium` and an agent. Both MCP servers are skipped without `node` and `chromium`. The Claude, Codex and Mistral Vibe extensions ship their own copy of their agent (200 to 600 MB): the wizard asks whether to keep the command-line one too. Without it, `agent-vm claude` says it is not installed. OpenCode’s extension does not: it runs the `opencode` command, so `code-opencode` always installs it. This is only what the template ships: the agent is root in the VM and reaches the internet, so it installs whatever else it needs.', | |
| 690 | 删除: dockerTitle: 'Why not Docker', | |
| 691 | 删除: dockerLede: | |
| 692 | 删除: 'On Linux, containers share the host kernel, so a compromised dependency that finds a kernel bug is on your host. On macOS, Docker Desktop already runs a VM, which narrows the gap, but it is one VM shared by every container rather than one per project. A VM brings its own kernel, and root inside it still has the hypervisor between it and your machine. The practical differences matter as much as the security one.', | |
| 693 | 删除: dockerHeaders: ['', 'No sandbox', 'Docker / devcontainer', 'agent-vm'], | |
| 694 | 删除: docker: [ | |
| 695 | 删除: ['Agent can run any command', 'Yes', 'Yes', 'Yes'], | |
| 696 | 删除: ['Host files it can reach', 'All of them', 'What you mount', 'The project directory'], | |
| 697 | 删除: [ | |
| 698 | 删除: 'git credentials, SSH agent', | |
| 699 | 删除: 'Yours', | |
| 700 | 删除: 'None with plain Docker, forwarded by VS Code devcontainers', | |
| 701 | 删除: 'Nothing, beyond what you put in ~/.agent-vm/env', | |
| 702 | 删除: ], | |
| 703 | 删除: ['Outbound network', 'Open', 'Open by default', 'The internet, not your machine or local network ([Network and ports](#network-and-ports))'], | |
| 704 | 删除: ['Shares the host kernel', 'Yes', 'On Linux; on macOS, the Docker Desktop VM’s', 'No'], | |
| 705 | 删除: [ | |
| 706 | 删除: 'Reaching the host needs', | |
| 707 | 删除: 'Nothing', | |
| 708 | 删除: 'A kernel bug, plus a hypervisor bug on macOS', | |
| 709 | 删除: 'A hypervisor bug', | |
| 710 | 删除: ], | |
| 711 | 删除: ['Docker inside', 'Yes', 'Needs DinD or a socket mount', 'Yes, natively'], | |
| 712 | 删除: ['Headless browser', 'On the host', 'Up to your image', 'Chromium, included'], | |
| 713 | 删除: [ | |
| 714 | 删除: 'Environment definition', | |
| 715 | 删除: 'None, your machine', | |
| 716 | 删除: 'A devcontainer.json versioned with the project', | |
| 717 | 删除: 'One base template, the same for every project', | |
| 718 | 删除: ], | |
| 719 | 删除: ], | |
| 720 | 删除: dockerNote: | |
| 721 | 删除: 'Docker runs natively inside the VM with no Docker-in-Docker, and headless Chromium works out of the box. On a Mac, this replaces Docker Desktop.', | |
| 722 | 删除: }, | |
| 723 | 删除: | |
| 724 | 删除: contribute: { | |
| 725 | 删除: eyebrow: 'Contribute', | |
| 726 | 删除: title: 'Patches welcome.', | |
| 727 | 删除: lede: | |
| 728 | 删除: 'agent-vm is a Go program with Lima built in from upstream sources plus small patches, and a test suite that creates no VMs and needs no network. Bug reports, fixes and support for new agents are all welcome.', | |
| 729 | 删除: testsTitle: 'Run the tests', | |
| 730 | 删除: testsBody: | |
| 731 | 删除: 'Two suites. Neither touches your VMs, your `~/.agent-vm` or your git config.', | |
| 732 | 删除: testsList: [ | |
| 733 | 删除: '`make test-go` runs against a fake VM backend in throwaway folders: no VM, no network. Where 0.2’s bash version is compared, its results were recorded in `testdata/bashref`.', | |
| 734 | 删除: 'The end-to-end tests boot real VMs in their own Lima home: the VM suite checks what a fake cannot (root in the guest cannot write `.git` or a guarded file, nor reach this machine’s loopback); the CLI suite runs `setup` and a command in a project.', | |
| 735 | 删除: '`make fuzz` runs every fuzzer, `FUZZTIME` each: the SFTP server’s name matching and a hostile client’s requests, the git scan, the env and volumes parsers, paths and names.', | |
| 736 | 删除: ], | |
| 737 | 删除: testsCode: 'make test-go # fast, no VM\ngo test -tags e2e ./internal/vm/ ./internal/cli/ # real VMs\nmake fuzz FUZZTIME=5m', | |
| 738 | 删除: shellsTitle: 'Patch Lima, its SFTP server and its network', | |
| 739 | 删除: shellsBody: | |
| 740 | 删除: '`third_party/` holds Lima, sshocker, pkg/sftp and gvisor-tap-vsock: each the upstream commit in `third_party/SOURCES` plus the patches in `patches/`, every one small enough to be sent upstream. Never edit `third_party/` by hand: change a patch, then rebuild it. CI checks that nothing else is there.', | |
| 741 | 删除: shellsCode: 'scripts/third-party-sync sshocker # rebuild from SOURCES and patches\nmake check-third-party # what CI checks\nmake test-third-party # their own tests, patched', | |
| 742 | 删除: structureTitle: 'Where things live', | |
| 743 | 删除: structureHeaders: ['File', 'What it is'], | |
| 744 | 删除: structure: [ | |
| 745 | 删除: ['cmd/agent-vm/', 'The command’s entry point.'], | |
| 746 | 删除: ['internal/cli/', 'The commands, the start flow and its checks, setup, doctor.'], | |
| 747 | 删除: ['internal/vm/', 'The VMs, through the Lima built in.'], | |
| 748 | 删除: ['internal/limaembed/', 'Lima’s host agent, run as `agent-vm hostagent`, and the files it needs.'], | |
| 749 | 删除: ['internal/mounts/, internal/gitguard/', 'The shares, and the .git protection.'], | |
| 750 | 删除: ['internal/netguard/, internal/guard/', 'Network isolation, and the guarded files.'], | |
| 751 | 删除: ['third_party/, patches/', 'Lima and its SFTP server and network stack, upstream plus patches.'], | |
| 752 | 删除: ['agent-vm.setup.sh', 'Package installation, runs inside the base VM during setup.'], | |
| 753 | 删除: ['agent-vm.sh', 'Runs agent-vm: the binary next to it in a release, the one make builds in a clone. 0.2’s links and shell rc lines lead here.'], | |
| 754 | 删除: ['runtime.example.sh', 'Commented template for ~/.agent-vm/runtime.sh.'], | |
| 755 | 删除: ['CHANGELOG.md', 'What changed in each release.'], | |
| 756 | 删除: ['release.sh', 'Checks, tags and publishes a release, a tarball per platform. --dry-run first.'], | |
| 757 | 删除: ['www/', 'This website. Astro, static, deployed to GitHub Pages.'], | |
| 758 | 删除: ['www/public/install.sh', 'The curl installer, served at /install.sh.'], | |
| 759 | 删除: ], | |
| 760 | 删除: guidelinesTitle: 'Before you open a PR', | |
| 761 | 删除: guidelines: [ | |
| 762 | 删除: 'Every code path should be safe to re-run: check state before acting rather than assuming a clean machine.', | |
| 763 | 删除: 'New behaviour gets a test, checked to fail without the change. The fake backend (`vmtest.Fake`) makes that cheap.', | |
| 764 | 删除: 'A change to Lima, sshocker, pkg/sftp or gvisor-tap-vsock is a patch in `patches/`, small enough to be sent upstream.', | |
| 765 | 删除: 'Integrator-facing surfaces (`info`, `env`, `version`) are contracts. Adding keys is fine, changing meanings is not.', | |
| 766 | 删除: 'No secret, token or personal path in a commit, a test fixture or an issue.', | |
| 767 | 删除: ], | |
| 768 | 删除: issuesLabel: 'Open an issue', | |
| 769 | 删除: issuesHref: 'https://github.com/sylvinus/agent-vm/issues', | |
| 770 | 删除: prLabel: 'Browse pull requests', | |
| 771 | 删除: prHref: 'https://github.com/sylvinus/agent-vm/pulls', | |
| 772 | 删除: repoLabel: 'Read the source', | |
| 773 | 删除: repoHref: 'https://github.com/sylvinus/agent-vm', | |
| 774 | 删除: chatLabel: 'Chat on Matrix', | |
| 775 | 删除: chatHref: 'https://matrix.to/#/#agent-vm:matrix.org', | |
| 776 | 删除: }, | |
| 777 | 删除: | |
| 778 | 删除: credits: { | |
| 779 | 删除: eyebrow: 'Credits', | |
| 780 | 删除: title: 'Built on other people’s work.', | |
| 781 | 删除: lede: | |
| 782 | 删除: 'agent-vm is a thin layer over software other people wrote. Most of what makes it work is on this list.', | |
| 783 | 删除: groups: [ | |
| 784 | 删除: { | |
| 785 | 删除: title: 'The machine', | |
| 786 | 删除: items: [ | |
| 787 | 删除: { name: 'Lima', note: 'Linux VMs on macOS and Linux, built into agent-vm.', href: 'https://lima-vm.io/' }, | |
| 788 | 删除: { name: 'sshocker and pkg/sftp', note: 'The SFTP server that serves the shares and keeps .git read-only.', href: 'https://github.com/lima-vm/sshocker' }, | |
| 789 | 删除: { name: 'gvisor-tap-vsock', note: 'Each VM’s network stack, where the isolation applies.', href: 'https://github.com/containers/gvisor-tap-vsock' }, | |
| 790 | 删除: { name: 'Debian', note: 'The guest distribution. Debian 13.', href: 'https://www.debian.org/' }, | |
| 791 | 删除: { name: 'mise', note: 'Runtime version manager inside the VM.', href: 'https://mise.jdx.dev/' }, | |
| 792 | 删除: ], | |
| 793 | 删除: }, | |
| 794 | 删除: { | |
| 795 | 删除: title: 'The agents', | |
| 796 | 删除: items: [ | |
| 797 | 删除: { name: 'Claude Code', note: 'Anthropic.', href: 'https://claude.ai/code' }, | |
| 798 | 删除: { name: 'OpenCode', note: 'Open-source terminal agent.', href: 'https://github.com/anomalyco/opencode' }, | |
| 799 | 删除: { name: 'Codex CLI', note: 'OpenAI.', href: 'https://github.com/openai/codex' }, | |
| 800 | 删除: { name: 'Mistral Vibe', note: 'Mistral AI.', href: 'https://docs.mistral.ai/vibe/code/cli/install-setup' }, | |
| 801 | 删除: { name: 'Pi', note: 'Minimal open-source harness.', href: 'https://pi.dev' }, | |
| 802 | 删除: ], | |
| 803 | 删除: }, | |
| 804 | 删除: { | |
| 805 | 删除: title: 'Browser access', | |
| 806 | 删除: items: [ | |
| 807 | 删除: { | |
| 808 | 删除: name: 'Chrome DevTools MCP', | |
| 809 | 删除: note: 'Wired into every installed agent by default.', | |
| 810 | 删除: href: 'https://github.com/ChromeDevTools/chrome-devtools-mcp', | |
| 811 | 删除: }, | |
| 812 | 删除: { | |
| 813 | 删除: name: 'Playwright MCP', | |
| 814 | 删除: note: 'Pointed at the same Chromium.', | |
| 815 | 删除: href: 'https://github.com/microsoft/playwright-mcp', | |
| 816 | 删除: }, | |
| 817 | 删除: ], | |
| 818 | 删除: }, | |
| 819 | 删除: ], | |
| 820 | 删除: authorTitle: 'Maintainer', | |
| 821 | 删除: authorBody: 'Built and maintained by Sylvain Zimmer.', | |
| 822 | 删除: authorHref: 'https://github.com/sylvinus', | |
| 823 | 删除: authorName: 'sylvinus', | |
| 824 | 删除: licenseTitle: 'License', | |
| 825 | 删除: licenseBody: 'MIT: use, copy, modify and redistribute it, as long as the copyright and license notice stay with it. No warranty.', | |
| 826 | 删除: licenseHref: 'https://github.com/sylvinus/agent-vm/blob/main/LICENSE', | |
| 827 | 删除: }, | |
| 828 | 删除: | |
| 829 | 删除: footer: { | |
| 830 | 删除: tagline: 'A disposable Linux VM per project for AI coding agents.', | |
| 831 | 删除: license: 'MIT', | |
| 832 | 删除: backToTop: 'Back to top', | |
| 833 | 删除: }, | |
| 834 | 删除: | |
| 835 | 删除: ui: { | |
| 836 | 删除: copy: 'Copy', | |
| 837 | 删除: copied: 'Copied', | |
| 838 | 删除: copyFailed: 'Copy failed', | |
| 839 | 删除: copyLabel: 'Copy code to clipboard', | |
| 840 | 删除: anchorLabel: 'Link to this section (copies it)', | |
| 841 | 删除: linkCopied: 'Link copied', | |
| 842 | 删除: }, | |
| 843 | 删除:}; | |
| 844 | 删除: | |
| 845 | 删除:// Not `as const`: the literal types it would produce are exactly what every | |
| 846 | 删除:// other locale fails to match. Widened to string, the shape still has to line | |
| 847 | 删除:// up, which is the part worth enforcing. | |
| 848 | 删除:export type Dictionary = typeof en; | |
| @@ -1,845 +0,0 @@ | ||
| 1 | 删除:// Version française. Typée contre `en.ts` : une clé manquante ou renommée | |
| 2 | 删除:// casse le build au lieu de retomber silencieusement sur l'anglais. | |
| 3 | 删除:// | |
| 4 | 删除:// Ce n'est pas une traduction mot à mot de `en.ts` : c'est le même propos, | |
| 5 | 删除:// écrit en français. Les commandes shell, elles, sont identiques partout. | |
| 6 | 删除:// | |
| 7 | 删除:// Même règle de style qu'en anglais : on dit ce que fait l'outil. Pas de | |
| 8 | 删除:// slogan, pas d'absolu que le code ne tient pas (« impossible à quitter », | |
| 9 | 删除:// « plus rien ne sort »), pas de phrase dont le seul rôle est de sonner bien. | |
| 10 | 删除: | |
| 11 | 删除:import type { Dictionary } from './en'; | |
| 12 | 删除: | |
| 13 | 删除:export const fr: Dictionary = { | |
| 14 | 删除: meta: { | |
| 15 | 删除: lang: 'fr', | |
| 16 | 删除: label: 'Français', | |
| 17 | 删除: title: 'agent-vm | une VM Linux jetable par projet pour les agents de code IA', | |
| 18 | 删除: description: | |
| 19 | 删除: 'agent-vm donne à chaque projet sa propre VM Linux et y lance l\'agent de code sans demande de confirmation. Tes clés SSH, tes sessions de navigateur, le reste de ton disque et ton réseau local restent hors de sa portée. Un seul binaire, Lima intégré, sous licence MIT.', | |
| 20 | 删除: skipToContent: 'Aller au contenu', | |
| 21 | 删除: }, | |
| 22 | 删除: | |
| 23 | 删除: nav: { | |
| 24 | 删除: sections: { | |
| 25 | 删除: install: 'Installation', | |
| 26 | 删除: usage: 'Utilisation', | |
| 27 | 删除: reference: 'Référence', | |
| 28 | 删除: architecture: 'Architecture', | |
| 29 | 删除: security: 'Sécurité', | |
| 30 | 删除: contribute: 'Contribuer', | |
| 31 | 删除: credits: 'Crédits', | |
| 32 | 删除: }, | |
| 33 | 删除: github: 'GitHub', | |
| 34 | 删除: menu: 'Menu', | |
| 35 | 删除: language: 'Langue', | |
| 36 | 删除: }, | |
| 37 | 删除: | |
| 38 | 删除: hero: { | |
| 39 | 删除: title: 'Donne aux agents une machine qu\'ils peuvent casser.', | |
| 40 | 删除: titleAccent: 'Garde la tienne.', | |
| 41 | 删除: lede: | |
| 42 | 删除: 'agent-vm lance les agents de code IA avec toutes les permissions, dans une VM Linux par projet. Ils n\'y atteignent ni tes clés SSH, ni tes sessions de navigateur, ni le reste de ton disque, ni ton réseau local.', | |
| 43 | 删除: installLabel: 'Pour commencer', | |
| 44 | 删除: ctaPrimary: 'Installer', | |
| 45 | 删除: ctaSecondary: 'Comment ça marche', | |
| 46 | 删除: meta: 'Licence MIT · macOS, Linux, Windows (expérimental) · Lima intégré', | |
| 47 | 删除: terminalCaption: | |
| 48 | 删除: 'Seul le dossier du projet est monté.', | |
| 49 | 删除: points: [ | |
| 50 | 删除: { | |
| 51 | 删除: title: 'Un seul binaire, [Lima](https://lima-vm.io/) intégré', | |
| 52 | 删除: body: 'Ni Lima à installer, ni Node, ni npm, ni Docker Desktop sur ta machine : la chaîne d\'outils vit dans la VM. Sous Linux, les VM ont besoin de QEMU et d\'un accès à KVM.', | |
| 53 | 删除: }, | |
| 54 | 删除: { | |
| 55 | 删除: title: 'Un noyau séparé, pas un simple namespace', | |
| 56 | 删除: body: 'Sous Linux, sortir d\'un conteneur, c\'est atterrir sur l\'hôte. Sortir d\'une VM, c\'est d\'abord devoir franchir l\'hyperviseur.', | |
| 57 | 删除: }, | |
| 58 | 删除: { | |
| 59 | 删除: title: 'Les ports sont redirigés automatiquement', | |
| 60 | 删除: body: 'Un serveur de dev lancé dans la VM répond sur localhost, au même port, avec une notification, sans option ni configuration. Un port déjà pris par un de tes programmes lui est laissé.', | |
| 61 | 删除: }, | |
| 62 | 删除: { | |
| 63 | 删除: title: 'Tout est prêt, et root pour le reste', | |
| 64 | 删除: body: 'La VM de base contient les outils de dev, Docker, Chromium headless et les agents, choisis dans un assistant de setup. L\'agent est root dans sa VM : il installe lui-même ce qui lui manque.', | |
| 65 | 删除: }, | |
| 66 | 删除: ], | |
| 67 | 删除: }, | |
| 68 | 删除: | |
| 69 | 删除: threat: { | |
| 70 | 删除: eyebrow: 'Pourquoi ce projet', | |
| 71 | 删除: title: 'Pourquoi ne pas lancer l\'agent directement sur ta machine ?', | |
| 72 | 删除: lede: | |
| 73 | 删除: 'Chaque agent propose une option qui désactive les demandes de confirmation, et beaucoup s\'en servent ainsi. Quand ça se passe dans ton répertoire personnel, trois choses peuvent mal tourner.', | |
| 74 | 删除: reasons: [ | |
| 75 | 删除: { | |
| 76 | 删除: title: 'Installer une dépendance, c\'est exécuter du code', | |
| 77 | 删除: body: 'npm a lancé les scripts d\'installation de chaque paquet par défaut jusqu\'à npm 12 (juillet 2026), pip lance toujours le build d\'un paquet source, Cargo son `build.rs`, et tes tests exécutent ensuite tout ce qui a été installé. En 2025, le ver Shai-Hulud s\'est propagé ainsi dans des milliers de paquets npm : il récupérait jetons npm, PAT GitHub, clés SSH et identifiants cloud, puis s\'en servait pour se republier.', | |
| 78 | 删除: }, | |
| 79 | 删除: { | |
| 80 | 删除: title: 'On finit par tout valider', | |
| 81 | 删除: body: 'L\'autre option, c\'est de valider chaque commande à la main. Au bout de quelques dizaines de demandes, on répond par réflexe, et celle qui comptait reçoit le même oui que les autres. C\'est pour ça que l\'option qui désactive tout existe, et qu\'on s\'en sert.', | |
| 82 | 删除: }, | |
| 83 | 删除: { | |
| 84 | 删除: title: 'L\'agent lui-même n\'est pas fiable', | |
| 85 | 删除: body: 'Pas besoin d\'un paquet compromis. Un agent lit des issues, des pages web, des README, et tout ce qu\'il lit peut essayer de lui donner des ordres. Il fait aussi des erreurs toutes bêtes : le mauvais chemin, un `git checkout .` sur du travail pas encore commité.', | |
| 86 | 删除: }, | |
| 87 | 删除: ], | |
| 88 | 删除: closing: | |
| 89 | 删除: 'Une VM limite ce qu\'une erreur ou un agent compromis peut atteindre au projet, à Internet et à ce que tu lui confies, comme [son fichier d\'env](#share-secrets-across-vms). Ta machine et ton réseau local restent hors d\'atteinte : voir [Sécurité](#security).', | |
| 90 | 删除: }, | |
| 91 | 删除: | |
| 92 | 删除: install: { | |
| 93 | 删除: eyebrow: 'Installation', | |
| 94 | 删除: title: 'Installer, construire une image de base, lancer un agent.', | |
| 95 | 删除: lede: | |
| 96 | 删除: 'agent-vm, c\'est un seul binaire, Lima intégré, sans démon : chaque VM en marche est servie par un processus agent-vm à elle.', | |
| 97 | 删除: prerequisitesTitle: 'Prérequis', | |
| 98 | 删除: prerequisites: [ | |
| 99 | 删除: { name: 'macOS, Linux ou Windows', note: 'Windows est expérimental.', href: '' }, | |
| 100 | 删除: { | |
| 101 | 删除: name: 'QEMU, sous Linux et Windows', | |
| 102 | 删除: note: 'macOS n\'a besoin de rien d\'autre. Sous Linux, KVM aussi : `agent-vm setup` dit ce qui manque et comment l\'installer. Sous Windows, QEMU 7.2 ou plus récent et la fonctionnalité Windows Hypervisor Platform.', | |
| 103 | 删除: href: '', | |
| 104 | 删除: }, | |
| 105 | 删除: { | |
| 106 | 删除: name: 'Un abonnement ou une clé API pour ton agent', | |
| 107 | 删除: note: 'L\'authentification se fait dans la VM, VM par VM.', | |
| 108 | 删除: href: '', | |
| 109 | 删除: }, | |
| 110 | 删除: ], | |
| 111 | 删除: methodsTitle: 'Installer la commande', | |
| 112 | 删除: methodsBody: 'Au choix. Chacune met `agent-vm` dans ton `PATH` ; seuls les paquets Linux demandent root.', | |
| 113 | 删除: methodsLabel: 'Méthode d\'installation', | |
| 114 | 删除: methods: [ | |
| 115 | 删除: { | |
| 116 | 删除: id: 'curl', | |
| 117 | 删除: label: 'curl', | |
| 118 | 删除: code: 'curl -fsSL https://www.agent-vm.org/install.sh | sh', | |
| 119 | 删除: note: 'Télécharge depuis GitHub la dernière version publiée, compilée pour ta machine, la vérifie avec le `SHA256SUMS` de la version, la décompresse dans `~/.local/share/agent-vm` et place un lien `agent-vm` dans `~/.local/bin`. Propose ensuite de lancer l\'étape 2 dans la foulée. Relance-le pour mettre à jour. `sh -s -- --version X.Y.Z` installe une version donnée, `sh -s -- --git` un clone de `main`.', | |
| 120 | 删除: }, | |
| 121 | 删除: { | |
| 122 | 删除: id: 'brew', | |
| 123 | 删除: label: 'Homebrew', | |
| 124 | 删除: code: 'brew install sylvinus/tap/agent-vm', | |
| 125 | 删除: note: 'macOS, ou Linux avec Homebrew. `brew upgrade agent-vm` le met à jour.', | |
| 126 | 删除: }, | |
| 127 | 删除: { | |
| 128 | 删除: id: 'linux', | |
| 129 | 删除: label: 'Paquet Linux', | |
| 130 | 删除: code: 'sudo apt install ./agent-vm_X.Y.Z_amd64.deb\nsudo dnf install ./agent-vm-X.Y.Z-1.x86_64.rpm', | |
| 131 | 删除: note: 'Télécharge le `.deb` ou le `.rpm` de ton architecture (`amd64`, `arm64` ; `x86_64`, `aarch64`) depuis les versions publiées sur GitHub. Il installe `agent-vm` dans `/usr/bin` et recommande QEMU et ssh. Pas encore dans un dépôt de paquets : installe le nouveau fichier pour mettre à jour.', | |
| 132 | 删除: }, | |
| 133 | 删除: { | |
| 134 | 删除: id: 'nix', | |
| 135 | 删除: label: 'Nix', | |
| 136 | 删除: code: 'nix run github:sylvinus/agent-vm\nnix profile install github:sylvinus/agent-vm', | |
| 137 | 删除: note: 'Linux, NixOS compris. QEMU est fourni ; ssh est celui du système. `nix profile upgrade agent-vm` le met à jour.', | |
| 138 | 删除: }, | |
| 139 | 删除: { | |
| 140 | 删除: id: 'git', | |
| 141 | 删除: label: 'git', | |
| 142 | 删除: code: 'git clone https://github.com/sylvinus/agent-vm.git\ncd agent-vm && ./agent-vm.sh install', | |
| 143 | 删除: note: 'Le compile, avec Go (et sous macOS les outils en ligne de commande de Xcode), puis `install` place un lien symbolique `agent-vm` dans ton `PATH`. Après un `git pull`, relance `./agent-vm.sh install` pour recompiler. Il propose aussi de lancer l\'étape 2 dans la foulée.', | |
| 144 | 删除: }, | |
| 145 | 删除: { | |
| 146 | 删除: id: 'windows', | |
| 147 | 删除: label: 'Windows', | |
| 148 | 删除: code: '# dans Git Bash (expérimental)\nwinget install SoftwareFreedom.QEMU\ncurl -fsSL https://www.agent-vm.org/install.sh | sh', | |
| 149 | 删除: note: 'Expérimental. Sans Git Bash, télécharge `agent-vm-X.Y.Z-windows-amd64.tar.gz` (ou `-arm64`) depuis les versions publiées sur GitHub, décompresse-le avec `tar -xzf`, et lance `agent-vm.exe install` dans PowerShell. Les VM ont aussi besoin de la fonctionnalité Windows Hypervisor Platform, qu\'un administrateur active une fois : voir [Windows et WSL](#windows-and-wsl).', | |
| 150 | 删除: }, | |
| 151 | 删除: ], | |
| 152 | 删除: steps: [ | |
| 153 | 删除: { | |
| 154 | 删除: title: 'Construire l\'image de base', | |
| 155 | 删除: body: 'À faire une seule fois. Un assistant choisit ce qui entre dans l\'image : Entrée prend la sélection par défaut (voir [Ce qu\'il y a dans la VM](#what-is-in-the-vm)). Crée avec elle une VM Debian 13, puis la garde, arrêtée, comme image de base.', | |
| 156 | 删除: code: 'agent-vm setup', | |
| 157 | 删除: }, | |
| 158 | 删除: { | |
| 159 | 删除: title: 'Lancer un agent dans ton projet', | |
| 160 | 删除: body: 'Clone l\'image en une VM dédiée à ce dossier, y monte le dossier et lance l\'agent, sans demande de confirmation. Un démarrage peut d\'abord s\'arrêter sur une question de sécurité : voir [Protéger .git](#git).', | |
| 161 | 删除: code: 'cd ton-projet\nagent-vm opencode # ou : agent-vm claude', | |
| 162 | 删除: }, | |
| 163 | 删除: ], | |
| 164 | 删除: }, | |
| 165 | 删除: | |
| 166 | 删除: | |
| 167 | 删除: usage: { | |
| 168 | 删除: eyebrow: 'Utilisation', | |
| 169 | 删除: title: 'Les commandes du quotidien.', | |
| 170 | 删除: lede: | |
| 171 | 删除: 'À lancer depuis le dossier de ton projet. La [Référence](#reference) liste chaque commande, option et fichier.', | |
| 172 | 删除: cards: [ | |
| 173 | 删除: { | |
| 174 | 删除: title: 'Lancer un agent', | |
| 175 | 删除: body: 'Les arguments supplémentaires sont transmis tels quels à l\'agent : tout ce que sa CLI accepte fonctionne ici.', | |
| 176 | 删除: code: 'agent-vm opencode # OpenCode\nagent-vm claude # Claude Code\nagent-vm codex # Codex CLI\nagent-vm vibe # Mistral Vibe\nagent-vm pi # Pi\n\nagent-vm claude -p "corrige les erreurs de lint"\nagent-vm opencode run "mets à jour le changelog"', | |
| 177 | 删除: }, | |
| 178 | 删除: { | |
| 179 | 删除: title: 'Accéder au serveur de dev', | |
| 180 | 删除: body: 'Chaque port ouvert dans la VM est redirigé vers le même port de ton localhost : un serveur de dev s\'ouvre dans ton navigateur comme d\'habitude, et une notification le signale. Un port sur lequel écoute déjà un de tes programmes n\'est pas pris : la notification le dit aussi. Les ports 32768-60999, que la VM attribue aux programmes qui demandent un port libre quelconque, ne sont pas redirigés. Considère les ports redirigés comme ceux de l\'agent.', | |
| 181 | 删除: code: 'agent-vm run npm run dev # puis ouvre localhost:5173\nagent-vm run docker compose up', | |
| 182 | 删除: }, | |
| 183 | 删除: { | |
| 184 | 删除: title: 'Entrer dans la VM', | |
| 185 | 删除: body: 'Un shell pour aller voir ce qui s\'y passe, ou une commande isolée quand tu sais déjà ce que tu veux.', | |
| 186 | 删除: code: 'agent-vm shell # zsh dans la VM\nagent-vm run npm install # commande unique\nagent-vm run --tty opencode # un PTY pour les TUI\nagent-vm sh -c "ls -la | grep config"\nagent-vm code # VS Code dans le navigateur, si installé', | |
| 187 | 删除: }, | |
| 188 | 删除: { | |
| 189 | 删除: title: 'Gérer le parc', | |
| 190 | 删除: body: 'Dans `list`, la VM du dossier courant est marquée d\'un `>`. Si un dossier a été renommé, seul `list` permet de retrouver sa VM.', | |
| 191 | 删除: code: 'agent-vm list # chaque VM, la courante marquée\nagent-vm stop # arrête, garde le disque\nagent-vm rm # arrête et supprime\nagent-vm destroy-all # tout, image de base comprise\nagent-vm doctor # ce qui ne va pas, et quoi lancer', | |
| 192 | 删除: }, | |
| 193 | 删除: { | |
| 194 | 删除: title: 'Restreindre la session', | |
| 195 | 删除: body: '`--readonly` passe tous les partages de l\'hôte en lecture seule, volumes `rw` compris, et c\'est l\'hôte qui l\'impose : root dans la VM ne peut pas le lever. Les paquets s\'installent toujours sur le disque de la VM, mais rien n\'arrive dans le projet. `--scratch` ne monte rien de ce qui est à toi : l\'agent clone le code avec un jeton tiré d\'`agent-vm env`, pousse son travail, et la VM est supprimée à la sortie.', | |
| 196 | 删除: code: 'agent-vm --readonly shell # rien de modifiable sur l\'hôte\nagent-vm --scratch claude # rien de monté, supprimée après\nagent-vm --rm run npm test # détruit la VM à la sortie', | |
| 197 | 删除: }, | |
| 198 | 删除: { | |
| 199 | 删除: title: 'Redimensionner à la volée', | |
| 200 | 删除: body: 'Une nouvelle VM reprend les 10 Go de disque, 3 Go de mémoire (4 avec code-server choisi dans l\'assistant) et 1 CPU de l\'image. Passe une autre valeur et la VM est reconfigurée, après confirmation si elle tourne. Le disque ne fait que grandir. CPU et mémoire sont plafonnés à la moitié de l\'hôte, par VM.', | |
| 201 | 删除: code: 'agent-vm --disk 50 opencode\nagent-vm --memory 16 --cpus 8 shell\nagent-vm --reset claude # re-cloner depuis l\'image', | |
| 202 | 删除: }, | |
| 203 | 删除: { | |
| 204 | 删除: title: 'Partager des secrets entre VM', | |
| 205 | 删除: body: 'Des lignes `CLÉ=valeur` dans `~/.agent-vm/env`, poussées dans chaque VM à chaque commande. Tout ce qui tourne dans la VM peut les lire : mets-y des jetons étroits et révocables. Passe par `env set` : une seule apostrophe mal placée casse tout le fichier.', | |
| 206 | 删除: code: 'agent-vm env set GH_TOKEN # masqué, hors historique\nagent-vm env list # les noms, jamais les valeurs\nagent-vm env has ANTHROPIC_API_KEY\n\n# limité à ce projet\nagent-vm project-env set SOME_PATH ./config', | |
| 207 | 删除: }, | |
| 208 | 删除: { | |
| 209 | 删除: title: 'Éditer avec les outils de la VM', | |
| 210 | 删除: body: 'Pour les serveurs de langage, les linters, le débogueur et les paquets de la VM, fais tourner l\'éditeur dans la VM : `agent-vm code` sert VS Code (code-server) dans un onglet du navigateur, seule partie sur ta machine. Il s\'installe avec `code-server` ou un nom `code-*` ([Ce qu\'il y a dans la VM](#what-is-in-the-vm)). L\'onglet peut toujours ouvrir des liens, et chaque VM peut y envoyer ton navigateur, d\'où un mot de passe et un nom d\'hôte par VM ([Réseau et ports](#network-and-ports)). N\'y branche pas plutôt un éditeur de bureau en SSH ([SSH depuis ta machine](#ssh-from-your-machine)).', | |
| 211 | 删除: code: 'agent-vm setup --preinstall=default,code-claude # une fois\nagent-vm code # affiche l\'adresse et le mot de passe\n # Ctrl-C arrête l\'éditeur', | |
| 212 | 删除: }, | |
| 213 | 删除: ], | |
| 214 | 删除: gitTitle: 'Laisser l\'agent commiter', | |
| 215 | 删除: gitBody: | |
| 216 | 删除: 'git lit son identité dans l\'environnement : le fichier d\'env partagé suffit, sans aucun `git config` dans la VM. Les quatre variables sont nécessaires, car git exige un committer et pas seulement un auteur.', | |
| 217 | 删除: gitCode: | |
| 218 | 删除: '# ~/.agent-vm/env\nGIT_AUTHOR_NAME=Ton Nom\[email protected]\nGIT_COMMITTER_NAME=Ton Nom\[email protected]', | |
| 219 | 删除: gitNote: | |
| 220 | 删除: 'Ces variables passent avant `git config`, dans tous les dépôts de la VM : pour une identité par dépôt, règle plutôt `user.name` et `user.email` depuis un script de runtime. `gh` lit `GH_TOKEN` de lui-même, donc `gh pr create` fonctionne sans rien d\'autre. Un `git push` en HTTPS a besoin, lui, d\'un credential helper : une ligne `gh auth setup-git` dans ton [script de runtime](#customisation-files).', | |
| 221 | 删除: }, | |
| 222 | 删除: | |
| 223 | 删除: reference: { | |
| 224 | 删除: eyebrow: 'Référence', | |
| 225 | 删除: title: 'Chaque commande, option et fichier.', | |
| 226 | 删除: lede: 'Ce que les sections précédentes laissent de côté : toutes les commandes, les fichiers et variables de configuration, et ce sur quoi un script peut compter.', | |
| 227 | 删除: commandGroups: [ | |
| 228 | 删除: { | |
| 229 | 删除: title: 'Lancer un agent', | |
| 230 | 删除: rows: [ | |
| 231 | 删除: ['opencode [args]', 'Lance OpenCode avec `--auto`.'], | |
| 232 | 删除: ['claude [args]', 'Lance Claude Code avec `--dangerously-skip-permissions`.'], | |
| 233 | 删除: ['codex [args]', 'Lance Codex CLI avec `--dangerously-bypass-approvals-and-sandbox`.'], | |
| 234 | 删除: ['vibe [args]', 'Lance Mistral Vibe avec `--agent auto-approve`.'], | |
| 235 | 删除: ['pi [args]', 'Lance Pi, qui ne demande aucune permission.'], | |
| 236 | 删除: ], | |
| 237 | 删除: }, | |
| 238 | 删除: { | |
| 239 | 删除: title: 'Entrer dans la VM', | |
| 240 | 删除: rows: [ | |
| 241 | 删除: ['shell, sh', 'Ouvre un shell zsh dans la VM. `-c "…"` exécute une commande unique via un shell de connexion.'], | |
| 242 | 删除: ['run <cmd> [args]', 'Exécute une commande sans shell. `--tty` alloue un PTY pour les TUI.'], | |
| 243 | 删除: ['code', 'Sert VS Code (code-server) depuis la VM à `http://<nom-de-vm>.localhost:<port>/`, jusqu\'à Ctrl-C, à ouvrir dans ton navigateur. Son mot de passe est créé dans la VM à la première utilisation, puis affiché avec l\'adresse. Demande `code-server` ou un nom `code-*` au setup ([Ce qu\'il y a dans la VM](#what-is-in-the-vm)).'], | |
| 244 | 删除: ], | |
| 245 | 删除: }, | |
| 246 | 删除: { | |
| 247 | 删除: title: 'Gérer le parc', | |
| 248 | 删除: rows: [ | |
| 249 | 删除: ['list, status', 'Liste toutes les VM agent-vm, celle du dossier courant marquée d\'un `>`, avec la version d’agent-vm qui a construit la base dont chacune est clonée, et sa date.'], | |
| 250 | 删除: ['stop [vm-name]', 'Arrête la VM de ce dossier, ou celle dont tu donnes le nom. Le disque est conservé.'], | |
| 251 | 删除: ['rm [vm-name]', 'Arrête et supprime. Un nom issu de `list` permet de viser une VM dont le dossier a disparu.'], | |
| 252 | 删除: ['destroy-all', 'Arrête et supprime toutes les VM agent-vm, image de base comprise. `setup` la reconstruit.'], | |
| 253 | 删除: ['doctor', 'Vérifie l\'hôte, l\'image de base, tes fichiers de réglages et ce dossier, et dit quoi lancer. Ne modifie rien.'], | |
| 254 | 删除: ], | |
| 255 | 删除: }, | |
| 256 | 删除: { | |
| 257 | 删除: title: 'Installer et configurer', | |
| 258 | 删除: rows: [ | |
| 259 | 删除: ['install', 'Met `agent-vm` dans ton `PATH` : un lien vers le binaire qui le lance, dans `~/.local/bin`. L\'installeur curl le lance pour toi.'], | |
| 260 | 删除: ['uninstall', 'Retire ce lien. Les VM et `~/.agent-vm` restent.'], | |
| 261 | 删除: ['setup', 'Construit l\'image de base. `--preinstall=LIST` saute l\'assistant ([Ce qu\'il y a dans la VM](#what-is-in-the-vm)) ; `--disk`, `--memory` et `--cpus` la dimensionnent.'], | |
| 262 | 删除: ['env <sub>', '`set`, `get`, `has`, `unset`, `list` sur les secrets partagés par toutes les VM.'], | |
| 263 | 删除: ['project-env <sub>', 'Mêmes sous-commandes, limitées à ce projet. Prime sur le fichier partagé.'], | |
| 264 | 删除: ['help', 'Affiche l\'aide intégrée.'], | |
| 265 | 删除: ], | |
| 266 | 删除: }, | |
| 267 | 删除: { | |
| 268 | 删除: title: 'Interroger, depuis un script', | |
| 269 | 删除: rows: [ | |
| 270 | 删除: ['version', 'Affiche la version. `--min X.Y.Z` la vérifie au lieu de l\'afficher.'], | |
| 271 | 删除: ['info [dir]', 'État lisible par un programme, une paire `clé=valeur` par ligne.'], | |
| 272 | 删除: ['name [dir]', 'Affiche le nom de VM d\'un dossier. Par défaut, le dossier courant.'], | |
| 273 | 删除: ], | |
| 274 | 删除: }, | |
| 275 | 删除: ], | |
| 276 | 删除: optionsTitle: 'Options de VM', | |
| 277 | 删除: optionsNote: 'Pour `claude`, `opencode`, `codex`, `vibe`, `pi`, `shell`, `run` et `code`, à placer avant la commande ou juste après son nom. Tout ce qui suit appartient à la commande : dans `agent-vm run docker run --rm x`, `--rm` est l\'option de docker.', | |
| 278 | 删除: optionsHeaders: ['Option', 'Rôle', 'Défaut'], | |
| 279 | 删除: options: [ | |
| 280 | 删除: ['--disk GB', 'Taille du disque. Peut grandir, jamais rétrécir.', 'celle de l\'image (10)'], | |
| 281 | 删除: ['--memory GB', 'Mémoire de la VM. Plafonnée à la moitié de l\'hôte, par VM.', 'celle de l\'image (3, ou 4 avec code-server choisi dans l\'assistant)'], | |
| 282 | 删除: ['--cpus N', 'Nombre de CPU. Plafonné à la moitié de l\'hôte, par VM.', 'celui de l\'image (1)'], | |
| 283 | 删除: ['--ssh-port N', 'Port fixe sur l\'hôte pour le SSH de la VM, pour les outils qui l\'enregistrent. `0` revient à un nouveau port à chaque démarrage. Redémarre une VM en marche, après confirmation.', 'un nouveau par démarrage'], | |
| 284 | 删除: ['--reset', 'Détruit la VM et la re-clone depuis l\'image de base.', 'inactif'], | |
| 285 | 删除: ['--readonly', 'Tous les partages de l\'hôte en lecture seule, projet et volumes. Redémarre une VM en marche, après confirmation.', 'inactif'], | |
| 286 | 删除: ['--unsafe-writable-git', 'Laisse chaque `.git` modifiable pour que l\'agent puisse commiter, avec un avertissement. Voir [Protéger .git](#git).', 'inactif'], | |
| 287 | 删除: ['--unsafe-disable-security-prompts', 'Continue là où un démarrage s\'arrêterait sur une question de sécurité (voir [Protéger .git](#git)). Les avertissements restent affichés. Équivaut à `AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS=1`.', 'inactif'], | |
| 288 | 删除: ['--rm', 'Détruit la VM dès que la commande se termine.', 'inactif'], | |
| 289 | 删除: ['--scratch', 'Une nouvelle VM où rien de ce qui est à toi n\'est monté, supprimée à la fin de la commande (après confirmation sur un terminal). `~/.agent-vm/env` et `runtime.sh` y entrent, les fichiers du projet non. Plusieurs peuvent tourner en même temps.', 'inactif'], | |
| 290 | 删除: ], | |
| 291 | 删除: envTitle: 'Variables d\'environnement', | |
| 292 | 删除: envNote: 'Lues dans ton shell, jamais dans un fichier du projet.', | |
| 293 | 删除: envHeaders: ['Variable', 'Rôle', 'Défaut'], | |
| 294 | 删除: env: [ | |
| 295 | 删除: ['AGENT_VM_STATE_DIR', 'Déplace `~/.agent-vm`, VM comprises, pour des tests, la CI ou une seconde installation, sans déplacer `HOME`.', '~/.agent-vm'], | |
| 296 | 删除: ['AGENT_VM_LIMA_HOME', 'Où vivent les VM. Pas le dossier de ton propre Lima : agent-vm garde ses VM à part.', '~/.agent-vm/lima'], | |
| 297 | 删除: ['AGENT_VM_PROJECT_ENV', 'Le fichier d\'env du projet, relatif au projet ou absolu.', '.agent-vm.env'], | |
| 298 | 删除: ['AGENT_VM_PROJECT_RUNTIME', 'Le script de runtime du projet, relatif au projet ou absolu. Hors du projet, c\'est l\'hôte qui le lit.', '.agent-vm.runtime.sh'], | |
| 299 | 删除: ['AGENT_VM_HOST_SHARE', 'CPU et mémoire par VM sont plafonnés à ceux de l\'hôte divisés par ce nombre. `1` : tout l\'hôte.', '2'], | |
| 300 | 删除: ['AGENT_VM_BIN_DIR', 'Où `install` place le lien `agent-vm`.', '~/.local/bin'], | |
| 301 | 删除: ['AGENT_VM_SSHFS_CACHE', '`1` : sshfs met aussi en cache les partages modifiables, plus rapide sur beaucoup de fichiers (`git status`, `find`) ; la VM peut alors voir un fichier tel qu\'il était jusqu\'à 20 secondes avant, et le réécrire ainsi. S\'applique au prochain démarrage d\'une VM.', 'non définie'], | |
| 302 | 删除: ['AGENT_VM_NOTIFY', '`0` : pas de notification quand un port est redirigé, ou laissé à un de tes programmes.', 'non définie'], | |
| 303 | 删除: ['AGENT_VM_GUARDED_WRITES', '`deny` : refuse sans demander les écritures de la VM dans les [fichiers surveillés](#guarded-files), pour une machine sans personne devant l\'écran.', 'non définie'], | |
| 304 | 删除: ['AGENT_VM_UNSAFE_OPEN_NETWORK', '`1` : pas d\'[isolation réseau](#network-and-ports) : les VM atteignent ta machine et tes réseaux locaux. S\'applique au prochain démarrage d\'une VM.', 'non définie'], | |
| 305 | 删除: ['AGENT_VM_UNSAFE_WRITABLE_GIT', '`1` : équivaut à `--unsafe-writable-git`.', 'non définie'], | |
| 306 | 删除: ['AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS', '`1` : équivaut à `--unsafe-disable-security-prompts`.', 'non définie'], | |
| 307 | 删除: ], | |
| 308 | 删除: customTitle: 'Fichiers de personnalisation', | |
| 309 | 删除: customLede: | |
| 310 | 删除: 'Huit fichiers facultatifs, aucun n\'est nécessaire pour démarrer. Ceux propres à l\'utilisateur sont dans `~/.agent-vm/`, ceux propres à un projet dans le projet lui-même.', | |
| 311 | 删除: customTable: { | |
| 312 | 删除: headers: ['Fichier', 'Portée', 'Quand'], | |
| 313 | 删除: rows: [ | |
| 314 | 删除: ['~/.agent-vm/env', 'Toutes les VM', 'Copié à chaque lancement'], | |
| 315 | 删除: ['~/.agent-vm/volumes', 'Toutes les VM, ou les projets qu\'une entrée désigne', 'Monté à la création de la VM'], | |
| 316 | 删除: ['~/.agent-vm/network', 'Toutes les VM : ce qu\'elles peuvent atteindre ([Réseau et ports](#network-and-ports))', 'Lu au démarrage d\'une VM'], | |
| 317 | 删除: ['~/.agent-vm/guarded', 'Toutes les VM : les fichiers sur lesquels demander ([Fichiers surveillés](#guarded-files))', 'Lu au démarrage d\'une VM'], | |
| 318 | 删除: ['~/.agent-vm/setup.sh', 'Image de base', 'Une fois, pendant agent-vm setup'], | |
| 319 | 删除: ['~/.agent-vm/runtime.sh', 'Toutes les VM', 'À chaque commande qui entre dans une VM, en premier'], | |
| 320 | 删除: ['.agent-vm.runtime.sh', 'Un seul projet', 'À chaque commande qui entre dans sa VM, après le global'], | |
| 321 | 删除: ['.agent-vm.env', 'Un seul projet', 'Copié après l\'env partagé, et prioritaire sur lui'], | |
| 322 | 删除: ], | |
| 323 | 删除: }, | |
| 324 | 删除: volumesTitle: 'Montages en plus : ~/.agent-vm/volumes', | |
| 325 | 删除: volumesBody: | |
| 326 | 删除: 'Une ligne `source[:destination][:mode][:projet]` par montage, `~` développé à gauche, `#` pour les commentaires. Le mode est `ro` (par défaut) ou `rw`, et `rw` ne marche que pour les dossiers. Sans destination, le chemin est monté au même endroit dans la VM ; une destination relative est dans le projet. Le quatrième champ limite l\'entrée aux projets qu\'il désigne, `*` couvrant n\'importe quoi.', | |
| 327 | 删除: volumesCode: | |
| 328 | 删除: '# ~/.agent-vm/volumes\n~/.gitconfig # même chemin, lecture seule\n~/.cache/shared:/home/you.guest/.cache/shared:rw\n\n# seulement dans ~/work/webapp, en .claude, lecture seule\n~/.claude-vm/webapp:.claude:ro:~/work/webapp\n\n# tous les projets sous ~/work\n~/.cache/pip:/home/you.guest/.cache/pip:rw:~/work/*\n\n# même chemin, un seul projet\n~/datasets::ro:~/work/ml', | |
| 329 | 删除: volumesNote: | |
| 330 | 删除: 'La liste reste de ton côté, pas dans le projet : l\'agent écrit dans le projet, et pourrait sinon monter n\'importe quel dossier de l\'hôte dans sa VM. Une destination relative qui sort du projet, par `..` ou un lien symbolique, est ignorée. Les changements valent pour les nouvelles VM : `--reset` les réapplique.', | |
| 331 | 删除: nodeTitle: 'Node.js : node_modules dans la VM', | |
| 332 | 删除: nodeBody: | |
| 333 | 删除: 'Des centaines de milliers de fichiers sont lents à travers le partage, et les paquets natifs diffèrent de toute façon entre macOS et Linux. Monte un dossier du disque de la VM par-dessus `node_modules` depuis le [script de runtime](#customisation-files) du projet, lancé à chaque commande :', | |
| 334 | 删除: nodeCode: | |
| 335 | 删除: '#!/bin/bash\n# .agent-vm.runtime.sh\nset -e\nmkdir -p "$HOME/node_modules" node_modules\nmountpoint -q node_modules ||\n sudo mount --bind "$HOME/node_modules" node_modules', | |
| 336 | 删除: nodeNote: 'L\'hôte voit un `node_modules` vide, ou garde le sien : installe aussi de ce côté si ton éditeur a besoin des paquets. Dans un workspace, répète le montage pour un paquet qui a un gros `node_modules` à lui. Un serveur de dev dans la VM peut avoir besoin du polling pour voir les modifications faites sur l\'hôte (Vite : `server.watch.usePolling`).', | |
| 337 | 删除: scriptsTitle: 'Depuis un script', | |
| 338 | 删除: scriptsParas: [ | |
| 339 | 删除: 'Passe par ces commandes plutôt que de parser la sortie destinée aux humains ou de lire `~/.agent-vm` : les noms de VM et les fichiers d\'état sont des détails d\'implémentation. Aucune ne démarre de VM.', | |
| 340 | 删除: '`version --min` renvoie `0` si la version suffit, `1` si elle est plus ancienne, `2` pour un appel mal formé ; un moteur antérieur à `--min` l\'ignore et renvoie `0`. Dans `info`, les booléens valent `1` ou `0`, `unknown` quand c\'est indéterminable, et `base_exists=1` veut dire que l\'image est utilisable.', | |
| 341 | 删除: 'Un démarrage ne pose ses questions que si la sortie d\'erreur est un terminal : sinon, il s\'arrête là. `security_questions` dans `info` les nomme à l\'avance (`hooks`, `git-config`, `bare-repo` ou `none`), et `--unsafe-disable-security-prompts` les accepte une fois l\'accord de l\'utilisateur obtenu.', | |
| 342 | 删除: ], | |
| 343 | 删除: scriptsCode: | |
| 344 | 删除: 'agent-vm version --min 0.2.0 || exit 1 # silencieux si OK\nagent-vm name [dir] # nom de la VM d\'un dossier\nagent-vm info [dir] # une paire clé=valeur par ligne\n\n# clés de info : version, template, state_dir,\n# project_env, dir, vm_name, base_exists,\n# vm_exists, vm_running, vm_stale,\n# ssh_host, ssh_config, git_protected,\n# security_questions', | |
| 345 | 删除: groups: [ | |
| 346 | 删除: { | |
| 347 | 删除: title: 'Installation et mise à jour', | |
| 348 | 删除: topics: [ | |
| 349 | 删除: { | |
| 350 | 删除: title: 'Options de l\'installeur', | |
| 351 | 删除: paras: [ | |
| 352 | 删除: 'Les options se placent après `sh -s --` : `--version X.Y.Z`, `--git` pour un clone de `main`, `--dir DIR` au lieu de `~/.local/share/agent-vm`. Pour lire l\'installeur d\'abord, télécharge-le, puis lance-le avec `sh`.', | |
| 353 | 删除: ], | |
| 354 | 删除: list: [], | |
| 355 | 删除: code: 'curl -fsSL https://www.agent-vm.org/install.sh |\n sh -s -- --dir ~/tools/agent-vm\n\n# le lire d\'abord\ncurl -fsSLO https://www.agent-vm.org/install.sh\nsh install.sh', | |
| 356 | 删除: }, | |
| 357 | 删除: { | |
| 358 | 删除: title: 'Mettre à jour', | |
| 359 | 删除: paras: [ | |
| 360 | 删除: 'Relance l\'installeur curl, `brew upgrade agent-vm`, ou `git pull && ./agent-vm.sh install` dans un clone. `agent-vm uninstall` retire le lien ; les VM et `~/.agent-vm` restent.', | |
| 361 | 删除: 'Relancer `setup` reconstruit l\'image de base, pas les VM qui en sont clonées : agent-vm les signale, et `--reset` en reclone une. Son journal complet est dans `~/.agent-vm/setup.log`.', | |
| 362 | 删除: ], | |
| 363 | 删除: list: [], | |
| 364 | 删除: code: '', | |
| 365 | 删除: }, | |
| 366 | 删除: { | |
| 367 | 删除: title: 'Depuis la 0.2', | |
| 368 | 删除: paras: [ | |
| 369 | 删除: 'Lima est intégré : le Lima de Homebrew, ou la version de Lima installée par la 0.2, peut partir, sauf si tu t\'en sers pour tes propres VM. agent-vm garde ses VM dans `~/.agent-vm/lima`, à l\'écart des tiennes, et les nomme sans le préfixe `agent-vm-` : `ton-projet-1a2b3c4d`, et `base` pour l\'image.', | |
| 370 | 删除: 'La première commande qui a besoin des VM propose de déplacer celles de la 0.2 depuis `~/.lima` (ou `$LIMA_HOME`), en arrêtant d\'abord celles qui tournent : elles gardent leurs disques, partages et réglages. Si tu refuses, agent-vm redemande la fois suivante ; sans terminal pour demander, il les déplace. `doctor` et `info` se contentent de regarder, et disent s\'il en reste à déplacer.', | |
| 371 | 删除: 'Pour mettre à jour, relance l\'installeur curl, ou `git pull && ./agent-vm.sh install` dans un clone (Go nécessaire) : le lien de ton `PATH` mène alors au binaire. D\'ici là, le lien de la 0.2 vers `agent-vm.sh` continue de marcher (dans un clone, après un `git pull`, il compile d\'abord agent-vm), tout comme une ligne de ton fichier rc qui le source, dont `install` signale qu\'elle peut partir. Une VM issue d\'une base construite par la 0.1.0 ne démarre plus : lance `agent-vm setup`, puis `--reset`.', | |
| 372 | 删除: ], | |
| 373 | 删除: list: [], | |
| 374 | 删除: code: '', | |
| 375 | 删除: }, | |
| 376 | 删除: { | |
| 377 | 删除: title: 'Windows et WSL', | |
| 378 | 删除: paras: [ | |
| 379 | 删除: 'Sous Windows, agent-vm tourne nativement, depuis PowerShell ou Git Bash, avec QEMU ; c\'est expérimental. Tes dossiers y sont `C:/Users/toi/projet`, et `/c/Users/toi/projet` dans la VM, comme avec la 0.2. Le fichier des volumes accepte `C:/x` ou `C:\\x`, et le `/c/x` de la 0.2.', | |
| 380 | 删除: 'Les VM ont besoin de la fonctionnalité Windows Hypervisor Platform. Elle est désactivée par défaut et seul un administrateur peut l\'activer, une fois, dans les Fonctionnalités de Windows ou avec la commande ci-dessous, puis un redémarrage. Sur un portable géré, c\'est une demande au service informatique. Un démarrage qui échoue faute d\'elle le dit.', | |
| 381 | 删除: 'WSL2, c\'est Linux pour agent-vm, et ses VM ont besoin de KVM, que WSL2 n\'a qu\'avec la virtualisation imbriquée transmise par l\'hôte Windows. WSL1 ne peut pas faire tourner de VM.', | |
| 382 | 删除: ], | |
| 383 | 删除: list: [], | |
| 384 | 删除: code: '# dans PowerShell en administrateur, puis redémarrer\nDISM /Online /Enable-Feature `\n /FeatureName:HypervisorPlatform /All', | |
| 385 | 删除: }, | |
| 386 | 删除: { | |
| 387 | 删除: title: 'Chemins', | |
| 388 | 删除: paras: [ | |
| 389 | 删除: 'Les chemins avec un espace, un guillemet, une barre oblique inverse, un caractère de contrôle, `{{` (Lima le lit comme un modèle) ou des octets qui ne sont pas de l\'UTF-8 sont refusés. Les chemins d\'iCloud Drive contiennent des espaces : passe par un lien symbolique. Un nom de dossier trop long pour les chemins de sockets de Lima est raccourci dans le nom de la VM, qui garde l\'empreinte du chemin complet.', | |
| 390 | 删除: ], | |
| 391 | 删除: list: [], | |
| 392 | 删除: code: 'ln -s ~/Library/Mobile\\ Documents/com~apple~CloudDocs/Dev \\\n ~/Dev\ncd ~/Dev/ton-projet && agent-vm claude', | |
| 393 | 删除: }, | |
| 394 | 删除: { | |
| 395 | 删除: title: 'Ports et doctor', | |
| 396 | 删除: paras: [ | |
| 397 | 删除: 'Un port fixé avec `--ssh-port` reste jusqu\'à `--reset` ou `rm`. `doctor` n\'affiche aucun secret : sa sortie peut aller telle quelle dans une issue.', | |
| 398 | 删除: ], | |
| 399 | 删除: list: [], | |
| 400 | 删除: code: '', | |
| 401 | 删除: }, | |
| 402 | 删除: ], | |
| 403 | 删除: }, | |
| 404 | 删除: { | |
| 405 | 删除: title: 'Agents et configuration', | |
| 406 | 删除: topics: [ | |
| 407 | 删除: { | |
| 408 | 删除: title: 'Comment chaque agent est lancé', | |
| 409 | 删除: paras: [ | |
| 410 | 删除: 'Claude Code reçoit aussi le mode sans confirmation par des réglages gérés, car il perd l\'option quand il se relance lui-même ([#72479](https://github.com/anthropics/claude-code/issues/72479)). Pour Pi, setup règle `defaultProjectTrust: "always"`.', | |
| 411 | 删除: 'Connecte-toi dans la VM (`claude login`, `gh auth login`) : la connexion reste dans cette VM. Monter tes identifiants de l\'hôte les donnerait à tout ce qui y tourne.', | |
| 412 | 删除: 'Un terminal en couleurs 24 bits qui ne définit pas `COLORTERM` (Terminal.app sous macOS 26) a besoin de `export COLORTERM=truecolor`.', | |
| 413 | 删除: ], | |
| 414 | 删除: list: [], | |
| 415 | 删除: code: '', | |
| 416 | 删除: }, | |
| 417 | 删除: { | |
| 418 | 删除: title: 'Serveurs MCP', | |
| 419 | 删除: paras: [ | |
| 420 | 删除: 'Playwright MCP utilise le Chromium de la VM et ne télécharge aucun navigateur. Pour un autre moteur, modifie son entrée (retire `--executable-path`, ajoute `--browser firefox`) et lance `npx playwright install firefox`. Ajoute tes propres serveurs à `mcpServers` dans `~/.claude.json`, depuis `~/.agent-vm/setup.sh` ou dans une VM.', | |
| 421 | 删除: ], | |
| 422 | 删除: list: [], | |
| 423 | 删除: code: '{\n "mcpServers": {\n "postgres": {\n "command": "npx",\n "args": [\n "-y",\n "@modelcontextprotocol/server-postgres",\n "postgresql://localhost:5432/mydb"\n ]\n }\n }\n}', | |
| 424 | 删除: }, | |
| 425 | 删除: { | |
| 426 | 删除: title: 'Les fichiers d\'environnement', | |
| 427 | 删除: paras: [ | |
| 428 | 删除: 'agent-vm ne connaît aucun des noms : `gh` lit `GH_TOKEN`, Claude Code `ANTHROPIC_API_KEY`, Codex `OPENAI_API_KEY`, Vibe `MISTRAL_API_KEY`. Une modification n\'a pas besoin de `--reset`.', | |
| 429 | 删除: 'Le `.agent-vm.env` du projet est poussé après le fichier partagé et l\'emporte. Il est dans un dépôt, donc pas de secret dedans : `project-env set` affiche la ligne qui l\'ignore dans git.', | |
| 430 | 删除: '`get` et `has` lisent le fichier sans l\'exécuter, et sortent avec le code `2` sur une valeur qui demande un shell. `set` sans valeur te la fait taper sans l\'afficher, hors de l\'historique de ton shell.', | |
| 431 | 删除: ], | |
| 432 | 删除: list: [], | |
| 433 | 删除: code: '', | |
| 434 | 删除: }, | |
| 435 | 删除: { | |
| 436 | 删除: title: 'Montages supplémentaires, en détail', | |
| 437 | 删除: paras: [ | |
| 438 | 删除: 'Une destination est prise telle quelle, sans `~` : le dossier personnel dans la VM est `/home/<toi>.guest` (`.linux` avant Lima 2.1). Une source absente est ignorée, avec un avertissement.', | |
| 439 | 删除: 'Un fichier seul est lié en dur dans `~/.agent-vm/file-mounts/<vm>/` puis monté. D\'un système de fichiers à l\'autre, il est copié, et les modifications de l\'hôte attendent le démarrage suivant.', | |
| 440 | 删除: ], | |
| 441 | 删除: list: [], | |
| 442 | 删除: code: '# ~/.agent-vm/volumes : tes instructions et skills Claude,\n# pas tout ~/.claude, qui contient ta connexion sous Linux\n~/.claude/CLAUDE.md:/home/toi.guest/.claude/CLAUDE.md\n~/.claude/skills:/home/toi.guest/.claude/skills', | |
| 443 | 删除: }, | |
| 444 | 删除: { | |
| 445 | 删除: title: 'Scripts de setup et de runtime', | |
| 446 | 删除: paras: [ | |
| 447 | 删除: '`~/.agent-vm/setup.sh` tourne une fois dans l\'image, à la fin de `setup`, sous zsh avec sudo. `~/.agent-vm/runtime.sh`, puis le `.agent-vm.runtime.sh` du projet, tournent à chaque commande qui entre dans la VM : les deux doivent pouvoir être relancés. [`runtime.example.sh`](https://github.com/sylvinus/agent-vm/blob/main/runtime.example.sh) couvre l\'identité git, `gh auth setup-git`, les skills et les serveurs MCP.', | |
| 448 | 删除: 'Ils sont lus sur l\'entrée standard : donne `</dev/null` à une commande qui la lit. Pas de clé privée dedans, l\'agent peut lire ce qu\'ils mettent en place.', | |
| 449 | 删除: ], | |
| 450 | 删除: list: [], | |
| 451 | 删除: code: '# .agent-vm.runtime.sh\nmise install\nnpm install\ndocker compose up -d', | |
| 452 | 删除: }, | |
| 453 | 删除: ], | |
| 454 | 删除: }, | |
| 455 | 删除: ], | |
| 456 | 删除: }, | |
| 457 | 删除: | |
| 458 | 删除: security: { | |
| 459 | 删除: eyebrow: 'Sécurité', | |
| 460 | 删除: title: 'Ce qui traverse la frontière.', | |
| 461 | 删除: lede: 'La VM ne peut pas sortir de ses partages. Reste ce qui les traverse : le dossier du projet, que l\'agent écrit et que ta machine lit, le terminal et le réseau.', | |
| 462 | 删除: groups: [ | |
| 463 | 删除: { | |
| 464 | 删除: id: 'git', | |
| 465 | 删除: title: 'Protéger .git', | |
| 466 | 删除: topics: [ | |
| 467 | 删除: { | |
| 468 | 删除: title: 'Pourquoi .git', | |
| 469 | 删除: paras: [ | |
| 470 | 删除: 'Git, sur ta machine, exécute ce que désignent le `.git/config` et les hooks d\'un dépôt : `core.fsmonitor` à chaque `git status`, les hooks au commit. Ton éditeur et ton prompt lancent `git status` d\'eux-mêmes : une VM capable d\'écrire dans `.git` pourrait lancer des commandes sur ton hôte en quelques secondes, sans que rien n\'apparaisse dans `git diff`.', | |
| 471 | 删除: 'Chaque `.git` et `.hg` des partages est en lecture seule pour la VM, à toute profondeur, et c\'est le serveur SFTP intégré à agent-vm, sur ta machine, qui l\'impose (le `sshfs.readonlyNames` de Lima, pas encore intégré en amont : [lima-vm/lima#5529](https://github.com/lima-vm/lima/issues/5529)). L\'agent lit l\'historique mais ne peut pas commiter. Les partages sont en `reverse-sshfs`, plus lent sur beaucoup de fichiers (voir [Node.js](#node)), et sans le cache de sshfs sur ceux qui sont modifiables, pour que la VM ne réécrive jamais un fichier tel qu\'il était avant que tu le changes : `AGENT_VM_SSHFS_CACHE=1` échange cela contre de la vitesse.', | |
| 472 | 删除: ], | |
| 473 | 删除: list: [], | |
| 474 | 删除: code: 'agent-vm doctor # où tu en es\n\n# laisser l\'agent commiter quand même\nagent-vm --unsafe-writable-git claude', | |
| 475 | 删除: }, | |
| 476 | 删除: { | |
| 477 | 删除: title: 'Au-delà du nom .git', | |
| 478 | 删除: paras: [ | |
| 479 | 删除: 'Le dossier vers lequel pointe un `core.hooksPath` dans un partage (`.husky` pour husky) est aussi en lecture seule, comme un lien sur le chemin qui y mène, et de même pour les dépôts de tes volumes modifiables. Un dossier qui contient les fichiers internes de git (`HEAD`, `objects/`, `refs/`, un `config`) est un dépôt sous n\'importe quel nom : régler `safe.bareRepository` à `explicit` dans ta config git globale le fait ignorer par git, et celui d\'un volume modifiable est en lecture seule par son nom. Une config incluse depuis un partage, une commande ou un hook que git y lance, ou des hooks à la racine d\'un partage, ouvrent la même porte.', | |
| 480 | 删除: 'Avant de démarrer une VM aux partages modifiables, agent-vm s\'arrête sur chacun de ceux qu\'il trouve, pour demander : Entrée, ou l\'absence de terminal, annule. `doctor` les liste. `--unsafe-writable-git` (ou `AGENT_VM_UNSAFE_WRITABLE_GIT=1` dans ton shell, jamais lu depuis le projet) laisse l\'agent commiter et rouvre ce chemin vers ton hôte, avec un avertissement à chaque lancement.', | |
| 481 | 删除: ], | |
| 482 | 删除: list: [], | |
| 483 | 删除: code: '', | |
| 484 | 删除: }, | |
| 485 | 删除: { | |
| 486 | 删除: title: 'Lima, intégré', | |
| 487 | 删除: paras: [ | |
| 488 | 删除: 'agent-vm compile Lima, son serveur SFTP (sshocker et pkg/sftp) et sa pile réseau (gvisor-tap-vsock) depuis leurs sources amont, avec des [correctifs](https://github.com/sylvinus/agent-vm/blob/main/patches/README.md) assez petits pour être proposés en amont : les noms en lecture seule, des corrections du serveur SFTP (un ajout en fin de fichier qui faisait tomber la VM, des écritures appliquées dans le désordre), l\'isolation réseau, la vérification des ports. Chaque VM en marche est servie par un processus agent-vm, qui est l\'agent hôte de Lima.', | |
| 489 | 删除: 'Chaque partage est servi par le serveur SFTP intégré, cantonné à son dossier : agent-vm ne démarre aucune VM dont la config dit autre chose, quoi qui l\'ait réglée. Un `default.yaml` ou `override.yaml` dans `~/.agent-vm/lima/_config` s\'ajouterait à la config de chaque VM : agent-vm ne démarre aucune VM tant qu\'il y en a un.', | |
| 490 | 删除: ], | |
| 491 | 删除: list: [], | |
| 492 | 删除: code: '', | |
| 493 | 删除: }, | |
| 494 | 删除: ], | |
| 495 | 删除: }, | |
| 496 | 删除: { | |
| 497 | 删除: title: 'Ce que fait agent-vm', | |
| 498 | 删除: topics: [ | |
| 499 | 删除: { | |
| 500 | 删除: title: 'Dossiers et fichiers refusés', | |
| 501 | 删除: paras: [ | |
| 502 | 删除: 'agent-vm ne partage ni ton dossier personnel, ni `/`, ni son propre dossier, ni `~/.agent-vm`, ni le dossier de ton propre Lima (`~/.lima`), ni un dossier qui en contient un : `cd ~ && agent-vm shell` donnerait à la VM tes fichiers de configuration et tes clés SSH. `--unsafe-disable-security-prompts` lui fait partager son propre dossier, pour travailler sur agent-vm depuis un clone : la VM peut alors modifier l\'agent-vm que ta machine lance.', | |
| 503 | 删除: 'Il ne lit jamais un fichier du projet par son chemin, puisque la VM peut en faire un lien vers n\'importe lequel de tes fichiers. Ses propres appels à git dans un projet refusent un dépôt nu et ne lancent ni `core.fsmonitor` ni pager.', | |
| 504 | 删除: ], | |
| 505 | 删除: list: [], | |
| 506 | 删除: code: '', | |
| 507 | 删除: }, | |
| 508 | 删除: { | |
| 509 | 删除: title: '--readonly, en détail', | |
| 510 | 删除: paras: [ | |
| 511 | 删除: '`--readonly` couvre tous les partages, volumes `rw` compris : un volume accessible en écriture contenant le projet serait une seconde entrée. Le serveur SFTP intégré l\'impose sur ta machine, et agent-vm vérifie la config de chaque VM avant son démarrage, jamais sur la parole de l\'invité.', | |
| 512 | 删除: 'Une VM en marche dans l\'autre mode est redémarrée, après confirmation. Refusé, ou sans terminal, la commande échoue : la VM en lecture seule d\'une autre session ne repasse jamais en écriture sous elle.', | |
| 513 | 删除: ], | |
| 514 | 删除: list: [], | |
| 515 | 删除: code: '', | |
| 516 | 删除: }, | |
| 517 | 删除: ], | |
| 518 | 删除: }, | |
| 519 | 删除: { | |
| 520 | 删除: title: 'Ce qui, sur ta machine, lit aussi le projet', | |
| 521 | 删除: topics: [ | |
| 522 | 删除: { | |
| 523 | 删除: title: 'La règle', | |
| 524 | 删除: paras: [ | |
| 525 | 删除: 'Tout ce qui, sur ta machine, lit le projet et agit selon ce qu\'il y trouve peut exécuter ce que l\'agent a écrit. agent-vm ferme les portes de git (voir [Protéger .git](#git)), mais ne peut pas verrouiller les fichiers que lisent tes autres outils sans empêcher l\'agent de travailler.', | |
| 526 | 删除: 'Donc, sur ta machine, ouvre le projet dans ton éditeur et utilise git dedans ; lance tout le reste dans la VM, avec `agent-vm run`. Les listes qui suivent sont des exemples, pas un inventaire.', | |
| 527 | 删除: ], | |
| 528 | 删除: list: [ | |
| 529 | 删除: 'Rien du tout : ce qui se lance quand tu fais `cd` dans le dossier, quand ton prompt se redessine, quand ton éditeur l\'ouvre. Le cas le plus dangereux.', | |
| 530 | 删除: 'Un geste que tu fais de toute façon : `git commit` lance des hooks rangés dans l\'arborescence, `docker compose up` monte ce que nomme le fichier compose.', | |
| 531 | 删除: 'Lancer du code du projet : `npm test`, `make`, un build. C\'est le code de l\'agent : lance-le dans la VM.', | |
| 532 | 删除: ], | |
| 533 | 删除: code: '', | |
| 534 | 删除: }, | |
| 535 | 删除: { | |
| 536 | 删除: title: 'Fichiers surveillés', | |
| 537 | 删除: paras: [ | |
| 538 | 删除: 'Pour le premier cas, agent-vm surveille les fichiers que ta machine exécute d\'elle-même : quand la VM en écrit, crée, renomme ou supprime un, à n\'importe quelle profondeur des partages, une fenêtre te demande d\'abord. Un oui vaut jusqu\'à l\'arrêt de la VM ; un non, une minute, après quoi une nouvelle tentative redemande. Là où aucune fenêtre ne peut s\'afficher (pas de session graphique), l\'écriture est refusée et une notification le dit ; une fenêtre restée sans réponse deux minutes la refuse aussi. `AGENT_VM_GUARDED_WRITES=deny` les refuse toutes sans demander.', | |
| 539 | 删除: 'Surveillés par défaut : `.envrc` (direnv), `.vscode/tasks.json`, `.vscode/settings.json` et `.vscode/launch.json` (VS Code), `.pre-commit-config.yaml` (pre-commit), `lefthook.yml` et `.lefthook.yml` (lefthook), `mise.toml` et `.mise.toml` (mise). Les fichiers que l\'agent modifie couramment, comme un `Makefile` ou un `package.json`, ne le sont pas : ajoute-les dans `~/.agent-vm/guarded`, un chemin par ligne, lu au démarrage d\'une VM. `!chemin` retire un fichier par défaut, et `*.ext` surveille une extension. Sur un hôte Windows, `*.library-ms`, `*.searchConnector-ms`, `*.lnk`, `*.url`, `*.scf` et `desktop.ini` le sont aussi : l\'Explorateur envoie ton empreinte NTLM au serveur qu\'ils nomment quand il les affiche. Il n\'y a pas de fenêtre de confirmation sous Windows : les écritures de la VM sur ces fichiers sont refusées.', | |
| 540 | 删除: ], | |
| 541 | 删除: list: [], | |
| 542 | 删除: code: '# ~/.agent-vm/guarded\nMakefile # demander avant que la VM change un Makefile\n.github/workflows/ci.yml\n!.vscode/settings.json # plus demandé', | |
| 543 | 删除: }, | |
| 544 | 删除: { | |
| 545 | 删除: title: 'Éditeurs et agents', | |
| 546 | 删除: paras: [ | |
| 547 | 删除: 'Un fichier suivi modifié apparaît dans `git diff`, un nouveau comme non suivi ; un fichier dans un chemin ignoré (`node_modules`, `.venv`, `target/`) n\'apparaît nulle part.', | |
| 548 | 删除: ], | |
| 549 | 删除: list: [ | |
| 550 | 删除: 'VS Code : ouvre les projets agent-vm en mode restreint, et n\'approuve pas un dossier parent. Un espace de travail approuvé exécute du code du projet par ses tâches et extensions : `eslint.config.js`, `vite.config.ts`, `build.rs`.', | |
| 551 | 删除: 'IDE JetBrains : « Preview in Safe Mode ». Un projet approuvé lance ses scripts Gradle ou Maven à l\'import.', | |
| 552 | 删除: 'Vim : laisse `exrc` désactivé. Neovim et Emacs demandent avant d\'exécuter la config d\'un projet.', | |
| 553 | 删除: 'Les agents sur ta machine lancent des commandes depuis les hooks de `.claude/settings.json`, `.mcp.json` ou `.cursor/` : relis-les, et considère `CLAUDE.md` et `AGENTS.md` comme écrits par la VM.', | |
| 554 | 删除: ], | |
| 555 | 删除: code: '', | |
| 556 | 删除: }, | |
| 557 | 删除: { | |
| 558 | 删除: title: 'SSH depuis ta machine', | |
| 559 | 删除: paras: [ | |
| 560 | 删除: 'Ne branche pas VS Code Remote-SSH ou open-remote-ssh sur une VM d\'agent. Ils font tourner un serveur dans la VM, que contrôle root dans la VM, et l\'éditeur sur ta machine lui fait confiance. La page de Remote-SSH chez Microsoft le dit : « a compromised remote could use the VS Code Remote connection to execute code on your local machine », et c\'est voulu. Des articles publics le montrent ouvrant un terminal sur l\'hôte et y lançant des commandes. Cela supprime la frontière que pose agent-vm, ce qui est pire qu\'ouvrir le projet en mode restreint. JetBrains Gateway ne se dit pas plus sûr : sa page sur le modèle de sécurité dit que ce que charge le backend arrive sur ta machine sans rien demander, que le backend y ouvre des liens (après confirmation) et décide de la version du client qu\'elle télécharge. Pour les serveurs de langage et un débogueur avec les paquets de la VM, utilise [`agent-vm code`](#edit-with-the-vm-s-tools).', | |
| 561 | 删除: 'Pour des scripts, `scp` ou `rsync`, `agent-vm info` affiche l\'alias SSH comme `ssh_host`. Mets ces lignes en haut de `~/.ssh/config` : un `ForwardAgent yes` trouvé avant elles donnerait tes clés SSH à la VM. `lima-*` couvre aussi les VM de ton propre Lima, si tu en as un. `--ssh-port` fixe le port pour les outils qui l\'enregistrent.', | |
| 562 | 删除: ], | |
| 563 | 删除: list: [], | |
| 564 | 删除: code: '# en haut de ~/.ssh/config\nInclude ~/.agent-vm/lima/*/ssh.config\nHost lima-*\n ForwardAgent no\n ForwardX11 no\n\nagent-vm info | grep ^ssh_host # l\'alias à utiliser\nagent-vm --ssh-port 2222 shell # un port fixe', | |
| 565 | 删除: }, | |
| 566 | 删除: { | |
| 567 | 删除: title: 'Shell, commandes, hooks', | |
| 568 | 删除: paras: [], | |
| 569 | 删除: list: [ | |
| 570 | 删除: 'direnv ne charge qu\'un `.envrc` que tu as autorisé, et une modification retire l\'autorisation ; agent-vm demande aussi avant que la VM en écrive un ([Fichiers surveillés](#guarded-files)).', | |
| 571 | 删除: 'mise fait confiance à une config selon son chemin : une VM autorisée à modifier un `mise.toml` approuvé fait lancer ses hooks à ton shell, et définir son environnement, au `cd` suivant, variables `AGENT_VM_UNSAFE_*` d\'agent-vm comprises. agent-vm demande avant cette écriture ; `mise settings set paranoid true` lie aussi la confiance au contenu. Une config sous un autre nom (`mise.local.toml`, `.mise/config.toml`) n\'est surveillée qu\'une fois que tu l\'ajoutes.', | |
| 572 | 删除: '`npm run`, `make`, `./gradlew`, `pytest`, `node_modules/.bin`, un `.venv` activé : chacun lance des fichiers que l\'agent peut écrire. Lance-les dans la VM.', | |
| 573 | 删除: '`docker compose up` sur ta machine peut monter n\'importe lequel de tes dossiers dans un conteneur root. Docker tourne dans la VM : sers-t\'en là.', | |
| 574 | 删除: 'lefthook et pre-commit gardent leurs commandes dans l\'arborescence : agent-vm demande avant que la VM change leur config, mais pas les scripts qu\'elle nomme. Les hooks de husky appellent des scripts du projet. Relis-les dans le diff, ou commite avec `--no-verify`.', | |
| 575 | 删除: ], | |
| 576 | 删除: code: '', | |
| 577 | 删除: }, | |
| 578 | 删除: { | |
| 579 | 删除: title: 'Gestionnaires de fichiers', | |
| 580 | 删除: paras: [], | |
| 581 | 删除: list: [ | |
| 582 | 删除: 'macOS : les fichiers écrits à travers le partage ne portent pas l\'attribut de quarantaine, donc Gatekeeper ne vérifie pas un `.app`, `.command` ou `.pkg` laissé là. Ne les ouvre pas depuis le Finder.', | |
| 583 | 删除: 'Windows : l\'Explorateur peut contacter le serveur nommé dans un `.library-ms`, `.searchConnector-ms`, `.lnk`, `.url`, `.scf` ou `desktop.ini` qu\'il affiche, et lui envoyer ton empreinte NTLM ([CVE-2025-24054](https://research.checkpoint.com/2025/cve-2025-24054-ntlm-exploit-in-the-wild/) pour `.library-ms`, [CVE-2025-50154](https://nvd.nist.gov/vuln/detail/CVE-2025-50154) et [CVE-2025-59214](https://nvd.nist.gov/vuln/detail/CVE-2025-59214) pour `.lnk`). Des correctifs ont déjà été contournés. agent-vm refuse sous Windows les écritures de la VM sur ces fichiers ; garde Windows à jour, le SMB sortant (TCP 445) bloqué et, si tu peux, [NTLM bloqué côté client SMB](https://learn.microsoft.com/en-us/powershell/module/smbshare/set-smbclientconfiguration).', | |
| 584 | 删除: 'Linux : Dolphin, sous KDE, lançait des commandes depuis un `.desktop` d\'un dossier qu\'il ne faisait qu\'afficher (CVE-2019-14744, corrigée dans KDE Frameworks 5.61).', | |
| 585 | 删除: ], | |
| 586 | 删除: code: '', | |
| 587 | 删除: }, | |
| 588 | 删除: ], | |
| 589 | 删除: }, | |
| 590 | 删除: { | |
| 591 | 删除: title: 'Terminal et réseau', | |
| 592 | 删除: topics: [ | |
| 593 | 删除: { | |
| 594 | 删除: title: 'Séquences d\'échappement du terminal', | |
| 595 | 删除: paras: [ | |
| 596 | 删除: 'Ce qu\'affiche la VM arrive tel quel dans ton terminal, et les terminaux réagissent aux séquences d\'échappement. agent-vm ne peut pas les filtrer sans casser les interfaces plein écran des agents.', | |
| 597 | 删除: ], | |
| 598 | 删除: list: [ | |
| 599 | 删除: 'Presse-papiers : OSC 52 permet à un programme d\'écrire dans ton presse-papiers, et, dans certains terminaux, de le lire. N\'autorise jamais la lecture, et regarde ce que tu colles dans un shell de l\'hôte.', | |
| 600 | 删除: 'Réponses tapées à ta place : une séquence envoyée juste avant la sortie peut faire taper le terminal dans ton shell. Certaines ont été de vrais bugs (iTerm2 [CVE-2024-38396](https://www.sentinelone.com/vulnerability-database/cve-2024-38396/)) : garde ton terminal à jour.', | |
| 601 | 删除: 'Fonctions qui agissent sur ta machine : transfert de fichiers et triggers d\'iTerm2, contrôle à distance de kitty (laisse-le désactivé), liens dont le texte diffère de la cible.', | |
| 602 | 删除: 'Usurpation : la VM peut afficher un faux prompt de l\'hôte après une fausse sortie. Vérifie où tu es avant de taper un secret.', | |
| 603 | 删除: ], | |
| 604 | 删除: code: '', | |
| 605 | 删除: }, | |
| 606 | 删除: { | |
| 607 | 删除: title: 'Réseau et ports', | |
| 608 | 删除: paras: [ | |
| 609 | 删除: 'Une VM atteint Internet, pas ta machine : sa boucle locale (où sont redirigés les ports des autres VM), ses propres adresses et tes réseaux locaux (plages privées, link-local et CGNAT) sont refusés, sur ta machine, par la pile réseau qu\'agent-vm fait tourner pour chaque VM. Root dans la VM ne peut pas le lever.', | |
| 610 | 删除: 'Il n\'y a pas de `~/.agent-vm/network` par défaut, et il n\'en faut pas : sans lui, les VM atteignent tout Internet et rien de ta machine ni de tes réseaux locaux. Écris-en un pour ouvrir des passages, lu au démarrage d\'une VM, une ligne chacun : `allow` une adresse (`192.168.1.20`), une adresse et un port (`192.168.1.20:5432`, `[fd00::5]:80`), un réseau (`10.8.0.0/16`), ou un service de la boucle locale de ta machine, `localhost:PORT` (`localhost` seul ouvre tous les ports), que la VM atteint à `192.168.5.2`. Une ligne `allow` vaut pour TCP et UDP.', | |
| 611 | 删除: 'Les lignes `domain` restreignent Internet lui-même : ces domaines et leurs sous-domaines (`domain github.com` couvre `api.github.com` ; `*.github.com` revient au même) deviennent les seuls noms que les VM résolvent, et une adresse n\'est joignable qu\'une fois donnée par le DNS d\'agent-vm pour l\'un d\'eux. Les lignes `allow` s\'appliquent toujours. Une ligne illisible arrête le démarrage, en la nommant ; `doctor` vérifie le fichier. `AGENT_VM_UNSAFE_OPEN_NETWORK=1` dans ton shell désactive l\'isolation.', | |
| 612 | 删除: 'Chaque port qu\'écoute une VM est redirigé vers ton `127.0.0.1`, et une notification le signale, sauf 32768-60999 : l\'invité les attribue aux programmes qui demandent un port libre quelconque (le port DevTools de Chromium, les serveurs de langage), et ils restent dans la VM. Un port sur lequel écoute un de tes programmes lui est laissé, avec une notification aussi : sous macOS, une VM qui écouterait la première sur 5432 recevrait sinon les connexions, et les mots de passe, destinés à ton Postgres local. Sur un port libre, ce que tu y envoies va à la VM : regarde la notification.', | |
| 613 | 删除: 'Aucune VM n\'atteint plus l\'éditeur d\'une autre, mais `agent-vm code` donne toujours à chacune son propre mot de passe, créé dans cette VM, et son propre nom d\'hôte, `<nom-de-vm>.localhost`. Une VM peut servir une page sur un port redirigé et envoyer ton navigateur au nom d\'hôte d\'une autre VM sur ce port ; les navigateurs rangent les cookies par nom d\'hôte et non par port, donc le navigateur lui remet le cookie de cet éditeur. La VM ne peut pas s\'en servir contre l\'éditeur lui-même, puisque ta boucle locale lui est refusée, mais arrête `agent-vm code` (Ctrl-C) quand tu ne t\'en sers pas. Chrome et Firefox résolvent `*.localhost` eux-mêmes ; Safari peut ne pas le faire, et `127.0.0.1` dans une fenêtre privée réservée à l\'éditeur fait alors la même chose.', | |
| 614 | 删除: ], | |
| 615 | 删除: list: [], | |
| 616 | 删除: code: '# ~/.agent-vm/network\nallow localhost:11434 # Ollama sur cette machine, à 192.168.5.2:11434\nallow 192.168.1.20:5432 # une base de données du réseau local\nallow 10.8.0.0/16 # un VPN\n\n# seulement ceux-là sur Internet, sous-domaines compris\ndomain github.com\ndomain npmjs.org', | |
| 617 | 删除: }, | |
| 618 | 删除: ], | |
| 619 | 删除: }, | |
| 620 | 删除: ], | |
| 621 | 删除: }, | |
| 622 | 删除: | |
| 623 | 删除: architecture: { | |
| 624 | 删除: eyebrow: 'Architecture', | |
| 625 | 删除: title: 'Une image de base, puis un clone par dossier.', | |
| 626 | 删除: lede: | |
| 627 | 删除: 'L\'installation des outils ne se paie qu\'une fois, au setup. Chaque projet n\'est ensuite qu\'un clone d\'une VM qui contient déjà toute la chaîne d\'outils.', | |
| 628 | 删除: steps: [ | |
| 629 | 删除: { | |
| 630 | 删除: n: '01', | |
| 631 | 删除: title: 'setup construit l\'image', | |
| 632 | 删除: body: 'agent-vm crée une VM Debian 13 avec le Lima qu\'il intègre. `agent-vm.setup.sh` y installe les outils de dev, Docker, Chromium et les agents, puis la VM est arrêtée et conservée comme image de base.', | |
| 633 | 删除: }, | |
| 634 | 删除: { | |
| 635 | 删除: n: '02', | |
| 636 | 删除: title: 'Le premier lancement la clone', | |
| 637 | 删除: body: 'Lancer un agent dans un dossier clone l\'image en une VM persistante rattachée à ce chemin, y monte le répertoire de travail et exécute les [scripts de runtime](#customisation-files) : celui de l\'utilisateur d\'abord, celui du projet ensuite.', | |
| 638 | 删除: }, | |
| 639 | 删除: { | |
| 640 | 删除: n: '03', | |
| 641 | 删除: title: 'L\'agent travaille sans surveillance', | |
| 642 | 删除: body: 'Il est lancé avec son option d\'approbation automatique. Il atteint Internet, pas ta machine. Les ports qu\'il ouvre dans la VM sont redirigés vers la tienne : un serveur de dev reste joignable depuis ton navigateur, comme d\'habitude.', | |
| 643 | 删除: }, | |
| 644 | 删除: { | |
| 645 | 删除: n: '04', | |
| 646 | 删除: title: 'La VM survit à la session', | |
| 647 | 删除: body: 'Elle reste là après la sortie de l\'agent. Toute commande lancée ensuite dans le même dossier la réutilise, avec ses conteneurs et ses identifiants, jusqu\'à `rm` ou `--rm`.', | |
| 648 | 删除: }, | |
| 649 | 删除: ], | |
| 650 | 删除: diagram: { | |
| 651 | 删除: hostTitle: 'Ta machine', | |
| 652 | 删除: hostItems: ['Clés SSH', 'Jetons d\'API', 'Sessions de navigateur', 'Config git', 'Tout le reste'], | |
| 653 | 删除: hostNote: 'Seul agent-vm est installé', | |
| 654 | 删除: boundaryLabel: 'Frontière de l\'hyperviseur', | |
| 655 | 删除: vmTitle: 'La VM', | |
| 656 | 删除: vmItems: ['L\'agent', 'node, python, docker, ...', 'Chromium headless, ...', 'Ports redirigés vers l\'hôte'], | |
| 657 | 删除: vmNote: 'Noyau séparé', | |
| 658 | 删除: sharedLabel: 'Partagé', | |
| 659 | 删除: sharedTitle: '~/work/ton-projet', | |
| 660 | 删除: sharedBody: | |
| 661 | 删除: 'Le dossier de ton projet, monté dans la VM au même chemin. Ton éditeur et l\'agent travaillent sur les mêmes fichiers, il n\'y a donc rien à recopier. Lecture-écriture par défaut, lecture seule avec `--readonly`. Tout ce qui traverse d\'autre, c\'est toi qui l\'as choisi : le fichier d\'env, et les montages ajoutés dans `~/.agent-vm/volumes`.', | |
| 662 | 删除: }, | |
| 663 | 删除: isolationNote: | |
| 664 | 删除: 'Chaque VM s\'authentifie de son côté : le `claude login` se fait dedans. Les identifiants survivent aux redémarrages de cette VM et ne sont partagés ni avec l\'hôte ni avec les autres VM. Chaque VM a aussi sa propre pile réseau, qui atteint Internet et pas ta machine : voir [Réseau et ports](#network-and-ports).', | |
| 665 | 删除: contentsTitle: 'Ce qu\'il y a dans la VM', | |
| 666 | 删除: contentsLede: | |
| 667 | 删除: 'L\'assistant de setup propose la sélection par défaut : tout ce qui suit, sauf les lignes marquées non. Réponds `n` pour choisir élément par élément. `--preinstall` prend les noms à la place, séparés par des virgules, plus `default`, `all` ou `none`, et saute l\'assistant, comme un setup sans terminal.', | |
| 668 | 删除: contentsHeaders: ['Catégorie', 'Paquets', 'Nom', 'Par défaut'], | |
| 669 | 删除: contents: [ | |
| 670 | 删除: ['Base', 'git, curl, wget, jq, zsh, ca-certificates, sshfs, build-essential, pkgconf, patch, unzip, zip, ripgrep, fd-find, htop', 'toujours', 'oui'], | |
| 671 | 删除: ['Bibliothèques de compilation', 'libssl-dev, libreadline-dev, zlib1g-dev, libyaml-dev, libffi-dev', 'toujours', 'oui'], | |
| 672 | 删除: ['Gestionnaire de versions', 'mise', 'toujours', 'oui'], | |
| 673 | 删除: ['Python', 'python3, pip, venv', 'python', 'oui'], | |
| 674 | 删除: ['Node.js', 'Node.js 24 LTS via NodeSource', 'node', 'oui'], | |
| 675 | 删除: ['Ruby', 'ruby-full', 'ruby', 'non'], | |
| 676 | 删除: ['Rust', 'rustup, toolchain stable', 'rust', 'non'], | |
| 677 | 删除: ['Go', 'golang-go', 'golang', 'non'], | |
| 678 | 删除: ['CLI GitHub', 'gh', 'gh', 'oui'], | |
| 679 | 删除: ['Navigateur', 'Chromium headless, xvfb', 'chromium', 'oui'], | |
| 680 | 删除: ['Conteneurs', 'Docker Engine, Docker Compose', 'docker', 'oui'], | |
| 681 | 删除: ['Agents IA', 'Claude Code, OpenCode, Codex CLI, Mistral Vibe', 'claude, opencode, codex, vibe', 'oui'], | |
| 682 | 删除: ['Agents IA', 'Pi', 'pi', 'non'], | |
| 683 | 删除: ['MCP', 'Chrome DevTools MCP, câblé dans chaque agent installé sauf Pi (pas de support MCP)', 'mcp-chrome', 'oui'], | |
| 684 | 删除: ['MCP', 'Playwright MCP, réutilisant le même Chromium', 'mcp-playwright', 'non'], | |
| 685 | 删除: ['Éditeur', 'code-server (VS Code dans le navigateur, pour `agent-vm code`), thème sombre, GitHub Copilot désactivé, sans télémétrie', 'code-server', 'non'], | |
| 686 | 删除: ['Éditeur', 'L\'extension Claude Code, OpenCode, Codex ou Mistral Vibe, chacune démarrant sans demande de permission, avec code-server', 'code-claude, code-opencode, code-codex, code-vibe', 'non'], | |
| 687 | 删除: ], | |
| 688 | 删除: contentsCode: | |
| 689 | 删除: 'agent-vm setup --preinstall=default # sans question\nagent-vm setup --preinstall=default,rust # avec Rust en plus\nagent-vm setup --preinstall=python,docker,claude # Claude seul, minimal\nagent-vm setup --preinstall=default,code-claude # avec l\'éditeur\nagent-vm setup --disk 50 --memory 16 --cpus 8 # une image plus grosse', | |
| 690 | 删除: contentsNote: | |
| 691 | 删除: '`codex` et `pi` entraînent `node`, tout comme `mcp-chrome` avec `chromium` et un agent. Les deux serveurs MCP sont ignorés sans `node` et `chromium`. Les extensions Claude, Codex et Mistral Vibe apportent leur propre copie de leur agent (200 à 600 Mo) : l\'assistant demande s\'il faut garder aussi celle en ligne de commande. Sans elle, `agent-vm claude` dit qu\'il n\'est pas installé. Celle d\'OpenCode non : elle lance la commande `opencode`, donc `code-opencode` l\'installe toujours. Ce n\'est que ce que l\'image contient au départ : l\'agent est root dans la VM et atteint Internet, il installe lui-même ce qui lui manque.', | |
| 692 | 删除: dockerTitle: 'Pourquoi pas Docker', | |
| 693 | 删除: dockerLede: | |
| 694 | 删除: 'Sous Linux, les conteneurs partagent le noyau de l\'hôte : une dépendance compromise qui trouve une faille dans le noyau se retrouve sur ta machine. Sous macOS, Docker Desktop fait déjà tourner une VM, ce qui réduit l\'écart, mais c\'est une seule VM partagée par tous tes conteneurs, pas une par projet. Une VM a son propre noyau, et root dans la VM a encore l\'hyperviseur entre lui et ton poste. Les différences pratiques comptent autant que celle-ci.', | |
| 695 | 删除: dockerHeaders: ['', 'Sans isolation', 'Docker / devcontainer', 'agent-vm'], | |
| 696 | 删除: docker: [ | |
| 697 | 删除: ['L\'agent peut tout exécuter', 'Oui', 'Oui', 'Oui'], | |
| 698 | 删除: ['Fichiers de l\'hôte accessibles', 'Tous', 'Ce que tu montes', 'Le dossier du projet'], | |
| 699 | 删除: [ | |
| 700 | 删除: 'Identifiants git, agent SSH', | |
| 701 | 删除: 'Les tiens', | |
| 702 | 删除: 'Aucun avec Docker seul, transmis par les devcontainers de VS Code', | |
| 703 | 删除: 'Rien, sauf ce que tu mets dans ~/.agent-vm/env', | |
| 704 | 删除: ], | |
| 705 | 删除: ['Réseau sortant', 'Ouvert', 'Ouvert par défaut', 'Internet, pas ta machine ni ton réseau local ([Réseau et ports](#network-and-ports))'], | |
| 706 | 删除: ['Partage le noyau de l\'hôte', 'Oui', 'Sous Linux ; sous macOS, celui de la VM Docker Desktop', 'Non'], | |
| 707 | 删除: [ | |
| 708 | 删除: 'Pour atteindre l\'hôte, il faut', | |
| 709 | 删除: 'Rien', | |
| 710 | 删除: 'Une faille du noyau, plus une faille de l\'hyperviseur sous macOS', | |
| 711 | 删除: 'Une faille de l\'hyperviseur', | |
| 712 | 删除: ], | |
| 713 | 删除: ['Docker à l\'intérieur', 'Oui', 'Exige DinD ou un montage de socket', 'Oui, nativement'], | |
| 714 | 删除: ['Navigateur headless', 'Sur l\'hôte', 'À prévoir dans ton image', 'Chromium, inclus'], | |
| 715 | 删除: [ | |
| 716 | 删除: 'Définition de l\'environnement', | |
| 717 | 删除: 'Aucune, ta machine', | |
| 718 | 删除: 'Un devcontainer.json versionné avec le projet', | |
| 719 | 删除: 'Une image de base unique, la même pour tous tes projets', | |
| 720 | 删除: ], | |
| 721 | 删除: ], | |
| 722 | 删除: dockerNote: | |
| 723 | 删除: 'Docker tourne nativement dans la VM, sans Docker-in-Docker, et Chromium headless fonctionne d\'emblée. Sur un Mac, ça remplace Docker Desktop.', | |
| 724 | 删除: }, | |
| 725 | 删除: | |
| 726 | 删除: contribute: { | |
| 727 | 删除: eyebrow: 'Contribuer', | |
| 728 | 删除: title: 'Les contributions sont bienvenues.', | |
| 729 | 删除: lede: | |
| 730 | 删除: 'agent-vm est un programme Go qui intègre Lima, compilé depuis ses sources amont avec de petits correctifs, et une suite de tests qui ne crée aucune VM et n\'a pas besoin du réseau. Rapports de bugs, corrections, prise en charge de nouveaux agents : tout est bienvenu.', | |
| 731 | 删除: testsTitle: 'Lancer les tests', | |
| 732 | 删除: testsBody: | |
| 733 | 删除: 'Deux suites. Aucune ne touche à tes VM, à ton `~/.agent-vm` ni à ta config git.', | |
| 734 | 删除: testsList: [ | |
| 735 | 删除: '`make test-go` tourne avec un faux gestionnaire de VM dans des dossiers jetables : aucune VM, aucun réseau. Là où la version bash de la 0.2 sert de comparaison, ses résultats ont été enregistrés dans `testdata/bashref`.', | |
| 736 | 删除: 'Les tests de bout en bout démarrent de vraies VM dans leur propre dossier Lima : la suite des VM vérifie ce qu\'un faux ne peut pas (root dans l\'invité ne peut écrire ni dans `.git` ni dans un fichier surveillé, ni atteindre la boucle locale de cette machine) ; celle de la CLI lance `setup` puis une commande dans un projet.', | |
| 737 | 删除: '`make fuzz` lance chaque fuzzer, `FUZZTIME` chacun : la comparaison des noms du serveur SFTP et les requêtes d\'un client hostile, l\'analyse git, les lecteurs d\'env et de volumes, les chemins et les noms.', | |
| 738 | 删除: ], | |
| 739 | 删除: testsCode: 'make test-go # rapide, sans VM\ngo test -tags e2e ./internal/vm/ ./internal/cli/ # vraies VM\nmake fuzz FUZZTIME=5m', | |
| 740 | 删除: shellsTitle: 'Corriger Lima, son serveur SFTP et son réseau', | |
| 741 | 删除: shellsBody: | |
| 742 | 删除: '`third_party/` contient Lima, sshocker, pkg/sftp et gvisor-tap-vsock : chacun est le commit amont de `third_party/SOURCES` plus les correctifs de `patches/`, chacun assez petit pour être proposé en amont. Ne modifie jamais `third_party/` à la main : change un correctif, puis reconstruis-le. La CI vérifie qu\'il n\'y a rien d\'autre.', | |
| 743 | 删除: shellsCode: 'scripts/third-party-sync sshocker # reconstruit depuis SOURCES et les correctifs\nmake check-third-party # ce que vérifie la CI\nmake test-third-party # leurs propres tests, corrigés', | |
| 744 | 删除: structureTitle: 'Où se trouve quoi', | |
| 745 | 删除: structureHeaders: ['Fichier', 'Ce que c\'est'], | |
| 746 | 删除: structure: [ | |
| 747 | 删除: ['cmd/agent-vm/', 'Le point d\'entrée de la commande.'], | |
| 748 | 删除: ['internal/cli/', 'Les commandes, le démarrage et ses vérifications, setup, doctor.'], | |
| 749 | 删除: ['internal/vm/', 'Les VM, via le Lima intégré.'], | |
| 750 | 删除: ['internal/limaembed/', 'L\'agent hôte de Lima, lancé comme `agent-vm hostagent`, et les fichiers dont il a besoin.'], | |
| 751 | 删除: ['internal/mounts/, internal/gitguard/', 'Les partages, et la protection de .git.'], | |
| 752 | 删除: ['internal/netguard/, internal/guard/', 'L\'isolation réseau, et les fichiers surveillés.'], | |
| 753 | 删除: ['third_party/, patches/', 'Lima, son serveur SFTP et sa pile réseau, en amont plus les correctifs.'], | |
| 754 | 删除: ['agent-vm.setup.sh', 'Installation des paquets, exécutée dans la VM de base pendant le setup.'], | |
| 755 | 删除: ['agent-vm.sh', 'Lance agent-vm : le binaire à côté de lui dans une version publiée, celui que construit make dans un clone. Les liens et lignes de fichier rc laissés par la 0.2 mènent ici.'], | |
| 756 | 删除: ['runtime.example.sh', 'Modèle commenté pour ~/.agent-vm/runtime.sh.'], | |
| 757 | 删除: ['CHANGELOG.md', 'Ce qui change à chaque version.'], | |
| 758 | 删除: ['release.sh', 'Vérifie, tague et publie une version, une archive par plateforme. --dry-run d\'abord.'], | |
| 759 | 删除: ['www/', 'Ce site. Astro, statique, déployé sur GitHub Pages.'], | |
| 760 | 删除: ['www/public/install.sh', 'L\'installeur curl, servi à /install.sh.'], | |
| 761 | 删除: ], | |
| 762 | 删除: guidelinesTitle: 'Avant d\'ouvrir une PR', | |
| 763 | 删除: guidelines: [ | |
| 764 | 删除: 'Tout le code doit pouvoir être relancé : vérifie l\'état avant d\'agir plutôt que de supposer une machine vierge.', | |
| 765 | 删除: 'Tout nouveau comportement a son test, vérifié en échec sans le changement. Le faux gestionnaire (`vmtest.Fake`) rend ça peu coûteux.', | |
| 766 | 删除: 'Un changement de Lima, sshocker, pkg/sftp ou gvisor-tap-vsock est un correctif dans `patches/`, assez petit pour être proposé en amont.', | |
| 767 | 删除: 'Les commandes destinées aux intégrateurs (`info`, `env`, `version`) sont des contrats. Ajouter des clés, oui ; en changer le sens, non.', | |
| 768 | 删除: 'Aucun secret, jeton ou chemin personnel dans un commit, une fixture de test ou une issue.', | |
| 769 | 删除: ], | |
| 770 | 删除: issuesLabel: 'Ouvrir une issue', | |
| 771 | 删除: issuesHref: 'https://github.com/sylvinus/agent-vm/issues', | |
| 772 | 删除: prLabel: 'Parcourir les pull requests', | |
| 773 | 删除: prHref: 'https://github.com/sylvinus/agent-vm/pulls', | |
| 774 | 删除: repoLabel: 'Lire le code', | |
| 775 | 删除: repoHref: 'https://github.com/sylvinus/agent-vm', | |
| 776 | 删除: chatLabel: 'Discuter sur Matrix', | |
| 777 | 删除: chatHref: 'https://matrix.to/#/#agent-vm:matrix.org', | |
| 778 | 删除: }, | |
| 779 | 删除: | |
| 780 | 删除: credits: { | |
| 781 | 删除: eyebrow: 'Crédits', | |
| 782 | 删除: title: 'Construit sur le travail des autres.', | |
| 783 | 删除: lede: | |
| 784 | 删除: 'agent-vm n\'est qu\'une fine couche au-dessus de logiciels écrits par d\'autres. L\'essentiel de ce qui le fait fonctionner figure dans cette liste.', | |
| 785 | 删除: groups: [ | |
| 786 | 删除: { | |
| 787 | 删除: title: 'La machine', | |
| 788 | 删除: items: [ | |
| 789 | 删除: { name: 'Lima', note: 'Des VM Linux sur macOS et Linux, intégré à agent-vm.', href: 'https://lima-vm.io/' }, | |
| 790 | 删除: { name: 'sshocker et pkg/sftp', note: 'Le serveur SFTP qui sert les partages et garde .git en lecture seule.', href: 'https://github.com/lima-vm/sshocker' }, | |
| 791 | 删除: { name: 'gvisor-tap-vsock', note: 'La pile réseau de chaque VM, où s\'applique l\'isolation.', href: 'https://github.com/containers/gvisor-tap-vsock' }, | |
| 792 | 删除: { name: 'Debian', note: 'La distribution invitée. Debian 13.', href: 'https://www.debian.org/' }, | |
| 793 | 删除: { name: 'mise', note: 'Gestionnaire de versions de runtimes dans la VM.', href: 'https://mise.jdx.dev/' }, | |
| 794 | 删除: ], | |
| 795 | 删除: }, | |
| 796 | 删除: { | |
| 797 | 删除: title: 'Les agents', | |
| 798 | 删除: items: [ | |
| 799 | 删除: { name: 'Claude Code', note: 'Anthropic.', href: 'https://claude.ai/code' }, | |
| 800 | 删除: { name: 'OpenCode', note: 'Agent terminal open source.', href: 'https://github.com/anomalyco/opencode' }, | |
| 801 | 删除: { name: 'Codex CLI', note: 'OpenAI.', href: 'https://github.com/openai/codex' }, | |
| 802 | 删除: { name: 'Mistral Vibe', note: 'Mistral AI.', href: 'https://docs.mistral.ai/vibe/code/cli/install-setup' }, | |
| 803 | 删除: { name: 'Pi', note: 'Harnais open source minimaliste.', href: 'https://pi.dev' }, | |
| 804 | 删除: ], | |
| 805 | 删除: }, | |
| 806 | 删除: { | |
| 807 | 删除: title: 'Accès navigateur', | |
| 808 | 删除: items: [ | |
| 809 | 删除: { | |
| 810 | 删除: name: 'Chrome DevTools MCP', | |
| 811 | 删除: note: 'Câblé par défaut dans chaque agent installé.', | |
| 812 | 删除: href: 'https://github.com/ChromeDevTools/chrome-devtools-mcp', | |
| 813 | 删除: }, | |
| 814 | 删除: { | |
| 815 | 删除: name: 'Playwright MCP', | |
| 816 | 删除: note: 'Pointé sur le même Chromium.', | |
| 817 | 删除: href: 'https://github.com/microsoft/playwright-mcp', | |
| 818 | 删除: }, | |
| 819 | 删除: ], | |
| 820 | 删除: }, | |
| 821 | 删除: ], | |
| 822 | 删除: authorTitle: 'Mainteneur', | |
| 823 | 删除: authorBody: 'Construit et maintenu par Sylvain Zimmer.', | |
| 824 | 删除: authorHref: 'https://github.com/sylvinus', | |
| 825 | 删除: authorName: 'sylvinus', | |
| 826 | 删除: licenseTitle: 'Licence', | |
| 827 | 删除: licenseBody: 'MIT : utilisation, copie, modification et redistribution libres, à condition de conserver la mention de copyright et la licence. Sans garantie.', | |
| 828 | 删除: licenseHref: 'https://github.com/sylvinus/agent-vm/blob/main/LICENSE', | |
| 829 | 删除: }, | |
| 830 | 删除: | |
| 831 | 删除: footer: { | |
| 832 | 删除: tagline: 'Une VM Linux jetable par projet pour les agents de code IA.', | |
| 833 | 删除: license: 'MIT', | |
| 834 | 删除: backToTop: 'Haut de page', | |
| 835 | 删除: }, | |
| 836 | 删除: | |
| 837 | 删除: ui: { | |
| 838 | 删除: copy: 'Copier', | |
| 839 | 删除: copied: 'Copié', | |
| 840 | 删除: copyFailed: 'Échec de la copie', | |
| 841 | 删除: copyLabel: 'Copier le code dans le presse-papiers', | |
| 842 | 删除: anchorLabel: 'Lien vers cette section (le copie)', | |
| 843 | 删除: linkCopied: 'Lien copié', | |
| 844 | 删除: }, | |
| 845 | 删除:}; | |
| @@ -1,38 +0,0 @@ | ||
| 1 | 删除:import { en, type Dictionary } from './en'; | |
| 2 | 删除:import { fr } from './fr'; | |
| 3 | 删除:import { applyFrenchTypography } from '../lib/french-typography'; | |
| 4 | 删除: | |
| 5 | 删除:export const LOCALES = ['en', 'fr'] as const; | |
| 6 | 删除:export type Locale = (typeof LOCALES)[number]; | |
| 7 | 删除:export const DEFAULT_LOCALE: Locale = 'en'; | |
| 8 | 删除: | |
| 9 | 删除:// Done once at module load rather than per render: the French copy is written | |
| 10 | 删除:// with plain apostrophes and ordinary spaces, and reaches the page with the | |
| 11 | 删除:// right characters. | |
| 12 | 删除:const dictionaries: Record<Locale, Dictionary> = { | |
| 13 | 删除: en, | |
| 14 | 删除: fr: applyFrenchTypography(fr), | |
| 15 | 删除:}; | |
| 16 | 删除: | |
| 17 | 删除:export function isLocale(value: string | undefined): value is Locale { | |
| 18 | 删除: return value !== undefined && (LOCALES as readonly string[]).includes(value); | |
| 19 | 删除:} | |
| 20 | 删除: | |
| 21 | 删除:/** Dictionary for a locale. Falls back to the default rather than throwing: | |
| 22 | 删除: * an unknown locale can only come from a URL, and a 404 is the router's job. */ | |
| 23 | 删除:export function t(locale: string | undefined): Dictionary { | |
| 24 | 删除: return isLocale(locale) ? dictionaries[locale] : dictionaries[DEFAULT_LOCALE]; | |
| 25 | 删除:} | |
| 26 | 删除: | |
| 27 | 删除:/** Root-relative path for a locale. English is unprefixed (prefixDefaultLocale | |
| 28 | 删除: * is false), French lives under /fr/. */ | |
| 29 | 删除:export function localeHref(locale: Locale): string { | |
| 30 | 删除: return locale === DEFAULT_LOCALE ? '/' : `/${locale}/`; | |
| 31 | 删除:} | |
| 32 | 删除: | |
| 33 | 删除:/** The other locales, for the language switcher. */ | |
| 34 | 删除:export function otherLocales(current: Locale): Locale[] { | |
| 35 | 删除: return LOCALES.filter((l) => l !== current); | |
| 36 | 删除:} | |
| 37 | 删除: | |
| 38 | 删除:export type { Dictionary }; | |
| @@ -0,0 +1,94 @@ | ||
| 1 | 新增:export const languages = [ | |
| 2 | 新增: { | |
| 3 | 新增: code: 'zh', name: '简体中文', lang: 'zh-CN', dir: 'ltr', | |
| 4 | 新增: languageLabel: '语言', downloadLabel: '下载 macOS 版', | |
| 5 | 新增: checksLabel: '网络与隔离检查', communityCheckLabel: '社区浏览器检查', | |
| 6 | 新增: firstLookLabel: '首次启动界面', releaseNotesLabel: '版本说明与校验文件', issuesLabel: '问题反馈', | |
| 7 | 新增: }, | |
| 8 | 新增: { | |
| 9 | 新增: code: 'zh-TW', name: '繁體中文', lang: 'zh-TW', dir: 'ltr', | |
| 10 | 新增: languageLabel: '語言', downloadLabel: '下載 macOS 版', | |
| 11 | 新增: checksLabel: '網路與隔離檢查', communityCheckLabel: '社群瀏覽器檢查', | |
| 12 | 新增: firstLookLabel: '首次啟動畫面', releaseNotesLabel: '版本說明與校驗檔案', issuesLabel: '問題回報', | |
| 13 | 新增: }, | |
| 14 | 新增: { | |
| 15 | 新增: code: 'ru', name: 'Русский', lang: 'ru', dir: 'ltr', | |
| 16 | 新增: languageLabel: 'Язык', downloadLabel: 'Скачать версию для macOS', | |
| 17 | 新增: checksLabel: 'Проверка сети и изоляции', communityCheckLabel: 'Проверка браузера от сообщества', | |
| 18 | 新增: firstLookLabel: 'Экран первого запуска', releaseNotesLabel: 'Примечания к выпуску и контрольные суммы', issuesLabel: 'Сообщить о проблеме', | |
| 19 | 新增: }, | |
| 20 | 新增: { | |
| 21 | 新增: code: 'ar', name: 'العربية', lang: 'ar', dir: 'rtl', | |
| 22 | 新增: languageLabel: 'اللغة', downloadLabel: 'تنزيل إصدار macOS', | |
| 23 | 新增: checksLabel: 'فحص الشبكة والعزل', communityCheckLabel: 'فحص المتصفح من المجتمع', | |
| 24 | 新增: firstLookLabel: 'واجهة التشغيل الأول', releaseNotesLabel: 'ملاحظات الإصدار وملفات التحقق', issuesLabel: 'الإبلاغ عن مشكلة', | |
| 25 | 新增: }, | |
| 26 | 新增: { | |
| 27 | 新增: code: 'fa', name: 'فارسی', lang: 'fa', dir: 'rtl', | |
| 28 | 新增: languageLabel: 'زبان', downloadLabel: 'دانلود نسخهٔ macOS', | |
| 29 | 新增: checksLabel: 'بررسی شبکه و جداسازی', communityCheckLabel: 'بررسی مرورگر توسط جامعهٔ کاربران', | |
| 30 | 新增: firstLookLabel: 'صفحهٔ نخستین اجرا', releaseNotesLabel: 'یادداشتهای انتشار و فایلهای صحتسنجی', issuesLabel: 'گزارش مشکل', | |
| 31 | 新增: }, | |
| 32 | 新增: { | |
| 33 | 新增: code: 'ko', name: '한국어', lang: 'ko', dir: 'ltr', | |
| 34 | 新增: languageLabel: '언어', downloadLabel: 'macOS 버전 다운로드', | |
| 35 | 新增: checksLabel: '네트워크 및 격리 검사', communityCheckLabel: '커뮤니티 브라우저 검사', | |
| 36 | 新增: firstLookLabel: '첫 실행 화면', releaseNotesLabel: '릴리스 노트 및 체크섬 파일', issuesLabel: '문제 제보', | |
| 37 | 新增: }, | |
| 38 | 新增: { | |
| 39 | 新增: code: 'es', name: 'Español', lang: 'es', dir: 'ltr', | |
| 40 | 新增: languageLabel: 'Idioma', downloadLabel: 'Descargar para macOS', | |
| 41 | 新增: checksLabel: 'Comprobación de red y aislamiento', communityCheckLabel: 'Comprobación del navegador de la comunidad', | |
| 42 | 新增: firstLookLabel: 'Pantalla del primer inicio', releaseNotesLabel: 'Notas de la versión y archivos de sumas de comprobación', issuesLabel: 'Informar de un problema', | |
| 43 | 新增: }, | |
| 44 | 新增: { | |
| 45 | 新增: code: 'my', name: 'မြန်မာဘာသာ', lang: 'my', dir: 'ltr', | |
| 46 | 新增: languageLabel: 'ဘာသာစကား', downloadLabel: 'macOS ဗားရှင်းကို ဒေါင်းလုဒ်လုပ်ရန်', | |
| 47 | 新增: checksLabel: 'ကွန်ရက်နှင့် သီးခြားခွဲထားမှု စစ်ဆေးချက်များ', communityCheckLabel: 'အသိုင်းအဝိုင်း၏ ဘရောက်ဇာ စစ်ဆေးချက်', | |
| 48 | 新增: firstLookLabel: 'ပထမဆုံး စတင်အသုံးပြုသည့် မျက်နှာပြင်', releaseNotesLabel: 'ဗားရှင်းမှတ်စုများနှင့် စစ်ဆေးအတည်ပြုဖိုင်များ', issuesLabel: 'ပြဿနာတင်ပြရန်', | |
| 49 | 新增: }, | |
| 50 | 新增: { | |
| 51 | 新增: code: 'be', name: 'Беларуская', lang: 'be', dir: 'ltr', | |
| 52 | 新增: languageLabel: 'Мова', downloadLabel: 'Спампаваць версію для macOS', | |
| 53 | 新增: checksLabel: 'Праверка сеткі і ізаляцыі', communityCheckLabel: 'Праверка браўзера ад супольнасці', | |
| 54 | 新增: firstLookLabel: 'Экран першага запуску', releaseNotesLabel: 'Заўвагі да выпуску і файлы кантрольных сум', issuesLabel: 'Паведаміць пра праблему', | |
| 55 | 新增: }, | |
| 56 | 新增: { | |
| 57 | 新增: code: 'ps', name: 'پښتو', lang: 'ps', dir: 'rtl', | |
| 58 | 新增: languageLabel: 'ژبه', downloadLabel: 'د macOS نسخه ډاونلوډ کړئ', | |
| 59 | 新增: checksLabel: 'د شبکې او جلاوالي کتنې', communityCheckLabel: 'د ټولنې د براوزر کتنه', | |
| 60 | 新增: firstLookLabel: 'د لومړي ځل پیل پرده', releaseNotesLabel: 'د نسخې یادښتونه او د بشپړتیا د تایید فایلونه', issuesLabel: 'ستونزه راپور کړئ', | |
| 61 | 新增: }, | |
| 62 | 新增: { | |
| 63 | 新增: code: 'prs', name: 'دری', lang: 'prs', dir: 'rtl', | |
| 64 | 新增: languageLabel: 'زبان', downloadLabel: 'دانلود نسخۀ macOS', | |
| 65 | 新增: checksLabel: 'بررسی شبکه و جداسازی', communityCheckLabel: 'بررسی مرورگر توسط جامعۀ کاربران', | |
| 66 | 新增: firstLookLabel: 'صفحۀ نخستین اجرا', releaseNotesLabel: 'یادداشتهای نشر و فایلهای بررسی صحت', issuesLabel: 'گزارش مشکل', | |
| 67 | 新增: }, | |
| 68 | 新增: { | |
| 69 | 新增: code: 'am', name: 'አማርኛ', lang: 'am', dir: 'ltr', | |
| 70 | 新增: languageLabel: 'ቋንቋ', downloadLabel: 'የmacOS ስሪትን ያውርዱ', | |
| 71 | 新增: checksLabel: 'የአውታረ መረብ እና የማግለል ምርመራዎች', communityCheckLabel: 'የማህበረሰብ አሳሽ ምርመራ', | |
| 72 | 新增: firstLookLabel: 'የመጀመሪያ ጅምር ማያ ገጽ', releaseNotesLabel: 'የስሪት ማስታወሻዎች እና የቼክሰም ፋይሎች', issuesLabel: 'ችግር ያሳውቁ', | |
| 73 | 新增: }, | |
| 74 | 新增: { | |
| 75 | 新增: code: 'so', name: 'Soomaali', lang: 'so', dir: 'ltr', | |
| 76 | 新增: languageLabel: 'Luqadda', downloadLabel: 'Soo dejiso nooca macOS', | |
| 77 | 新增: checksLabel: 'Hubinta shabakadda iyo go’doominta', communityCheckLabel: 'Hubinta biraawsarka ee bulshada', | |
| 78 | 新增: firstLookLabel: 'Shaashadda bilowga koowaad', releaseNotesLabel: 'Qoraallada sii-deynta iyo faylasha wadarta hubinta', issuesLabel: 'Soo sheeg dhibaato', | |
| 79 | 新增: }, | |
| 80 | 新增: { | |
| 81 | 新增: code: 'ti', name: 'ትግርኛ', lang: 'ti', dir: 'ltr', | |
| 82 | 新增: languageLabel: 'ቋንቋ', downloadLabel: 'ናይ macOS ስሪት ኣውርድ', | |
| 83 | 新增: checksLabel: 'መርመራ መርበብን ምፍላይን', communityCheckLabel: 'ናይ ማሕበረሰብ መርመራ መርበብ መዳህሰሲ', | |
| 84 | 新增: firstLookLabel: 'ናይ መጀመርታ ምጅማር ስክሪን', releaseNotesLabel: 'መግለጺ ስሪትን ፋይላት ቼክሳምን', issuesLabel: 'ጸገም ሓብር', | |
| 85 | 新增: }, | |
| 86 | 新增: { | |
| 87 | 新增: code: 'fr', name: 'Français', lang: 'fr', dir: 'ltr', | |
| 88 | 新增: languageLabel: 'Langue', downloadLabel: 'Télécharger pour macOS', | |
| 89 | 新增: checksLabel: 'Contrôles du réseau et de l’isolation', communityCheckLabel: 'Contrôle communautaire du navigateur', | |
| 90 | 新增: firstLookLabel: 'Écran du premier démarrage', releaseNotesLabel: 'Notes de version et fichiers de sommes de contrôle', issuesLabel: 'Signaler un problème', | |
| 91 | 新增: }, | |
| 92 | 新增:] as const; | |
| 93 | 新增: | |
| 94 | 新增:export type CageLocale = typeof languages[number]['code']; | |
| @@ -1,116 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:import '@fontsource-variable/inter'; | |
| 3 | 删除:import '@fontsource-variable/jetbrains-mono'; | |
| 4 | 删除:import '../styles/global.css'; | |
| 5 | 删除: | |
| 6 | 删除:import Nav from '../components/Nav.astro'; | |
| 7 | 删除:import Footer from '../components/Footer.astro'; | |
| 8 | 删除:import { t, localeHref, LOCALES, type Locale } from '../i18n'; | |
| 9 | 删除: | |
| 10 | 删除:interface Props { | |
| 11 | 删除: locale: Locale; | |
| 12 | 删除:} | |
| 13 | 删除: | |
| 14 | 删除:const { locale } = Astro.props; | |
| 15 | 删除:const d = t(locale); | |
| 16 | 删除:const site = Astro.site ?? new URL('https://www.agent-vm.org'); | |
| 17 | 删除:const canonical = new URL(localeHref(locale), site).href; | |
| 18 | 删除:--- | |
| 19 | 删除: | |
| 20 | 删除:<!doctype html> | |
| 21 | 删除:<html lang={locale}> | |
| 22 | 删除: <head> | |
| 23 | 删除: <meta charset="utf-8" /> | |
| 24 | 删除: <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /> | |
| 25 | 删除: <title>{d.meta.title}</title> | |
| 26 | 删除: <meta name="description" content={d.meta.description} /> | |
| 27 | 删除: <link rel="canonical" href={canonical} /> | |
| 28 | 删除: <link rel="icon" href="/favicon.svg" type="image/svg+xml" /> | |
| 29 | 删除: <link rel="icon" href="/favicon.png" type="image/png" sizes="32x32" /> | |
| 30 | 删除: <link rel="apple-touch-icon" href="/apple-touch-icon.png" sizes="180x180" /> | |
| 31 | 删除: <meta name="generator" content={Astro.generator} /> | |
| 32 | 删除: | |
| 33 | 删除: { | |
| 34 | 删除: LOCALES.map((l) => ( | |
| 35 | 删除: <link rel="alternate" hreflang={l} href={new URL(localeHref(l), site).href} /> | |
| 36 | 删除: )) | |
| 37 | 删除: } | |
| 38 | 删除: <link rel="alternate" hreflang="x-default" href={new URL('/', site).href} /> | |
| 39 | 删除: | |
| 40 | 删除: <meta property="og:type" content="website" /> | |
| 41 | 删除: <meta property="og:site_name" content="agent-vm" /> | |
| 42 | 删除: <meta property="og:title" content={d.meta.title} /> | |
| 43 | 删除: <meta property="og:description" content={d.meta.description} /> | |
| 44 | 删除: <meta property="og:url" content={canonical} /> | |
| 45 | 删除: <meta property="og:locale" content={locale === 'fr' ? 'fr_FR' : 'en_US'} /> | |
| 46 | 删除: <meta property="og:image" content={new URL('/og.png', site).href} /> | |
| 47 | 删除: <meta name="twitter:card" content="summary_large_image" /> | |
| 48 | 删除: | |
| 49 | 删除: <meta name="theme-color" content="#131210" /> | |
| 50 | 删除: </head> | |
| 51 | 删除: | |
| 52 | 删除: <body> | |
| 53 | 删除: <a class="skip-link" href="#main">{d.meta.skipToContent}</a> | |
| 54 | 删除: <Nav locale={locale} /> | |
| 55 | 删除: <main id="main"> | |
| 56 | 删除: <slot /> | |
| 57 | 删除: </main> | |
| 58 | 删除: <Footer locale={locale} /> | |
| 59 | 删除: | |
| 60 | 删除: <script> | |
| 61 | 删除: // Scroll spy: mark the section the reader is actually in. rootMargin | |
| 62 | 删除: // pulls the trigger line under the sticky nav. | |
| 63 | 删除: // The links carry a path as well as a fragment, so match on the hash. | |
| 64 | 删除: const links = Array.from( | |
| 65 | 删除: document.querySelectorAll<HTMLAnchorElement>('[data-nav-link]'), | |
| 66 | 删除: ); | |
| 67 | 删除: const hashOf = (link: HTMLAnchorElement) => new URL(link.href).hash; | |
| 68 | 删除: const sections = links | |
| 69 | 删除: .map((link) => document.querySelector(hashOf(link))) | |
| 70 | 删除: .filter((el): el is HTMLElement => el instanceof HTMLElement); | |
| 71 | 删除: | |
| 72 | 删除: if (sections.length > 0 && 'IntersectionObserver' in window) { | |
| 73 | 删除: const visible = new Set<string>(); | |
| 74 | 删除: | |
| 75 | 删除: const observer = new IntersectionObserver( | |
| 76 | 删除: (entries) => { | |
| 77 | 删除: for (const entry of entries) { | |
| 78 | 删除: if (entry.isIntersecting) visible.add(entry.target.id); | |
| 79 | 删除: else visible.delete(entry.target.id); | |
| 80 | 删除: } | |
| 81 | 删除: // Topmost visible section wins, so scrolling up does not keep the | |
| 82 | 删除: // previous one lit. | |
| 83 | 删除: const active = sections.find((s) => visible.has(s.id)); | |
| 84 | 删除: for (const link of links) { | |
| 85 | 删除: const on = active !== undefined && hashOf(link) === `#${active.id}`; | |
| 86 | 删除: link.toggleAttribute('data-current', on); | |
| 87 | 删除: } | |
| 88 | 删除: }, | |
| 89 | 删除: { rootMargin: '-25% 0px -60% 0px', threshold: 0 }, | |
| 90 | 删除: ); | |
| 91 | 删除: | |
| 92 | 删除: for (const section of sections) observer.observe(section); | |
| 93 | 删除: } | |
| 94 | 删除: | |
| 95 | 删除: // Mobile nav disclosure. | |
| 96 | 删除: const navToggle = document.querySelector<HTMLButtonElement>('[data-nav-toggle]'); | |
| 97 | 删除: const navPanel = document.querySelector<HTMLElement>('[data-nav-panel]'); | |
| 98 | 删除: | |
| 99 | 删除: if (navToggle && navPanel) { | |
| 100 | 删除: const setOpen = (open: boolean) => { | |
| 101 | 删除: navToggle.setAttribute('aria-expanded', open ? 'true' : 'false'); | |
| 102 | 删除: navPanel.toggleAttribute('data-open', open); | |
| 103 | 删除: }; | |
| 104 | 删除: navToggle.addEventListener('click', () => { | |
| 105 | 删除: setOpen(navToggle.getAttribute('aria-expanded') !== 'true'); | |
| 106 | 删除: }); | |
| 107 | 删除: navPanel.addEventListener('click', (event) => { | |
| 108 | 删除: if (event.target instanceof HTMLAnchorElement) setOpen(false); | |
| 109 | 删除: }); | |
| 110 | 删除: document.addEventListener('keydown', (event) => { | |
| 111 | 删除: if (event.key === 'Escape') setOpen(false); | |
| 112 | 删除: }); | |
| 113 | 删除: } | |
| 114 | 删除: </script> | |
| 115 | 删除: </body> | |
| 116 | 删除:</html> | |
| @@ -1,44 +0,0 @@ | ||
| 1 | 删除:/** | |
| 2 | 删除: * French typographic fixes, applied once to the French dictionary at load. | |
| 3 | 删除: * | |
| 4 | 删除: * Doing it here rather than in the source strings keeps `fr.ts` writable with | |
| 5 | 删除: * an ordinary keyboard, and keeps the two dictionaries looking like each other. | |
| 6 | 删除: * | |
| 7 | 删除: * Two rules: | |
| 8 | 删除: * - a straight apostrophe between letters becomes a typographic one; | |
| 9 | 删除: * - the space before `;` `!` `?` `»` and after `«` becomes a narrow no-break | |
| 10 | 删除: * space, and the one before `:` a full no-break space, so the punctuation | |
| 11 | 删除: * never starts a line on its own. | |
| 12 | 删除: */ | |
| 13 | 删除: | |
| 14 | 删除:const NARROW_NBSP = ' '; | |
| 15 | 删除:const NBSP = ' '; | |
| 16 | 删除: | |
| 17 | 删除:export function frenchTypography(text: string): string { | |
| 18 | 删除: return text | |
| 19 | 删除: .replace(/(\p{L})'(\p{L})/gu, '$1’$2') | |
| 20 | 删除: .replace(/ :/g, `${NBSP}:`) | |
| 21 | 删除: .replace(/ ([;!?»])/g, `${NARROW_NBSP}$1`) | |
| 22 | 删除: .replace(/« /g, `«${NARROW_NBSP}`); | |
| 23 | 删除:} | |
| 24 | 删除: | |
| 25 | 删除:/** Keys whose values are shell snippets, identifiers or URLs. Reflowing those | |
| 26 | 删除: * would corrupt a command the reader is meant to paste. */ | |
| 27 | 删除:function isVerbatimKey(key: string): boolean { | |
| 28 | 删除: return key === 'code' || key === 'href' || key === 'lang' || key.endsWith('Code'); | |
| 29 | 删除:} | |
| 30 | 删除: | |
| 31 | 删除:export function applyFrenchTypography<T>(value: T, key = ''): T { | |
| 32 | 删除: if (typeof value === 'string') { | |
| 33 | 删除: return (isVerbatimKey(key) ? value : frenchTypography(value)) as T; | |
| 34 | 删除: } | |
| 35 | 删除: if (Array.isArray(value)) { | |
| 36 | 删除: return value.map((item) => applyFrenchTypography(item, key)) as T; | |
| 37 | 删除: } | |
| 38 | 删除: if (value !== null && typeof value === 'object') { | |
| 39 | 删除: const out: Record<string, unknown> = {}; | |
| 40 | 删除: for (const [k, v] of Object.entries(value)) out[k] = applyFrenchTypography(v, k); | |
| 41 | 删除: return out as T; | |
| 42 | 删除: } | |
| 43 | 删除: return value; | |
| 44 | 删除:} | |
| @@ -1,30 +0,0 @@ | ||
| 1 | 删除:const ESCAPES: Record<string, string> = { | |
| 2 | 删除: '&': '&', | |
| 3 | 删除: '<': '<', | |
| 4 | 删除: '>': '>', | |
| 5 | 删除: '"': '"', | |
| 6 | 删除:}; | |
| 7 | 删除: | |
| 8 | 删除:export function escapeHtml(text: string): string { | |
| 9 | 删除: return text.replace(/[&<>"]/g, (ch) => ESCAPES[ch]!); | |
| 10 | 删除:} | |
| 11 | 删除: | |
| 12 | 删除:/** | |
| 13 | 删除: * Turns `backticks` in the dictionary strings into <code> elements, and | |
| 14 | 删除: * [text](target) into links: to another site for an https URL, opened in a | |
| 15 | 删除: * new tab, or to a heading of this page for a #anchor. | |
| 16 | 删除: * | |
| 17 | 删除: * Everything is escaped first, so the only markup that survives is the one | |
| 18 | 删除: * this function emits. The input is our own copy, not user input, but escaping | |
| 19 | 删除: * is what makes that stay true when someone adds a `<` to a sentence. Any | |
| 20 | 删除: * other target is left as text. | |
| 21 | 删除: */ | |
| 22 | 删除:export function inline(text: string): string { | |
| 23 | 删除: return escapeHtml(text) | |
| 24 | 删除: .replace(/`([^`]+)`/g, '<code>$1</code>') | |
| 25 | 删除: .replace(/\[([^\]]+)\]\((https:\/\/[^)\s]+|#[a-z0-9-]+)\)/g, (_, label: string, target: string) => | |
| 26 | 删除: target.startsWith('#') | |
| 27 | 删除: ? `<a href="${target}">${label}</a>` | |
| 28 | 删除: : `<a href="${target}" target="_blank" rel="noopener noreferrer">${label}</a>`, | |
| 29 | 删除: ); | |
| 30 | 删除:} | |
| @@ -1,138 +0,0 @@ | ||
| 1 | 删除:/** | |
| 2 | 删除: * A small shell highlighter. | |
| 3 | 删除: * | |
| 4 | 删除: * Every snippet on this site is a shell command or an env file, so a full | |
| 5 | 删除: * grammar (and the dual-theme CSS a Shiki setup would need) buys nothing. This | |
| 6 | 删除: * handles comments, quoted strings, variables, flags and the leading command, | |
| 7 | 删除: * which is the whole visual vocabulary the page uses. | |
| 8 | 删除: * | |
| 9 | 删除: * The scanner walks raw text and escapes at render time, so a quote inside the | |
| 10 | 删除: * source is still a quote to the tokeniser rather than an `"`. | |
| 11 | 删除: */ | |
| 12 | 删除: | |
| 13 | 删除:export type TokenKind = | |
| 14 | 删除: | 'plain' | |
| 15 | 删除: | 'command' | |
| 16 | 删除: | 'flag' | |
| 17 | 删除: | 'string' | |
| 18 | 删除: | 'variable' | |
| 19 | 删除: | 'comment'; | |
| 20 | 删除: | |
| 21 | 删除:export interface Token { | |
| 22 | 删除: kind: TokenKind; | |
| 23 | 删除: text: string; | |
| 24 | 删除:} | |
| 25 | 删除: | |
| 26 | 删除:const WORD_CHARS = /[A-Za-z0-9_./~@+:-]/; | |
| 27 | 删除:const IDENT_START = /[A-Za-z_]/; | |
| 28 | 删除:const IDENT = /[A-Za-z0-9_]/; | |
| 29 | 删除: | |
| 30 | 删除:/** True when `#` at this index starts a comment rather than sitting inside a | |
| 31 | 删除: * word (a fragment id, a colour). Shell only treats it as a comment at the | |
| 32 | 删除: * start of a word. */ | |
| 33 | 删除:function startsComment(line: string, i: number): boolean { | |
| 34 | 删除: return i === 0 || /\s/.test(line[i - 1]!); | |
| 35 | 删除:} | |
| 36 | 删除: | |
| 37 | 删除:function tokenizeLine(line: string): Token[] { | |
| 38 | 删除: const tokens: Token[] = []; | |
| 39 | 删除: let i = 0; | |
| 40 | 删除: // The first bare word on a line is the command being run. `ENV=value cmd` | |
| 41 | 删除: // and a continuation line are rare enough here not to matter. | |
| 42 | 删除: let seenWord = false; | |
| 43 | 删除: | |
| 44 | 删除: const push = (kind: TokenKind, text: string) => { | |
| 45 | 删除: if (text === '') return; | |
| 46 | 删除: const last = tokens[tokens.length - 1]; | |
| 47 | 删除: if (last && last.kind === kind) last.text += text; | |
| 48 | 删除: else tokens.push({ kind, text }); | |
| 49 | 删除: }; | |
| 50 | 删除: | |
| 51 | 删除: while (i < line.length) { | |
| 52 | 删除: const ch = line[i]!; | |
| 53 | 删除: | |
| 54 | 删除: if (ch === '#' && startsComment(line, i)) { | |
| 55 | 删除: push('comment', line.slice(i)); | |
| 56 | 删除: break; | |
| 57 | 删除: } | |
| 58 | 删除: | |
| 59 | 删除: if (ch === '"' || ch === "'") { | |
| 60 | 删除: const quote = ch; | |
| 61 | 删除: let j = i + 1; | |
| 62 | 删除: while (j < line.length) { | |
| 63 | 删除: if (line[j] === '\\' && quote === '"') j += 2; | |
| 64 | 删除: else if (line[j] === quote) { | |
| 65 | 删除: j += 1; | |
| 66 | 删除: break; | |
| 67 | 删除: } else j += 1; | |
| 68 | 删除: } | |
| 69 | 删除: push('string', line.slice(i, j)); | |
| 70 | 删除: i = j; | |
| 71 | 删除: continue; | |
| 72 | 删除: } | |
| 73 | 删除: | |
| 74 | 删除: if (ch === '$' && i + 1 < line.length) { | |
| 75 | 删除: const next = line[i + 1]!; | |
| 76 | 删除: if (next === '(') { | |
| 77 | 删除: let depth = 0; | |
| 78 | 删除: let j = i + 1; | |
| 79 | 删除: while (j < line.length) { | |
| 80 | 删除: if (line[j] === '(') depth += 1; | |
| 81 | 删除: else if (line[j] === ')') { | |
| 82 | 删除: depth -= 1; | |
| 83 | 删除: if (depth === 0) { | |
| 84 | 删除: j += 1; | |
| 85 | 删除: break; | |
| 86 | 删除: } | |
| 87 | 删除: } | |
| 88 | 删除: j += 1; | |
| 89 | 删除: } | |
| 90 | 删除: push('variable', line.slice(i, j)); | |
| 91 | 删除: i = j; | |
| 92 | 删除: continue; | |
| 93 | 删除: } | |
| 94 | 删除: if (next === '{') { | |
| 95 | 删除: const close = line.indexOf('}', i); | |
| 96 | 删除: const j = close === -1 ? line.length : close + 1; | |
| 97 | 删除: push('variable', line.slice(i, j)); | |
| 98 | 删除: i = j; | |
| 99 | 删除: continue; | |
| 100 | 删除: } | |
| 101 | 删除: if (IDENT_START.test(next)) { | |
| 102 | 删除: let j = i + 1; | |
| 103 | 删除: while (j < line.length && IDENT.test(line[j]!)) j += 1; | |
| 104 | 删除: push('variable', line.slice(i, j)); | |
| 105 | 删除: i = j; | |
| 106 | 删除: continue; | |
| 107 | 删除: } | |
| 108 | 删除: } | |
| 109 | 删除: | |
| 110 | 删除: if (ch === '-' && (i === 0 || /\s/.test(line[i - 1]!)) && i + 1 < line.length) { | |
| 111 | 删除: let j = i; | |
| 112 | 删除: while (j < line.length && (line[j] === '-' || WORD_CHARS.test(line[j]!))) j += 1; | |
| 113 | 删除: push('flag', line.slice(i, j)); | |
| 114 | 删除: i = j; | |
| 115 | 删除: continue; | |
| 116 | 删除: } | |
| 117 | 删除: | |
| 118 | 删除: if (WORD_CHARS.test(ch)) { | |
| 119 | 删除: let j = i; | |
| 120 | 删除: while (j < line.length && WORD_CHARS.test(line[j]!)) j += 1; | |
| 121 | 删除: // The first word is the command, or the key of a `KEY=value` env line. | |
| 122 | 删除: // Both are what the eye should land on first. | |
| 123 | 删除: push(seenWord ? 'plain' : 'command', line.slice(i, j)); | |
| 124 | 删除: seenWord = true; | |
| 125 | 删除: i = j; | |
| 126 | 删除: continue; | |
| 127 | 删除: } | |
| 128 | 删除: | |
| 129 | 删除: push('plain', ch); | |
| 130 | 删除: i += 1; | |
| 131 | 删除: } | |
| 132 | 删除: | |
| 133 | 删除: return tokens; | |
| 134 | 删除:} | |
| 135 | 删除: | |
| 136 | 删除:export function highlightShell(code: string): Token[][] { | |
| 137 | 删除: return code.replace(/\n+$/, '').split('\n').map(tokenizeLine); | |
| 138 | 删除:} | |
| @@ -1,12 +0,0 @@ | ||
| 1 | 删除:/** | |
| 2 | 删除: * A heading's anchor. Built from the English text by the callers, so a link | |
| 3 | 删除: * copied from /fr/ still works on /, and the other way round. | |
| 4 | 删除: */ | |
| 5 | 删除:export function slug(text: string): string { | |
| 6 | 删除: return text | |
| 7 | 删除: .normalize('NFKD') | |
| 8 | 删除: .replace(/[̀-ͯ]/g, '') | |
| 9 | 删除: .toLowerCase() | |
| 10 | 删除: .replace(/[^a-z0-9]+/g, '-') | |
| 11 | 删除: .replace(/^-+|-+$/g, ''); | |
| 12 | 删除:} | |
| @@ -1,4 +1,4 @@ | ||
| 1 | 1 | --- |
| 2 | 2 | import '../styles/cage.css'; |
| 3 | 3 | --- |
| 4 | 删除:<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>页面未找到 · Cage</title></head><body><main class="wrap" style="padding-top:100px"><p class="eyebrow">404</p><h1>这个页面暂时找不到。</h1><p style="margin:30px 0">从 Cage 首页继续查看下载和入门指南。</p><a class="button" href="/">回到首页</a></main></body></html> | |
| 4 | 新增:<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>页面未找到 · Cage</title></head><body><main class="wrap" style="padding-top:100px"><p class="eyebrow">404</p><h1>这个页面暂时找不到。</h1><p style="margin:30px 0">从 Cage 首页继续查看下载和入门指南。</p><a class="button" href={import.meta.env.BASE_URL}>回到首页</a></main></body></html> | |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增:--- | |
| 2 | 新增:import CageHome from '../../components/CageHome.astro'; | |
| 3 | 新增:import { languages } from '../../i18n/cage'; | |
| 4 | 新增:export function getStaticPaths() { | |
| 5 | 新增: return languages.filter(language => language.code !== 'zh').map(language => ({ params: { locale: language.code }, props: { locale: language.code } })); | |
| 6 | 新增:} | |
| 7 | 新增:const { locale } = Astro.props; | |
| 8 | 新增:--- | |
| 9 | 新增:<CageHome locale={locale} /> | |
| @@ -1,3 +0,0 @@ | ||
| 1 | 删除:--- | |
| 2 | 删除:return Astro.redirect('/'); | |
| 3 | 删除:--- | |
| @@ -1,55 +1,4 @@ | ||
| 1 | 1 | --- |
| 2 | 删除:import '@fontsource-variable/inter'; | |
| 3 | 删除:import '../styles/cage.css'; | |
| 4 | 删除:const repo = 'https://github.com/Lee-xeo/Claude-Cage'; | |
| 5 | 删除:const release = `${repo}/releases/tag/v0.2.0-alpha.1`; | |
| 6 | 删除:const dmg = `${repo}/releases/download/v0.2.0-alpha.1/Cage-0.2.0-alpha.1-macos-arm64.dmg`; | |
| 7 | 删除:const guide = `${repo}/blob/main/docs/getting-started.md`; | |
| 2 | 新增:import CageHome from '../components/CageHome.astro'; | |
| 8 | 3 | --- |
| 9 | 删除:<!doctype html> | |
| 10 | 删除:<html lang="zh-CN"> | |
| 11 | 删除: <head> | |
| 12 | 删除: <meta charset="UTF-8" /> | |
| 13 | 删除: <meta name="viewport" content="width=device-width, initial-scale=1" /> | |
| 14 | 删除: <meta name="description" content="Cage 是 Mac 上的独立 Claude 编码工作区。把终端、浏览器和编辑器放进持久 Linux 环境,只共享你选择的项目。" /> | |
| 15 | 删除: <meta name="theme-color" content="#faf8f4" /> | |
| 16 | 删除: <title>Cage — 给 Claude 一个独立的工作区</title> | |
| 17 | 删除: <link rel="icon" href="/cage-icon.png" /> | |
| 18 | 删除: </head> | |
| 19 | 删除: <body> | |
| 20 | 删除: <a class="skip" href="#main">跳到正文</a> | |
| 21 | 删除: <header class="nav wrap"> | |
| 22 | 删除: <a class="brand" href="#" aria-label="Cage 首页"><img src="/cage-icon.png" width="40" height="40" alt="" /><span>Cage</span></a> | |
| 23 | 删除: <nav aria-label="主导航"><a href="#how">开始使用</a><a href="#boundaries">隔离边界</a><a href={repo}>GitHub <span aria-hidden="true">↗</span></a><a class="nav-download" href="#download">下载 <span aria-hidden="true">↓</span></a></nav> | |
| 24 | 删除: </header> | |
| 25 | 删除: <main id="main"> | |
| 26 | 删除: <section class="hero wrap"> | |
| 27 | 删除: <div class="eyebrow"><span class="seed"></span> 给专注工作,留一片独立空间 <span class="alpha">MACOS · ALPHA</span></div> | |
| 28 | 删除: <div class="hero-copy"> | |
| 29 | 删除: <h1>让 Claude 放手做事。<br /><em>让工作各有边界。</em></h1> | |
| 30 | 删除: <div class="hero-aside"><p>终端、浏览器、编辑器,<br />都在一个独立的 Linux 环境里。<br />你的 Mac,只共享你选择的项目。</p><a class="button" href="#download">下载 macOS 版 <span aria-hidden="true">↓</span></a><span class="requirements">Apple Silicon · macOS 14 或更新版本</span></div> | |
| 31 | 删除: </div> | |
| 32 | 删除: <figure class="product"><div class="window-bar"><span class="window-dots" aria-hidden="true">● ● ●</span><span>Cage · 你的独立工作区</span><span class="window-label">就在本机</span></div><img src="/workbench.png" width="1360" height="850" alt="Cage 浅色工作台:在同一窗口里管理项目、终端与浏览器标签" fetchpriority="high" /><figcaption>Cage 工作台 · 演示项目 hello-cage</figcaption></figure> | |
| 33 | 删除: </section> | |
| 34 | 删除: <section class="tools wrap" aria-labelledby="tools-title"> | |
| 35 | 删除: <div class="section-intro"><span class="eyebrow">熟悉的工具,更清楚的边界</span><h2 id="tools-title">工作连在一起,<br />环境独立出来。</h2></div> | |
| 36 | 删除: <div class="tool-list"><article><span class="tool-icon" aria-hidden="true">>_</span><div><h3>在终端里,把任务交给 Claude</h3><p>开发工具在 Linux 中运行。打开项目,输入 <code>claude</code>,在 Cage 内完成首次账户登录。</p></div></article><article><span class="tool-icon" aria-hidden="true">◎</span><div><h3>在浏览器里,查看真正的结果</h3><p>网页在独立环境内打开,使用你选定的代理。访问 localhost,直接预览刚刚运行的服务。</p></div></article><article><span class="tool-icon" aria-hidden="true">⌘</span><div><h3>在编辑器里,接着你的项目工作</h3><p>明确选择一个本地文件夹。文件同步到你的 Mac,修改即时可见;请为重要项目保留备份。</p></div></article></div> | |
| 37 | 删除: </section> | |
| 38 | 删除: <section id="how" class="start-section"> | |
| 39 | 删除: <div class="wrap"><div class="section-heading"><div><span class="eyebrow">第一次打开,也知道下一步</span><h2>三步,进入工作状态。</h2></div><a class="text-link" href={guide}>完整入门指南 <span aria-hidden="true">↗</span></a></div> | |
| 40 | 删除: <div class="steps"><article><span class="step-number">01</span><h3>连接你的代理</h3><p>导入 Clash / Mihomo YAML 或订阅,选择节点。代理核心随 App 提供,无需另装 Clash。</p><span class="step-note">需要自备可用代理</span></article><article><span class="step-number">02</span><h3>准备独立环境</h3><p>点击启动,按提示确认 Git 安全保护,再下载 Linux 镜像与开发工具。查看阶段进度,网络检查通过后再开始联网工作。</p><span class="step-note">首次准备需要联网与等待</span></article><article><span class="step-number">03</span><h3>打开项目,开始工作</h3><p>选择项目文件夹,新建终端运行 Claude。账户在 Cage 内登录,环境和登录状态会保留。</p><span class="step-note">需要自备 Claude 账户或授权</span></article></div> | |
| 41 | 删除: <details class="first-look"><summary>第一次打开 Cage,会看到什么? <span aria-hidden="true">+</span></summary><img src="/first-run.png" width="1280" height="850" alt="首次打开 Cage 的引导界面,主要操作为配置网络与代理" loading="lazy" /></details></div> | |
| 42 | 删除: </section> | |
| 43 | 删除: <section id="boundaries" class="boundaries wrap"><div><span class="eyebrow">边界说清楚,用起来更踏实</span><h2>你选择共享什么。<br />Cage 告诉你运行状态。</h2><p class="section-lead">独立环境、指定代理、可查看的网络检查。<br />每一项能力,都有明确的适用范围。</p></div><div class="boundary-list"><article><span aria-hidden="true">↗</span><div><h3>外部连接经过指定代理</h3><p>代理不可用时不直连回退。关键检查失败或证据不完整时,暂停外网,保留可用的离线工作。</p></div></article><article><span aria-hidden="true">↔</span><div><h3>共享范围由你明确选择</h3><p>只共享默认工作区与主动打开的项目。共享文件的修改和删除会影响主机;同一环境中的项目共享账户与工具。</p></div></article><article><span aria-hidden="true">i</span><div><h3>知道它能保护什么,也知道限制</h3><p>当前出站支持 IPv4 TCP,.git 等元数据默认只读。隔离和检查无法承诺账户不会受限,也不能替代项目备份。</p></div></article></div></section> | |
| 44 | 删除: <section id="download" class="download-section wrap"><div class="download-box"><img src="/cage-icon.png" width="84" height="84" alt="Cage 图标" /><span class="eyebrow">从一个独立工作区开始</span><h2>把 Cage 带到你的 Mac。</h2><p>安装应用,配置代理,打开你的第一个项目。</p><a class="button" href={dmg}>下载 macOS 安装包 <span aria-hidden="true">↗</span></a><div class="download-meta"><span>v0.2.0-alpha.1</span><span>Apple Silicon(M 系列)</span><span>macOS 14+</span></div><p class="access-note">当前为私有 Alpha。请使用已获仓库访问权限的 GitHub 账号下载。<br />Release 提供安装包、校验文件与对应版本说明;Intel、Windows 和 Linux 暂不提供安装包。</p><a class="text-link" href={release}>版本说明与校验文件 ↗</a><a class="text-link" style="margin-top:16px" href={guide}>查看安装、升级与卸载说明 ↗</a></div></section> | |
| 45 | 删除: <section class="faq wrap" aria-labelledby="faq-title"><h2 id="faq-title">开始之前,你可能想知道。</h2><div><details><summary>需要在 Mac 上安装开发环境吗?</summary><p>使用打包好的 App 无需安装 Go、Node.js 或 Clash。Cage 首次启动会联网下载 Linux 镜像,并在其中安装开发工具,因此并非完全离线安装。</p></details><details><summary>包含 Claude 订阅或代理服务吗?</summary><p>不包含。请准备自己的 Claude 账户或授权,以及可用的代理。内置导入支持包含 proxies 或 payload 的 Clash / Mihomo YAML;Base64 节点列表和分享链接暂不支持。</p></details><details><summary>关掉窗口后,工作还在吗?</summary><p>关闭窗口会保留运行环境。退出应用时可以选择继续运行或停止环境。停止会结束终端进程,项目文件和虚拟磁盘中的登录状态会保留。</p></details><details><summary>现在适合用于什么?</summary><p>当前是供早期体验与反馈的 Alpha。已验证部分隔离与界面功能,完整的干净机器安装、真实 Claude 授权和模型请求仍需验收。请先使用有备份的测试项目。</p></details><details><summary>项目是否开源?</summary><p>Cage 正在筹备开源,当前仓库保持私有。Cage 自有代码采用 MIT 许可,基于 agent-vm、Lima 等项目构建;noVNC、Mihomo 等依赖保留各自许可。源码入口和版本记录都在 GitHub。</p></details></div></section> | |
| 46 | 删除: </main> | |
| 47 | 删除: <footer class="wrap"><a class="brand" href="#"><img src="/cage-icon.png" width="28" height="28" alt="" />Cage</a><span>独立工作,边界清楚。</span><div><a href={repo}>GitHub ↗</a><a href={guide}>文档 ↗</a><a href={`${repo}/blob/main/SECURITY.md`}>安全报告 ↗</a></div><small>Cage 是独立项目,与 Anthropic 无隶属或背书关系。Claude 是 Anthropic 的产品名称。</small></footer> | |
| 48 | 删除: <script> | |
| 49 | 删除: if (!window.matchMedia('(prefers-reduced-motion: reduce)').matches) { | |
| 50 | 删除: const observer = new IntersectionObserver((entries) => { for (const entry of entries) { if (entry.isIntersecting) { entry.target.classList.add('revealed'); observer.unobserve(entry.target); } } }, { threshold: 0.08 }); | |
| 51 | 删除: document.querySelectorAll('.tools, .steps article, .boundaries, .download-box').forEach((el) => { el.classList.add('reveal'); observer.observe(el); }); | |
| 52 | 删除: } | |
| 53 | 删除: </script> | |
| 54 | 删除: </body> | |
| 55 | 删除:</html> | |
| 4 | 新增:<CageHome locale="zh" /> | |
| @@ -703,3 +703,78 @@ code { | ||
| 703 | 703 | transform: none; |
| 704 | 704 | } |
| 705 | 705 | } |
| 706 | 新增: | |
| 707 | 新增:/* Shared README-led presentation across the three locale routes. */ | |
| 708 | 新增:figure { margin: 0; } | |
| 709 | 新增:.lines { white-space: pre-line; } | |
| 710 | 新增:.language-switch { display: flex; justify-content: flex-end; gap: 22px; padding-bottom: 18px; font-size: 12px; color: var(--muted); } | |
| 711 | 新增:.language-switch [aria-current="page"] { color: var(--accent); text-decoration: underline; text-underline-offset: 5px; } | |
| 712 | 新增:.story-hero { display: grid; grid-template-columns: 1.1fr 1fr; align-items: center; gap: 65px; padding: 40px 0 80px; } | |
| 713 | 新增:.story-copy h1 { margin: 24px 0 18px; } | |
| 714 | 新增:.tagline { font-size: 23px; } | |
| 715 | 新增:.hero-intro { color: var(--muted); margin: 20px 0 28px; max-width: 34em; } | |
| 716 | 新增:.story-copy .requirements { display: block; margin-top: 16px; } | |
| 717 | 新增:.character { overflow: hidden; border-radius: 13px; border: 1px solid var(--line); } | |
| 718 | 新增:.character img { width: 100%; } | |
| 719 | 新增:.manifesto { border-top: 1px solid var(--line); padding-top: 60px; } | |
| 720 | 新增:.manifesto h2 { margin: 15px 0 24px; } | |
| 721 | 新增:.manifesto > p { max-width: 850px; } | |
| 722 | 新增:.small-note { font-size: 13px; color: var(--muted); margin-top: 20px; } | |
| 723 | 新增:.evidence { padding-top: 90px; padding-bottom: 90px; } | |
| 724 | 新增:.evidence h2 { margin-top: 16px; } | |
| 725 | 新增:.evidence .section-lead { max-width: 850px; } | |
| 726 | 新增:.evidence-grid { display: grid; grid-template-columns: 1fr 1fr; align-items: start; gap: 30px; margin-top: 35px; } | |
| 727 | 新增:.evidence-grid figure { background: #fff; border: 1px solid var(--line); border-radius: 13px; overflow: hidden; } | |
| 728 | 新增:.evidence-grid img { width: 100%; } | |
| 729 | 新增:.quick-start { max-width: 950px; padding-bottom: 65px; } | |
| 730 | 新增:.quick-start h2 { margin: 15px 0 22px; } | |
| 731 | 新增:.quick-start pre { white-space: pre-wrap; overflow-wrap: anywhere; background: #faf8f4; border: 1px solid #dacebf; border-radius: 8px; padding: 24px; line-height: 1.8; margin: 25px 0; } | |
| 732 | 新增:.steps-title { font-size: 29px; } | |
| 733 | 新增:.update-note { margin-top: 0; } | |
| 734 | 新增:.community { display: grid; grid-template-columns: 1fr 320px; gap: 85px; align-items: center; padding-top: 90px; } | |
| 735 | 新增:.community h2 { margin: 16px 0 24px; } | |
| 736 | 新增:.community p { color: var(--muted); max-width: 42em; } | |
| 737 | 新增:.community-links { display: flex; gap: 30px; margin-top: 25px; } | |
| 738 | 新增:.community figure { border: 1px solid var(--line); border-radius: 13px; overflow: hidden; background: white; } | |
| 739 | 新增:.community figcaption { text-align: center; } | |
| 740 | 新增:@media (max-width: 900px) { | |
| 741 | 新增: .story-hero { gap: 30px; } | |
| 742 | 新增: .story-copy h1 { font-size: 42px; } | |
| 743 | 新增: .community { gap: 35px; grid-template-columns: 1fr 260px; } | |
| 744 | 新增: .nav nav { gap: 16px; } | |
| 745 | 新增: .nav .brand { font-size: 21px; } | |
| 746 | 新增:} | |
| 747 | 新增:@media (max-width: 640px) { | |
| 748 | 新增: .nav nav > a:not(.nav-download) { display: none; } | |
| 749 | 新增: .nav .brand { font-size: 20px; } | |
| 750 | 新增: .nav-download { max-width: 150px; text-align: center; } | |
| 751 | 新增: .language-switch { justify-content: flex-start; gap: 24px; padding-bottom: 0; } | |
| 752 | 新增: .story-hero { grid-template-columns: 1fr; padding-top: 35px; padding-bottom: 50px; gap: 35px; } | |
| 753 | 新增: .story-copy h1 { font-size: clamp(32px, 8vw, 42px); } | |
| 754 | 新增: .tagline { font-size: 20px; } | |
| 755 | 新增: .character { max-width: 420px; } | |
| 756 | 新增: .manifesto { padding-top: 45px; } | |
| 757 | 新增: .evidence { padding-top: 60px; padding-bottom: 55px; } | |
| 758 | 新增: .evidence-grid { grid-template-columns: 1fr; gap: 25px; } | |
| 759 | 新增: .quick-start { padding-bottom: 45px; } | |
| 760 | 新增: .quick-start pre { padding: 18px; font-size: 13px; } | |
| 761 | 新增: .community { grid-template-columns: 1fr; gap: 30px; padding-top: 60px; } | |
| 762 | 新增: .community figure { max-width: 300px; } | |
| 763 | 新增: .community-links { flex-wrap: wrap; } | |
| 764 | 新增:} | |
| 765 | 新增:.language-switch { align-items: center; } | |
| 766 | 新增:.language-switch select { color: inherit; font: inherit; background: transparent; border: 1px solid var(--line); border-radius: 6px; padding: 9px 30px 9px 12px; min-width: 140px; } | |
| 767 | 新增:.language-switch select:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; } | |
| 768 | 新增:.key-features { max-width: 850px; padding-inline-start: 22px; line-height: 1.85; } | |
| 769 | 新增:.key-features li { margin-top: 12px; } | |
| 770 | 新增:.doc-links { list-style: none; padding: 0; margin: 0; } | |
| 771 | 新增:.doc-links li { padding: 20px 0; border-top: 1px solid var(--line); } | |
| 772 | 新增:.doc-links p { color: var(--muted); font-size: 14px; margin-top: 8px; } | |
| 773 | 新增:.license { padding-bottom: 60px; } | |
| 774 | 新增:.license h2 { font-size: 24px; margin-bottom: 20px; } | |
| 775 | 新增:.license p { max-width: 900px; white-space: pre-line; font-size: 14px; color: var(--muted); } | |
| 776 | 新增:[dir="rtl"] { letter-spacing: normal; } | |
| 777 | 新增:[dir="rtl"] .nav nav { margin-left: 0; margin-right: auto; } | |
| 778 | 新增:[dir="rtl"] footer > div { margin-left: 0; margin-right: auto; } | |
| 779 | 新增:[dir="rtl"] .quick-start pre { text-align: start; } | |
| 780 | 新增:[dir="rtl"] h1, [dir="rtl"] h2, [dir="rtl"] h3 { letter-spacing: normal; } | |
| @@ -1,408 +0,0 @@ | ||
| 1 | 删除:/* --------------------------------------------------------------------------- | |
| 2 | 删除: agent-vm.org design tokens | |
| 3 | 删除: | |
| 4 | 删除: Dark only: one palette, no toggle, no `prefers-color-scheme` branch. The | |
| 5 | 删除: page is a terminal-adjacent thing and reads as one. Low-contrast hairlines, | |
| 6 | 删除: one accent, no gradients, no glass, no drop shadows beyond a hairline. | |
| 7 | 删除: --------------------------------------------------------------------------- */ | |
| 8 | 删除: | |
| 9 | 删除::root { | |
| 10 | 删除: color-scheme: dark; | |
| 11 | 删除: | |
| 12 | 删除: --paper: #131210; | |
| 13 | 删除: --paper-sunk: #0e0d0b; | |
| 14 | 删除: --surface: #1b1916; | |
| 15 | 删除: --surface-2: #211e1a; | |
| 16 | 删除: | |
| 17 | 删除: --ink: #f1ece2; | |
| 18 | 删除: --ink-2: #b8afa1; | |
| 19 | 删除: --ink-3: #8f877a; | |
| 20 | 删除: --ink-4: #665f55; | |
| 21 | 删除: | |
| 22 | 删除: --line: #2c2823; | |
| 23 | 删除: --line-strong: #3d3831; | |
| 24 | 删除: | |
| 25 | 删除: --accent: #e08c3e; | |
| 26 | 删除: --accent-hover: #efa055; | |
| 27 | 删除: --accent-wash: #241a11; | |
| 28 | 删除: --accent-line: #4a3620; | |
| 29 | 删除: | |
| 30 | 删除: --safe: #6fb18c; | |
| 31 | 删除: --safe-wash: #14201a; | |
| 32 | 删除: --safe-line: #2c4437; | |
| 33 | 删除: | |
| 34 | 删除: --danger: #d9705a; | |
| 35 | 删除: | |
| 36 | 删除: --code-bg: #0c0b0a; | |
| 37 | 删除: --code-ink: #e7e0d3; | |
| 38 | 删除: --code-ink-2: #8f8779; | |
| 39 | 删除: --code-line: #262320; | |
| 40 | 删除: | |
| 41 | 删除: --font-sans: 'Inter Variable', ui-sans-serif, system-ui, -apple-system, | |
| 42 | 删除: 'Segoe UI', Roboto, sans-serif; | |
| 43 | 删除: --font-mono: 'JetBrains Mono Variable', ui-monospace, 'SF Mono', Menlo, | |
| 44 | 删除: Consolas, monospace; | |
| 45 | 删除: | |
| 46 | 删除: --radius: 6px; | |
| 47 | 删除: --radius-lg: 10px; | |
| 48 | 删除: | |
| 49 | 删除: --container: 76rem; | |
| 50 | 删除: --gutter: clamp(1.25rem, 4vw, 2.5rem); | |
| 51 | 删除: --section-gap: clamp(4.5rem, 9vw, 8rem); | |
| 52 | 删除: | |
| 53 | 删除: --nav-h: 3.75rem; | |
| 54 | 删除:} | |
| 55 | 删除: | |
| 56 | 删除:/* --------------------------------------------------------------------------- */ | |
| 57 | 删除: | |
| 58 | 删除:*, | |
| 59 | 删除:*::before, | |
| 60 | 删除:*::after { | |
| 61 | 删除: box-sizing: border-box; | |
| 62 | 删除:} | |
| 63 | 删除: | |
| 64 | 删除:html { | |
| 65 | 删除: scroll-behavior: smooth; | |
| 66 | 删除: /* Anchor targets must clear the sticky nav. */ | |
| 67 | 删除: scroll-padding-top: calc(var(--nav-h) + 1.5rem); | |
| 68 | 删除: -webkit-text-size-adjust: 100%; | |
| 69 | 删除:} | |
| 70 | 删除: | |
| 71 | 删除:@media (prefers-reduced-motion: reduce) { | |
| 72 | 删除: html { | |
| 73 | 删除: scroll-behavior: auto; | |
| 74 | 删除: } | |
| 75 | 删除: *, | |
| 76 | 删除: *::before, | |
| 77 | 删除: *::after { | |
| 78 | 删除: animation-duration: 0.01ms !important; | |
| 79 | 删除: animation-iteration-count: 1 !important; | |
| 80 | 删除: transition-duration: 0.01ms !important; | |
| 81 | 删除: } | |
| 82 | 删除:} | |
| 83 | 删除: | |
| 84 | 删除:body { | |
| 85 | 删除: margin: 0; | |
| 86 | 删除: background: var(--paper); | |
| 87 | 删除: color: var(--ink); | |
| 88 | 删除: font-family: var(--font-sans); | |
| 89 | 删除: font-size: 1rem; | |
| 90 | 删除: line-height: 1.65; | |
| 91 | 删除: font-synthesis-weight: none; | |
| 92 | 删除: text-rendering: optimizeLegibility; | |
| 93 | 删除: -webkit-font-smoothing: antialiased; | |
| 94 | 删除:} | |
| 95 | 删除: | |
| 96 | 删除:img, | |
| 97 | 删除:svg { | |
| 98 | 删除: max-width: 100%; | |
| 99 | 删除: height: auto; | |
| 100 | 删除:} | |
| 101 | 删除: | |
| 102 | 删除:h1, | |
| 103 | 删除:h2, | |
| 104 | 删除:h3, | |
| 105 | 删除:h4 { | |
| 106 | 删除: margin: 0; | |
| 107 | 删除: font-weight: 620; | |
| 108 | 删除: letter-spacing: -0.021em; | |
| 109 | 删除: line-height: 1.12; | |
| 110 | 删除: text-wrap: balance; | |
| 111 | 删除:} | |
| 112 | 删除: | |
| 113 | 删除:h1 { | |
| 114 | 删除: font-size: clamp(2.6rem, 6.2vw, 4.4rem); | |
| 115 | 删除: letter-spacing: -0.034em; | |
| 116 | 删除: line-height: 1.02; | |
| 117 | 删除:} | |
| 118 | 删除: | |
| 119 | 删除:h2 { | |
| 120 | 删除: font-size: clamp(1.95rem, 3.6vw, 2.85rem); | |
| 121 | 删除: letter-spacing: -0.028em; | |
| 122 | 删除:} | |
| 123 | 删除: | |
| 124 | 删除:h3 { | |
| 125 | 删除: font-size: 1.125rem; | |
| 126 | 删除: letter-spacing: -0.014em; | |
| 127 | 删除: line-height: 1.35; | |
| 128 | 删除:} | |
| 129 | 删除: | |
| 130 | 删除:p { | |
| 131 | 删除: margin: 0; | |
| 132 | 删除:} | |
| 133 | 删除: | |
| 134 | 删除:a { | |
| 135 | 删除: color: var(--accent); | |
| 136 | 删除: text-decoration-thickness: 1px; | |
| 137 | 删除: text-underline-offset: 0.18em; | |
| 138 | 删除: transition: color 0.12s ease; | |
| 139 | 删除:} | |
| 140 | 删除: | |
| 141 | 删除:a:hover { | |
| 142 | 删除: color: var(--accent-hover); | |
| 143 | 删除:} | |
| 144 | 删除: | |
| 145 | 删除::focus-visible { | |
| 146 | 删除: outline: 2px solid var(--accent); | |
| 147 | 删除: outline-offset: 3px; | |
| 148 | 删除: border-radius: 3px; | |
| 149 | 删除:} | |
| 150 | 删除: | |
| 151 | 删除:code, | |
| 152 | 删除:kbd, | |
| 153 | 删除:samp, | |
| 154 | 删除:pre { | |
| 155 | 删除: font-family: var(--font-mono); | |
| 156 | 删除: font-feature-settings: 'liga' 0; | |
| 157 | 删除:} | |
| 158 | 删除: | |
| 159 | 删除:ul, | |
| 160 | 删除:ol { | |
| 161 | 删除: margin: 0; | |
| 162 | 删除: padding: 0; | |
| 163 | 删除:} | |
| 164 | 删除: | |
| 165 | 删除:/* --------------------------------------------------------------------------- */ | |
| 166 | 删除:/* Layout primitives */ | |
| 167 | 删除: | |
| 168 | 删除:.container { | |
| 169 | 删除: width: 100%; | |
| 170 | 删除: max-width: var(--container); | |
| 171 | 删除: margin-inline: auto; | |
| 172 | 删除: padding-inline: var(--gutter); | |
| 173 | 删除:} | |
| 174 | 删除: | |
| 175 | 删除:.section { | |
| 176 | 删除: padding-block: var(--section-gap); | |
| 177 | 删除: border-top: 1px solid var(--line); | |
| 178 | 删除: /* No scroll-margin here: html's scroll-padding-top already clears the | |
| 179 | 删除: sticky nav, and the two would stack into a visible gap. */ | |
| 180 | 删除:} | |
| 181 | 删除: | |
| 182 | 删除:.section--flush { | |
| 183 | 删除: border-top: 0; | |
| 184 | 删除:} | |
| 185 | 删除: | |
| 186 | 删除:.section-head { | |
| 187 | 删除: display: grid; | |
| 188 | 删除: gap: 1.15rem; | |
| 189 | 删除: max-width: 44rem; | |
| 190 | 删除: margin-bottom: clamp(2.5rem, 5vw, 4rem); | |
| 191 | 删除:} | |
| 192 | 删除: | |
| 193 | 删除:.eyebrow { | |
| 194 | 删除: display: flex; | |
| 195 | 删除: align-items: center; | |
| 196 | 删除: gap: 0.7rem; | |
| 197 | 删除: margin: 0; | |
| 198 | 删除: font-family: var(--font-mono); | |
| 199 | 删除: font-size: 0.7rem; | |
| 200 | 删除: font-weight: 500; | |
| 201 | 删除: letter-spacing: 0.14em; | |
| 202 | 删除: text-transform: uppercase; | |
| 203 | 删除: color: var(--accent); | |
| 204 | 删除:} | |
| 205 | 删除: | |
| 206 | 删除:.eyebrow::after { | |
| 207 | 删除: content: ''; | |
| 208 | 删除: flex: 0 1 4rem; | |
| 209 | 删除: height: 1px; | |
| 210 | 删除: background: var(--accent-line); | |
| 211 | 删除:} | |
| 212 | 删除: | |
| 213 | 删除:.lede { | |
| 214 | 删除: font-size: clamp(1.05rem, 1.6vw, 1.2rem); | |
| 215 | 删除: line-height: 1.6; | |
| 216 | 删除: color: var(--ink-2); | |
| 217 | 删除: text-wrap: pretty; | |
| 218 | 删除:} | |
| 219 | 删除: | |
| 220 | 删除:.prose { | |
| 221 | 删除: color: var(--ink-2); | |
| 222 | 删除: text-wrap: pretty; | |
| 223 | 删除:} | |
| 224 | 删除: | |
| 225 | 删除:.prose code { | |
| 226 | 删除: font-size: 0.86em; | |
| 227 | 删除: padding: 0.1em 0.28em; | |
| 228 | 删除: border: 1px solid var(--line); | |
| 229 | 删除: border-radius: 4px; | |
| 230 | 删除: background: var(--surface-2); | |
| 231 | 删除: color: var(--ink); | |
| 232 | 删除: white-space: nowrap; | |
| 233 | 删除:} | |
| 234 | 删除: | |
| 235 | 删除:/* Cards --------------------------------------------------------------------- */ | |
| 236 | 删除: | |
| 237 | 删除:.card { | |
| 238 | 删除: background: var(--surface); | |
| 239 | 删除: border: 1px solid var(--line); | |
| 240 | 删除: border-radius: var(--radius-lg); | |
| 241 | 删除: padding: clamp(1.25rem, 2.4vw, 1.75rem); | |
| 242 | 删除:} | |
| 243 | 删除: | |
| 244 | 删除:.card--sunk { | |
| 245 | 删除: background: var(--surface-2); | |
| 246 | 删除:} | |
| 247 | 删除: | |
| 248 | 删除:.note { | |
| 249 | 删除: border: 1px solid var(--line); | |
| 250 | 删除: border-left: 3px solid var(--line-strong); | |
| 251 | 删除: border-radius: var(--radius); | |
| 252 | 删除: background: var(--surface-2); | |
| 253 | 删除: padding: 1.1rem 1.25rem; | |
| 254 | 删除:} | |
| 255 | 删除: | |
| 256 | 删除:.note--accent { | |
| 257 | 删除: border-color: var(--accent-line); | |
| 258 | 删除: border-left-color: var(--accent); | |
| 259 | 删除: background: var(--accent-wash); | |
| 260 | 删除:} | |
| 261 | 删除: | |
| 262 | 删除:.note__title { | |
| 263 | 删除: display: block; | |
| 264 | 删除: margin-bottom: 0.4rem; | |
| 265 | 删除: font-size: 0.94rem; | |
| 266 | 删除: font-weight: 620; | |
| 267 | 删除: color: var(--ink); | |
| 268 | 删除: letter-spacing: -0.01em; | |
| 269 | 删除:} | |
| 270 | 删除: | |
| 271 | 删除:/* Buttons ------------------------------------------------------------------- */ | |
| 272 | 删除: | |
| 273 | 删除:.btn { | |
| 274 | 删除: display: inline-flex; | |
| 275 | 删除: align-items: center; | |
| 276 | 删除: gap: 0.5rem; | |
| 277 | 删除: padding: 0.68rem 1.2rem; | |
| 278 | 删除: border: 1px solid transparent; | |
| 279 | 删除: border-radius: var(--radius); | |
| 280 | 删除: font-size: 0.94rem; | |
| 281 | 删除: font-weight: 560; | |
| 282 | 删除: letter-spacing: -0.008em; | |
| 283 | 删除: text-decoration: none; | |
| 284 | 删除: cursor: pointer; | |
| 285 | 删除: transition: background-color 0.14s ease, border-color 0.14s ease, | |
| 286 | 删除: color 0.14s ease; | |
| 287 | 删除:} | |
| 288 | 删除: | |
| 289 | 删除:.btn--primary { | |
| 290 | 删除: background: var(--ink); | |
| 291 | 删除: color: var(--paper); | |
| 292 | 删除:} | |
| 293 | 删除: | |
| 294 | 删除:.btn--primary:hover { | |
| 295 | 删除: background: var(--accent); | |
| 296 | 删除: color: #17140f; | |
| 297 | 删除:} | |
| 298 | 删除: | |
| 299 | 删除:.btn--ghost { | |
| 300 | 删除: background: transparent; | |
| 301 | 删除: border-color: var(--line-strong); | |
| 302 | 删除: color: var(--ink); | |
| 303 | 删除:} | |
| 304 | 删除: | |
| 305 | 删除:.btn--ghost:hover { | |
| 306 | 删除: border-color: var(--ink-3); | |
| 307 | 删除: color: var(--ink); | |
| 308 | 删除: background: var(--surface-2); | |
| 309 | 删除:} | |
| 310 | 删除: | |
| 311 | 删除:/* Tables -------------------------------------------------------------------- */ | |
| 312 | 删除: | |
| 313 | 删除:.table-wrap { | |
| 314 | 删除: overflow-x: auto; | |
| 315 | 删除: border: 1px solid var(--line); | |
| 316 | 删除: border-radius: var(--radius-lg); | |
| 317 | 删除: background: var(--surface); | |
| 318 | 删除:} | |
| 319 | 删除: | |
| 320 | 删除:table { | |
| 321 | 删除: width: 100%; | |
| 322 | 删除: border-collapse: collapse; | |
| 323 | 删除: font-size: 0.9rem; | |
| 324 | 删除:} | |
| 325 | 删除: | |
| 326 | 删除:thead th { | |
| 327 | 删除: position: sticky; | |
| 328 | 删除: top: 0; | |
| 329 | 删除: text-align: left; | |
| 330 | 删除: font-family: var(--font-mono); | |
| 331 | 删除: font-size: 0.68rem; | |
| 332 | 删除: font-weight: 500; | |
| 333 | 删除: letter-spacing: 0.12em; | |
| 334 | 删除: text-transform: uppercase; | |
| 335 | 删除: color: var(--ink-3); | |
| 336 | 删除: background: var(--surface-2); | |
| 337 | 删除: padding: 0.75rem 1rem; | |
| 338 | 删除: border-bottom: 1px solid var(--line); | |
| 339 | 删除: white-space: nowrap; | |
| 340 | 删除:} | |
| 341 | 删除: | |
| 342 | 删除:tbody td { | |
| 343 | 删除: padding: 0.72rem 1rem; | |
| 344 | 删除: border-bottom: 1px solid var(--line); | |
| 345 | 删除: color: var(--ink-2); | |
| 346 | 删除: vertical-align: top; | |
| 347 | 删除:} | |
| 348 | 删除: | |
| 349 | 删除:tbody tr:last-child td { | |
| 350 | 删除: border-bottom: 0; | |
| 351 | 删除:} | |
| 352 | 删除: | |
| 353 | 删除:tbody td:first-child { | |
| 354 | 删除: color: var(--ink); | |
| 355 | 删除: font-weight: 500; | |
| 356 | 删除:} | |
| 357 | 删除: | |
| 358 | 删除:td code, | |
| 359 | 删除:th code { | |
| 360 | 删除: font-size: 0.85em; | |
| 361 | 删除: color: var(--ink); | |
| 362 | 删除: white-space: nowrap; | |
| 363 | 删除:} | |
| 364 | 删除: | |
| 365 | 删除:.table--code tbody td:first-child { | |
| 366 | 删除: font-family: var(--font-mono); | |
| 367 | 删除: font-size: 0.83rem; | |
| 368 | 删除: font-weight: 450; | |
| 369 | 删除: white-space: nowrap; | |
| 370 | 删除: color: var(--accent); | |
| 371 | 删除:} | |
| 372 | 删除: | |
| 373 | 删除:.table--grid tbody td:not(:first-child) { | |
| 374 | 删除: font-variant-numeric: tabular-nums; | |
| 375 | 删除:} | |
| 376 | 删除: | |
| 377 | 删除:/* Utilities ----------------------------------------------------------------- */ | |
| 378 | 删除: | |
| 379 | 删除:.visually-hidden { | |
| 380 | 删除: position: absolute; | |
| 381 | 删除: width: 1px; | |
| 382 | 删除: height: 1px; | |
| 383 | 删除: margin: -1px; | |
| 384 | 删除: padding: 0; | |
| 385 | 删除: overflow: hidden; | |
| 386 | 删除: clip-path: inset(50%); | |
| 387 | 删除: white-space: nowrap; | |
| 388 | 删除: border: 0; | |
| 389 | 删除:} | |
| 390 | 删除: | |
| 391 | 删除:.skip-link { | |
| 392 | 删除: position: absolute; | |
| 393 | 删除: left: 0.75rem; | |
| 394 | 删除: top: -4rem; | |
| 395 | 删除: z-index: 100; | |
| 396 | 删除: padding: 0.6rem 1rem; | |
| 397 | 删除: background: var(--ink); | |
| 398 | 删除: color: var(--paper); | |
| 399 | 删除: border-radius: var(--radius); | |
| 400 | 删除: text-decoration: none; | |
| 401 | 删除: font-size: 0.9rem; | |
| 402 | 删除: transition: top 0.15s ease; | |
| 403 | 删除:} | |
| 404 | 删除: | |
| 405 | 删除:.skip-link:focus { | |
| 406 | 删除: top: 0.75rem; | |
| 407 | 删除: color: var(--paper); | |
| 408 | 删除:} | |

