Compare commits

...
30 changed files with 1588 additions and 213 deletions

No files matched your search

+64 -8
View File
@@ -17,6 +17,10 @@ on:
description: "Publish as an alpha prerelease (never stable)"
type: boolean
default: true
rebuild:
description: "Build a new patch revision (runtime-<commit>-pN) even if this upstream commit is already released"
type: boolean
default: false
permissions:
contents: write
@@ -36,22 +40,50 @@ jobs:
outputs:
commit: ${{ steps.r.outputs.commit }}
skip: ${{ steps.r.outputs.skip }}
suffix: ${{ steps.r.outputs.suffix }}
steps:
- id: r
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
WANT: ${{ inputs.upstream_commit }}
REBUILD: ${{ inputs.rebuild }}
run: |
set -euo pipefail
git clone -q --filter=blob:none --no-checkout "$UPSTREAM_URL" up
commit="$(git -C up rev-parse --verify "${WANT:-HEAD}^{commit}")"
echo "commit=$commit" >> "$GITHUB_OUTPUT"
# Already published (alpha or stable) under any short-hash length?
skip=false
# Already published (alpha or stable) under any short-hash length or -pN revision?
max_rev=0
for tag in $(gh release list -R "$GITHUB_REPOSITORY" --limit 1000 --json tagName -q '.[].tagName' | grep '^runtime-' || true); do
case "$commit" in "${tag#runtime-}"*) skip=true; echo "Upstream $commit is already released as $tag";; esac
rest="${tag#runtime-}"
base="${rest%%-p*}"
case "$commit" in
"$base"*)
rev=1
if [ "$rest" != "$base" ]; then
num="${rest#"$base"-p}"
case "$num" in
''|*[!0-9]*) ;;
*) rev="$num" ;;
esac
fi
if [ "$rev" -gt "$max_rev" ]; then max_rev="$rev"; fi
echo "Upstream $commit is already released as $tag (rev $rev)"
;;
esac
done
skip=false
suffix=""
if [ "$max_rev" -gt 0 ]; then
if [ "$REBUILD" = "true" ]; then
suffix="-p$((max_rev + 1))"
echo "Rebuild requested: will publish with suffix $suffix"
else
skip=true
fi
fi
echo "skip=$skip" >> "$GITHUB_OUTPUT"
echo "suffix=$suffix" >> "$GITHUB_OUTPUT"
build:
needs: resolve
@@ -60,6 +92,7 @@ jobs:
timeout-minutes: 150
outputs:
short: ${{ steps.patches.outputs.short }}
release_id: ${{ steps.patches.outputs.release_id }}
applied: ${{ steps.patches.outputs.applied }}
merged: ${{ steps.patches.outputs.merged }}
conflict: ${{ steps.patches.outputs.conflict }}
@@ -99,8 +132,10 @@ jobs:
git -C $work submodule update --init --depth 1 vendor/qemu
if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu }
if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' }
$short = (git -C $work rev-parse --short HEAD).Trim()
$short = (git -C $work rev-parse --short=7 HEAD).Trim()
$releaseId = "$short${{ needs.resolve.outputs.suffix }}"
"short=$short" >> $env:GITHUB_OUTPUT
"release_id=$releaseId" >> $env:GITHUB_OUTPUT
# Applies what applies, skips what upstream already has, stops on a
# conflict without touching the patch (AGENTS.md rule 4).
@@ -120,6 +155,7 @@ jobs:
if (-not $ok) { throw 'patch queue does not apply' }
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
"RELEASE_ID=$releaseId" >> $env:GITHUB_ENV
"CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV
"XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV
"XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV
@@ -151,6 +187,7 @@ jobs:
-OutDir $outDir `
-TempRoot $env:RUNNER_TEMP `
-Channel alpha `
-ReleaseId $env:RELEASE_ID `
-Patches $applied
- name: Alpha entry gate
@@ -159,14 +196,14 @@ jobs:
$ErrorActionPreference = 'Stop'
& ./scripts/check-runtime-alpha.ps1 `
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
-Commit $env:SHORT_COMMIT `
-Commit $env:RELEASE_ID `
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
- name: Upload alpha artifacts
uses: actions/upload-artifact@v4
with:
name: reims-runtime-win-x64-${{ env.SHORT_COMMIT }}-alpha
name: reims-runtime-win-x64-${{ env.RELEASE_ID }}-alpha
path: |
${{ runner.temp }}/releases/reims-runtime-*.tar.zst
${{ runner.temp }}/releases/SHA256SUMS.txt
@@ -180,14 +217,15 @@ jobs:
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$c = $env:SHORT_COMMIT
$c = $env:RELEASE_ID
$short = $env:SHORT_COMMIT
$dir = Join-Path $env:RUNNER_TEMP 'releases'
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", 'SHA256SUMS.txt') |
ForEach-Object { Join-Path $dir $_ }
$applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' }
$merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' }
$notes = @"
**Alpha** runtime, built automatically from upstream [steelbrain/reims-vgpu@$c](https://github.com/steelbrain/reims-vgpu/commit/${{ needs.resolve.outputs.commit }}).
**Alpha** runtime (``$c``), built automatically from upstream [steelbrain/reims-vgpu@$short](https://github.com/steelbrain/reims-vgpu/commit/${{ needs.resolve.outputs.commit }}).
Not smoke-tested on a real host. It becomes stable only after ``scripts/smoke-runtime.ps1`` passes on a real Windows host and a person approves (portable-runtime-spec.md section 6).
@@ -199,6 +237,24 @@ jobs:
gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
- name: Mirror alpha prerelease to GitCode (best-effort)
if: github.event_name == 'schedule' || inputs.publish
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
GITHUB_REPO: ${{ github.repository }}
shell: pwsh
run: |
if (-not $env:GITCODE_TOKEN) {
Write-Host 'GITCODE_TOKEN not set; skipping GitCode mirror'
exit 0
}
$tag = "runtime-$($env:RELEASE_ID)"
git fetch --tags origin
git -c credential.helper= push "https://Nwflower:$($env:GITCODE_TOKEN)@gitcode.com/Nwflower/Reims-Go.git" "refs/tags/${tag}:refs/tags/${tag}"
python scripts/sync-gitcode-release.py $tag
- name: Prune old alpha prereleases
if: github.event_name == 'schedule' || inputs.publish
env:
+75
View File
@@ -0,0 +1,75 @@
name: Sync Mirror to GitCode
on:
push:
branches: [main]
release:
types: [published, released, edited, prereleased]
workflow_dispatch:
inputs:
tag:
description: "Specific release tag to sync (empty = latest app release + all runtime-* releases)"
required: false
default: ""
sync_releases:
description: "Also sync Release metadata and assets to GitCode"
type: boolean
default: true
concurrency:
group: sync-gitcode
cancel-in-progress: false
jobs:
sync:
runs-on: ubuntu-latest
env:
GITCODE_REPO: Nwflower/Reims-Go
GITCODE_USER: Nwflower
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Push main branch and tags to GitCode
env:
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
run: |
set -euo pipefail
if [ -z "$GITCODE_TOKEN" ]; then
echo "GITCODE_TOKEN secret is not configured; skipping."
exit 0
fi
git fetch --tags origin
# Use GIT_ASKPASS so the token never appears in URLs or process argv.
askpass="$(mktemp)"
chmod 700 "$askpass"
cat > "$askpass" <<'EOF'
#!/bin/sh
case "$1" in
*Username*) printf '%s\n' "$GITCODE_USER" ;;
*) printf '%s\n' "$GITCODE_TOKEN" ;;
esac
EOF
trap 'rm -f "$askpass"' EXIT
GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= push "https://gitcode.com/${GITCODE_REPO}.git" HEAD:refs/heads/main
GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= push "https://gitcode.com/${GITCODE_REPO}.git" --tags
- name: Sync Release and assets to GitCode
if: github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && inputs.sync_releases)
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }}
GITHUB_REPO: ${{ github.repository }}
TARGET_TAG: ${{ github.event.release.tag_name || inputs.tag }}
run: |
set -euo pipefail
if [ -z "$GITCODE_TOKEN" ]; then
echo "GITCODE_TOKEN secret is not configured; skipping release sync."
exit 0
fi
if [ -n "$TARGET_TAG" ]; then
python3 scripts/sync-gitcode-release.py "$TARGET_TAG"
else
python3 scripts/sync-gitcode-release.py
fi
+1 -1
View File
@@ -59,7 +59,7 @@ flowchart TB
### 3.2 `internal/runtime` — 便携运行时管理
- 维护 `<DataRoot>\runtimes\` 下的多版本便携运行时包:
- **来源**:本仓库的 GitHub Release(tag `runtime-<commit>`,预发布为 `alpha`(CI 每天自动构建),正式发布为 `stable`),支持断点续传,并对照 `SHA256SUMS.txt` 校验;也可以导入本地 `.tar.zst` 包。下载端点只有这一个,没有镜像,也不测速选路;
- **来源**:本仓库的 GitHub Release(主源,tag `runtime-<commit>`,预发布为 `alpha`,正式发布为 `stable`)与官方镜像仓 [GitCode `Nwflower/Reims-Go`](https://gitcode.com/Nwflower/Reims-Go)(支持 `auto` 自动回退、`github`、`gitcode` 三种模式;自动读取环境变量与 Windows 系统代理;GitHub 限流时自动降级网页解析),均支持 HTTP `Range` 断点续传并强制对照 `SHA256SUMS.txt` 校验;也可以导入本地 `.tar.zst` 包;
- 校验 `manifest.json` 与 SHA256 后解压至 `<commit>.tmp` 再原子重命名,失败不破坏现有版本;
- 统一构造子进程环境(`XDG_*`、`REIMS_CTL_QEMU`、`PATH`),彻底消除对用户全局环境变量与 C 盘的依赖;
+1
View File
@@ -114,6 +114,7 @@ reims-runtime-<commit>/
| :--- | :--- | :--- | :--- |
| `reims-vgpu-win32-unicode-input.patch` | `reims-vgpu` 的 `crates/reims-vgpu-window`(`native/windows.rs`、`native/sdl_thread/ui.rs`) | SDL3 窗口层未开启 TextInput 且只转发 `0x04..=0xE7` 物理扫描码,导致直接投递 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR` 或宿主机 IME 上屏的文字被吞;通过 `SDL_SetWindowsMessageHook` 仅在设置 `REIMS_GO_INPUT_URL`(仅限 `127.0.0.1`)时异步转发非物理按键字符给宿主机文本注入桥 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时冒烟验证后提 PR |
| `reims-vgpu-cargo-lock.patch` | 上游 `reims-vgpu`(`3731afd`)的 `Cargo.lock` | 不改代码。cargo 构建时会给 `metal2vulkan`、`metal2vulkan-air`、`metal2vulkan-runtime` 补上 `source = "git+…metal2vulkan?rev=0b0ac58…"`;带上这个补丁,源码包才和实际构建一致 | 不需要上游 PR;上游 `Cargo.lock` 补齐后删除 |
| `reims-ctl-win32-random-bytes.patch` | `steelbrain/reims-vgpu` (`3731afd`) 的 `crates/reims-ctl/src/vm.rs` | `random_bytes()`(`vm.rs:849-864`)在打不开 `/dev/urandom` 时退回用「纳秒时间 ^ (pid << 64)」当种子。Windows 上永远走这条退路,于是新 VM 的 MAC 后 3 字节(也就是 OpenCore 的 ROM)只剩约 22 位、可预测的时钟熵,第 4 段永远是 4 的倍数。改成用 std `RandomState` 做哈希(它的密钥来自系统随机源 ProcessPrng),不加依赖,不改 Cargo 文件 | 2026-11-29 新增补丁,`git apply --check` 通过;本机没有 Rust 工具链,尚未编译,待编入下一版 alpha 运行时验证后提 PR |
| `qemu-whpx-win10-compat.patch` | `vendor/qemu` 的 `target/i386/whpx/whpx-all.c` | ① `whpx_tsc_deadline_refused()`(`3210-3230`)原实现在真实分区上建、删 vCPU 0,Win10 19045 上随后 `whpx_init_vcpu()` 再次创建 vCPU 0 时必现 `WHvCreateVirtualProcessor` 返回 `E_INVALIDARG`(`hr=80070057`),改为独立临时探测分区;② `whpx_set_registers()`(`534`)直接调用 `WHvResetPartition` 未判空,Win10 19045 的 `WinHvPlatform.dll` 不导出该接口导致重置阶段必现 `0xc0000005 at 0x0` 崩溃(已核对导出表,10 个 supplemental API 中仅此一处漏判空) | 2026-11-28 实测复现并修复,待提交上游 PR(由人操作) |
| `qemu-whpx-win10-startup-ipis.patch` | 同上(在前一项之后应用) | Win10 开启内核 irqchip 时转发多核 INIT/SIPI,避免 XNU 从核启动停住 | 已合入补丁队列,客体冷重启待验证,待提交上游 PR |
| `qemu-whpx-nested-virt-nonfatal.patch` | 同上(在前两项之后应用) | 部分 Win11 宿主 `WHvSetPartitionProperty(NestedVirtualization)` 返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)导致 QEMU 在 `whpx-all.c:3479-3483` 直接致命退出,改为非致命警告并清零 `Bank1.NestedVirtSupport`,保留 `kernel-irqchip=on` 内核态 x2APIC 加速 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时并在 Win11 真机冒烟验证后提 PR |
+1 -1
View File
@@ -134,7 +134,7 @@ flowchart LR
### 核心体验的实现与跟进清单
- [ ] **M5.1(上游运行时联动)**:**沉浸全屏、无黑边缩放与 GPU 性能升级**
- 本仓已完成:VM 详情页与设置页/新建向导补齐「无边框全屏启动」一键开关(走 `reims-ctl set --borderless`,支持运行中变更进入待生效列表)与 `Ctrl+Alt+Enter` / `Ctrl+Alt+G` 热切快捷键提示条;
- 本仓已完成:VM 详情页与设置页/新建向导补齐「无边框全屏启动」开关(走 `reims-ctl set --borderless`,支持运行中变更进入待生效列表)与按显卡后端区分的真实快捷键提示(`reims-vgpu` 捕获时显示 `Ctrl+Alt+Win` 释放输入,`vmware-svga` GTK 窗口显示 `Ctrl+Alt+F` / `Ctrl+Alt+G`);
- 待上游跟进:待 [`docs/upstream-pr-prep.md`](upstream-pr-prep.md) 中上游 `reims-vgpu` PR 合入后由 `build-runtime.yml` 产出新 `alpha`,冒烟后升为 `stable`:`#123`(`Ctrl+Alt+Enter` 运行中热切全屏)、`#172`(Windows 拖动窗口动态贴合、消除黑边)、`#152`(原生 Windows Vulkan 后端)、`#153`(NVIDIA MAILBOX/FIFO 首帧优化)、`#107`(采样纹理回读就地消费)。
- [ ] **M5.2(本仓 + 上游)**:**HiDPI 智能推荐与 Mac 键位习惯适配**
- 本仓已完成:`internal/host` 新增原生 Windows 物理显示器与 DPI 缩放探测(`EnumDisplayMonitors` + `EnumDisplaySettingsW` + `GetDpiForMonitor`),按主屏分辨率与 DPI 缩放自动推荐 1× / 2× HiDPI 预设(2K/2.5K/4K/16:10),并在宿主页、新建向导第 4 步与设置页展示智能推荐与多屏引导;设置页键盘分类补齐 Mac 键位提示;
+6 -1
View File
@@ -16,7 +16,7 @@ import { I18nKey, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
import { LogLine, appendLog } from './lib/logs'
import { currentTask, upsertTask } from './lib/tasks'
import { AppState, CachedInstaller, CreateOpts, Locale, Task, VMDetail, VMStats } from './types'
import { AppState, CachedInstaller, CreateOpts, Locale, RuntimeSource, Task, VMDetail, VMStats } from './types'
import { TooltipProvider } from './ui/controls'
import { Toaster, useToasts } from './ui/toast'
import { api, events } from './wails'
@@ -176,6 +176,9 @@ export const App: React.FC = () => {
const setChannel = (alpha: boolean) => {
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(refresh).catch((e) => fail(tr('failGeneric'), e))
}
const setSource = (source: RuntimeSource) => {
api.SetRuntimeSource(source).then(refresh).catch((e) => fail(tr('failGeneric'), e))
}
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
const importRuntime = async () => {
try {
@@ -492,6 +495,7 @@ export const App: React.FC = () => {
onFinish={() => setSetupStage(null)}
onError={fail}
onChannel={setChannel}
onSource={setSource}
onInstallRuntime={installRuntime}
onCancelTask={cancelTask}
onImportRuntime={importRuntime}
@@ -573,6 +577,7 @@ export const App: React.FC = () => {
onSetLocale={setLang}
runtimeTask={runtimeTask}
onChannel={setChannel}
onSource={setSource}
onInstallRuntime={installRuntime}
onCancelTask={cancelTask}
/>
+5 -2
View File
@@ -2,7 +2,7 @@ import { Cpu, Download, HardDrive, MemoryStick, RefreshCw, ShieldCheck } from 'l
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { findOptimization, kernelIrqchipHint, optBadgeClass, optStatusLabel } from '../lib/optimizations'
import { AppState, AppUpdateInfo, Locale, Task } from '../types'
import { AppState, AppUpdateInfo, Locale, RuntimeSource, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { api } from '../wails'
import { RuntimeOnline } from './RuntimeOnline'
@@ -15,11 +15,12 @@ interface Props {
onSetLocale: (l: Locale) => void
runtimeTask: Task | null
onChannel: (alpha: boolean) => void
onSource: (source: RuntimeSource) => void
onInstallRuntime: (commit: string) => void
onCancelTask: (id: string) => void
}
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, onSetLocale, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => {
export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, onSetLocale, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask }) => {
const [importing, setImporting] = useState(false)
const [enabling, setEnabling] = useState(false)
const [openingSched, setOpeningSched] = useState(false)
@@ -144,9 +145,11 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onError, o
<RuntimeOnline
locale={locale}
channel={config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
source={config.runtime_source === 'github' || config.runtime_source === 'gitcode' ? config.runtime_source : 'auto'}
installed={runtimes ?? []}
task={runtimeTask}
onChannel={onChannel}
onSource={onSource}
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
+45 -8
View File
@@ -1,17 +1,19 @@
import { Download, LoaderCircle, Pause } from 'lucide-react'
import { Download, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { taskDetail } from '../lib/tasks'
import { InstalledRuntime, Locale, RemoteRuntime, Task } from '../types'
import { InstalledRuntime, Locale, RemoteRuntime, RuntimeSource, Task } from '../types'
import { Button, IconButton } from '../ui/controls'
import { api } from '../wails'
interface Props {
locale: Locale
channel: 'stable' | 'alpha'
source: RuntimeSource
installed: InstalledRuntime[]
task: Task | null
onChannel: (alpha: boolean) => void
onSource: (source: RuntimeSource) => void
onInstall: (commit: string) => void
onCancel: (taskId: string) => void
}
@@ -23,12 +25,13 @@ const shortQemu = (v: string) => v.replace(/^QEMU emulator version\s*/i, 'QEMU '
/**
* The runtime rows: the active runtime and whether it is current (or, with
* none installed, the newest release to install), then the alpha switch.
* none installed, the newest release to install), then download source and alpha switches.
*/
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, task, onChannel, onInstall, onCancel }) => {
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, source, installed, task, onChannel, onSource, onInstall, onCancel }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [remote, setRemote] = useState<RemoteRuntime[] | null>(null)
const [error, setError] = useState('')
const [reload, setReload] = useState(0)
useEffect(() => {
let live = true
@@ -38,11 +41,16 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
.then((list) => { if (live) setRemote(list ?? []) })
.catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) })
return () => { live = false }
}, [channel, task?.status === 'done'])
}, [channel, source, task?.status === 'done', reload])
const active = installed.find((i) => i.active) ?? installed[0]
const latest = remote?.[0]
const isInstalled = (c: string) => installed.some((i) => i.commit.startsWith(c) || c.startsWith(i.commit))
const sameRuntimeId = (a: string, b: string) => {
const [baseA, revA = ''] = a.split('-', 2)
const [baseB, revB = ''] = b.split('-', 2)
return revA === revB && (baseA.startsWith(baseB) || baseB.startsWith(baseA))
}
const isInstalled = (c: string) => installed.some((i) => sameRuntimeId(i.commit, c))
const running = task?.status === 'running'
const updatable = !!latest && !isInstalled(latest.commit)
@@ -58,16 +66,21 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
} else if (active && !updatable) {
sub = <div className="row-sub">{shortQemu(active.manifest.qemu_version)}</div>
} else if (error) {
sub = <div className="row-sub" title={error}>{tr('runtimeLookupFailed')}</div>
const isRateLimit = /rate limit|HTTP 403|HTTP 429/i.test(error)
const msg = isRateLimit ? tr('runtimeLookupRateLimit') : `${tr('runtimeLookupFailed')}: ${error}`
sub = <div className="row-sub" title={error}>{msg}</div>
} else if (!remote) {
sub = <div className="row-sub">…</div>
} else if (!latest) {
sub = <div className="row-sub">{tr('runtimeNoneOnChannel')}</div>
} else {
const srcLabel = latest.source === 'gitcode' ? 'GitCode' : latest.source === 'github' ? 'GitHub' : ''
sub = (
<div className="row-sub">
{active ? tr('runtimeNewer', { v: latest.commit }) : tr('runtimeLatest', { v: latest.commit })}
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)} · {gb(latest.archive_size)}
{' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)}
{srcLabel ? ` · ${srcLabel}` : ''}
{latest.archive_size > 0 ? ` · ${gb(latest.archive_size)}` : ''}
</div>
)
}
@@ -84,6 +97,10 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
<div className="row-right">
{running && task?.cancelable ? (
<IconButton label={tr('pauseDownload')} icon={<Pause size={16} />} onClick={() => onCancel(task.id)} />
) : !running && error ? (
<Button icon={<RefreshCw size={14} />} onClick={() => setReload((n) => n + 1)}>
{tr('runtimeRetry')}
</Button>
) : !running && updatable ? (
<Button variant="primary" icon={<Download size={14} />} onClick={() => onInstall(latest!.commit)}>
{tr(active ? 'runtimeUpdate' : 'runtimeInstall')}
@@ -93,6 +110,26 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
) : null}
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('runtimeSource')}</div>
<div className="row-sub">{tr('runtimeSourceHint')}</div>
</div>
<div className="row-right">
<div className="segmented" role="group" aria-label={tr('runtimeSource')}>
{(['auto', 'github', 'gitcode'] as RuntimeSource[]).map((s) => (
<button
key={s}
type="button"
aria-pressed={source === s}
onClick={() => onSource(s)}
>
{tr(`runtimeSource_${s}` as I18nKey)}
</button>
))}
</div>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('runtimeAlpha')}</div>
+5 -2
View File
@@ -1,7 +1,7 @@
import { FolderOpen, HardDrive } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { AppState, DataRootCheck, DataRootChoice, Locale, Task } from '../types'
import { AppState, DataRootCheck, DataRootChoice, Locale, RuntimeSource, Task } from '../types'
import { Button } from '../ui/controls'
import { recommendedMemoryGB, shortGPUName } from '../lib/format'
import { api } from '../wails'
@@ -17,6 +17,7 @@ interface Props {
onFinish: () => void
onError: (title: string, e: unknown) => void
onChannel: (alpha: boolean) => void
onSource: (source: RuntimeSource) => void
onInstallRuntime: (commit: string) => void
onCancelTask: (id: string) => void
onImportRuntime: () => void
@@ -148,7 +149,7 @@ const FolderStep: React.FC<StepProps> = ({ locale, tr, onLocale, onFolderDone, o
)
}
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => {
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => {
const ready = !!state.active_runtime
const { host } = state
const [enabling, setEnabling] = useState(false)
@@ -215,9 +216,11 @@ const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onCh
<RuntimeOnline
locale={locale}
channel={state.config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
source={state.config.runtime_source === 'github' || state.config.runtime_source === 'gitcode' ? state.config.runtime_source : 'auto'}
installed={state.runtimes ?? []}
task={runtimeTask}
onChannel={onChannel}
onSource={onSource}
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
+180 -99
View File
@@ -1,6 +1,7 @@
import * as Menu from '@radix-ui/react-dropdown-menu'
import {
Activity,
AlertTriangle,
Archive,
ChevronRight,
Copy,
@@ -9,10 +10,14 @@ import {
Disc,
Ellipsis,
FolderOpen,
Globe,
HardDrive,
Info,
Keyboard,
LifeBuoy,
MemoryStick,
Monitor,
Network,
Play,
Power,
RotateCw,
@@ -181,81 +186,120 @@ export const VMPage: React.FC<Props> = ({
// Each fact is said once (docs/ui-audit.md H1); raw upstream values live in
// "Technical details" at the bottom.
const diskUsed = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
const specs: { label: string; value: string }[] = detail
const specs: { label: string; value: string; icon: React.ReactNode }[] = detail
? [
{ label: tr('factCPU'), value: tr('cores', { n: detail.cpus }) },
{ label: tr('factMemory'), value: formatMemory(detail.memory) },
{ label: tr('factGraphics'), value: graphicsLabel(locale, detail, host) + (detail.displays > 1 ? ` × ${detail.displays}` : '') },
{ label: tr('factCPU'), value: tr('cores', { n: detail.cpus }), icon: <Cpu size={14} aria-hidden="true" /> },
{ label: tr('factMemory'), value: formatMemory(detail.memory), icon: <MemoryStick size={14} aria-hidden="true" /> },
{ label: tr('factGraphics'), value: graphicsLabel(locale, detail, host) + (detail.displays > 1 ? ` × ${detail.displays}` : ''), icon: <Monitor size={14} aria-hidden="true" /> },
{
label: tr('factDisk'),
value: diskUsed && stats
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats.disk_actual_bytes), max: formatBytes(stats.disk_virtual_bytes) })
: controllerLabel(detail.disk_controller),
icon: <HardDrive size={14} aria-hidden="true" />,
},
{ label: tr('fieldNetwork'), value: detail.network ? (detail.ssh_port > 0 ? `NAT · SSH ${detail.ssh_port}` : 'NAT') : tr('off') },
...(detail.guest_lang ? [{ label: tr('specLang'), value: splitLangLabel('', guestLangLabel(locale, detail.guest_lang)).label }] : []),
{ label: tr('fieldNetwork'), value: detail.network ? (detail.ssh_port > 0 ? `NAT · SSH ${detail.ssh_port}` : 'NAT') : tr('off'), icon: <Network size={14} aria-hidden="true" /> },
...(detail.guest_lang ? [{ label: tr('specLang'), value: splitLangLabel('', guestLangLabel(locale, detail.guest_lang)).label, icon: <Globe size={14} aria-hidden="true" /> }] : []),
]
: []
// QEMU's working set runs a little above the guest's RAM, so the bar is the
// share of host memory it takes (the label says "host memory").
const hostBytes = (host.total_ram_gb || 0) * 1024 ** 3
const cpuPct = running && stats ? Math.min(100, Math.max(0, stats.cpu_percent || 0)) : 0
const memPct = running && stats && hostBytes > 0 ? Math.min(100, (stats.memory_rss_bytes / hostBytes) * 100) : 0
const meterTone = (pct: number) => (pct >= 90 ? ' high' : pct >= 75 ? ' warn' : '')
const copyTechSummary = () => {
if (!detail) return
const rows = [
`${tr('fieldKind')}: ${detail.kind || '—'}`,
`${tr('fieldCPUModel')}: ${detail.cpu_model || 'auto'}`,
`${tr('fieldGraphicsBackend')}: ${detail.graphics}`,
...(detail.gpu && detail.gpu !== 'auto' ? [`${tr('fieldICD')}: ${detail.gpu}`] : []),
`${tr('resolution')}: ${detail.displays} × ${detail.resolution}`,
`${tr('fieldController')}: ${detail.disk_controller}`,
`${tr('fieldDisk')}: ${detail.disk}`,
`${tr('fieldNetwork')}: ${detail.network_summary || tr('off')}`,
`${tr('fieldAudio')}: ${detail.audio_raw || tr('off')}`,
...(detail.guest_lang ? [`${tr('guestLang')}: ${detail.guest_lang}`] : []),
`${tr('fieldDir')}: ${detail.directory}`,
]
onCopy(rows.join('\n'))
}
return (
<div className="page vm-page">
<section className="vm-hero" aria-labelledby="vm-name">
<VMScreen thumb={thumb} running={running} startLabel={tr('start')} onStart={state === 'stopped' && !busy ? () => onAction('start') : undefined} />
<h1 className="vm-hero-name" id="vm-name">{name}</h1>
<div className="vm-hero-sub">
<div className={`vm-hero-pill${running ? ' is-running' : state === 'broken' ? ' is-broken' : ''}`}>
<StatusShape kind={statusKind(state)} />
{tr(`state_${state}` as I18nKey)}
{running && stats && stats.uptime_seconds > 0 && <span className="muted">· {formatUptime(stats.uptime_seconds, locale)}</span>}
<span>{tr(`state_${state}` as I18nKey)}</span>
{running && stats && stats.uptime_seconds > 0 && <span>· {formatUptime(stats.uptime_seconds, locale)}</span>}
</div>
{specs.length > 0 && (
<dl className="vm-specs">
{specs.map((s) => (
<React.Fragment key={s.label}>
<dt>{s.label}</dt>
<dd>{s.value}</dd>
</React.Fragment>
))}
</dl>
)}
<div className="vm-hero-actions">
{primary}
{running && (
<Button icon={<Square size={13} />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
<Button icon={<Square size={13} aria-hidden="true" />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
)}
<Tip label={tr('settings')} shortcut="Ctrl+,">
<Button icon={<Settings size={14} />} disabled={!detail} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
<Button icon={<Settings size={14} aria-hidden="true" />} disabled={!detail} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
</Tip>
{menu}
</div>
</section>
{specs.length > 0 && (
<dl className="vm-spec-grid">
{specs.map((s) => (
<div className="vm-spec-item" key={s.label}>
<span className="vm-spec-icon">{s.icon}</span>
<span className="vm-spec-meta">
<dt className="vm-spec-label">{s.label}</dt>
<dd className="vm-spec-val" title={s.value}>{s.value}</dd>
</span>
</div>
))}
</dl>
)}
{running && stats && (
<div className="vm-meters">
<div className="vm-telemetry-card">
<div className="vm-meter">
<span className="vm-meter-label"><Cpu size={12} aria-hidden="true" />{tr('statsCPU')}</span>
<span className="vm-meter-value">{Math.round(Math.min(100, Math.max(0, stats.cpu_percent || 0)))}%</span>
<div className="resource-meter"><span style={{ width: `${Math.min(100, Math.max(0, stats.cpu_percent || 0))}%` }} /></div>
<span className="vm-meter-label"><Cpu size={13} aria-hidden="true" />{tr('statsCPU')}</span>
<span className="vm-meter-value">{Math.round(cpuPct)}%</span>
<div className="resource-meter" aria-hidden="true">
<span className={`meter-fill${meterTone(cpuPct)}`} style={{ transform: `scaleX(${cpuPct / 100})` }} />
</div>
</div>
<div className="vm-meter">
<span className="vm-meter-label"><MemoryStick size={12} aria-hidden="true" />{tr('statsMemory')}</span>
<span className="vm-meter-label"><MemoryStick size={13} aria-hidden="true" />{tr('statsMemory')}</span>
<span className="vm-meter-value">{stats.memory_rss_bytes > 0 ? formatBytes(stats.memory_rss_bytes) : '—'}</span>
<div className="resource-meter"><span style={{ width: `${memPct}%` }} /></div>
<div className="resource-meter" aria-hidden="true">
<span className={`meter-fill${meterTone(memPct)}`} style={{ transform: `scaleX(${memPct / 100})` }} />
</div>
</div>
</div>
)}
{state === 'broken' && <div className="notice notice-error">{tr('brokenHint')}</div>}
{state === 'broken' && (
<div className="notice notice-error" role="alert">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('brokenHint')}</span>
</span>
</div>
)}
{pending.length > 0 && (
<div className="notice">
<span>
{tr('pendingTitle')}:
<span className="mono">{pending.map((p) => `${p.field} ${p.from}→${p.to}`).join(' · ')}</span>
<span className="notice-main">
<Info size={15} className="notice-icon" aria-hidden="true" />
<span>
{tr('pendingTitle')}:
<span className="mono">{pending.map((p) => `${p.field} ${p.from}→${p.to}`).join(' · ')}</span>
</span>
</span>
{running && (
<Button busy={busyAction === 'restart'} disabled={busy} onClick={() => onAction('restart')}>
@@ -267,19 +311,28 @@ export const VMPage: React.FC<Props> = ({
{(host.data_root_drive_type === 'usb' || host.data_root_drive_type === 'removable' || host.data_root_drive_type === 'network') && (
<div className="notice">
<span>{tr('diagExternalDriveWarn', { dir: host.data_root })}</span>
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('diagExternalDriveWarn', { dir: host.data_root })}</span>
</span>
</div>
)}
{(host.memory_load_pct ?? 0) >= 85 && (
<div className="notice">
<span>{tr('diagHighMemWarn', { pct: host.memory_load_pct ?? 0 })}</span>
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('diagHighMemWarn', { pct: host.memory_load_pct ?? 0 })}</span>
</span>
</div>
)}
{detail && !detail.has_installer && detail.disk_controller === 'ahci' && (
<div className="notice">
<span>{tr('diagAhciUpgradeHint')}</span>
<div className="notice notice-info">
<span className="notice-main">
<Info size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('diagAhciUpgradeHint')}</span>
</span>
<Button busy={busyAction === 'upgradeNVMe'} disabled={busy} onClick={() => onAction('upgradeNVMe')}>
{tr('upgradeToNVMe')}
</Button>
@@ -304,15 +357,15 @@ export const VMPage: React.FC<Props> = ({
</h2>
{!hasInstaller ? (
<>
<ol className="steps">
<li>{tr('guideBuiltIn1')}</li>
<li>{tr('guideBuiltIn2')}</li>
<li>{tr('guideBuiltIn3')}</li>
<ol className="guide-steps">
<li className="guide-step"><span className="guide-step-num">1</span><span className="guide-step-body">{tr('guideBuiltIn1')}</span></li>
<li className="guide-step"><span className="guide-step-num">2</span><span className="guide-step-body">{tr('guideBuiltIn2')}</span></li>
<li className="guide-step"><span className="guide-step-num">3</span><span className="guide-step-body">{tr('guideBuiltIn3')}</span></li>
</ol>
<div className="card-foot">
<Button
variant="secondary"
icon={<Disc size={14} />}
icon={<Disc size={14} aria-hidden="true" />}
busy={busyAction === 'attachInstaller'}
disabled={busy}
onClick={() => onAction('attachInstaller')}
@@ -331,26 +384,29 @@ export const VMPage: React.FC<Props> = ({
</>
) : isOffline ? (
<>
<ol className="steps">
<li>{tr('guideOffline1')}</li>
<li>
{tr('guideOffline2')}
<div className="cmd-line guide-cmd">
<code>{OFFLINE_INSTALL_CMD}</code>
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(OFFLINE_INSTALL_CMD)} />
{running && (
<IconButton
small
label={tr('typeIntoVM')}
icon={<Keyboard size={14} />}
busy={busyAction === 'type'}
disabled={busy}
onClick={() => onTypeText(OFFLINE_INSTALL_CMD)}
/>
)}
</div>
<ol className="guide-steps">
<li className="guide-step"><span className="guide-step-num">1</span><span className="guide-step-body">{tr('guideOffline1')}</span></li>
<li className="guide-step">
<span className="guide-step-num">2</span>
<span className="guide-step-body">
{tr('guideOffline2')}
<div className="cmd-line guide-cmd">
<code>{OFFLINE_INSTALL_CMD}</code>
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(OFFLINE_INSTALL_CMD)} />
{running && (
<IconButton
small
label={tr('typeIntoVM')}
icon={<Keyboard size={14} />}
busy={busyAction === 'type'}
disabled={busy}
onClick={() => onTypeText(OFFLINE_INSTALL_CMD)}
/>
)}
</div>
</span>
</li>
<li>{tr('guideOffline3')}</li>
<li className="guide-step"><span className="guide-step-num">3</span><span className="guide-step-body">{tr('guideOffline3')}</span></li>
</ol>
<div className="card-foot">
<Button
@@ -365,10 +421,10 @@ export const VMPage: React.FC<Props> = ({
</>
) : (
<>
<ol className="steps">
<li>{tr('guideStep1')}</li>
<li>{tr('guideStep2')}</li>
<li>{tr('guideStep3')}</li>
<ol className="guide-steps">
<li className="guide-step"><span className="guide-step-num">1</span><span className="guide-step-body">{tr('guideStep1')}</span></li>
<li className="guide-step"><span className="guide-step-num">2</span><span className="guide-step-body">{tr('guideStep2')}</span></li>
<li className="guide-step"><span className="guide-step-num">3</span><span className="guide-step-body">{tr('guideStep3')}</span></li>
</ol>
<div className="card-foot">
<Button
@@ -467,29 +523,37 @@ export const VMPage: React.FC<Props> = ({
{detail && (
<details className="tech">
<summary><ChevronRight size={14} /> {tr('techInfo')}</summary>
<dl className="kv-list">
<dt>{tr('fieldKind')}</dt><dd>{detail.kind || '—'}</dd>
<dt>{tr('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || 'auto'}</dd>
<dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd>
{detail.gpu && detail.gpu !== 'auto' && (<><dt>{tr('fieldICD')}</dt><dd className="mono">{detail.gpu}</dd></>)}
<dt>{tr('resolution')}</dt><dd>{detail.displays} × {detail.resolution}</dd>
<dt>{tr('fieldController')}</dt><dd>{detail.disk_controller}</dd>
<dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd>
<dt>{tr('fieldNetwork')}</dt><dd className="mono">{detail.network_summary || tr('off')}</dd>
<dt>{tr('fieldAudio')}</dt><dd>{detail.audio_raw || tr('off')}</dd>
{detail.guest_lang && (<><dt>{tr('guestLang')}</dt><dd className="mono">{detail.guest_lang}</dd></>)}
<dt>{tr('fieldDir')}</dt><dd className="mono">{detail.directory}</dd>
</dl>
<summary><ChevronRight size={14} aria-hidden="true" /> {tr('techInfo')}</summary>
<div className="tech-body">
<IconButton small className="tech-copy" label={tr('copyTechInfo')} icon={<Copy size={14} />} onClick={copyTechSummary} />
<dl className="kv-list">
<dt>{tr('fieldKind')}</dt><dd>{detail.kind || '—'}</dd>
<dt>{tr('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || 'auto'}</dd>
<dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd>
{detail.gpu && detail.gpu !== 'auto' && (<><dt>{tr('fieldICD')}</dt><dd className="mono">{detail.gpu}</dd></>)}
<dt>{tr('resolution')}</dt><dd>{detail.displays} × {detail.resolution}</dd>
<dt>{tr('fieldController')}</dt><dd>{detail.disk_controller}</dd>
<dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd>
<dt>{tr('fieldNetwork')}</dt><dd className="mono">{detail.network_summary || tr('off')}</dd>
<dt>{tr('fieldAudio')}</dt><dd>{detail.audio_raw || tr('off')}</dd>
{detail.guest_lang && (<><dt>{tr('guestLang')}</dt><dd className="mono">{detail.guest_lang}</dd></>)}
<dt>{tr('fieldDir')}</dt><dd className="mono">{detail.directory}</dd>
</dl>
</div>
</details>
)}
{detail && (
{detail && (detail.graphics === 'vmware-svga' ? (
<p className="vm-footnote">
<kbd>Ctrl+Alt+Enter</kbd> {tr('shortcutBarFullscreen')}
{detail.capture && <><span className="sep">·</span><kbd>Ctrl+Alt+G</kbd> {tr('shortcutBarRelease')}</>}
<kbd>Ctrl+Alt+F</kbd> {tr('shortcutBarFullscreen')}
<span className="sep">·</span>
<kbd>Ctrl+Alt+G</kbd> {tr('shortcutBarRelease')}
</p>
)}
) : detail.capture ? (
<p className="vm-footnote">
<kbd>Ctrl+Alt+Win</kbd> {tr('shortcutBarRelease')}
</p>
) : null)}
</div>
)
}
@@ -505,14 +569,20 @@ const VMScreen: React.FC<{ thumb: VMThumbnail | null; running: boolean; startLab
const shown = thumb?.data_url ?? ''
const under = prev.current !== shown ? prev.current : ''
useEffect(() => { prev.current = shown }, [shown])
if (!shown) return <IMacIcon running={running} />
if (!shown) {
return (
<div className="vm-imac-wrap">
<IMacIcon running={running} />
</div>
)
}
return (
<div className={`vm-screen${running ? ' is-live' : ' is-idle'}`} style={under ? { backgroundImage: `url(${under})` } : undefined}>
<img key={thumb?.captured_at} className="vm-screen-img" src={shown} alt="" draggable={false} />
{running && <span className="vm-screen-live" aria-hidden="true" />}
{onStart && (
<button type="button" className="vm-screen-play" aria-label={startLabel} onClick={onStart}>
<Play size={22} fill="currentColor" />
<Play size={22} fill="currentColor" aria-hidden="true" />
</button>
)}
</div>
@@ -522,32 +592,43 @@ const VMScreen: React.FC<{ thumb: VMThumbnail | null; running: boolean; startLab
const IMacIcon: React.FC<{ running: boolean }> = ({ running }) => (
<svg className="vm-imac-svg" viewBox="0 0 120 96" fill="none" aria-hidden="true">
<defs>
<linearGradient id="tahoeScreenOn" x1="16" y1="8" x2="104" y2="62" gradientUnits="userSpaceOnUse">
<stop offset="0%" stopColor="#4ec2ff" />
<stop offset="55%" stopColor="#1e88e5" />
<stop offset="100%" stopColor="#0f55b8" />
<linearGradient id="tahoeScreenOn" x1="14" y1="8" x2="106" y2="62" gradientUnits="userSpaceOnUse">
<stop offset="0%" stopColor="#63d2ff" />
<stop offset="52%" stopColor="#1d86f2" />
<stop offset="100%" stopColor="#0d4db3" />
</linearGradient>
<linearGradient id="tahoeScreenOff" x1="16" y1="8" x2="104" y2="62" gradientUnits="userSpaceOnUse">
<stop offset="0%" stopColor="#2c2e35" />
<stop offset="100%" stopColor="#18191e" />
<linearGradient id="tahoeScreenOff" x1="14" y1="8" x2="106" y2="62" gradientUnits="userSpaceOnUse">
<stop offset="0%" stopColor="#2e3139" />
<stop offset="100%" stopColor="#16181d" />
</linearGradient>
<linearGradient id="imacChin" x1="12" y1="62" x2="108" y2="74" gradientUnits="userSpaceOnUse">
<stop offset="0%" stopColor="#e8eaee" />
<stop offset="100%" stopColor="#d4d7dd" />
<linearGradient id="screenSheen" x1="14" y1="9" x2="66" y2="54" gradientUnits="userSpaceOnUse">
<stop offset="0%" stopColor="rgba(255,255,255,0.22)" />
<stop offset="100%" stopColor="rgba(255,255,255,0)" />
</linearGradient>
<linearGradient id="imacChin" x1="10" y1="61" x2="110" y2="74" gradientUnits="userSpaceOnUse">
<stop offset="0%" stopColor="#eff1f5" />
<stop offset="50%" stopColor="#e2e5eb" />
<stop offset="100%" stopColor="#d3d7df" />
</linearGradient>
<linearGradient id="imacStand" x1="50" y1="73" x2="70" y2="90" gradientUnits="userSpaceOnUse">
<stop offset="0%" stopColor="#c4c8cf" />
<stop offset="100%" stopColor="#e2e5ea" />
<stop offset="0%" stopColor="#bfc4cd" />
<stop offset="55%" stopColor="#dde0e7" />
<stop offset="100%" stopColor="#c7ccd5" />
</linearGradient>
</defs>
<path d="M51 73H69L72 88H48L51 73Z" fill="url(#imacStand)" />
<rect x="42" y="87" width="36" height="3.5" rx="1.75" fill="#cfd3da" />
<rect x="10" y="6" width="100" height="68" rx="6" fill="#1d1e22" />
<rect x="42" y="87" width="36" height="3.5" rx="1.75" fill="#cfd4dc" />
<rect x="10" y="6" width="100" height="68" rx="6.5" fill="#1b1c21" />
<rect x="10.5" y="6.5" width="99" height="67" rx="6" stroke="rgba(255,255,255,0.14)" strokeWidth="1" />
<path d="M10 61H110V68C110 71.3137 107.314 74 104 74H16C12.6863 74 10 71.3137 10 68V61Z" fill="url(#imacChin)" />
<rect x="13.5" y="9.5" width="93" height="49" rx="2.5" fill={running ? 'url(#tahoeScreenOn)' : 'url(#tahoeScreenOff)'} />
{running && (
<path d="M13.5 47C34 39 58 49 78 41C92 35.5 100 37 106.5 39V58.5H13.5V47Z" fill="rgba(255,255,255,0.18)" />
<>
<path d="M13.5 46C34 37 56 49 79 39.5C92 34 100 36 106.5 38.5V58.5H13.5V46Z" fill="rgba(255,255,255,0.20)" />
<path d="M13.5 51.5C38 45 64 53 106.5 46.5V58.5H13.5V51.5Z" fill="rgba(255,255,255,0.12)" />
</>
)}
<circle cx="60" cy="67.5" r="1.8" fill="#8e9299" />
<path d="M13.5 9.5H68L42 58.5H13.5V9.5Z" fill="url(#screenSheen)" />
<circle cx="60" cy="67.5" r="1.7" fill="#8b9099" />
</svg>
)
+16 -2
View File
@@ -182,7 +182,14 @@ const dict = {
runtimeAlphaHint: 'Alpha 版由 CI 每天从上游自动构建,未经真实宿主冒烟测试',
runtimeChannel_alpha: 'Alpha 版',
runtimeChannel_stable: '稳定版',
runtimeLookupFailed: '无法读取 GitHub 上的运行时列表',
runtimeLookupFailed: '无法读取运行时列表',
runtimeLookupRateLimit: 'GitHub 接口限流(HTTP 403),可切换 GitCode 镜像、稍后重试或手动导入',
runtimeRetry: '重试',
runtimeSource: '下载源',
runtimeSourceHint: '自动模式优先 GitHub,连不上时自动切换 GitCode 国内镜像',
runtimeSource_auto: '自动',
runtimeSource_github: 'GitHub',
runtimeSource_gitcode: 'GitCode',
// Toasts & dialogs
toastStopped: '{name} 已关机',
@@ -695,7 +702,14 @@ const dict = {
runtimeAlphaHint: 'Built daily from upstream by CI; not smoke-tested on a real host',
runtimeChannel_alpha: 'Alpha',
runtimeChannel_stable: 'Stable',
runtimeLookupFailed: 'Couldn’t read the runtime list from GitHub',
runtimeLookupFailed: 'Couldn’t read the runtime list',
runtimeLookupRateLimit: 'GitHub API rate limit reached (HTTP 403); switch to GitCode mirror, retry later, or import a local bundle',
runtimeRetry: 'Retry',
runtimeSource: 'Download source',
runtimeSourceHint: 'Auto tries GitHub first and falls back to the GitCode mirror if unreachable',
runtimeSource_auto: 'Auto',
runtimeSource_github: 'GitHub',
runtimeSource_gitcode: 'GitCode',
toastStopped: '{name} shut down',
toastEjected: 'Installer ejected',
+4
View File
@@ -8,9 +8,12 @@ type Model<T> = Omit<T, 'convertValues'>
export type Locale = 'zh-CN' | 'en-US'
export type RuntimeSource = 'auto' | 'github' | 'gitcode'
export type Config = Model<config.Config> & {
locale: Locale
runtime_channel?: 'stable' | 'alpha' | ''
runtime_source?: RuntimeSource | ''
}
export type DisplayInfo = host.DisplayInfo
@@ -40,6 +43,7 @@ export type InstalledRuntime = Model<runtime.Installed>
export type RemoteRuntime = Model<runtime.Remote> & {
channel: 'stable' | 'alpha'
source?: 'github' | 'gitcode'
}
export type VMListItem = Model<reims.VMListItem> & {
+2
View File
@@ -108,6 +108,8 @@ export function SetMinimizeToTray(arg1:boolean):Promise<void>;
export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetRuntimeSource(arg1:string):Promise<void>;
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<main.DriveShareSettings>;
export function ShowMainWindow():Promise<void>;
+4
View File
@@ -206,6 +206,10 @@ export function SetRuntimeChannel(arg1) {
return window['go']['main']['App']['SetRuntimeChannel'](arg1);
}
export function SetRuntimeSource(arg1) {
return window['go']['main']['App']['SetRuntimeSource'](arg1);
}
export function SetVMDriveShareSettings(arg1, arg2, arg3) {
return window['go']['main']['App']['SetVMDriveShareSettings'](arg1, arg2, arg3);
}
+18 -10
View File
@@ -14,14 +14,15 @@ import (
rt "github.com/Nwflower/reims-go/internal/runtime"
)
// runtime available [--alpha]: published runtimes on GitHub Releases.
// runtime available [--alpha] [--source auto|github|gitcode]: published runtimes.
func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) error {
fs := flag.NewFlagSet("runtime available", flag.ContinueOnError)
alpha := alphaFlag(fs, cfg, "Include alpha runtimes")
source := fs.String("source", rt.NormalizeSource(cfg.RuntimeSource), "Download source: auto, github, or gitcode")
if err := fs.Parse(flagsFirst(args)); err != nil {
return err
}
list, err := rt.DefaultSource().ListRemote(context.Background(), *alpha)
list, err := rt.DefaultSourceFor(*source).ListRemote(context.Background(), *alpha)
if err != nil {
return err
}
@@ -29,7 +30,7 @@ func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) err
fmt.Println(i18n.T(loc, "runtime.remote.empty"))
return nil
}
fmt.Printf("%-9s %-10s %-11s %9s %s\n", "COMMIT", "CHANNEL", "PUBLISHED", "SIZE", "INSTALLED")
fmt.Printf("%-12s %-10s %-8s %-11s %9s %s\n", "COMMIT", "CHANNEL", "SOURCE", "PUBLISHED", "SIZE", "INSTALLED")
for _, r := range list {
mark := ""
if rt.IsInstalled(cfg, r.Commit) {
@@ -39,15 +40,16 @@ func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) err
if len(date) >= 10 {
date = date[:10]
}
fmt.Printf("%-9s %-10s %-11s %9s %s\n", r.Commit, r.Channel, date, humanBytes(r.ArchiveSize), mark)
fmt.Printf("%-12s %-10s %-8s %-11s %9s %s\n", r.Commit, r.Channel, r.Source, date, humanBytes(r.ArchiveSize), mark)
}
return nil
}
// runtime fetch [commit|latest] [--alpha]: download, verify, install, activate.
// runtime fetch [commit|latest] [--alpha] [--source auto|github|gitcode]: download, verify, install, activate.
func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
fs := flag.NewFlagSet("runtime fetch", flag.ContinueOnError)
alpha := alphaFlag(fs, cfg, "Allow alpha runtimes for \"latest\"")
source := fs.String("source", rt.NormalizeSource(cfg.RuntimeSource), "Download source: auto, github, or gitcode")
if err := fs.Parse(flagsFirst(args)); err != nil {
return err
}
@@ -56,7 +58,7 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
src := rt.DefaultSource()
src := rt.DefaultSourceFor(*source)
list, err := src.ListRemote(ctx, *alpha || explicit)
if err != nil {
return err
@@ -106,14 +108,20 @@ func alphaFlag(fs *flag.FlagSet, cfg *config.Config, usage string) *bool {
return v
}
// flagsFirst moves "-x" arguments before positional ones, so
// "fetch latest --alpha" works like "fetch --alpha latest" (the flag
// package stops at the first positional argument).
// flagsFirst moves "-x" arguments (and their values for value flags like
// --source) before positional ones, so "fetch latest --source gitcode --alpha"
// works like "fetch --source gitcode --alpha latest" (the flag package stops
// at the first positional argument).
func flagsFirst(args []string) []string {
var flags, rest []string
for _, a := range args {
for i := 0; i < len(args); i++ {
a := args[i]
if len(a) > 1 && a[0] == '-' {
flags = append(flags, a)
if (a == "-source" || a == "--source") && i+1 < len(args) {
i++
flags = append(flags, args[i])
}
} else {
rest = append(rest, a)
}
+4
View File
@@ -20,6 +20,10 @@ type Config struct {
// whether online install offers alpha runtimes (portable-runtime-spec.md §6).
// "candidate", the name used before 2026-11-28, is read as "alpha".
RuntimeChannel string `json:"runtime_channel,omitempty"`
// RuntimeSource chooses where online runtimes and app updates are fetched:
// "auto" (default, also when empty: try GitHub first, fall back to GitCode),
// "github", or "gitcode".
RuntimeSource string `json:"runtime_source,omitempty"`
// MinimizeToTray keeps Reims-Go running in the Windows system tray when the
// main window is closed so Guest Tools bridges stay alive. Defaults to true.
MinimizeToTray *bool `json:"minimize_to_tray,omitempty"`
+3 -1
View File
@@ -12,6 +12,8 @@ import (
"path/filepath"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/netproxy"
)
// PinnedAsset describes a file that upstream `reims-util` caches under
@@ -180,7 +182,7 @@ func (c *idleTimeoutConn) Read(p []byte) (int, error) {
func newIdleHTTPClient(idle time.Duration) *http.Client {
dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Proxy: netproxy.ProxyFromEnvOrSystem,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := dialer.DialContext(ctx, network, addr)
if err != nil {
+145
View File
@@ -0,0 +1,145 @@
package netproxy
import (
"net"
"net/http"
"net/url"
"path"
"strings"
"time"
)
// ProxyFromEnvOrSystem resolves a proxy for req, preferring standard
// HTTP_PROXY/HTTPS_PROXY/NO_PROXY environment variables and falling back to
// the host OS proxy settings (Windows Internet Settings registry).
func ProxyFromEnvOrSystem(req *http.Request) (*url.URL, error) {
if u, err := http.ProxyFromEnvironment(req); u != nil || err != nil {
return u, err
}
return systemProxy(req)
}
// NewTransport returns an http.Transport configured with env/OS proxy support
// and bounded connection/header timeouts (without limiting streaming body
// download duration).
func NewTransport() *http.Transport {
var tr *http.Transport
if base, ok := http.DefaultTransport.(*http.Transport); ok {
tr = base.Clone()
} else {
tr = &http.Transport{}
}
tr.Proxy = ProxyFromEnvOrSystem
tr.DialContext = (&net.Dialer{
Timeout: 20 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext
tr.TLSHandshakeTimeout = 20 * time.Second
tr.ResponseHeaderTimeout = 30 * time.Second
return tr
}
// NewClient returns an http.Client using NewTransport.
func NewClient() *http.Client {
return &http.Client{Transport: NewTransport()}
}
// parseWindowsProxyServer parses Windows Internet Settings ProxyServer values:
// either a single proxy ("127.0.0.1:7890", "http://127.0.0.1:7890") or a
// semicolon-separated per-scheme map ("http=127.0.0.1:7890;https=127.0.0.1:7890;socks=127.0.0.1:7891").
func parseWindowsProxyServer(server, reqScheme string) (*url.URL, error) {
server = strings.TrimSpace(server)
if server == "" {
return nil, nil
}
reqScheme = strings.ToLower(strings.TrimSpace(reqScheme))
if reqScheme == "" {
reqScheme = "http"
}
var chosen, chosenKey string
if !strings.Contains(server, "=") {
chosen = server
} else {
byScheme := map[string]string{}
for _, entry := range strings.Split(server, ";") {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
k, v, ok := strings.Cut(entry, "=")
if !ok {
continue
}
k = strings.ToLower(strings.TrimSpace(k))
v = strings.TrimSpace(v)
if k != "" && v != "" {
byScheme[k] = v
}
}
for _, key := range []string{reqScheme, "http", "https", "socks5", "socks"} {
if v, ok := byScheme[key]; ok {
chosen = v
chosenKey = key
break
}
}
}
if chosen == "" {
return nil, nil
}
if !strings.Contains(chosen, "://") {
if chosenKey == "socks" || chosenKey == "socks5" {
chosen = "socks5://" + chosen
} else {
// In Windows Internet Settings, "https=host:port" denotes an HTTP
// CONNECT proxy used for HTTPS requests, not a TLS proxy endpoint.
chosen = "http://" + chosen
}
}
u, err := url.Parse(chosen)
if err != nil || u.Host == "" {
return nil, nil
}
return u, nil
}
// shouldBypassWindowsProxy evaluates Windows ProxyOverride rules (semicolon or
// whitespace separated patterns, including "<local>" and "*" wildcards).
func shouldBypassWindowsProxy(override, host string) bool {
host = strings.ToLower(strings.TrimSpace(host))
if host == "" {
return false
}
fields := strings.FieldsFunc(override, func(r rune) bool {
return r == ';' || r == ' ' || r == '\t' || r == ','
})
for _, pat := range fields {
pat = strings.ToLower(strings.TrimSpace(pat))
if pat == "" {
continue
}
if pat == "<local>" {
if !strings.Contains(host, ".") || host == "localhost" || host == "127.0.0.1" || host == "::1" {
return true
}
continue
}
// Strip optional scheme or port in Windows bypass rules (e.g. "http://*.local").
if _, after, ok := strings.Cut(pat, "://"); ok {
pat = after
}
if h, _, err := net.SplitHostPort(pat); err == nil && h != "" {
pat = h
}
if pat == host {
return true
}
if strings.ContainsAny(pat, "*?") {
if matched, err := path.Match(pat, host); err == nil && matched {
return true
}
}
}
return false
}
+65
View File
@@ -0,0 +1,65 @@
package netproxy
import (
"net/http"
"testing"
)
func TestParseWindowsProxyServer(t *testing.T) {
cases := []struct {
server string
scheme string
want string
}{
{"127.0.0.1:7890", "https", "http://127.0.0.1:7890"},
{"http://127.0.0.1:7890", "https", "http://127.0.0.1:7890"},
{"socks5://127.0.0.1:7891", "https", "socks5://127.0.0.1:7891"},
{"http=127.0.0.1:7890;https=127.0.0.1:7891", "https", "http://127.0.0.1:7891"},
{"http=127.0.0.1:7890;https=127.0.0.1:7891", "http", "http://127.0.0.1:7890"},
{"socks=127.0.0.1:10808", "https", "socks5://127.0.0.1:10808"},
{"http=127.0.0.1:8080", "https", "http://127.0.0.1:8080"},
{"", "https", ""},
}
for _, tc := range cases {
u, err := parseWindowsProxyServer(tc.server, tc.scheme)
if err != nil {
t.Fatalf("parseWindowsProxyServer(%q, %q) err = %v", tc.server, tc.scheme, err)
}
got := ""
if u != nil {
got = u.String()
}
if got != tc.want {
t.Errorf("parseWindowsProxyServer(%q, %q) = %q, want %q", tc.server, tc.scheme, got, tc.want)
}
}
}
func TestShouldBypassWindowsProxy(t *testing.T) {
override := "localhost;127.*;10.*;*.local;<local>"
for host, want := range map[string]bool{
"localhost": true,
"127.0.0.1": true,
"10.0.0.5": true,
"nas.local": true,
"intranet": true,
"api.github.com": false,
"github.com": false,
} {
if got := shouldBypassWindowsProxy(override, host); got != want {
t.Errorf("shouldBypassWindowsProxy(%q, %q) = %v, want %v", override, host, got, want)
}
}
}
func TestProxyFromEnvTakesPrecedence(t *testing.T) {
t.Setenv("HTTPS_PROXY", "http://127.0.0.1:19999")
req, _ := http.NewRequest(http.MethodGet, "https://api.github.com/repos/Nwflower/reims-go/releases", nil)
u, err := ProxyFromEnvOrSystem(req)
if err != nil {
t.Fatal(err)
}
if u == nil || u.String() != "http://127.0.0.1:19999" {
t.Fatalf("got %v, want http://127.0.0.1:19999", u)
}
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !windows
package netproxy
import (
"net/http"
"net/url"
)
func systemProxy(*http.Request) (*url.URL, error) {
return nil, nil
}
+38
View File
@@ -0,0 +1,38 @@
//go:build windows
package netproxy
import (
"net/http"
"net/url"
"golang.org/x/sys/windows/registry"
)
const internetSettingsPath = `Software\Microsoft\Windows\CurrentVersion\Internet Settings`
func systemProxy(req *http.Request) (*url.URL, error) {
if req == nil || req.URL == nil {
return nil, nil
}
k, err := registry.OpenKey(registry.CURRENT_USER, internetSettingsPath, registry.QUERY_VALUE)
if err != nil {
return nil, nil
}
defer k.Close()
enabled, _, err := k.GetIntegerValue("ProxyEnable")
if err != nil || enabled == 0 {
return nil, nil
}
server, _, err := k.GetStringValue("ProxyServer")
if err != nil || server == "" {
return nil, nil
}
if override, _, err := k.GetStringValue("ProxyOverride"); err == nil && override != "" {
if shouldBypassWindowsProxy(override, req.URL.Hostname()) {
return nil, nil
}
}
return parseWindowsProxyServer(server, req.URL.Scheme)
}
+346 -18
View File
@@ -16,27 +16,56 @@ import (
"bufio"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/netproxy"
)
const (
DefaultReleasesRepo = "Nwflower/reims-go"
DefaultAPIBase = "https://api.github.com"
runtimeTagPrefix = "runtime-"
sumsAsset = "SHA256SUMS.txt"
DefaultReleasesRepo = "Nwflower/reims-go"
DefaultAPIBase = "https://api.github.com"
DefaultWebBase = "https://github.com"
DefaultGitCodeRepo = "Nwflower/Reims-Go"
DefaultGitCodeAPIBase = "https://api.gitcode.com/api/v5"
DefaultGitCodeWebBase = "https://gitcode.com"
runtimeTagPrefix = "runtime-"
sumsAsset = "SHA256SUMS.txt"
)
const (
SourceAuto = "auto"
SourceGitHub = "github"
SourceGitCode = "gitcode"
)
// NormalizeSource maps a stored or user-given source name to SourceAuto,
// SourceGitHub, or SourceGitCode. Empty or unknown values default to SourceAuto.
func NormalizeSource(s string) string {
switch strings.ToLower(strings.TrimSpace(s)) {
case SourceGitHub:
return SourceGitHub
case SourceGitCode:
return SourceGitCode
default:
return SourceAuto
}
}
var errRateLimited = errors.New("GitHub API rate limit reached")
const (
ChannelStable = "stable"
ChannelAlpha = "alpha"
@@ -61,20 +90,73 @@ func NormalizeChannel(s string) string {
// app releases and (until pruned) daily alpha runtimes.
const maxReleasePages = 10
// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO
// overrides the repository (for forks and testing).
// fallbackProbeTimeout bounds how long a primary source query may block when a
// mirror fallback is configured, so unreachable hosts fail over quickly.
const fallbackProbeTimeout = 8 * time.Second
// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO and
// REIMS_GO_GITCODE_REPO override the repositories (for forks and testing).
type Source struct {
APIBase string
Repo string
Client *http.Client
Provider string
APIBase string
WebBase string
Repo string
Client *http.Client
Fallbacks []Source
}
func DefaultSource() Source {
func githubSource(client *http.Client) Source {
repo := os.Getenv("REIMS_GO_RELEASES_REPO")
if repo == "" {
repo = DefaultReleasesRepo
}
return Source{APIBase: DefaultAPIBase, Repo: repo, Client: &http.Client{Timeout: 0}}
return Source{
Provider: SourceGitHub,
APIBase: DefaultAPIBase,
WebBase: DefaultWebBase,
Repo: repo,
Client: client,
}
}
func gitcodeSource(client *http.Client) Source {
repo := os.Getenv("REIMS_GO_GITCODE_REPO")
if repo == "" {
repo = DefaultGitCodeRepo
}
return Source{
Provider: SourceGitCode,
APIBase: DefaultGitCodeAPIBase,
WebBase: DefaultGitCodeWebBase,
Repo: repo,
Client: client,
}
}
// DefaultSource returns the default runtime source (SourceAuto unless
// REIMS_GO_SOURCE overrides it).
func DefaultSource() Source {
return DefaultSourceFor("")
}
// DefaultSourceFor returns a Source configured for mode ("auto", "github", or
// "gitcode"). When mode is empty, REIMS_GO_SOURCE is consulted before falling
// back to "auto" (GitHub primary, GitCode fallback).
func DefaultSourceFor(mode string) Source {
if strings.TrimSpace(mode) == "" {
mode = os.Getenv("REIMS_GO_SOURCE")
}
client := netproxy.NewClient()
switch NormalizeSource(mode) {
case SourceGitHub:
return githubSource(client)
case SourceGitCode:
return gitcodeSource(client)
default:
gh := githubSource(client)
gh.Fallbacks = []Source{gitcodeSource(client)}
return gh
}
}
// Remote is a runtime package published as a release.
@@ -82,6 +164,7 @@ type Remote struct {
Commit string `json:"commit"`
Tag string `json:"tag"`
Channel string `json:"channel"`
Source string `json:"source,omitempty"`
PublishedAt string `json:"published_at"`
PageURL string `json:"page_url"`
ArchiveName string `json:"archive_name"`
@@ -97,6 +180,7 @@ type ghRelease struct {
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
PublishedAt string `json:"published_at"`
CreatedAt string `json:"created_at"`
HTMLURL string `json:"html_url"`
Assets []ghAsset `json:"assets"`
}
@@ -121,18 +205,80 @@ func newRequest(ctx context.Context, url string) (*http.Request, error) {
}
// A generic client name; nothing about the user (GitHub requires a User-Agent).
req.Header.Set("User-Agent", "reims-go")
if req.URL.Host == "api.github.com" {
if tok := strings.TrimSpace(os.Getenv("GITHUB_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
} else if tok := strings.TrimSpace(os.Getenv("GH_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
}
return req, nil
}
func (s Source) providerName() string {
if s.Provider != "" {
return s.Provider
}
if strings.Contains(strings.ToLower(s.APIBase), "gitcode.com") {
return SourceGitCode
}
return SourceGitHub
}
func (s Source) webBase() string {
if s.WebBase != "" {
return strings.TrimRight(s.WebBase, "/")
}
if strings.TrimRight(s.APIBase, "/") == DefaultAPIBase {
return DefaultWebBase
}
if strings.TrimRight(s.APIBase, "/") == DefaultGitCodeAPIBase {
return DefaultGitCodeWebBase
}
return ""
}
// ListRemote lists published runtime packages, newest first. Alpha runtimes
// are included only when includeAlpha is set.
// are included only when includeAlpha is set. When Fallbacks are configured,
// a failing primary source automatically fails over to the next mirror.
func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) {
primaryCtx := ctx
var cancel context.CancelFunc
if len(s.Fallbacks) > 0 {
primaryCtx, cancel = context.WithTimeout(ctx, fallbackProbeTimeout)
defer cancel()
}
out, err := s.listRemoteSingle(primaryCtx, includeAlpha)
if err == nil {
return out, nil
}
if ctx.Err() != nil || len(s.Fallbacks) == 0 {
return nil, err
}
var lastErr error
for _, fb := range s.Fallbacks {
fbOut, fbErr := fb.listRemoteSingle(ctx, includeAlpha)
if fbErr == nil {
return fbOut, nil
}
lastErr = fbErr
}
return nil, fmt.Errorf("%w (mirror fallback failed: %v)", err, lastErr)
}
func (s Source) listRemoteSingle(ctx context.Context, includeAlpha bool) ([]Remote, error) {
base := strings.TrimRight(s.APIBase, "/")
url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", base, s.Repo)
provider := s.providerName()
var rels []ghRelease
for page := 0; url != "" && page < maxReleasePages; page++ {
batch, next, err := s.releasesPage(ctx, url)
if err != nil {
if errors.Is(err, errRateLimited) && provider == SourceGitHub && s.webBase() != "" {
if fb, ferr := s.listRemoteWeb(ctx, includeAlpha); ferr == nil {
return fb, nil
}
}
return nil, err
}
rels = append(rels, batch...)
@@ -148,7 +294,22 @@ func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, er
continue
}
commit := strings.TrimPrefix(r.TagName, runtimeTagPrefix)
rem := Remote{Commit: commit, Tag: r.TagName, PublishedAt: r.PublishedAt, PageURL: r.HTMLURL, Channel: ChannelStable}
pub := r.PublishedAt
if pub == "" {
pub = r.CreatedAt
}
pageURL := r.HTMLURL
if pageURL == "" && s.webBase() != "" {
pageURL = fmt.Sprintf("%s/%s/releases/tag/%s", s.webBase(), s.Repo, r.TagName)
}
rem := Remote{
Commit: commit,
Tag: r.TagName,
Source: provider,
PublishedAt: pub,
PageURL: pageURL,
Channel: ChannelStable,
}
if r.Prerelease {
rem.Channel = ChannelAlpha
}
@@ -171,10 +332,21 @@ func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, er
}
out = append(out, rem)
}
sort.SliceStable(out, func(i, j int) bool { return out[i].PublishedAt > out[j].PublishedAt })
sortRemotesNewestFirst(out)
return out, nil
}
func sortRemotesNewestFirst(out []Remote) {
sort.SliceStable(out, func(i, j int) bool {
ti, ei := time.Parse(time.RFC3339, out[i].PublishedAt)
tj, ej := time.Parse(time.RFC3339, out[j].PublishedAt)
if ei == nil && ej == nil && !ti.Equal(tj) {
return ti.After(tj)
}
return out[i].PublishedAt > out[j].PublishedAt
})
}
// releasesPage fetches one page of the releases API and returns the URL of
// the next page from the Link header ("" on the last page).
func (s Source) releasesPage(ctx context.Context, url string) ([]ghRelease, string, error) {
@@ -189,7 +361,7 @@ func (s Source) releasesPage(ctx context.Context, url string) ([]ghRelease, stri
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {
return nil, "", fmt.Errorf("GitHub API rate limit reached; try again later (HTTP %d)", resp.StatusCode)
return nil, "", fmt.Errorf("%w; try again later (HTTP %d)", errRateLimited, resp.StatusCode)
}
if resp.StatusCode != http.StatusOK {
return nil, "", fmt.Errorf("list runtime releases: HTTP %d", resp.StatusCode)
@@ -201,6 +373,128 @@ func (s Source) releasesPage(ctx context.Context, url string) ([]ghRelease, stri
return rels, nextLink(resp.Header.Get("Link")), nil
}
type atomFeed struct {
Entries []atomEntry `xml:"entry"`
}
type atomEntry struct {
Title string `xml:"title"`
Updated string `xml:"updated"`
Links []atomLink `xml:"link"`
}
type atomLink struct {
Rel string `xml:"rel,attr"`
Href string `xml:"href,attr"`
}
var (
reExpandedAssetHref = regexp.MustCompile(`href="(/[^"]+/releases/download/[^"]+)"`)
rePrereleaseBadge = regexp.MustCompile(`(?i)>\s*Pre-release\s*<`)
)
// listRemoteWeb reads runtime releases from GitHub's public Atom feed and
// expanded_assets fragments, which do not consume api.github.com's 60 req/hr
// unauthenticated IP quota.
func (s Source) listRemoteWeb(ctx context.Context, includeAlpha bool) ([]Remote, error) {
web := s.webBase()
atomURL := fmt.Sprintf("%s/%s/releases.atom", web, s.Repo)
body, err := s.fetchText(ctx, atomURL, "application/atom+xml, application/xml")
if err != nil {
return nil, err
}
var feed atomFeed
if err := xml.Unmarshal([]byte(body), &feed); err != nil {
return nil, fmt.Errorf("parse releases.atom: %w", err)
}
var out []Remote
for _, e := range feed.Entries {
var pageURL string
for _, l := range e.Links {
if l.Rel == "" || l.Rel == "alternate" {
pageURL = l.Href
break
}
}
idx := strings.LastIndex(pageURL, "/releases/tag/")
if idx < 0 {
continue
}
tag := pageURL[idx+len("/releases/tag/"):]
if !strings.HasPrefix(tag, runtimeTagPrefix) {
continue
}
commit := strings.TrimPrefix(tag, runtimeTagPrefix)
tagURL := fmt.Sprintf("%s/%s/releases/tag/%s", web, s.Repo, tag)
channel := ChannelStable
if tagHTML, err := s.fetchText(ctx, tagURL, "text/html"); err == nil {
if rePrereleaseBadge.MatchString(tagHTML) {
channel = ChannelAlpha
}
} else if strings.Contains(strings.ToLower(e.Title), "(alpha)") {
channel = ChannelAlpha
}
if channel == ChannelAlpha && !includeAlpha {
continue
}
expURL := fmt.Sprintf("%s/%s/releases/expanded_assets/%s", web, s.Repo, tag)
expHTML, err := s.fetchText(ctx, expURL, "text/html")
if err != nil {
continue
}
rem := Remote{
Commit: commit,
Tag: tag,
Channel: channel,
Source: SourceGitHub,
PublishedAt: e.Updated,
PageURL: pageURL,
}
for _, m := range reExpandedAssetHref.FindAllStringSubmatch(expHTML, -1) {
href := m[1]
name := path.Base(href)
dl := web + href
switch {
case name == "reims-runtime-win-x64-"+commit+".tar.zst":
rem.ArchiveName, rem.ArchiveURL = name, dl
case name == sumsAsset:
rem.SumsURL = dl
case strings.HasPrefix(name, "reims-runtime-src-"):
rem.SourceName, rem.SourceURL = name, dl
}
}
if rem.ArchiveURL == "" || rem.SumsURL == "" || rem.SourceURL == "" {
continue
}
out = append(out, rem)
}
sort.SliceStable(out, func(i, j int) bool { return out[i].PublishedAt > out[j].PublishedAt })
return out, nil
}
func (s Source) fetchText(ctx context.Context, rawURL, accept string) (string, error) {
req, err := newRequest(ctx, rawURL)
if err != nil {
return "", err
}
if accept != "" {
req.Header.Set("Accept", accept)
}
resp, err := s.client().Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("fetch %s: HTTP %d", rawURL, resp.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return "", err
}
return string(data), nil
}
// nextLink returns the rel="next" target of an RFC 8288 Link header.
func nextLink(h string) string {
for _, part := range strings.Split(h, ",") {
@@ -221,7 +515,8 @@ func nextLink(h string) string {
return ""
}
// Pick finds a release by commit prefix, or the newest for "" / "latest".
// Pick finds a release by exact ID, revision-matching commit prefix, or the
// newest for "" / "latest".
func Pick(list []Remote, want string) (*Remote, error) {
want = strings.TrimSpace(want)
if len(list) == 0 {
@@ -231,7 +526,17 @@ func Pick(list []Remote, want string) (*Remote, error) {
return &list[0], nil
}
for i := range list {
if strings.HasPrefix(list[i].Commit, want) || strings.HasPrefix(want, list[i].Commit) {
if list[i].Commit == want {
return &list[i], nil
}
}
for i := range list {
if sameRuntimeID(list[i].Commit, want) {
return &list[i], nil
}
}
for i := range list {
if strings.HasPrefix(list[i].Commit, want) {
return &list[i], nil
}
}
@@ -374,6 +679,29 @@ func DownloadsDir(cfg *config.Config) string {
return filepath.Join(cfg.DataRoot, "downloads")
}
// splitRuntimeID separates "<commit>" and an optional patch-revision suffix
// such as "-p2" in "3731afd-p2".
func splitRuntimeID(id string) (base, rev string) {
if i := strings.IndexByte(id, '-'); i >= 0 {
return id[:i], id[i+1:]
}
return id, ""
}
// sameRuntimeID reports whether a and b refer to the same runtime build,
// allowing short/full commit prefix matching only within the same revision.
func sameRuntimeID(a, b string) bool {
if a == "" || b == "" {
return false
}
baseA, revA := splitRuntimeID(a)
baseB, revB := splitRuntimeID(b)
if revA != revB {
return false
}
return strings.HasPrefix(baseA, baseB) || strings.HasPrefix(baseB, baseA)
}
// IsInstalled reports whether commit is already unpacked under runtimes/.
func IsInstalled(cfg *config.Config, commit string) bool {
list, err := List(cfg)
@@ -381,7 +709,7 @@ func IsInstalled(cfg *config.Config, commit string) bool {
return false
}
for _, it := range list {
if strings.HasPrefix(it.Commit, commit) || strings.HasPrefix(commit, it.Commit) {
if sameRuntimeID(it.Commit, commit) {
return true
}
}
+139
View File
@@ -202,3 +202,142 @@ func TestNormalizeChannel(t *testing.T) {
}
}
}
func TestSameRuntimeIDDistinguishesPatchRevisions(t *testing.T) {
cases := []struct {
a, b string
want bool
}{
{"3731afd", "3731afd", true},
{"3731afd", "3731afd9b134", true},
{"3731afd", "3731afd-p2", false},
{"3731afd-p2", "3731afd", false},
{"3731afd-p2", "3731afd-p2", true},
{"3731afd-p2", "3731afd-p3", false},
{"3731afd-p2", "3731afd9b134-p2", true},
}
for _, tc := range cases {
if got := sameRuntimeID(tc.a, tc.b); got != tc.want {
t.Errorf("sameRuntimeID(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.want)
}
}
list := []Remote{
{Commit: "3731afd-p2", Channel: ChannelAlpha},
{Commit: "3731afd", Channel: ChannelStable},
}
if r, err := Pick(list, "3731afd-p2"); err != nil || r.Commit != "3731afd-p2" {
t.Fatalf("Pick(-p2) = %+v, %v", r, err)
}
if r, err := Pick(list, "3731afd"); err != nil || r.Commit != "3731afd" {
t.Fatalf("Pick(base) = %+v, %v", r, err)
}
if r, err := Pick(list, "latest"); err != nil || r.Commit != "3731afd-p2" {
t.Fatalf("Pick(latest) = %+v, %v", r, err)
}
}
func TestListRemoteFallsBackToWebOnRateLimit(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "API rate limit exceeded", http.StatusForbidden)
})
mux.HandleFunc("/o/r/releases.atom", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<entry>
<title>Portable Runtime runtime-3731afd-p2 (alpha)</title>
<updated>2026-11-29T08:00:00Z</updated>
<link rel="alternate" href="https://github.com/o/r/releases/tag/runtime-3731afd-p2"/>
</entry>
<entry>
<title>Runtime 3731afd</title>
<updated>2026-11-28T11:00:00Z</updated>
<link rel="alternate" href="https://github.com/o/r/releases/tag/runtime-3731afd"/>
</entry>
<entry>
<title>Reims-Go v0.2.4</title>
<updated>2026-11-29T07:00:00Z</updated>
<link rel="alternate" href="https://github.com/o/r/releases/tag/v0.2.4"/>
</entry>
</feed>`)
})
mux.HandleFunc("/o/r/releases/tag/runtime-3731afd-p2", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `<span class="Label Label--warning">Pre-release</span>`)
})
mux.HandleFunc("/o/r/releases/tag/runtime-3731afd", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `<span class="Label Label--success">Latest</span>`)
})
mux.HandleFunc("/o/r/releases/expanded_assets/runtime-3731afd-p2", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `<a href="/o/r/releases/download/runtime-3731afd-p2/reims-runtime-win-x64-3731afd-p2.tar.zst">a</a>
<a href="/o/r/releases/download/runtime-3731afd-p2/reims-runtime-src-3731afd-p2.tar.zst">b</a>
<a href="/o/r/releases/download/runtime-3731afd-p2/SHA256SUMS.txt">c</a>`)
})
mux.HandleFunc("/o/r/releases/expanded_assets/runtime-3731afd", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `<a href="/o/r/releases/download/runtime-3731afd/reims-runtime-win-x64-3731afd.tar.zst">a</a>
<a href="/o/r/releases/download/runtime-3731afd/reims-runtime-src-3731afd.tar.zst">b</a>
<a href="/o/r/releases/download/runtime-3731afd/SHA256SUMS.txt">c</a>`)
})
srv := httptest.NewServer(mux)
defer srv.Close()
src := Source{APIBase: srv.URL, WebBase: srv.URL, Repo: "o/r", Client: srv.Client()}
stable, err := src.ListRemote(context.Background(), false)
if err != nil {
t.Fatal(err)
}
if len(stable) != 1 || stable[0].Commit != "3731afd" || stable[0].Channel != ChannelStable {
t.Fatalf("stable fallback = %+v", stable)
}
all, err := src.ListRemote(context.Background(), true)
if err != nil {
t.Fatal(err)
}
if len(all) != 2 || all[0].Commit != "3731afd-p2" || all[0].Channel != ChannelAlpha {
t.Fatalf("all fallback = %+v", all)
}
}
func TestListRemoteAutoFallsBackToGitCode(t *testing.T) {
badPrimary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "gateway down", http.StatusBadGateway)
}))
defer badPrimary.Close()
var gcSrv *httptest.Server
gcSrv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/v5/repos/o/r/releases" {
http.NotFound(w, r)
return
}
// Matches real GitCode API v5 shape: created_at (+08:00), no published_at or html_url.
fmt.Fprintf(w, `[
{"tag_name":"runtime-3731afd","prerelease":false,"created_at":"2026-11-28T19:03:04+08:00","assets":[
{"name":"reims-runtime-win-x64-3731afd.tar.zst","size":168000000,"browser_download_url":"%s/dl/rt"},
{"name":"reims-runtime-src-3731afd.tar.zst","size":500,"browser_download_url":"%s/dl/src"},
{"name":"SHA256SUMS.txt","size":100,"browser_download_url":"%s/dl/sums"}
]}
]`, gcSrv.URL, gcSrv.URL, gcSrv.URL)
}))
defer gcSrv.Close()
src := Source{
Provider: SourceGitHub,
APIBase: badPrimary.URL,
Repo: "o/r",
Client: badPrimary.Client(),
Fallbacks: []Source{{
Provider: SourceGitCode,
APIBase: gcSrv.URL + "/api/v5",
WebBase: "https://gitcode.com",
Repo: "o/r",
Client: gcSrv.Client(),
}},
}
list, err := src.ListRemote(context.Background(), false)
if err != nil {
t.Fatal(err)
}
if len(list) != 1 || list[0].Commit != "3731afd" || list[0].Source != SourceGitCode || list[0].PageURL != "https://gitcode.com/o/r/releases/tag/runtime-3731afd" {
t.Fatalf("gitcode fallback = %+v", list)
}
}
+92 -9
View File
@@ -8,6 +8,9 @@ import (
"os"
"strconv"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/netproxy"
)
// Version is the current Reims-Go release version. Release builds may override
@@ -17,26 +20,69 @@ import (
var Version = "v0.2.4"
const (
DefaultReleasesRepo = "Nwflower/Reims-Go"
DefaultAPIBase = "https://api.github.com"
DefaultReleasesRepo = "Nwflower/Reims-Go"
DefaultAPIBase = "https://api.github.com"
DefaultWebBase = "https://github.com"
DefaultGitCodeRepo = "Nwflower/Reims-Go"
DefaultGitCodeAPIBase = "https://api.gitcode.com/api/v5"
DefaultGitCodeWebBase = "https://gitcode.com"
)
const fallbackProbeTimeout = 8 * time.Second
// Source configures where app releases are checked.
type Source struct {
APIBase string
Repo string
Client *http.Client
APIBase string
WebBase string
Repo string
Client *http.Client
Fallbacks []Source
}
func DefaultSource() Source {
func githubSource(client *http.Client) Source {
repo := os.Getenv("REIMS_GO_RELEASES_REPO")
if repo == "" {
repo = DefaultReleasesRepo
}
return Source{
APIBase: DefaultAPIBase,
WebBase: DefaultWebBase,
Repo: repo,
Client: &http.Client{},
Client: client,
}
}
func gitcodeSource(client *http.Client) Source {
repo := os.Getenv("REIMS_GO_GITCODE_REPO")
if repo == "" {
repo = DefaultGitCodeRepo
}
return Source{
APIBase: DefaultGitCodeAPIBase,
WebBase: DefaultGitCodeWebBase,
Repo: repo,
Client: client,
}
}
func DefaultSource() Source {
return DefaultSourceFor("")
}
func DefaultSourceFor(mode string) Source {
if strings.TrimSpace(mode) == "" {
mode = os.Getenv("REIMS_GO_SOURCE")
}
client := netproxy.NewClient()
switch strings.ToLower(strings.TrimSpace(mode)) {
case "github":
return githubSource(client)
case "gitcode":
return gitcodeSource(client)
default:
gh := githubSource(client)
gh.Fallbacks = []Source{gitcodeSource(client)}
return gh
}
}
@@ -57,6 +103,7 @@ type ghRelease struct {
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
PublishedAt string `json:"published_at"`
CreatedAt string `json:"created_at"`
HTMLURL string `json:"html_url"`
Assets []ghAsset `json:"assets"`
}
@@ -125,9 +172,32 @@ func Compare(a, b string) int {
return 0
}
// CheckUpdate queries GitHub Releases for the newest stable (non-draft,
// non-prerelease) application release tagged "vX.Y.Z".
// CheckUpdate queries GitHub/GitCode Releases for the newest stable (non-draft,
// non-prerelease) application release tagged "vX.Y.Z", failing over to
// Fallbacks when the primary source is unreachable.
func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, error) {
primaryCtx := ctx
var cancel context.CancelFunc
if len(s.Fallbacks) > 0 {
primaryCtx, cancel = context.WithTimeout(ctx, fallbackProbeTimeout)
defer cancel()
}
info, err := s.checkUpdateSingle(primaryCtx, current)
if err == nil {
return info, nil
}
if ctx.Err() != nil || len(s.Fallbacks) == 0 {
return info, err
}
for _, fb := range s.Fallbacks {
if fbInfo, fbErr := fb.checkUpdateSingle(ctx, current); fbErr == nil {
return fbInfo, nil
}
}
return info, err
}
func (s Source) checkUpdateSingle(ctx context.Context, current string) (UpdateInfo, error) {
if current == "" {
current = Version
}
@@ -143,6 +213,13 @@ func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, er
}
req.Header.Set("User-Agent", "reims-go")
req.Header.Set("Accept", "application/vnd.github+json")
if req.URL.Host == "api.github.com" {
if tok := strings.TrimSpace(os.Getenv("GITHUB_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
} else if tok := strings.TrimSpace(os.Getenv("GH_TOKEN")); tok != "" {
req.Header.Set("Authorization", "Bearer "+tok)
}
}
resp, err := client.Do(req)
if err != nil {
@@ -181,7 +258,13 @@ func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, er
info.Latest = best.TagName
info.PageURL = best.HTMLURL
if info.PageURL == "" && s.WebBase != "" {
info.PageURL = fmt.Sprintf("%s/%s/releases/tag/%s", strings.TrimRight(s.WebBase, "/"), s.Repo, best.TagName)
}
info.PublishedAt = best.PublishedAt
if info.PublishedAt == "" {
info.PublishedAt = best.CreatedAt
}
for _, a := range best.Assets {
lower := strings.ToLower(a.Name)
if strings.HasSuffix(lower, ".exe") && !strings.Contains(lower, "-cli-") {
+1
View File
@@ -12,6 +12,7 @@
| :--- | :--- | :--- | :--- |
| `reims-vgpu-cargo-lock.patch` | `steelbrain/reims-vgpu` (`3731afd`) 的 `Cargo.lock` | 不改代码:cargo 构建时给 `metal2vulkan`、`metal2vulkan-air`、`metal2vulkan-runtime` 三个包补上了 `source = "git+…metal2vulkan?rev=0b0ac58…"`。为了让源码包和实际构建逐字节一致,照实声明(2026-11-28 从本机构建目录 `git diff` 取得) | 不需要上游修复;上游 `Cargo.lock` 补齐后即可删除 |
| `reims-vgpu-win32-unicode-input.patch` | `steelbrain/reims-vgpu` (`3731afd`) 的 `crates/reims-vgpu-window` | Windows 窗口层仅处理 `SDL_EVENT_KEY_DOWN`/`UP` 且丢弃扫描码为 0 的 `VK_PACKET` 及 `WM_CHAR`/`WM_UNICHAR`/`WM_IME_CHAR`,导致远程输入法、宿主机 IME、语音输入注入的文字无法进入客体;通过 `SDL_SetWindowsMessageHook` 在配置 `REIMS_GO_INPUT_URL` 时将非物理按键字符异步转发至本地回环桥,物理键码路径零影响 | 2026-11-28 新增补丁,待编入下一版 alpha 运行时实测验证后提上游 PR |
| `reims-ctl-win32-random-bytes.patch` | `steelbrain/reims-vgpu` (`3731afd`) 的 `crates/reims-ctl/src/vm.rs` | `random_bytes()`(`vm.rs:849-864`)在打不开 `/dev/urandom` 时退回用「纳秒时间 ^ (pid << 64)」当种子。Windows 上永远走这条退路,于是新 VM 的 MAC 后 3 字节(也就是 OpenCore 的 ROM)只剩约 22 位、可预测的时钟熵,第 4 段永远是 4 的倍数。改成用 std `RandomState` 做哈希(它的密钥来自系统随机源 ProcessPrng),不加依赖,不改 Cargo 文件 | 2026-11-29 新增补丁,`git apply --check` 通过;本机没有 Rust 工具链,尚未编译,待编入下一版 alpha 运行时验证后提 PR |
| `qemu-whpx-win10-compat.patch` | `steelbrain/qemu-reims-vgpu` (`4571bc5`) | 修复 Windows 10 19045 上 WHPX 两处必现崩溃:① `whpx_tsc_deadline_refused()` 在正式 partition 上删建 vCPU 0 导致 `WHvCreateVirtualProcessor` 返回 `0x80070057`;② `whpx_set_registers()` 调用 Win11 新增的 `WHvResetPartition` 未判空导致 `0xc0000005` 崩溃 | 待提交上游 PR |
| `qemu-whpx-win10-startup-ipis.patch` | 同上,须在前一项之后应用 | Win10 开启内核 irqchip 时,将多核客体的 INIT/SIPI 经 `WHvRequestInterrupt` 转发,避免 XNU 启动从核时停住。8 核两次冷启动与 12 核冷启动均验证 x2APIC、FileVault、SSH 和图形登录,默认 8 核启动与正常关机也通过。多核整体性能收益和客体冷重启仍待验证 | 待提交上游 PR |
| `qemu-whpx-nested-virt-nonfatal.patch` | 同上,须在前两项之后应用 | 部分 Windows 11 宿主(如 24H2/Home 或 Core Ultra 200)在 `WHvGetCapability` 报告 `Bank1.NestedVirtSupport=1`,但 `WHvSetPartitionProperty(NestedVirtualization)` 返回 `hr=0x80370302`(`WHV_E_UNKNOWN_PROPERTY`)。原代码将其视为致命错误直接中止启动,迫使退回 `kernel-irqchip=off`;改为 `warn_report` 并清零 `Bank1.NestedVirtSupport`,保留完整的 Hyper-V 内核态 x2APIC / SynIC 加速 | 待真机编译冒烟后提交上游 PR |
@@ -0,0 +1,30 @@
diff --git a/crates/reims-ctl/src/vm.rs b/crates/reims-ctl/src/vm.rs
index e8b8e92..f62174f 100644
--- a/crates/reims-ctl/src/vm.rs
+++ b/crates/reims-ctl/src/vm.rs
@@ -853,12 +853,22 @@ fn random_bytes<const N: usize>() -> [u8; N] {
.and_then(|mut f| f.read_exact(&mut b))
.is_err()
{
+ // Windows has no /dev/urandom. The clock alone is no random source there: it counts
+ // 100 ns, so its low bytes hold some 22 bits, the first of them a multiple of 4, and the
+ // pid, shifted past them, changes none. std's RandomState is keyed from the OS's random
+ // source (ProcessPrng on Windows), so a hash it keys is unpredictable; the clock and the
+ // pid are hashed in too.
+ use std::hash::{BuildHasher, Hasher};
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
- let seed = t.as_nanos() ^ (std::process::id() as u128) << 64;
- for (i, x) in b.iter_mut().enumerate() {
- *x = (seed >> (i * 8)) as u8;
+ let keys = std::collections::hash_map::RandomState::new();
+ for (i, chunk) in b.chunks_mut(8).enumerate() {
+ let mut h = keys.build_hasher();
+ h.write_usize(i);
+ h.write_u128(t.as_nanos());
+ h.write_u32(std::process::id());
+ chunk.copy_from_slice(&h.finish().to_le_bytes()[..chunk.len()]);
}
}
b
+1
View File
@@ -5,6 +5,7 @@
# scripts/pack-runtime.ps1 both read this file; add or retire patches here.
reims-vgpu reims-vgpu-cargo-lock.patch
reims-vgpu reims-vgpu-win32-unicode-input.patch
reims-vgpu reims-ctl-win32-random-bytes.patch
vendor/qemu qemu-whpx-win10-compat.patch
vendor/qemu qemu-whpx-win10-startup-ipis.patch
vendor/qemu qemu-whpx-nested-virt-nonfatal.patch
+39 -11
View File
@@ -32,35 +32,43 @@ func (a *App) includeAlpha() bool {
return rt.NormalizeChannel(a.cfg.RuntimeChannel) == rt.ChannelAlpha
}
func (a *App) runtimeSource() string {
a.mu.Lock()
defer a.mu.Unlock()
return rt.NormalizeSource(a.cfg.RuntimeSource)
}
// remoteCache keeps the release list for a while: GitHub allows 60
// unauthenticated API requests an hour, and the host page, first launch and
// the CLI all ask for it.
var remoteCache struct {
sync.Mutex
at time.Time
alpha bool
list []rt.Remote
at time.Time
alpha bool
source string
list []rt.Remote
}
const remoteCacheTTL = 10 * time.Minute
// ListRemoteRuntimes lists published runtimes for the configured channel.
// ListRemoteRuntimes lists published runtimes for the configured channel and source.
func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) {
alpha := a.includeAlpha()
source := a.runtimeSource()
remoteCache.Lock()
defer remoteCache.Unlock()
if remoteCache.list != nil && remoteCache.alpha == alpha && time.Since(remoteCache.at) < remoteCacheTTL {
if remoteCache.list != nil && remoteCache.alpha == alpha && remoteCache.source == source && time.Since(remoteCache.at) < remoteCacheTTL {
return remoteCache.list, nil
}
list, err := rt.DefaultSource().ListRemote(a.baseCtx(), alpha)
list, err := rt.DefaultSourceFor(source).ListRemote(a.baseCtx(), alpha)
if err != nil {
return nil, err
}
remoteCache.at, remoteCache.alpha, remoteCache.list = time.Now(), alpha, list
remoteCache.at, remoteCache.alpha, remoteCache.source, remoteCache.list = time.Now(), alpha, source, list
return list, nil
}
// forgetRemoteRuntimes drops the cached list (after an install or a channel change).
// forgetRemoteRuntimes drops the cached list (after an install or a channel/source change).
func forgetRemoteRuntimes() {
remoteCache.Lock()
remoteCache.list = nil
@@ -83,6 +91,25 @@ func (a *App) SetRuntimeChannel(channel string) error {
return config.Save("", a.cfg)
}
// SetRuntimeSource picks "auto", "github", or "gitcode" for online runtime and
// app update lookups.
func (a *App) SetRuntimeSource(source string) error {
switch strings.ToLower(strings.TrimSpace(source)) {
case "", rt.SourceAuto, rt.SourceGitHub, rt.SourceGitCode:
source = rt.NormalizeSource(source)
default:
return fmt.Errorf("unknown runtime source %q", source)
}
a.mu.Lock()
defer a.mu.Unlock()
a.cfg.RuntimeSource = source
forgetRemoteRuntimes()
appUpdateCache.Lock()
appUpdateCache.info = nil
appUpdateCache.Unlock()
return config.Save("", a.cfg)
}
// InstallRuntimeOnline downloads, verifies and installs a published runtime
// ("" or "latest" for the newest on the channel) and makes it active. It runs
// in the background and returns the task ID; CancelTask pauses the download,
@@ -129,12 +156,12 @@ func (a *App) InstallRuntimeOnline(commit string) (string, error) {
}
func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, taskID string) (string, error) {
src := rt.DefaultSource()
src := rt.DefaultSourceFor(cfg.RuntimeSource)
step := func(msg string) {
a.emitLog("runtime", msg)
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: msg, Percent: -1})
}
step("Looking up runtime releases on GitHub")
step("Looking up runtime releases")
// An explicit commit may be an alpha even on the stable channel: the
// user asked for it by name.
list, err := src.ListRemote(ctx, rt.NormalizeChannel(cfg.RuntimeChannel) == rt.ChannelAlpha || (commit != "" && commit != "latest"))
@@ -193,12 +220,13 @@ var appUpdateCache struct {
// CheckAppUpdate checks GitHub Releases for a newer stable Reims-Go version.
// Results are cached for 10 minutes unless force is true.
func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
source := a.runtimeSource()
appUpdateCache.Lock()
defer appUpdateCache.Unlock()
if !force && appUpdateCache.info != nil && time.Since(appUpdateCache.at) < remoteCacheTTL {
return *appUpdateCache.info, nil
}
info, err := version.DefaultSource().CheckUpdate(a.baseCtx(), version.Version)
info, err := version.DefaultSourceFor(source).CheckUpdate(a.baseCtx(), version.Version)
if err != nil {
return info, err
}
+45 -40
View File
@@ -43,6 +43,9 @@ param(
[ValidateSet('alpha', 'stable')]
[string]$Channel = 'alpha',
[int]$ZstdLevel = 15,
# Release identifier for archive names and manifest.commit (defaults to short
# upstream commit; e.g. "3731afd-p2" for a patch-queue rebuild of 3731afd).
[string]$ReleaseId = '',
# Names from patches/series.txt actually applied. Not given: all of them.
# Given but empty: none (every patch already upstream).
[string[]]$Patches = @()
@@ -93,6 +96,7 @@ foreach ($p in @($ctlExe, $utilExe, $qemuExe)) {
$commit = (git -C $ReimsRepo rev-parse --short HEAD).Trim()
$fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim()
$id = if ($ReleaseId -and $ReleaseId.Trim()) { $ReleaseId.Trim() } else { $commit }
$qemuRepo = Join-Path $ReimsRepo 'vendor\qemu'
$qemuCommit = (git -C $qemuRepo rev-parse HEAD).Trim()
@@ -139,7 +143,9 @@ foreach ($e in $series) {
Paths = $paths
}
}
$patches = @()
# Avoid colliding with the [string[]]$Patches parameter (PowerShell variable
# names are case-insensitive; reusing $patches coerces every entry to a string).
$patchEntries = @()
# Group patches by repo so multi-patch stacks (e.g. 2-3 QEMU WHPX patches) are
# verified together against a clean HEAD export with zero undeclared diff.
$byTarget = [ordered]@{}
@@ -150,46 +156,45 @@ foreach ($ps in $patchSpecs) {
$byTarget[$ps.Target] = [Collections.Generic.List[hashtable]]::new()
}
$byTarget[$ps.Target].Add($ps)
$patches += [ordered]@{ name = $ps.Name; target = $ps.Target; sha256 = (Get-Sha256 $file) }
$patchEntries += [ordered]@{ name = $ps.Name; target = $ps.Target; sha256 = (Get-Sha256 $file) }
}
foreach ($targetName in $byTarget.Keys) {
$group = $byTarget[$targetName]
$repo = $group[0].Repo
$paths = @($group | ForEach-Object { $_.Paths } | Where-Object { $_ } | Select-Object -Unique)
$diffArgs = @('-C', $repo, '-c', 'core.autocrlf=false', 'diff')
if ($paths.Count) { $diffArgs += $paths }
# Use --full-index so blob hash abbreviation lengths match regardless of
# object count between the upstream clone and the single-commit verify repo.
$diffArgs = @('-C', $repo, '-c', 'core.autocrlf=false', 'diff', '--full-index')
if ($paths.Count) { $diffArgs += '--'; $diffArgs += $paths }
$treeDiff = (& git @diffArgs | Out-String).Replace("`r`n", "`n").TrimEnd()
if ($group.Count -eq 1) {
$patchText = [IO.File]::ReadAllText((Join-Path $patchesDir $group[0].Name)).Replace("`r`n", "`n").TrimEnd()
if ($treeDiff -ne $patchText) {
throw "$($group[0].Name) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)."
# Apply the declared patch stack to a clean temporary clone of HEAD and compare diffs byte-for-byte.
$verifyDir = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid())
try {
New-Item -ItemType Directory -Force -Path $verifyDir | Out-Null
$headRev = (git -C $repo rev-parse HEAD).Trim()
Invoke-Native 'git' @('init', '-q', $verifyDir)
$tar = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid() + '.tar')
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $headRev)
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $verifyDir)
Remove-Item -LiteralPath $tar -Force
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'add', '-A')
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'commit', '-q', '-m', 'base')
foreach ($ps in $group) {
$pf = Join-Path $patchesDir $ps.Name
Invoke-Native 'git' @('-C', $verifyDir, 'apply', '--check', $pf)
Invoke-Native 'git' @('-C', $verifyDir, 'apply', $pf)
}
} else {
# Apply the declared patch stack to a clean temporary clone of HEAD and compare diffs byte-for-byte.
$verifyDir = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid())
try {
New-Item -ItemType Directory -Force -Path $verifyDir | Out-Null
$headRev = (git -C $repo rev-parse HEAD).Trim()
Invoke-Native 'git' @('init', '-q', $verifyDir)
$tar = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid() + '.tar')
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $headRev)
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $verifyDir)
Remove-Item -LiteralPath $tar -Force
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'add', '-A')
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'commit', '-q', '-m', 'base')
foreach ($ps in $group) {
$pf = Join-Path $patchesDir $ps.Name
Invoke-Native 'git' @('-C', $verifyDir, 'apply', '--check', $pf)
Invoke-Native 'git' @('-C', $verifyDir, 'apply', $pf)
}
$expectedDiff = (& git -C $verifyDir -c core.autocrlf=false diff | Out-String).Replace("`r`n", "`n").TrimEnd()
if ($treeDiff -ne $expectedDiff) {
throw "Patch stack ($(($group | ForEach-Object { $_.Name }) -join ', ')) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
} finally {
if (Test-Path -LiteralPath $verifyDir) { Remove-Item -Recurse -Force -LiteralPath $verifyDir }
$expectedDiff = (& git -C $verifyDir -c core.autocrlf=false diff --full-index | Out-String).Replace("`r`n", "`n").TrimEnd()
if ($treeDiff -ne $expectedDiff) {
$treeStat = (& git -C $repo diff --stat -- @paths | Out-String).Trim()
$expStat = (& git -C $verifyDir diff --stat | Out-String).Trim()
Write-Host "Build tree diff --stat:`n$treeStat"
Write-Host "Expected patch stack diff --stat:`n$expStat"
throw "Patch stack ($(($group | ForEach-Object { $_.Name }) -join ', ')) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
} finally {
if (Test-Path -LiteralPath $verifyDir) { Remove-Item -Recurse -Force -LiteralPath $verifyDir }
}
}
# Anything else changed in the build trees is undeclared: refuse.
@@ -206,9 +211,9 @@ if ($otherCtl.Count -or $otherQemu.Count) {
throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu -join "`n")"
}
$bundleName = "reims-runtime-win-x64-$commit"
$srcName = "reims-runtime-src-$commit"
$stageRoot = Join-Path $TempRoot "pack-$commit"
$bundleName = "reims-runtime-win-x64-$id"
$srcName = "reims-runtime-src-$id"
$stageRoot = Join-Path $TempRoot "pack-$id"
$bundleDir = Join-Path $stageRoot $bundleName
$srcDir = Join-Path $stageRoot $srcName
if (Test-Path -LiteralPath $stageRoot) { Remove-Item -Recurse -Force -LiteralPath $stageRoot }
@@ -260,7 +265,7 @@ $msysText = @"
# (pacman -Qo on the build machine, $(Get-Date -Format 'yyyy-MM-dd')).
#
# Sources: every package whose licence requires source (GPL / LGPL / MPL) is in
# reims-runtime-msys2-src-$commit.tar.zst, published beside this runtime.
# reims-runtime-msys2-src-$id.tar.zst, published beside this runtime.
# The same files are also at:
# https://repo.msys2.org/mingw/sources/ (<package>-<version>.src.tar.zst, by pkgbase)
# https://github.com/msys2/MINGW-packages (build recipes)
@@ -340,12 +345,12 @@ $manifest = [ordered]@{
name = $bundleName
platform = 'windows-x86_64'
upstream_repo = 'https://github.com/steelbrain/reims-vgpu'
commit = $commit
commit = $id
full_commit = $fullCommit
vendor_qemu_commit = $qemuCommit
util_commit = $utilCommit
metal2vulkan_commit = $m2vCommit
patches = $patches
patches = $patchEntries
channel = $Channel
source_package = "$srcName.tar.zst"
qemu_version = $qemuVersionLine
@@ -372,7 +377,7 @@ Write-Utf8 "$runtimeArchive.sha256" "$rtHash $bundleName.tar.zst`n"
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') "$rtHash $bundleName.tar.zst`n$srcHash $srcName.tar.zst`n"
# Sources of the copyleft MSYS2 packages, as their own asset (adds a line to SHA256SUMS.txt).
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $commit -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $id -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
Remove-Item -Recurse -Force -LiteralPath $stageRoot
@@ -380,4 +385,4 @@ Write-Host ''
Write-Host '==> Done' -ForegroundColor Green
'{0,-10} {1} {2:N1} MB' -f 'runtime', $runtimeArchive, ((Get-Item $runtimeArchive).Length / 1MB)
'{0,-10} {1} {2:N1} MB' -f 'source', $srcArchive, ((Get-Item $srcArchive).Length / 1MB)
"channel $Channel; patches: $(($patches | ForEach-Object { $_.name }) -join ', '); DLLs: $($dlls.Count)"
"channel $Channel; patches: $(($patchEntries | ForEach-Object { $_.name }) -join ', '); DLLs: $($dlls.Count)"
+201
View File
@@ -0,0 +1,201 @@
#!/usr/bin/env python3
"""Mirror GitHub Releases (metadata + all assets) to GitCode via API v5.
Used by .github/workflows/sync-gitcode.yml and build-runtime.yml.
Requires environment variables:
GITCODE_TOKEN Personal access token with repo & release write scope
GH_TOKEN GitHub token for `gh release view/download`
Optional environment variables:
GITHUB_REPO Default: Nwflower/reims-go
GITCODE_REPO Default: Nwflower/Reims-Go
"""
import json
import os
import subprocess
import sys
import tempfile
import urllib.error
import urllib.parse
import urllib.request
GITHUB_REPO = os.environ.get("GITHUB_REPO", "Nwflower/reims-go")
GITCODE_REPO = os.environ.get("GITCODE_REPO", "Nwflower/Reims-Go")
GITCODE_API = "https://api.gitcode.com/api/v5"
def gc_request(method: str, path: str, token: str, payload=None):
url = f"{GITCODE_API}{path}"
data = None
headers = {
"Authorization": f"Bearer {token}",
"User-Agent": "reims-go-sync",
"Accept": "application/json",
}
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json; charset=utf-8"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
raw = resp.read()
return resp.status, json.loads(raw.decode("utf-8")) if raw else None
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="replace")
return e.code, body
def list_gitcode_releases(token: str) -> dict:
by_tag = {}
for page in range(1, 20):
status, data = gc_request(
"GET",
f"/repos/{GITCODE_REPO}/releases?page={page}&per_page=100",
token,
)
if status != 200 or not isinstance(data, list) or not data:
break
for rel in data:
tag = rel.get("tag_name")
if tag:
by_tag[tag] = rel
if len(data) < 100:
break
return by_tag
def gh_json(args: list[str]):
out = subprocess.check_output(["gh", *args], text=True)
return json.loads(out)
def ensure_gitcode_release(tag: str, gh_rel: dict, existing: dict | None, token: str) -> dict:
payload = {
"tag_name": tag,
"name": gh_rel.get("name") or tag,
"body": gh_rel.get("body") or "",
"prerelease": bool(gh_rel.get("isPrerelease")),
"target_commitish": "main",
}
if existing is None:
status, res = gc_request("POST", f"/repos/{GITCODE_REPO}/releases", token, payload)
if status not in (200, 201):
raise RuntimeError(f"create GitCode release {tag} failed (HTTP {status}): {res}")
print(f"created GitCode release {tag} (prerelease={payload['prerelease']})")
return res if isinstance(res, dict) else {}
# Update title/body/prerelease (e.g. when an alpha runtime is promoted to stable).
enc_tag = urllib.parse.quote(tag, safe="")
status, res = gc_request("PATCH", f"/repos/{GITCODE_REPO}/releases/{enc_tag}", token, payload)
if status in (200, 201):
print(f"updated GitCode release {tag} (prerelease={payload['prerelease']})")
if isinstance(res, dict):
return res
else:
print(f"notice PATCH release {tag} returned HTTP {status}; continuing with existing release")
return existing
def upload_asset(tag: str, file_path: str, file_name: str, token: str):
enc_tag = urllib.parse.quote(tag, safe="")
enc_name = urllib.parse.quote(file_name, safe="")
status, data = gc_request(
"GET",
f"/repos/{GITCODE_REPO}/releases/{enc_tag}/upload_url?file_name={enc_name}",
token,
)
if status != 200 or not isinstance(data, dict) or not data.get("url"):
raise RuntimeError(f"get upload_url for {tag}/{file_name} failed (HTTP {status}): {data}")
cmd = ["curl", "-fSL", "--retry", "3", "--retry-delay", "5", "-X", "PUT", "-T", file_path]
for k, v in (data.get("headers") or {}).items():
cmd.extend(["-H", f"{k}: {v}"])
cmd.append(data["url"])
subprocess.check_call(cmd)
print(f"uploaded {tag}/{file_name}")
def sync_tag(tag: str, gc_releases: dict, token: str):
gh_rel = gh_json([
"release", "view", tag, "-R", GITHUB_REPO,
"--json", "tagName,name,body,isPrerelease,isDraft,assets",
])
if gh_rel.get("isDraft"):
print(f"skip {tag} (draft)")
return
existing = gc_releases.get(tag)
rel = ensure_gitcode_release(tag, gh_rel, existing, token)
# Refresh existing attachment map so idempotent reruns skip matching assets.
have = {}
for a in (existing or rel).get("assets") or []:
if a.get("type") == "attach" and a.get("name"):
have[a["name"]] = a.get("size")
assets = gh_rel.get("assets") or []
if not assets:
print(f"done {tag} (no assets)")
return
with tempfile.TemporaryDirectory(prefix="gc-sync-") as tmp:
for asset in assets:
name = asset["name"]
size = asset.get("size")
if name in have and (size is None or have[name] == size):
print(f"exists {tag}/{name} ({size} bytes)")
continue
print(f"fetching {tag}/{name} ({size} bytes) from GitHub...")
subprocess.check_call([
"gh", "release", "download", tag, "-R", GITHUB_REPO,
"-p", name, "-D", tmp, "--clobber",
])
local_path = os.path.join(tmp, name)
try:
upload_asset(tag, local_path, name, token)
finally:
if os.path.exists(local_path):
os.remove(local_path)
def default_tags() -> list[str]:
rels = gh_json([
"release", "list", "-R", GITHUB_REPO, "--limit", "50",
"--json", "tagName,isDraft,isPrerelease,isLatest",
])
tags = []
seen_latest_app = False
for r in rels:
if r.get("isDraft"):
continue
tag = r["tagName"]
if tag.startswith("runtime-"):
tags.append(tag)
elif tag.startswith("v") and (r.get("isLatest") or not seen_latest_app):
tags.append(tag)
seen_latest_app = True
return tags
def main():
token = os.environ.get("GITCODE_TOKEN", "").strip()
if not token:
print("GITCODE_TOKEN is not set; skipping GitCode release sync.", file=sys.stderr)
sys.exit(1)
tags = [t.strip() for t in sys.argv[1:] if t.strip()]
if not tags:
tags = default_tags()
if not tags:
print("No releases to sync.")
return
gc_releases = list_gitcode_releases(token)
for tag in tags:
sync_tag(tag, gc_releases, token)
if __name__ == "__main__":
main()