From f6f6bfce3442d1977cda97529a72431ac378561f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Sat, 28 Nov 2026 04:11:37 -0700 Subject: [PATCH] feat: online runtime install, first-launch data folder picker, source packages - Runtime: list and fetch runtimes from this repo's GitHub Releases (stable by default, candidate on request), with SHA256 check and resume. CLI gains `runtime available` and `runtime fetch`; the host page gets an online install row and a "receive candidates" switch. - First launch: pick a data folder (non-system drives first, USB never recommended); the choice is recorded in %APPDATA%\reims-go\location.json. Existing installs in the default folder are adopted without asking. - pack-runtime.ps1: also builds the matching source package, records every patch with its SHA256 and the channel, and refuses undeclared changes in the build trees. - patches: declare reims-vgpu-cargo-lock.patch (Cargo.lock source lines). - UI: sidebar and VM page restyle, new design tokens. Co-Authored-By: Claude Opus 5.5 --- .claude/launch.json | 6 + app.go | 11 +- cmd/reims-go/main.go | 14 +- cmd/reims-go/runtime_fetch.go | 99 ++++++ frontend/src/App.tsx | 92 +++++- frontend/src/components/HostView.tsx | 22 +- frontend/src/components/RuntimeOnline.tsx | 102 +++++++ frontend/src/components/Setup.tsx | 177 +++++++++++ frontend/src/components/Sidebar.tsx | 56 ++-- frontend/src/components/VMPage.tsx | 127 ++++++-- frontend/src/i18n.ts | 66 ++++ frontend/src/lib/tasks.ts | 1 + frontend/src/styles/app.css | 354 +++++++++++++++------- frontend/src/styles/tokens.css | 148 ++++++--- frontend/src/types.ts | 35 +++ frontend/src/wails.ts | 15 + frontend/wailsjs/go/main/App.d.ts | 12 + frontend/wailsjs/go/main/App.js | 24 ++ frontend/wailsjs/go/models.ts | 126 ++++++++ internal/config/config.go | 108 ++++++- internal/config/config_test.go | 80 +++++ internal/host/drives_other.go | 35 +++ internal/host/drives_windows.go | 96 ++++++ internal/host/drives_windows_test.go | 21 ++ internal/i18n/i18n.go | 134 ++++---- internal/runtime/remote.go | 329 ++++++++++++++++++++ internal/runtime/remote_test.go | 154 ++++++++++ internal/runtime/runtime.go | 16 + patches/README.md | 1 + patches/reims-vgpu-cargo-lock.patch | 28 ++ runtime_bindings.go | 147 +++++++++ scripts/pack-runtime.ps1 | 337 ++++++++++++++------ setup.go | 186 ++++++++++++ 33 files changed, 2766 insertions(+), 393 deletions(-) create mode 100644 cmd/reims-go/runtime_fetch.go create mode 100644 frontend/src/components/RuntimeOnline.tsx create mode 100644 frontend/src/components/Setup.tsx create mode 100644 internal/config/config_test.go create mode 100644 internal/host/drives_other.go create mode 100644 internal/host/drives_windows.go create mode 100644 internal/host/drives_windows_test.go create mode 100644 internal/runtime/remote.go create mode 100644 internal/runtime/remote_test.go create mode 100644 patches/reims-vgpu-cargo-lock.patch create mode 100644 runtime_bindings.go create mode 100644 setup.go diff --git a/.claude/launch.json b/.claude/launch.json index 27c3230..992427c 100644 --- a/.claude/launch.json +++ b/.claude/launch.json @@ -6,6 +6,12 @@ "runtimeExecutable": "wails", "runtimeArgs": ["dev", "-browser=false"], "port": 34115 + }, + { + "name": "wails-dev-firstrun", + "runtimeExecutable": "pwsh", + "runtimeArgs": ["-NoProfile", "-Command", "$env:REIMS_GO_FIRST_RUN='1'; $env:REIMS_GO_LOCATION_FILE='D:/Build/Temp/reims-firstrun/location.json'; wails dev -browser=false"], + "port": 34115 } ] } diff --git a/app.go b/app.go index 3c3ca1f..86d6ebb 100644 --- a/app.go +++ b/app.go @@ -32,6 +32,8 @@ type AppState struct { VMs []reims.VMListItem `json:"vms"` Transitions map[string]string `json:"transitions"` PendingChanges map[string][]PendingChange `json:"pending_changes"` + // NeedsSetup is true on first launch, until a data folder is chosen (setup.go). + NeedsSetup bool `json:"needs_setup"` } type rebootWatcherEntry struct { @@ -48,15 +50,17 @@ type App struct { rebootWatchers map[string]rebootWatcherEntry nextWatcherID uint64 stopPoll context.CancelFunc + needsSetup bool } func NewApp() *App { - cfg, err := config.Load("") + cfg, needsSetup, err := config.Resolve() if err != nil { cfg = config.Default() } return &App{ cfg: cfg, + needsSetup: needsSetup, transitions: make(map[string]string), pendingChanges: make(map[string][]PendingChange), rebootWatchers: make(map[string]rebootWatcherEntry), @@ -190,6 +194,7 @@ func (a *App) GetState() AppState { for k, v := range a.pendingChanges { pcCopy[k] = append([]PendingChange(nil), v...) } + needsSetup := a.needsSetup a.mu.Unlock() rep := host.Inspect(cfgCopy.DataRoot) @@ -205,6 +210,7 @@ func (a *App) GetState() AppState { VMs: vms, Transitions: trCopy, PendingChanges: pcCopy, + NeedsSetup: needsSetup, } } @@ -241,6 +247,9 @@ func (a *App) SetDataRoot(dir string) error { if err == nil { err = config.Save("", a.cfg) } + if err == nil { + err = config.SaveLocation(dir) + } a.mu.Unlock() return err } diff --git a/cmd/reims-go/main.go b/cmd/reims-go/main.go index e9c56ec..e0a1f68 100644 --- a/cmd/reims-go/main.go +++ b/cmd/reims-go/main.go @@ -77,7 +77,9 @@ func printUsage(loc i18n.Locale) { fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]") fmt.Println("\n命令:") fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)") - fmt.Println(" runtime install 导入并校验便携运行时包(.tar.zst 或 .zip)") + fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--candidate 含候选版)") + fmt.Println(" runtime fetch [commit] 在线下载、校验并安装运行时(默认最新;Ctrl+C 暂停,再次运行续传)") + fmt.Println(" runtime install 导入并校验本地运行时包(.tar.zst 或 .zip)") fmt.Println(" runtime list 查看已安装的便携运行时版本") fmt.Println(" runtime use 切换当前激活运行时") fmt.Println(" vm list 列出已创建的虚拟机") @@ -95,7 +97,9 @@ func printUsage(loc i18n.Locale) { fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] [args]") fmt.Println("\nCommands:") fmt.Println(" doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)") - fmt.Println(" runtime install Verify and install a portable runtime (.tar.zst or .zip)") + fmt.Println(" runtime available List runtimes published on GitHub (--candidate includes candidates)") + fmt.Println(" runtime fetch [commit] Download, verify and install a runtime (newest by default; Ctrl+C pauses)") + fmt.Println(" runtime install Verify and install a local runtime package (.tar.zst or .zip)") fmt.Println(" runtime list List installed portable runtimes") fmt.Println(" runtime use Activate an installed runtime version") fmt.Println(" vm list List virtual machines") @@ -176,7 +180,7 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { if len(args) == 0 { - return fmt.Errorf("usage: reims-go runtime ") + return fmt.Errorf("usage: reims-go runtime ") } switch args[0] { case "install": @@ -229,6 +233,10 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { } } return fmt.Errorf("runtime %q not found", args[1]) + case "available": + return cmdRuntimeAvailable(cfg, loc, args[1:]) + case "fetch": + return cmdRuntimeFetch(cfg, loc, args[1:]) default: return fmt.Errorf("unknown runtime subcommand %q", args[0]) } diff --git a/cmd/reims-go/runtime_fetch.go b/cmd/reims-go/runtime_fetch.go new file mode 100644 index 0000000..12a1603 --- /dev/null +++ b/cmd/reims-go/runtime_fetch.go @@ -0,0 +1,99 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "os/signal" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/installer" + rt "github.com/Nwflower/reims-go/internal/runtime" +) + +// runtime available [--candidate]: published runtimes on GitHub Releases. +func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("runtime available", flag.ContinueOnError) + candidate := fs.Bool("candidate", cfg.RuntimeChannel == rt.ChannelCandidate, "Include candidate runtimes") + if err := fs.Parse(args); err != nil { + return err + } + list, err := rt.DefaultSource().ListRemote(context.Background(), *candidate) + if err != nil { + return err + } + if len(list) == 0 { + fmt.Println(i18n.T(loc, "runtime.remote.empty")) + return nil + } + fmt.Printf("%-9s %-10s %-11s %9s %s\n", "COMMIT", "CHANNEL", "PUBLISHED", "SIZE", "INSTALLED") + for _, r := range list { + mark := "" + if rt.IsInstalled(cfg, r.Commit) { + mark = "*" + } + date := r.PublishedAt + if len(date) >= 10 { + date = date[:10] + } + fmt.Printf("%-9s %-10s %-11s %9s %s\n", r.Commit, r.Channel, date, humanBytes(r.ArchiveSize), mark) + } + return nil +} + +// runtime fetch [commit|latest] [--candidate]: download, verify, install, activate. +func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("runtime fetch", flag.ContinueOnError) + candidate := fs.Bool("candidate", cfg.RuntimeChannel == rt.ChannelCandidate, "Allow candidate runtimes for \"latest\"") + if err := fs.Parse(args); err != nil { + return err + } + want := fs.Arg(0) + explicit := want != "" && want != "latest" + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + src := rt.DefaultSource() + list, err := src.ListRemote(ctx, *candidate || explicit) + if err != nil { + return err + } + r, err := rt.Pick(list, want) + if err != nil { + return err + } + if !rt.IsInstalled(cfg, r.Commit) { + fmt.Println(i18n.T(loc, "runtime.remote.downloading", r.Commit, r.Channel, humanBytes(r.ArchiveSize))) + bar := newProgressLine() + path, err := src.Download(ctx, *r, rt.DownloadsDir(cfg), func(done, total int64) { + p := -1.0 + if total > 0 { + p = float64(done) * 100 / float64(total) + } + bar.update(installer.Update{Kind: installer.KindProgress, Done: done, Total: total, Percent: p}) + }) + bar.finish() + if errors.Is(err, context.Canceled) { + fmt.Println(i18n.T(loc, "runtime.remote.paused")) + return nil + } + if err != nil { + return err + } + inst, err := rt.InstallFromArchive(cfg, path) + if err != nil { + return err + } + _ = os.Remove(path) + r.Commit = inst.Commit + } + cfg.ActiveRuntime = r.Commit + if err := config.Save("", cfg); err != nil { + return err + } + fmt.Println(i18n.T(loc, "runtime.activated", r.Commit)) + return nil +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 6488c69..f2ed762 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,10 +1,11 @@ -import { Minus, Square, X } from 'lucide-react' +import { Minus, Moon, Square, Sun, X } from 'lucide-react' import React, { useCallback, useEffect, useRef, useState } from 'react' import { CreateWizard } from './components/CreateWizard' import { DeleteDialog } from './components/DeleteDialog' import { HostView } from './components/HostView' import { LogPanel, LogTab } from './components/LogPanel' import { SettingsModal } from './components/SettingsModal' +import { Setup } from './components/Setup' import { HOST_ID, Sidebar } from './components/Sidebar' import { VMAction, VMPage } from './components/VMPage' import { I18nKey, t } from './i18n' @@ -36,6 +37,14 @@ export const App: React.FC = () => { const [deleteTarget, setDeleteTarget] = useState(null) const [busy, setBusy] = useState>({}) const [loadError, setLoadError] = useState('') + const [theme, setTheme] = useState<'light' | 'dark'>(() => { + try { return localStorage.getItem('reims-go-theme') === 'dark' ? 'dark' : 'light' } catch { return 'light' } + }) + + useEffect(() => { + document.documentElement.dataset.theme = theme + try { localStorage.setItem('reims-go-theme', theme) } catch {} + }, [theme]) const [logsOpen, setLogsOpen] = useState(false) const [logTab, setLogTab] = useState('app') @@ -47,6 +56,7 @@ export const App: React.FC = () => { const [taskMap, setTaskMap] = useState>({}) const onTaskRef = useRef<(task: Task) => void>(() => {}) const notifiedTasks = useRef(new Set()) + const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null) const toasts = useToasts() @@ -103,15 +113,45 @@ export const App: React.FC = () => { onTaskRef.current = (task: Task) => { // Toast once per finished download; only live events reach here, not the seed list. - if (task.status !== 'running' && task.kind === 'installer-download' && !notifiedTasks.current.has(task.id)) { + const notify = task.kind === 'installer-download' || task.kind === 'runtime-install' + if (task.status !== 'running' && notify && !notifiedTasks.current.has(task.id)) { notifiedTasks.current.add(task.id) - if (task.status === 'done') toasts.push({ kind: 'ok', title: tr('toastInstallerReady', { v: task.subject }) }) - else if (task.status === 'canceled') toasts.push({ kind: 'ok', title: tr('toastDownloadPaused') }) - else fail(tr('failDownload'), task.error ?? '') + const isRuntime = task.kind === 'runtime-install' + if (task.status === 'done') { + toasts.push({ kind: 'ok', title: isRuntime ? tr('toastRuntimeReady', { v: task.result || task.subject }) : tr('toastInstallerReady', { v: task.subject }) }) + } else if (task.status === 'canceled') toasts.push({ kind: 'ok', title: tr('toastDownloadPaused') }) + else fail(tr(isRuntime ? 'failRuntime' : 'failDownload'), task.error ?? '') } setTaskMap((prev) => upsertTask(prev, task)) } const { task: activeTask, running: runningTasks } = currentTask(taskMap) + const runtimeTask = Object.values(taskMap) + .filter((x) => x.kind === 'runtime-install') + .sort((a, b) => b.updated_at - a.updated_at)[0] ?? null + + const installRuntime = (commit: string) => { + backend.installRuntimeOnline(commit).catch((e) => fail(tr('failRuntime'), e)) + } + const setChannel = (candidate: boolean) => { + backend.setRuntimeChannel(candidate ? 'candidate' : 'stable').then(refresh).catch((e) => fail(tr('failGeneric'), e)) + } + const cancelTask = (id: string) => { backend.cancelTask(id).catch((e) => fail(tr('failGeneric'), e)) } + const importRuntime = async () => { + try { + const file = await backend.pickFile(tr('importRuntime'), '*.tar.zst;*.zip') + if (!file) return + await backend.installRuntimeArchive(file) + await refresh() + } catch (e) { + fail(tr('failRuntime'), e) + } + } + const folderDone = async () => { + const s = await backend.getState().catch(() => null) + if (s) setState(s) + setSetupStage(s?.active_runtime ? null : 'runtime') + } + const showSetup = !!state && (state.needs_setup || setupStage === 'runtime') const openLogs = (tab: LogTab = 'app') => { setLogTab(tab) @@ -220,13 +260,40 @@ export const App: React.FC = () => { reims-go -
e.stopPropagation()}> - - - +
e.stopPropagation()}> + +
+ + + +
+ {showSetup && state ? ( + setSetupStage(null)} + onError={fail} + onChannel={setChannel} + onInstallRuntime={installRuntime} + onCancelTask={cancelTask} + onImportRuntime={importRuntime} + /> + ) : (
{ onRefresh={refresh} onError={fail} onSetLocale={setLang} + runtimeTask={runtimeTask} + onChannel={setChannel} + onInstallRuntime={installRuntime} + onCancelTask={cancelTask} /> )}
@@ -284,10 +355,11 @@ export const App: React.FC = () => { onRefreshSerial={() => loadSerial()} task={activeTask} runningTasks={runningTasks} - onCancelTask={(id) => { backend.cancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }} + onCancelTask={cancelTask} />
+ )} {showWizard && state && ( void onError: (title: string, e: unknown) => void onSetLocale: (l: Locale) => void + runtimeTask: Task | null + onChannel: (candidate: boolean) => void + onInstallRuntime: (commit: string) => void + onCancelTask: (id: string) => void } -export const HostView: React.FC = ({ state, locale, onRefresh, onError, onSetLocale }) => { +export const HostView: React.FC = ({ state, locale, onRefresh, onError, onSetLocale, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => { const [importing, setImporting] = useState(false) const [enabling, setEnabling] = useState(false) const { host, config, runtimes } = state @@ -97,10 +102,21 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onError, o
{tr('hostRuntime')} -
+
+ +
{!runtimes || runtimes.length === 0 ? (
{tr('noRuntime')}
diff --git a/frontend/src/components/RuntimeOnline.tsx b/frontend/src/components/RuntimeOnline.tsx new file mode 100644 index 0000000..b210c33 --- /dev/null +++ b/frontend/src/components/RuntimeOnline.tsx @@ -0,0 +1,102 @@ +import { Download, LoaderCircle, Pause } 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 { Button, IconButton } from '../ui/controls' +import { backend } from '../wails' + +interface Props { + locale: Locale + channel: 'stable' | 'candidate' + installed: InstalledRuntime[] + task: Task | null + onChannel: (candidate: boolean) => void + onInstall: (commit: string) => void + onCancel: (taskId: string) => void +} + +const gb = (b: number) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : `${Math.ceil(b / 1e6)} MB`) + +/** Online runtime install: newest release on the channel, its install button or progress. */ +export const RuntimeOnline: React.FC = ({ locale, channel, installed, task, onChannel, onInstall, onCancel }) => { + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + const [remote, setRemote] = useState(null) + const [error, setError] = useState('') + + useEffect(() => { + let live = true + setRemote(null) + setError('') + backend.listRemoteRuntimes() + .then((list) => { if (live) setRemote(list ?? []) }) + .catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) }) + return () => { live = false } + }, [channel, task?.status === 'done']) + + const latest = remote?.[0] + const isInstalled = (c: string) => installed.some((i) => i.commit.startsWith(c) || c.startsWith(i.commit)) + const running = task?.status === 'running' + + let body: React.ReactNode + if (running && task) { + body = ( +
+ + {task.percent >= 0 &&
} + {task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)} +
+ ) + } else if (error) { + body =
{tr('runtimeLookupFailed')}
+ } else if (!remote) { + body =
…
+ } else if (!latest) { + body =
{tr('runtimeNoneOnChannel')}
+ } else { + body = ( +
+ {tr('runtimeLatest', { v: latest.commit })} + {' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)} + {' · '}{gb(latest.archive_size)} + {' · '}{latest.published_at.slice(0, 10)} +
+ ) + } + + return ( + <> +
+
+
{tr('runtimeOnline')}
+ {body} +
+
+ {running && task?.cancelable && ( + } onClick={() => onCancel(task.id)} /> + )} + {!running && latest && (isInstalled(latest.commit) + ? {tr('runtimeUpToDate')} + : )} +
+
+
+
+
{tr('runtimeCandidate')}
+
{tr('runtimeCandidateHint')}
+
+
+ +
+
+ + ) +} diff --git a/frontend/src/components/Setup.tsx b/frontend/src/components/Setup.tsx new file mode 100644 index 0000000..518292e --- /dev/null +++ b/frontend/src/components/Setup.tsx @@ -0,0 +1,177 @@ +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 { Button } from '../ui/controls' +import { backend } from '../wails' +import { RuntimeOnline } from './RuntimeOnline' + +interface Props { + locale: Locale + state: AppState + stage: 'folder' | 'runtime' + runtimeTask: Task | null + onLocale: (l: Locale) => void + onFolderDone: () => void + onFinish: () => void + onError: (title: string, e: unknown) => void + onChannel: (candidate: boolean) => void + onInstallRuntime: (commit: string) => void + onCancelTask: (id: string) => void + onImportRuntime: () => void +} + +const LOW_SPACE_GB = 60 + +/** First launch: choose the data folder, then (optionally) install the runtime. */ +export const Setup: React.FC = (p) => { + const tr = (k: I18nKey, v?: Record) => t(p.locale, k, v) + return ( +
+
+ {p.stage === 'folder' ? : } +
+
+ ) +} + +type StepProps = Props & { tr: (k: I18nKey, v?: Record) => string } + +const FolderStep: React.FC = ({ locale, tr, onLocale, onFolderDone, onError }) => { + const [choices, setChoices] = useState([]) + const [custom, setCustom] = useState('') + const [customMode, setCustomMode] = useState(false) + const [selected, setSelected] = useState('') + const [check, setCheck] = useState(null) + const [busy, setBusy] = useState(false) + + useEffect(() => { + backend.suggestDataRoots().then((list) => { + const l = list ?? [] + setChoices(l) + const rec = l.find((c) => c.recommended) ?? l[0] + if (rec) setSelected(rec.path) + }).catch((e) => onError(tr('failGeneric'), e)) + }, []) + + useEffect(() => { + if (!selected) { setCheck(null); return } + let live = true + backend.checkDataRoot(selected).then((c) => { if (live) setCheck(c) }).catch(() => {}) + return () => { live = false } + }, [selected]) + + const browse = async () => { + const dir = await backend.pickDirectory(tr('setupTitle')).catch(() => '') + if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) } + } + + const next = async () => { + setBusy(true) + try { + await backend.completeSetup(selected) + onFolderDone() + } catch (e) { + onError(tr('failGeneric'), e) + } finally { + setBusy(false) + } + } + + const option = (path: string, meta: React.ReactNode) => ( + + ) + + const notices: string[] = [] + if (check?.error) notices.push(check.error) + else if (check) { + if (check.system) notices.push(tr('setupWarnSystem')) + if (check.external) notices.push(tr('setupWarnExternal')) + if (check.free_gb > 0 && check.free_gb < LOW_SPACE_GB) notices.push(tr('setupWarnSpace')) + } + + return ( + <> +
+

{tr('setupTitle')}

+

{tr('setupDesc')}

+
+
+ {choices.map((c) => option(c.path, ( + <> + {tr('setupFree', { n: c.free_gb.toFixed(0) })} + {c.recommended && {tr('setupRecommended')}} + {c.system && {tr('setupSystem')}} + {c.external && {tr('setupExternal')}} + + )))} + {customMode ? ( +
+ custom && setSelected(custom)} + onChange={(e) => { setCustom(e.target.value); setSelected(e.target.value.trim()) }} + /> + +
+ ) : ( + + )} +
+ {notices.length > 0 && ( +
{notices.join(';')}
+ )} + {!check?.error && check?.has_config &&
{tr('setupReuse')}
} + {customMode && check && check.path === custom && !check.error && ( +
{tr('setupFree', { n: check.free_gb.toFixed(0) })}
+ )} +
+
+ + +
+ +
+ + ) +} + +const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFinish }) => { + const ready = !!state.active_runtime + return ( + <> +
+

{tr('setupRuntimeTitle')}

+

{tr('setupRuntimeDesc')}

+
+
+ +
+
+ + +
+ + ) +} diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index bb0eb2d..7071100 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -34,7 +34,14 @@ export const Sidebar: React.FC = ({ locale, vms, transitions, selected, h listRef.current?.querySelector(`[data-id="${CSS.escape(ids[next])}"]`)?.focus() } - const item = (id: string, label: string, icon: React.ReactNode, stateLabel: string, kind: ReturnType) => ( + const item = ( + id: string, + label: string, + icon: React.ReactNode, + badgeClass: string, + stateLabel: string, + kind: ReturnType, + ) => ( @@ -114,6 +106,15 @@ export const VMPage: React.FC = ({
+
+ +
{name}
+ + + {tr(`state_${state}` as I18nKey)} + +
+ {state === 'broken' &&
{tr('brokenHint')}
} {pending.length > 0 && ( @@ -160,14 +161,66 @@ export const VMPage: React.FC = ({ )} {detail && ( -
- } value={tr('cores', { n: detail.cpus })} /> - } value={formatMemory(detail.memory)} /> - } value={controllerLabel(detail.disk_controller)} /> - } value={graphicsLabel(locale, detail, host)} /> +
+
+ {locale === 'zh-CN' ? '名称' : 'Name'} + {name} +
+
+ {tr('factCPU')} + {tr('cores', { n: detail.cpus })}{detail.cpu_model ? ` · ${detail.cpu_model}` : ''} +
+
+ {tr('factGraphics')} + {graphicsLabel(locale, detail, host)} +
+
+ {tr('factMemory')} + {formatMemory(detail.memory)} +
+
+ {tr('factDisk')} + {controllerLabel(detail.disk_controller)} +
+
+ {tr('fieldNetwork')} + {detail.network_summary || tr('off')} +
)} + {detail && ( +
+
macOS
+
+
+ + + {detail.kind || 'x86-64 WHPX'} +
+
+
+ )} + + {detail && ( +
+
{tr('fieldDisplays')}
+
+
+ + + + {detail.displays} × {detail.resolution} · {detail.capture ? (locale === 'zh-CN' ? '输入捕获' : 'Input capture') : (locale === 'zh-CN' ? '自由指针' : 'Free pointer')} + +
+
+
+ )} + {detail && (
{tr('techInfo')} @@ -178,8 +231,6 @@ export const VMPage: React.FC = ({
{tr('fieldController')}
{detail.disk_controller}
{tr('fieldGraphicsBackend')}
{detail.graphics}
{detail.gpu && detail.gpu !== 'auto' && (<>
{tr('fieldICD')}
{detail.gpu}
)} -
{tr('fieldDisplays')}
{detail.displays} × {detail.resolution}
-
{tr('fieldNetwork')}
{detail.network_summary || tr('off')}
{tr('fieldAudio')}
{detail.audio_raw || tr('off')}
{tr('fieldDir')}
{detail.directory}
@@ -189,11 +240,35 @@ export const VMPage: React.FC = ({ ) } -const Fact: React.FC<{ label: string; icon: React.ReactNode; value: string }> = ({ label, icon, value }) => ( - - - {icon} - {value} - - +const IMacIcon: React.FC<{ running: boolean }> = ({ running }) => ( + ) diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index f1d45ba..3fa6c16 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -88,6 +88,40 @@ const dict = { toastInstallerReady: 'macOS {v} 安装包已就绪', toastDownloadPaused: '已暂停,再次下载会从中断处继续', failDownload: '下载失败', + taskRuntime: '安装运行时 {v}', + toastRuntimeReady: '运行时 {v} 已安装', + failRuntime: '运行时安装失败', + + // First launch + setupTitle: '选择数据目录', + setupDesc: '虚拟机、安装包和运行时都放在这里', + setupOther: '其他位置…', + setupFree: '可用 {n} GB', + setupSystem: '系统盘', + setupExternal: '外置盘', + setupWarnExternal: '外置盘拔出时,正在运行的虚拟机会损坏', + setupRecommended: '推荐', + setupWarnSystem: '放在系统盘,空间紧张时会影响 Windows', + setupWarnSpace: '可用空间不足 60 GB:一个离线安装包约 20 GB,虚拟磁盘会随使用增长', + setupReuse: '这里已有 reims-go 数据,会直接沿用', + setupContinue: '继续', + setupRuntimeTitle: '安装运行时', + setupRuntimeDesc: '运行虚拟机所需的 QEMU 与 reims-ctl,从 GitHub 下载并校验', + setupLater: '稍后', + setupDone: '完成', + setupImport: '导入本地包…', + + // Online runtimes + runtimeOnline: '在线安装', + runtimeLatest: '最新:{v}', + runtimeNoneOnChannel: '这个通道还没有发布运行时', + runtimeUpToDate: '已是最新', + runtimeInstall: '安装', + runtimeCandidate: '接收候选版', + runtimeCandidateHint: '候选版未经真实宿主冒烟测试', + runtimeChannel_candidate: '候选版', + runtimeChannel_stable: '稳定版', + runtimeLookupFailed: '无法读取 GitHub 上的运行时列表', // Toasts & dialogs toastStopped: '{name} 已关机', @@ -293,6 +327,38 @@ const dict = { toastInstallerReady: 'macOS {v} installer ready', toastDownloadPaused: 'Paused — downloading again continues where it stopped', failDownload: 'Download failed', + taskRuntime: 'Installing runtime {v}', + toastRuntimeReady: 'Runtime {v} installed', + failRuntime: 'Runtime install failed', + + setupTitle: 'Choose a data folder', + setupDesc: 'VMs, installers and runtimes all live here', + setupOther: 'Other location…', + setupFree: '{n} GB free', + setupSystem: 'System drive', + setupExternal: 'External', + setupWarnExternal: 'Unplugging an external drive corrupts running VMs', + setupRecommended: 'Recommended', + setupWarnSystem: 'On the system drive, low space can affect Windows', + setupWarnSpace: 'Under 60 GB free: an offline installer is about 20 GB and virtual disks grow with use', + setupReuse: 'This folder already has reims-go data; it will be reused', + setupContinue: 'Continue', + setupRuntimeTitle: 'Install the runtime', + setupRuntimeDesc: 'QEMU and reims-ctl, downloaded from GitHub and verified', + setupLater: 'Later', + setupDone: 'Done', + setupImport: 'Import a local package…', + + runtimeOnline: 'Online install', + runtimeLatest: 'Latest: {v}', + runtimeNoneOnChannel: 'No runtime published on this channel yet', + runtimeUpToDate: 'Up to date', + runtimeInstall: 'Install', + runtimeCandidate: 'Receive candidates', + runtimeCandidateHint: 'Candidates have not passed a real-host smoke test', + runtimeChannel_candidate: 'Candidate', + runtimeChannel_stable: 'Stable', + runtimeLookupFailed: 'Couldn’t read the runtime list from GitHub', toastStopped: '{name} shut down', toastEjected: 'Installer ejected', diff --git a/frontend/src/lib/tasks.ts b/frontend/src/lib/tasks.ts index 2e33146..a3f8c25 100644 --- a/frontend/src/lib/tasks.ts +++ b/frontend/src/lib/tasks.ts @@ -20,6 +20,7 @@ export function taskTitle(locale: Locale, task: Task): string { switch (task.kind) { case 'installer-download': return t(locale, 'taskDownload', { v: task.subject }) case 'vm-create': return t(locale, 'taskCreate', { name: task.subject }) + case 'runtime-install': return t(locale, 'taskRuntime', { v: task.subject }) default: return task.subject } } diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 829100c..5eb133e 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -5,7 +5,7 @@ html, body, #root { margin: 0; padding: 0; height: 100%; overflow: hidden; background: var(--surface-0); color: var(--text); - font-family: var(--font-sans); font-size: var(--fs-14); line-height: 1.5; + font-family: var(--font-sans); font-size: var(--fs-14); line-height: 1.48; -webkit-font-smoothing: antialiased; } @@ -31,59 +31,105 @@ h1, h2, h3, p { margin: 0; } @keyframes pulse { 50% { opacity: 0.35; } } /* ── Shell ─────────────────────────────────────────────── */ -.app-shell { display: flex; flex-direction: column; height: 100%; border: 1px solid var(--border); } +.app-shell { display: flex; flex-direction: column; height: 100%; background: var(--surface-0); } .titlebar { height: var(--titlebar-h); flex-shrink: 0; display: flex; align-items: center; justify-content: space-between; padding-left: var(--sp-4); - background: var(--surface-chrome); border-bottom: 1px solid var(--border); + background: var(--surface-chrome); + border-bottom: 1px solid var(--border); user-select: none; --wails-draggable: drag; } -.brand { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); font-weight: var(--fw-strong); } +.brand { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); font-weight: var(--fw-strong); color: var(--text); } .brand-mark { - width: 18px; height: 18px; border-radius: var(--r-sm); - background: var(--accent); color: var(--accent-text); - display: grid; place-items: center; font-size: var(--fs-12); font-weight: var(--fw-strong); + width: 20px; height: 20px; border-radius: 6px; + background: linear-gradient(145deg, #2d9cff 0%, #0066e6 100%); + color: #fff; + display: grid; place-items: center; font-size: 11px; font-weight: 700; + box-shadow: 0 1px 3px rgba(0, 102, 230, 0.32); } +.titlebar-right { display: flex; align-items: center; height: 100%; gap: var(--sp-1); --wails-draggable: no-drag; } +.theme-toggle { + width: 30px; height: 28px; margin-right: var(--sp-1); + border: 1px solid var(--border); border-radius: var(--r-md); + background: var(--surface-1); color: var(--text-2); + display: grid; place-items: center; cursor: pointer; + transition: background var(--dur-fast), color var(--dur-fast); +} +.theme-toggle:hover { background: var(--surface-hover); color: var(--text); } + .win-controls { display: flex; height: 100%; --wails-draggable: no-drag; } .win-btn { - width: 46px; height: 100%; border: none; background: transparent; color: var(--text-2); - display: grid; place-items: center; cursor: pointer; transition: background var(--dur-fast); + width: 44px; height: 100%; border: none; background: transparent; color: var(--text-2); + display: grid; place-items: center; cursor: pointer; transition: background var(--dur-fast), color var(--dur-fast); } .win-btn:hover { background: var(--surface-hover); color: var(--text); } -.win-btn.close:hover { background: #c42b1c; color: #fff; } +.win-btn.close:hover { background: #e81123; color: #fff; } .win-btn:focus-visible { border-radius: 0; } -.workspace { display: flex; flex: 1; min-height: 0; } +.workspace { display: flex; flex: 1; min-height: 0; background: var(--surface-canvas); } -/* ── Sidebar ───────────────────────────────────────────── */ -.sidebar { +/* ── Floating Tahoe Sidebar ────────────────────────────── */ +.sidebar-wrap { width: var(--sidebar-w); flex-shrink: 0; + padding: 10px 0 10px 10px; + display: flex; +} +.sidebar { + flex: 1; min-height: 0; display: flex; flex-direction: column; gap: var(--sp-1); - padding: var(--sp-2); overflow-y: auto; - background: var(--surface-sidebar); border-right: 1px solid var(--border); + padding: 10px 8px; overflow-y: auto; + background: var(--surface-sidebar); + border: 1px solid var(--surface-sidebar-border); + border-radius: 14px; + box-shadow: var(--surface-sidebar-shadow); } .sidebar-head { display: flex; align-items: center; justify-content: space-between; - padding: var(--sp-2) var(--sp-1) var(--sp-1) var(--sp-2); - font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-3); + padding: 4px 6px 6px 10px; + font-size: 11px; font-weight: var(--fw-strong); letter-spacing: 0.02em; + color: var(--text-3); text-transform: uppercase; } -.sidebar-sep { height: 1px; background: var(--border); margin: var(--sp-2); } -.nav { display: flex; flex-direction: column; gap: 2px; } -.nav-empty { padding: var(--sp-1) var(--sp-2); font-size: var(--fs-13); color: var(--text-3); } +.sidebar-sep { height: 1px; background: var(--border); margin: 8px 10px; } +.nav { display: flex; flex-direction: column; gap: 3px; } +.nav-empty { padding: 6px 10px; font-size: var(--fs-13); color: var(--text-3); } .nav-item { - width: 100%; height: 34px; padding: 0 var(--sp-2); - display: flex; align-items: center; gap: var(--sp-2); - border: none; border-radius: var(--r-md); background: transparent; color: var(--text-2); - text-align: left; cursor: pointer; transition: background var(--dur-fast), color var(--dur-fast); + width: 100%; height: 36px; padding: 0 10px; + display: flex; align-items: center; gap: 10px; + border: none; border-radius: 9px; background: transparent; color: var(--text); + text-align: left; cursor: pointer; + transition: background var(--dur-fast), color var(--dur-fast); } -.nav-item:hover { background: var(--surface-hover); color: var(--text); } -.nav-item[aria-selected="true"] { background: var(--accent-soft); color: var(--text); } -.nav-item[aria-selected="true"] > svg { color: var(--accent-soft-text); } +.nav-item:hover { background: var(--surface-hover); } +.nav-item[aria-selected="true"] { + background: var(--accent); + color: var(--accent-text); + font-weight: var(--fw-medium); + box-shadow: 0 1px 3px rgba(0, 122, 255, 0.28); +} +.nav-item[aria-selected="true"] .nav-icon-badge { + background: rgba(255, 255, 255, 0.22); + color: #ffffff; + box-shadow: none; +} +.nav-item[aria-selected="true"] .status-running { + background: #ffffff; + box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.25); +} +.nav-item[aria-selected="true"] .status-stopped { + border-color: rgba(255, 255, 255, 0.7); +} +.nav-icon-badge { + width: 24px; height: 24px; border-radius: 7px; flex-shrink: 0; + display: grid; place-items: center; color: #ffffff; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.14); +} +.nav-icon-vm { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); } +.nav-icon-host { background: linear-gradient(145deg, #8e8e93 0%, #636366 100%); } .nav-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-13); } -/* Status shapes: shape + colour, never colour alone */ +/* Status shapes */ .status { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; display: inline-block; } .status-running { background: var(--status-running); } .status-stopped { border: 1.5px solid var(--status-idle); } @@ -93,50 +139,101 @@ h1, h2, h3, p { margin: 0; } /* ── Main column ───────────────────────────────────────── */ .main { flex: 1; min-width: 0; display: flex; flex-direction: column; } -.scroll { flex: 1; overflow-y: auto; padding: var(--sp-6) var(--sp-8); } -.page { max-width: var(--page-max); margin: 0 auto; display: flex; flex-direction: column; gap: var(--sp-6); } +.scroll { flex: 1; overflow-y: auto; padding: 20px 32px 32px; } +.page { max-width: var(--page-max); margin: 0 auto; display: flex; flex-direction: column; gap: 20px; } -.page-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 32px; } -.page-title { display: flex; align-items: baseline; gap: var(--sp-3); min-width: 0; } -.page-title h1 { font-size: var(--fs-20); font-weight: var(--fw-strong); letter-spacing: -0.01em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.state-text { display: inline-flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); color: var(--text-2); white-space: nowrap; } -.actions { display: flex; align-items: center; gap: var(--sp-1); flex-shrink: 0; } -.actions .btn + .icon-btn, .actions .btn + .btn { margin-left: var(--sp-1); } +.page-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 34px; } +.page-title { display: flex; align-items: center; gap: 10px; min-width: 0; } +.page-title h1 { font-size: 16px; font-weight: var(--fw-strong); letter-spacing: -0.01em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.state-text { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-12); color: var(--text-2); white-space: nowrap; } +.actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; } -.section { display: flex; flex-direction: column; gap: var(--sp-2); } -.section-title { font-size: var(--fs-13); font-weight: var(--fw-strong); color: var(--text-2); display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); min-height: 28px; } +/* ── macOS Tahoe "About This Mac" Hero ─────────────────── */ +.vm-hero { + display: flex; flex-direction: column; align-items: center; + gap: 8px; padding: 4px 0 6px; text-align: center; +} +.vm-imac-svg { width: 112px; height: 88px; filter: drop-shadow(0 6px 14px rgba(15, 23, 42, 0.12)); } +.vm-hero-name { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; color: var(--text); } +.vm-hero-pill { + display: inline-flex; align-items: center; gap: 6px; + padding: 3px 10px; border-radius: 999px; + background: var(--surface-1); border: 1px solid var(--border); + font-size: var(--fs-12); font-weight: var(--fw-medium); color: var(--text-2); +} + +/* ── Tahoe Grouped Inset Sections ──────────────────────── */ +.section { display: flex; flex-direction: column; gap: 8px; } +.section-title { + font-size: var(--fs-13); font-weight: var(--fw-strong); color: var(--text); + padding: 0 4px; + display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); min-height: 26px; +} + +.tahoe-group { + background: var(--surface-1); + border: 1px solid var(--border); + border-radius: var(--r-lg); + overflow: hidden; +} +.tahoe-row { + display: flex; align-items: center; justify-content: space-between; gap: 16px; + min-height: 40px; padding: 9px 16px; + position: relative; font-size: 13.5px; +} +.tahoe-row + .tahoe-row::before { + content: ""; position: absolute; top: 0; left: 16px; right: 16px; + height: 1px; background: var(--border); +} +.tahoe-label { color: var(--text); font-weight: var(--fw-regular); display: inline-flex; align-items: center; gap: 10px; flex-shrink: 0; } +.tahoe-value { color: var(--text-2); text-align: right; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: text; } +.tahoe-orb { + width: 24px; height: 24px; border-radius: 50%; flex-shrink: 0; + background: radial-gradient(circle at 32% 30%, #6fd2ff 0%, #1c7ef2 55%, #0b419e 100%); + box-shadow: inset 0 1px 2px rgba(255, 255, 255, 0.55), 0 1px 3px rgba(0, 82, 204, 0.28); +} +.tahoe-display-icon { + width: 24px; height: 20px; border-radius: 4px; flex-shrink: 0; + background: linear-gradient(160deg, #5cc2ff 0%, #1b7ff2 100%); + border: 1.5px solid #2b2b2f; + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15); +} /* ── Buttons ───────────────────────────────────────────── */ .btn { - height: 30px; padding: 0 var(--sp-3); - display: inline-flex; align-items: center; justify-content: center; gap: var(--sp-2); + height: 30px; padding: 0 12px; + display: inline-flex; align-items: center; justify-content: center; gap: 6px; border-radius: var(--r-md); border: 1px solid var(--border-strong); - background: var(--surface-1); color: var(--text); - font-size: var(--fs-13); font-weight: var(--fw-regular); white-space: nowrap; flex-shrink: 0; - cursor: pointer; transition: background var(--dur-fast), border-color var(--dur-fast); + background: var(--surface-card-elevated); color: var(--text); + box-shadow: var(--shadow-btn); + font-size: var(--fs-13); font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0; + cursor: pointer; transition: background var(--dur-fast), border-color var(--dur-fast), transform var(--dur-fast); } .btn:hover:not(:disabled) { background: var(--surface-hover); } -.btn:disabled { opacity: 0.45; cursor: default; } -.btn-primary { background: var(--accent); border-color: transparent; color: var(--accent-text); font-weight: var(--fw-strong); } +.btn:disabled { opacity: 0.45; cursor: default; box-shadow: none; } +.btn-primary { background: var(--accent); border-color: transparent; color: var(--accent-text); font-weight: var(--fw-strong); box-shadow: 0 1px 3px rgba(0, 122, 255, 0.3); } .btn-primary:hover:not(:disabled) { background: var(--accent-hover); } .btn-danger { background: var(--danger); border-color: transparent; color: #fff; font-weight: var(--fw-strong); } -.btn-danger:hover:not(:disabled) { filter: brightness(1.08); background: var(--danger); } -.btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); } -.btn-ghost:hover:not(:disabled) { color: var(--text); } +.btn-danger:hover:not(:disabled) { filter: brightness(1.06); background: var(--danger); } +.btn-ghost { background: transparent; border-color: transparent; color: var(--text-2); box-shadow: none; } +.btn-ghost:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); } .icon-btn { width: 30px; height: 30px; flex-shrink: 0; display: inline-grid; place-items: center; - border: none; border-radius: var(--r-md); background: transparent; color: var(--text-2); + border: 1px solid var(--border); border-radius: var(--r-md); + background: var(--surface-card-elevated); color: var(--text-2); + box-shadow: var(--shadow-btn); cursor: pointer; transition: background var(--dur-fast), color var(--dur-fast); } .icon-btn:hover:not(:disabled), .icon-btn[data-state="open"] { background: var(--surface-hover); color: var(--text); } -.icon-btn:disabled { opacity: 0.4; cursor: default; } -.icon-btn.sm { width: 26px; height: 26px; } +.icon-btn:disabled { opacity: 0.4; cursor: default; box-shadow: none; } +.icon-btn.sm { width: 26px; height: 26px; border-color: transparent; background: transparent; box-shadow: none; } +.icon-btn.sm:hover:not(:disabled) { background: var(--surface-hover); } -.segmented { display: inline-flex; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-input); border: 1px solid var(--border); } -.segmented button { height: 24px; padding: 0 var(--sp-3); border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-2); font-size: var(--fs-13); cursor: pointer; } -.segmented button[aria-pressed="true"] { background: var(--surface-active); color: var(--text); font-weight: var(--fw-strong); } +.segmented { display: inline-flex; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-active); border: 1px solid var(--border); } +.segmented button { height: 24px; padding: 0 12px; border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-2); font-size: var(--fs-13); cursor: pointer; } +.segmented button[aria-pressed="true"] { background: var(--surface-card-elevated); color: var(--text); font-weight: var(--fw-strong); box-shadow: var(--shadow-btn); } /* ── Cards & notices ───────────────────────────────────── */ .card { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); padding: var(--sp-4); display: flex; flex-direction: column; gap: var(--sp-3); } @@ -145,70 +242,75 @@ h1, h2, h3, p { margin: 0; } .notice { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); - padding: var(--sp-2) var(--sp-2) var(--sp-2) var(--sp-4); + padding: 10px 12px 10px 14px; border-radius: var(--r-lg); background: var(--notice-soft); border: 1px solid var(--notice-border); - font-size: var(--fs-13); + font-size: var(--fs-13); color: var(--text); } -.notice-error { background: var(--danger-soft); border-color: rgba(240, 98, 90, 0.3); color: #ff9c95; padding: var(--sp-2) var(--sp-4); } +.notice-error { background: var(--danger-soft); border-color: rgba(255, 59, 48, 0.28); color: var(--danger-text); padding: 10px 14px; } .notice-error ul { margin: 0; padding-left: var(--sp-4); } .steps { margin: 0; padding-left: var(--sp-6); display: flex; flex-direction: column; gap: var(--sp-1); color: var(--text-2); font-size: var(--fs-13); } -/* ── Facts row (icon + value) ──────────────────────────── */ -.facts { display: flex; flex-wrap: wrap; gap: var(--sp-2) var(--sp-6); } -.fact { display: inline-flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-14); color: var(--text); border-radius: var(--r-sm); } -.fact > svg { color: var(--text-3); } - +/* ── Command line & technical details ──────────────────── */ .cmd-line { display: flex; align-items: center; gap: var(--sp-3); - padding: var(--sp-1) var(--sp-1) var(--sp-1) var(--sp-3); - border-radius: var(--r-lg); background: var(--surface-input); border: 1px solid var(--border); + padding: 6px 6px 6px 14px; + border-radius: var(--r-lg); background: var(--surface-1); border: 1px solid var(--border); } .cmd-line > svg { color: var(--text-3); } .cmd-line code { flex: 1; font-family: var(--font-mono); font-size: var(--fs-13); color: var(--text-code); user-select: text; } -/* ── Disclosure: technical details ─────────────────────── */ .tech > summary { list-style: none; cursor: pointer; display: inline-flex; align-items: center; gap: var(--sp-1); - font-size: var(--fs-13); color: var(--text-2); border-radius: var(--r-sm); + padding: 2px 4px; + font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text-2); border-radius: var(--r-sm); } .tech > summary::-webkit-details-marker { display: none; } .tech > summary svg { transition: transform var(--dur-fast); } .tech[open] > summary svg { transform: rotate(90deg); } .tech > summary:hover { color: var(--text); } -.kv-list { margin: var(--sp-3) 0 0; display: grid; grid-template-columns: max-content 1fr; gap: var(--sp-2) var(--sp-6); font-size: var(--fs-13); } +.kv-list { + margin: 10px 0 0; padding: 12px 16px; + background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); + display: grid; grid-template-columns: max-content 1fr; gap: 8px 24px; font-size: var(--fs-13); +} .kv-list dt { color: var(--text-3); } .kv-list dd { margin: 0; color: var(--text-2); word-break: break-all; user-select: text; } /* ── Grouped list (host page, settings) ────────────────── */ .list { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); overflow: hidden; } -.row { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); padding: var(--sp-3) var(--sp-4); position: relative; } -.row + .row::before { content: ""; position: absolute; top: 0; left: var(--sp-4); right: var(--sp-4); height: 1px; background: var(--border); } +.row { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); padding: 11px 16px; position: relative; } +.row + .row::before { content: ""; position: absolute; top: 0; left: 16px; right: 16px; height: 1px; background: var(--border); } .row-main { min-width: 0; flex: 1; display: flex; flex-direction: column; gap: 2px; } -.row-title { font-size: var(--fs-14); display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; } +.row-title { font-size: 13.5px; display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; color: var(--text); } .row-sub { font-size: var(--fs-12); color: var(--text-3); word-break: break-all; } .row-right { display: flex; align-items: center; gap: var(--sp-2); flex-shrink: 0; } -.badge { display: inline-flex; align-items: center; height: 20px; padding: 0 var(--sp-2); border-radius: var(--r-sm); font-size: var(--fs-12); white-space: nowrap; background: var(--surface-active); color: var(--text-2); } +.badge { display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border-radius: 999px; font-size: 11.5px; font-weight: var(--fw-medium); white-space: nowrap; background: var(--surface-active); color: var(--text-2); } .badge-accent { background: var(--accent-soft); color: var(--accent-soft-text); } -.badge-ok { background: rgba(63, 185, 80, 0.15); color: var(--status-running); } -.badge-warn { background: rgba(212, 167, 44, 0.15); color: var(--status-busy); } +.badge-ok { background: rgba(40, 205, 65, 0.14); color: #1a9e30; } +:root[data-theme="dark"] .badge-ok { color: var(--status-running); } +.badge-warn { background: rgba(255, 159, 10, 0.16); color: #b86e00; } +:root[data-theme="dark"] .badge-warn { color: var(--status-busy); } .badge-error { background: var(--danger); color: #fff; min-width: 18px; height: 18px; padding: 0 var(--sp-1); justify-content: center; border-radius: 999px; } -.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: var(--sp-3); } -.tile { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); padding: var(--sp-3) var(--sp-4); display: flex; flex-direction: column; gap: var(--sp-1); min-width: 0; } -.tile-head { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-12); color: var(--text-3); } -.tile-value { font-size: var(--fs-16); font-weight: var(--fw-strong); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.tile-value.ok { color: var(--status-running); } -.tile-value.warn { color: var(--status-busy); } +.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; } +.tile { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); padding: 12px 14px; display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.tile-head { display: flex; align-items: center; gap: 6px; font-size: var(--fs-12); color: var(--text-3); } +.tile-value { font-size: 15px; font-weight: var(--fw-strong); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text); } +.tile-value.ok { color: #1a9e30; } +:root[data-theme="dark"] .tile-value.ok { color: var(--status-running); } +.tile-value.warn { color: #b86e00; } +:root[data-theme="dark"] .tile-value.warn { color: var(--status-busy); } .tile-sub { font-size: var(--fs-12); color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.switch { position: relative; display: inline-block; width: 36px; height: 20px; flex-shrink: 0; cursor: pointer; } +/* macOS Tahoe Switch */ +.switch { position: relative; display: inline-block; width: 38px; height: 22px; flex-shrink: 0; cursor: pointer; } .switch input { position: absolute; opacity: 0; width: 100%; height: 100%; margin: 0; cursor: pointer; } -.slider { position: absolute; inset: 0; border-radius: 999px; background: var(--surface-active); border: 1px solid var(--border-strong); transition: background var(--dur); pointer-events: none; } -.slider::before { content: ""; position: absolute; width: 14px; height: 14px; left: 2px; top: 2px; border-radius: 50%; background: var(--text-2); transition: transform var(--dur), background var(--dur); } -.switch input:checked + .slider { background: var(--accent); border-color: transparent; } -.switch input:checked + .slider::before { transform: translateX(16px); background: #fff; } +.slider { position: absolute; inset: 0; border-radius: 999px; background: var(--surface-active); transition: background var(--dur); pointer-events: none; } +.slider::before { content: ""; position: absolute; width: 18px; height: 18px; left: 2px; top: 2px; border-radius: 50%; background: #ffffff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.22); transition: transform var(--dur); } +.switch input:checked + .slider { background: var(--accent); } +.switch input:checked + .slider::before { transform: translateX(16px); } .switch input:focus-visible + .slider { box-shadow: var(--focus-ring); } /* ── Log bar & panel ───────────────────────────────────── */ @@ -217,7 +319,7 @@ h1, h2, h3, p { margin: 0; } .tabs { display: flex; gap: 2px; } .tab { height: 24px; padding: 0 var(--sp-2); border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-3); font-size: var(--fs-12); cursor: pointer; } .tab:hover { color: var(--text); } -.tab[aria-selected="true"] { background: var(--surface-active); color: var(--text); } +.tab[aria-selected="true"] { background: var(--surface-active); color: var(--text); font-weight: var(--fw-medium); } .task { display: inline-flex; align-items: center; gap: var(--sp-2); min-width: 0; font-size: var(--fs-12); color: var(--text-2); } .task-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .progress { width: 96px; height: 4px; border-radius: 999px; background: var(--surface-active); overflow: hidden; flex-shrink: 0; } @@ -236,30 +338,30 @@ h1, h2, h3, p { margin: 0; } .jump-latest { position: absolute; right: var(--sp-4); bottom: var(--sp-3); } /* ── Overlays: dialog, menu, tooltip, toast ────────────── */ -.overlay { position: fixed; inset: 0; background: var(--scrim); z-index: 40; } +.overlay { position: fixed; inset: 0; background: var(--scrim); backdrop-filter: blur(4px); z-index: 40; } .dialog { position: fixed; z-index: 41; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 720px; max-width: calc(100vw - 48px); max-height: calc(100vh - 80px); display: flex; flex-direction: column; overflow: hidden; - background: var(--surface-2); border: 1px solid var(--border-strong); border-radius: var(--r-xl); - box-shadow: 0 24px 64px rgba(0, 0, 0, 0.5); + background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-xl); + box-shadow: var(--shadow-overlay); } .dialog.sm { width: 420px; } -.dialog-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: var(--sp-3) var(--sp-3) var(--sp-3) var(--sp-6); border-bottom: 1px solid var(--border); } +.dialog-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); padding: 14px 14px 14px 22px; border-bottom: 1px solid var(--border); } .dialog-title { font-size: var(--fs-16); font-weight: var(--fw-strong); } .dialog-desc { font-size: var(--fs-13); color: var(--text-2); } -.dialog-body { padding: var(--sp-6); overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); } -.dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: var(--sp-3) var(--sp-6); border-top: 1px solid var(--border); } -.dialog.sm .dialog-body { padding: var(--sp-6) var(--sp-6) var(--sp-4); gap: var(--sp-3); } -.dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: var(--sp-6); } +.dialog-body { padding: 20px 22px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: var(--sp-4); } +.dialog-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); padding: 12px 22px; border-top: 1px solid var(--border); } +.dialog.sm .dialog-body { padding: 22px 22px 14px; gap: var(--sp-3); } +.dialog.sm .dialog-foot { border-top: none; justify-content: flex-end; padding-top: 0; padding-bottom: 20px; } .menu { - min-width: 180px; padding: var(--sp-1); z-index: 50; - background: var(--surface-2); border: 1px solid var(--border-strong); border-radius: var(--r-lg); - box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45); + min-width: 184px; padding: 5px; z-index: 50; + background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg); + box-shadow: var(--shadow-overlay); } .menu-item { - height: 30px; padding: 0 var(--sp-2); display: flex; align-items: center; gap: var(--sp-2); + height: 30px; padding: 0 10px; display: flex; align-items: center; gap: 8px; border-radius: var(--r-sm); font-size: var(--fs-13); cursor: pointer; user-select: none; outline: none; } .menu-item > svg { color: var(--text-3); } @@ -270,12 +372,12 @@ h1, h2, h3, p { margin: 0; } .menu-item.danger > svg { color: var(--danger); } .menu-item.danger[data-highlighted] { background: var(--danger); color: #fff; } .menu-item.danger[data-highlighted] > svg { color: #fff; } -.menu-sep { height: 1px; margin: var(--sp-1) var(--sp-2); background: var(--border); } +.menu-sep { height: 1px; margin: 4px 8px; background: var(--border); } .tooltip { - z-index: 60; padding: var(--sp-1) var(--sp-2); border-radius: var(--r-sm); + z-index: 60; padding: 4px 9px; border-radius: var(--r-sm); background: var(--surface-2); border: 1px solid var(--border-strong); color: var(--text); - font-size: var(--fs-12); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.35); + font-size: var(--fs-12); box-shadow: 0 6px 18px rgba(15, 23, 42, 0.16); display: flex; gap: var(--sp-2); align-items: center; } .tooltip kbd { font-family: var(--font-sans); color: var(--text-3); } @@ -283,8 +385,8 @@ h1, h2, h3, p { margin: 0; } .toast-viewport { position: fixed; right: var(--sp-4); bottom: calc(var(--logbar-h) + var(--sp-4)); z-index: 70; display: flex; flex-direction: column; gap: var(--sp-2); width: 340px; max-width: calc(100vw - 32px); margin: 0; padding: 0; list-style: none; outline: none; } .toast { display: flex; align-items: flex-start; gap: var(--sp-3); padding: var(--sp-3); - background: var(--surface-2); border: 1px solid var(--border-strong); border-radius: var(--r-lg); - box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45); + background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-lg); + box-shadow: var(--shadow-overlay); } .toast > svg { margin-top: 2px; flex-shrink: 0; } .toast.ok > svg { color: var(--status-running); } @@ -295,16 +397,16 @@ h1, h2, h3, p { margin: 0; } .toast .btn { height: 26px; } /* ── Forms (wizard, settings) ──────────────────────────── */ -.field { display: flex; flex-direction: column; gap: var(--sp-2); } -.field-label { font-size: var(--fs-13); color: var(--text-2); } +.field { display: flex; flex-direction: column; gap: 6px; } +.field-label { font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text-2); } .field-row { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); } .input, .select { - width: 100%; height: 32px; padding: 0 var(--sp-3); + width: 100%; height: 32px; padding: 0 10px; border-radius: var(--r-md); border: 1px solid var(--border-strong); background: var(--surface-input); color: var(--text); font: inherit; font-size: var(--fs-13); } .input:focus, .select:focus { border-color: var(--accent); box-shadow: var(--focus-ring); } -.input[readonly] { color: var(--text-2); } +.input[readonly] { color: var(--text-2); background: var(--surface-1); } .input.mono { font-family: var(--font-mono); font-size: var(--fs-12); } .input-group { display: flex; gap: var(--sp-2); align-items: center; } .hint { font-size: var(--fs-12); color: var(--text-3); } @@ -314,23 +416,47 @@ h1, h2, h3, p { margin: 0; } .choice input { accent-color: var(--accent); margin: 0; } .presets { display: flex; flex-wrap: wrap; gap: var(--sp-2); } .preset { - height: 28px; padding: 0 var(--sp-3); border-radius: var(--r-md); - border: 1px solid var(--border-strong); background: transparent; color: var(--text-2); + height: 28px; padding: 0 12px; border-radius: var(--r-md); + border: 1px solid var(--border-strong); background: var(--surface-card-elevated); color: var(--text-2); font-size: var(--fs-13); cursor: pointer; } .preset:hover { background: var(--surface-hover); color: var(--text); } -.preset[aria-pressed="true"] { background: var(--accent); border-color: transparent; color: var(--accent-text); } +.preset[aria-pressed="true"] { background: var(--accent); border-color: transparent; color: var(--accent-text); font-weight: var(--fw-medium); } -.wizard-steps { display: flex; gap: var(--sp-1); padding: var(--sp-2) var(--sp-6); border-bottom: 1px solid var(--border); flex-wrap: wrap; } -.wizard-step { height: 26px; padding: 0 var(--sp-2); border: none; border-radius: var(--r-sm); background: transparent; color: var(--text-3); font-size: var(--fs-12); cursor: pointer; display: inline-flex; align-items: center; gap: var(--sp-1); } +.wizard-steps { display: flex; gap: var(--sp-1); padding: 10px 22px; border-bottom: 1px solid var(--border); flex-wrap: wrap; } +.wizard-step { height: 26px; padding: 0 10px; border: none; border-radius: 999px; background: transparent; color: var(--text-3); font-size: var(--fs-12); cursor: pointer; display: inline-flex; align-items: center; gap: var(--sp-1); } .wizard-step[aria-current="step"] { background: var(--accent-soft); color: var(--accent-soft-text); font-weight: var(--fw-strong); } .wizard-step.done { color: var(--text-2); } .wizard-step.done svg { color: var(--status-running); } .settings-split { display: flex; height: 460px; min-height: 0; } -.settings-nav { width: 180px; flex-shrink: 0; padding: var(--sp-2); border-right: 1px solid var(--border); display: flex; flex-direction: column; gap: 2px; overflow-y: auto; } -.settings-pane { flex: 1; padding: var(--sp-6); overflow-y: auto; display: flex; flex-direction: column; gap: var(--sp-4); } +.settings-nav { width: 186px; flex-shrink: 0; padding: 10px 8px; border-right: 1px solid var(--border); background: var(--surface-1); display: flex; flex-direction: column; gap: 3px; overflow-y: auto; } +.settings-pane { flex: 1; padding: 20px 24px; overflow-y: auto; display: flex; flex-direction: column; gap: var(--sp-4); } -.code { padding: var(--sp-3); border-radius: var(--r-md); background: var(--surface-input); border: 1px solid var(--border); font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); word-break: break-all; user-select: text; } +.code { padding: 10px 12px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border); font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); word-break: break-all; user-select: text; } .fieldset { border: 0; padding: 0; margin: 0; min-width: 0; } .fieldset legend { padding: 0; margin-bottom: var(--sp-2); } + +/* ── First launch ──────────────────────────────────────── */ +.setup { flex: 1; overflow-y: auto; display: grid; place-items: center; padding: var(--sp-8) var(--sp-4); } +.setup-card { width: 560px; max-width: 100%; display: flex; flex-direction: column; gap: var(--sp-6); } +.setup-head h1 { font-size: var(--fs-24); font-weight: var(--fw-strong); letter-spacing: -0.01em; } +.setup-head p { margin-top: var(--sp-1); color: var(--text-2); font-size: var(--fs-14); } +.setup-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); } +.choices-list { display: flex; flex-direction: column; gap: var(--sp-2); } +.choice-card { + display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4); + border-radius: var(--r-lg); border: 1px solid var(--border); background: var(--surface-1); + cursor: pointer; transition: border-color var(--dur-fast), background var(--dur-fast); +} +.choice-card:hover { background: var(--surface-hover); } +.choice-card[data-selected="true"] { border-color: var(--accent); background: var(--accent-soft); } +.choice-card input { position: absolute; opacity: 0; pointer-events: none; } +.choice-card:focus-within { box-shadow: var(--focus-ring); } +.choice-card > svg { color: var(--text-3); flex-shrink: 0; } +.choice-card[data-selected="true"] > svg { color: var(--accent-soft-text); } +.choice-card-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.choice-card-path { font-size: var(--fs-13); color: var(--text); word-break: break-all; } +.choice-card-meta { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-12); color: var(--text-3); } +.choice-other { align-self: flex-start; } +.task-inline { display: flex; align-items: center; gap: var(--sp-2); } diff --git a/frontend/src/styles/tokens.css b/frontend/src/styles/tokens.css index b86c334..7d23209 100644 --- a/frontend/src/styles/tokens.css +++ b/frontend/src/styles/tokens.css @@ -1,18 +1,18 @@ -/* Design tokens. Components reference these only — no raw colours, sizes or - spacing in component CSS or inline styles. See docs/ui-redesign.md §4.1. */ +/* Design tokens — macOS Tahoe System Settings aesthetic (Light default, Dark optional). */ :root { - color-scheme: dark; + color-scheme: light; /* Type */ - --font-sans: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif; - --font-mono: "Cascadia Mono", "JetBrains Mono", Consolas, monospace; - --fs-12: 12px; /* captions, badges, log text */ - --fs-13: 13px; /* secondary text, controls */ - --fs-14: 14px; /* body */ - --fs-16: 16px; /* subtitles */ - --fs-20: 20px; /* page titles */ - --fs-24: 24px; /* empty-state titles */ + --font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif; + --font-mono: "SF Mono", "Cascadia Mono", "JetBrains Mono", Consolas, monospace; + --fs-12: 12px; + --fs-13: 13px; + --fs-14: 14px; + --fs-16: 16px; + --fs-20: 20px; + --fs-24: 24px; --fw-regular: 400; + --fw-medium: 500; --fw-strong: 600; /* Spacing (4px grid) */ @@ -24,57 +24,109 @@ --sp-8: 32px; /* Radius */ - --r-sm: 4px; - --r-md: 6px; - --r-lg: 8px; - --r-xl: 12px; + --r-sm: 6px; + --r-md: 8px; + --r-lg: 12px; + --r-xl: 16px; - /* Surfaces */ - --surface-0: #1c1c1f; /* window */ - --surface-sidebar: #171719; - --surface-chrome: #141416; /* title bar, log bar */ - --surface-1: rgba(255, 255, 255, 0.04); /* cards */ - --surface-2: #26262b; /* menus, dialogs, tooltips */ - --surface-input: rgba(0, 0, 0, 0.25); - --surface-hover: rgba(255, 255, 255, 0.06); - --surface-active: rgba(255, 255, 255, 0.10); - --border: rgba(255, 255, 255, 0.08); - --border-strong: rgba(255, 255, 255, 0.14); - --scrim: rgba(0, 0, 0, 0.55); + /* Surfaces (macOS Tahoe Light) */ + --surface-0: #ffffff; + --surface-canvas: #ffffff; + --surface-sidebar: linear-gradient(180deg, #eff5fc 0%, #eaf2fa 100%); + --surface-sidebar-border: rgba(15, 23, 42, 0.07); + --surface-sidebar-shadow: 0 2px 14px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.8); + --surface-chrome: rgba(255, 255, 255, 0.88); + --surface-1: #f5f6f8; + --surface-card-elevated: #ffffff; + --surface-2: rgba(255, 255, 255, 0.96); + --surface-input: #ffffff; + --surface-hover: rgba(15, 23, 42, 0.05); + --surface-active: rgba(15, 23, 42, 0.09); + --border: rgba(15, 23, 42, 0.075); + --border-strong: rgba(15, 23, 42, 0.14); + --scrim: rgba(15, 23, 42, 0.28); + --shadow-btn: 0 1px 2px rgba(15, 23, 42, 0.06); + --shadow-overlay: 0 20px 56px rgba(15, 23, 42, 0.18), 0 0 0 1px rgba(15, 23, 42, 0.06); /* Text */ - --text: #f2f2f4; - --text-2: #a8a8b0; - --text-3: #74747e; - --text-code: #c9ccd6; + --text: #1d1d1f; + --text-2: #515154; + --text-3: #86868b; + --text-code: #2c2c30; - /* Semantics */ - --accent: #3b8cf6; - --accent-hover: #5299f7; + /* Semantics (Apple System Colours) */ + --accent: #007aff; + --accent-hover: #006be6; --accent-text: #ffffff; - --accent-soft: rgba(59, 140, 246, 0.18); - --accent-soft-text: #8dbcfb; - --focus-ring: 0 0 0 2px rgba(59, 140, 246, 0.55); + --accent-soft: rgba(0, 122, 255, 0.12); + --accent-soft-text: #0066d6; + --focus-ring: 0 0 0 3px rgba(0, 122, 255, 0.3); - --status-running: #3fb950; - --status-busy: #d4a72c; - --status-error: #f0625a; - --status-idle: #74747e; + --status-running: #28cd41; + --status-busy: #ff9f0a; + --status-error: #ff3b30; + --status-idle: #aeaeb2; - --danger: #f0625a; - --danger-soft: rgba(240, 98, 90, 0.14); - --notice-soft: rgba(212, 167, 44, 0.10); - --notice-border: rgba(212, 167, 44, 0.32); + --danger: #ff3b30; + --danger-soft: rgba(255, 59, 48, 0.10); + --danger-text: #d70015; + --notice-soft: rgba(255, 159, 10, 0.11); + --notice-border: rgba(255, 159, 10, 0.32); /* Motion */ --dur-fast: 120ms; --dur: 200ms; /* Layout */ - --titlebar-h: 40px; + --titlebar-h: 42px; --logbar-h: 32px; - --sidebar-w: 232px; - --page-max: 960px; + --sidebar-w: 244px; + --page-max: 700px; +} + +:root[data-theme="dark"] { + color-scheme: dark; + + --surface-0: #1e1e22; + --surface-canvas: #1e1e22; + --surface-sidebar: linear-gradient(180deg, #27282e 0%, #23242a 100%); + --surface-sidebar-border: rgba(255, 255, 255, 0.08); + --surface-sidebar-shadow: 0 4px 18px rgba(0, 0, 0, 0.32), inset 0 1px 0 rgba(255, 255, 255, 0.06); + --surface-chrome: rgba(28, 28, 32, 0.92); + --surface-1: rgba(255, 255, 255, 0.05); + --surface-card-elevated: rgba(255, 255, 255, 0.07); + --surface-2: #2b2c32; + --surface-input: rgba(0, 0, 0, 0.28); + --surface-hover: rgba(255, 255, 255, 0.07); + --surface-active: rgba(255, 255, 255, 0.12); + --border: rgba(255, 255, 255, 0.09); + --border-strong: rgba(255, 255, 255, 0.16); + --scrim: rgba(0, 0, 0, 0.55); + --shadow-btn: 0 1px 2px rgba(0, 0, 0, 0.28); + --shadow-overlay: 0 24px 64px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(255, 255, 255, 0.08); + + --text: #f5f5f7; + --text-2: #b4b4bc; + --text-3: #86868e; + --text-code: #d4d6e0; + + --accent: #0a84ff; + --accent-hover: #2492ff; + --accent-text: #ffffff; + --accent-soft: rgba(10, 132, 255, 0.22); + --accent-soft-text: #64b0ff; + --focus-ring: 0 0 0 3px rgba(10, 132, 255, 0.45); + + --status-running: #30d158; + --status-busy: #ffd60a; + --status-error: #ff453a; + --status-idle: #6e6e76; + + --danger: #ff453a; + --danger-soft: rgba(255, 69, 58, 0.16); + --danger-text: #ff8b83; + --notice-soft: rgba(255, 214, 10, 0.11); + --notice-border: rgba(255, 214, 10, 0.30); } @media (prefers-reduced-motion: reduce) { diff --git a/frontend/src/types.ts b/frontend/src/types.ts index b3ed735..f3f07cd 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -6,6 +6,7 @@ export interface Config { active_runtime?: string auto_pin_pcores: boolean default_gpu?: string + runtime_channel?: 'stable' | 'candidate' | '' } export interface GPUInfo { @@ -74,6 +75,8 @@ export interface AppState { vms: VMListItem[] | null transitions: Record pending_changes: Record + /** First launch: no data folder chosen yet (setup.go). */ + needs_setup: boolean } export interface VMDetail { @@ -207,3 +210,35 @@ export interface CachedInstaller { version?: string build?: string } + +/** A published runtime (GitHub Release, internal/runtime/remote.go). */ +export interface RemoteRuntime { + commit: string + tag: string + channel: 'stable' | 'candidate' + published_at: string + page_url: string + archive_name: string + archive_url: string + archive_size: number + sums_url: string + source_name?: string + source_url?: string +} + +export interface DataRootChoice { + path: string + free_gb: number + system: boolean + external: boolean + recommended: boolean +} + +export interface DataRootCheck { + path: string + free_gb: number + system: boolean + external: boolean + has_config: boolean + error?: string +} diff --git a/frontend/src/wails.ts b/frontend/src/wails.ts index 997a02a..5bd7656 100644 --- a/frontend/src/wails.ts +++ b/frontend/src/wails.ts @@ -1,6 +1,9 @@ import { AppState, CachedInstaller, + DataRootCheck, + DataRootChoice, + RemoteRuntime, Release, Task, CreateOpts, @@ -45,6 +48,12 @@ declare global { DownloadInstaller(version: string): Promise ListInstallers(): Promise DeleteInstaller(name: string): Promise + SuggestDataRoots(): Promise + CheckDataRoot(dir: string): Promise + CompleteSetup(dir: string): Promise + ListRemoteRuntimes(): Promise + SetRuntimeChannel(channel: string): Promise + InstallRuntimeOnline(commit: string): Promise } } } @@ -95,6 +104,12 @@ export const backend = { downloadInstaller: (version: string) => app().DownloadInstaller(version), listInstallers: () => app().ListInstallers(), deleteInstaller: (name: string) => app().DeleteInstaller(name), + suggestDataRoots: () => app().SuggestDataRoots(), + checkDataRoot: (dir: string) => app().CheckDataRoot(dir), + completeSetup: (dir: string) => app().CompleteSetup(dir), + listRemoteRuntimes: () => app().ListRemoteRuntimes(), + setRuntimeChannel: (channel: string) => app().SetRuntimeChannel(channel), + installRuntimeOnline: (commit: string) => app().InstallRuntimeOnline(commit), onTask: (cb: (task: Task) => void) => window.runtime?.EventsOn('reims:task', cb) ?? (() => {}), onStateChanged: (cb: () => void) => window.runtime?.EventsOn('reims:state-changed', cb) ?? (() => {}), onLog: (cb: (entry: LogEntry) => void) => window.runtime?.EventsOn('reims:log', cb) ?? (() => {}), diff --git a/frontend/wailsjs/go/main/App.d.ts b/frontend/wailsjs/go/main/App.d.ts index c31c6ad..091fbf8 100644 --- a/frontend/wailsjs/go/main/App.d.ts +++ b/frontend/wailsjs/go/main/App.d.ts @@ -9,6 +9,10 @@ export function ApplyVMSettings(arg1:reims.SetOpts):Promise; export function CancelTask(arg1:string):Promise; +export function CheckDataRoot(arg1:string):Promise; + +export function CompleteSetup(arg1:string):Promise; + export function CreateVM(arg1:reims.CreateOpts):Promise; export function DeleteInstaller(arg1:string):Promise; @@ -31,10 +35,14 @@ export function GetVMDetail(arg1:string):Promise; export function InstallRuntimeArchive(arg1:string):Promise; +export function InstallRuntimeOnline(arg1:string):Promise; + export function ListInstallers():Promise>; export function ListOfflineReleases():Promise>; +export function ListRemoteRuntimes():Promise>; + export function OpenVMFolder(arg1:string):Promise; export function PickDirectory(arg1:string):Promise; @@ -53,10 +61,14 @@ export function SetDataRoot(arg1:string):Promise; export function SetLocale(arg1:string):Promise; +export function SetRuntimeChannel(arg1:string):Promise; + export function StartVM(arg1:string):Promise; export function StopVM(arg1:string,arg2:boolean):Promise; +export function SuggestDataRoots():Promise>; + export function UseRuntime(arg1:string):Promise; export function ValidateCreate(arg1:reims.CreateOpts):Promise>; diff --git a/frontend/wailsjs/go/main/App.js b/frontend/wailsjs/go/main/App.js index 1ea888d..0d4785e 100644 --- a/frontend/wailsjs/go/main/App.js +++ b/frontend/wailsjs/go/main/App.js @@ -10,6 +10,14 @@ export function CancelTask(arg1) { return window['go']['main']['App']['CancelTask'](arg1); } +export function CheckDataRoot(arg1) { + return window['go']['main']['App']['CheckDataRoot'](arg1); +} + +export function CompleteSetup(arg1) { + return window['go']['main']['App']['CompleteSetup'](arg1); +} + export function CreateVM(arg1) { return window['go']['main']['App']['CreateVM'](arg1); } @@ -54,6 +62,10 @@ export function InstallRuntimeArchive(arg1) { return window['go']['main']['App']['InstallRuntimeArchive'](arg1); } +export function InstallRuntimeOnline(arg1) { + return window['go']['main']['App']['InstallRuntimeOnline'](arg1); +} + export function ListInstallers() { return window['go']['main']['App']['ListInstallers'](); } @@ -62,6 +74,10 @@ export function ListOfflineReleases() { return window['go']['main']['App']['ListOfflineReleases'](); } +export function ListRemoteRuntimes() { + return window['go']['main']['App']['ListRemoteRuntimes'](); +} + export function OpenVMFolder(arg1) { return window['go']['main']['App']['OpenVMFolder'](arg1); } @@ -98,6 +114,10 @@ export function SetLocale(arg1) { return window['go']['main']['App']['SetLocale'](arg1); } +export function SetRuntimeChannel(arg1) { + return window['go']['main']['App']['SetRuntimeChannel'](arg1); +} + export function StartVM(arg1) { return window['go']['main']['App']['StartVM'](arg1); } @@ -106,6 +126,10 @@ export function StopVM(arg1, arg2) { return window['go']['main']['App']['StopVM'](arg1, arg2); } +export function SuggestDataRoots() { + return window['go']['main']['App']['SuggestDataRoots'](); +} + export function UseRuntime(arg1) { return window['go']['main']['App']['UseRuntime'](arg1); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index dd104ea..ff65e3d 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -6,6 +6,7 @@ export namespace config { active_runtime?: string; auto_pin_pcores: boolean; default_gpu?: string; + runtime_channel?: string; static createFrom(source: any = {}) { return new Config(source); @@ -18,6 +19,7 @@ export namespace config { this.active_runtime = source["active_runtime"]; this.auto_pin_pcores = source["auto_pin_pcores"]; this.default_gpu = source["default_gpu"]; + this.runtime_channel = source["runtime_channel"]; } } @@ -173,6 +175,7 @@ export namespace main { vms: reims.VMListItem[]; transitions: Record; pending_changes: Record>; + needs_setup: boolean; static createFrom(source: any = {}) { return new AppState(source); @@ -187,6 +190,7 @@ export namespace main { this.vms = this.convertValues(source["vms"], reims.VMListItem); this.transitions = source["transitions"]; this.pending_changes = this.convertValues(source["pending_changes"], Array, true); + this.needs_setup = source["needs_setup"]; } convertValues(a: any, classs: any, asMap: boolean = false): any { @@ -207,6 +211,48 @@ export namespace main { return a; } } + export class DataRootCheck { + path: string; + free_gb: number; + system: boolean; + external: boolean; + has_config: boolean; + error?: string; + + static createFrom(source: any = {}) { + return new DataRootCheck(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.path = source["path"]; + this.free_gb = source["free_gb"]; + this.system = source["system"]; + this.external = source["external"]; + this.has_config = source["has_config"]; + this.error = source["error"]; + } + } + export class DataRootChoice { + path: string; + free_gb: number; + system: boolean; + external: boolean; + recommended: boolean; + + static createFrom(source: any = {}) { + return new DataRootChoice(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.path = source["path"]; + this.free_gb = source["free_gb"]; + this.system = source["system"]; + this.external = source["external"]; + this.recommended = source["recommended"]; + } + } export class PendingChange { field: string; from: string; @@ -471,6 +517,22 @@ export namespace reims { export namespace runtime { + export class Patch { + name: string; + target: string; + sha256: string; + + static createFrom(source: any = {}) { + return new Patch(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.name = source["name"]; + this.target = source["target"]; + this.sha256 = source["sha256"]; + } + } export class Manifest { schema_version: number; name: string; @@ -485,6 +547,12 @@ export namespace runtime { dll_count: number; raw_bytes: number; sha256: Record; + vendor_qemu_commit?: string; + util_commit?: string; + metal2vulkan_commit?: string; + patches?: Patch[]; + channel?: string; + source_package?: string; static createFrom(source: any = {}) { return new Manifest(source); @@ -505,7 +573,31 @@ export namespace runtime { this.dll_count = source["dll_count"]; this.raw_bytes = source["raw_bytes"]; this.sha256 = source["sha256"]; + this.vendor_qemu_commit = source["vendor_qemu_commit"]; + this.util_commit = source["util_commit"]; + this.metal2vulkan_commit = source["metal2vulkan_commit"]; + this.patches = this.convertValues(source["patches"], Patch); + this.channel = source["channel"]; + this.source_package = source["source_package"]; } + + convertValues(a: any, classs: any, asMap: boolean = false): any { + if (!a) { + return a; + } + if (a.slice && a.map) { + return (a as any[]).map(elem => this.convertValues(elem, classs)); + } else if ("object" === typeof a) { + if (asMap) { + for (const key of Object.keys(a)) { + a[key] = new classs(a[key]); + } + return a; + } + return new classs(a); + } + return a; + } } export class Installed { commit: string; @@ -543,6 +635,40 @@ export namespace runtime { return a; } } + + + export class Remote { + commit: string; + tag: string; + channel: string; + published_at: string; + page_url: string; + archive_name: string; + archive_url: string; + archive_size: number; + sums_url: string; + source_name?: string; + source_url?: string; + + static createFrom(source: any = {}) { + return new Remote(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.commit = source["commit"]; + this.tag = source["tag"]; + this.channel = source["channel"]; + this.published_at = source["published_at"]; + this.page_url = source["page_url"]; + this.archive_name = source["archive_name"]; + this.archive_url = source["archive_url"]; + this.archive_size = source["archive_size"]; + this.sums_url = source["sums_url"]; + this.source_name = source["source_name"]; + this.source_url = source["source_url"]; + } + } } diff --git a/internal/config/config.go b/internal/config/config.go index 1f5f11a..2aa9340 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -16,6 +16,9 @@ type Config struct { ActiveRuntime string `json:"active_runtime,omitempty"` AutoPinPCores bool `json:"auto_pin_pcores"` DefaultGPU string `json:"default_gpu,omitempty"` + // RuntimeChannel is "stable" (default, also when empty) or "candidate": + // whether online install offers candidate runtimes (portable-runtime-spec.md §6). + RuntimeChannel string `json:"runtime_channel,omitempty"` } func DefaultDataRoot() string { @@ -34,13 +37,110 @@ func DefaultDataRoot() string { return filepath.Join(home, "reims-go-data") } +// CurrentDataRoot is the data folder in effect: REIMS_GO_DATA_ROOT, else the +// folder chosen at first launch (LocationPath), else DefaultDataRoot. +func CurrentDataRoot() string { + if v := os.Getenv("REIMS_GO_DATA_ROOT"); v != "" { + return v + } + if root, ok := ReadLocation(); ok { + return root + } + return DefaultDataRoot() +} + func DefaultConfigPath() string { - return filepath.Join(DefaultDataRoot(), "reims-go.json") + return filepath.Join(CurrentDataRoot(), "reims-go.json") +} + +// LocationPath is the one small file kept outside the data folder: it records +// which folder was chosen, so the next launch finds it. %APPDATA%\reims-go on +// Windows. Everything else (runtimes, VMs, installers) lives in the data folder. +// REIMS_GO_LOCATION_FILE overrides it (testing the first-launch screen without +// touching the real pointer). +func LocationPath() string { + if p := os.Getenv("REIMS_GO_LOCATION_FILE"); p != "" { + return p + } + dir, err := os.UserConfigDir() + if err != nil { + return "" + } + return filepath.Join(dir, "reims-go", "location.json") +} + +type location struct { + DataRoot string `json:"data_root"` +} + +// ReadLocation returns the data folder chosen at first launch, if any. +func ReadLocation() (string, bool) { + p := LocationPath() + if p == "" { + return "", false + } + raw, err := os.ReadFile(p) + if err != nil { + return "", false + } + var loc location + if json.Unmarshal(raw, &loc) != nil || loc.DataRoot == "" { + return "", false + } + return loc.DataRoot, true +} + +// SaveLocation records the chosen data folder for the next launch. +func SaveLocation(dataRoot string) error { + p := LocationPath() + if p == "" { + return errors.New("no user config directory") + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return err + } + data, err := json.MarshalIndent(location{DataRoot: dataRoot}, "", " ") + if err != nil { + return err + } + return os.WriteFile(p, append(data, '\n'), 0o644) +} + +// Resolve loads the config for the app and reports whether first-launch setup +// is needed: no REIMS_GO_DATA_ROOT, no recorded folder, and no reims-go.json in +// the default folder. An install from before the picker existed (a config in +// the default folder) is adopted and recorded, so it is never asked again. +// legacyDataRoot is where installs before the first-launch picker kept their +// config; a variable so tests can point it elsewhere. +var legacyDataRoot = DefaultDataRoot + +func Resolve() (cfg *Config, needsSetup bool, err error) { + if os.Getenv("REIMS_GO_FIRST_RUN") == "1" { + // Simulate a fresh machine (testing the first-launch screen). + return Default(), true, nil + } + if os.Getenv("REIMS_GO_DATA_ROOT") != "" { + cfg, err = Load("") + return cfg, false, err + } + if _, ok := ReadLocation(); ok { + cfg, err = Load("") + return cfg, false, err + } + legacy := filepath.Join(legacyDataRoot(), "reims-go.json") + if _, statErr := os.Stat(legacy); statErr == nil { + cfg, err = Load(legacy) + if err == nil { + _ = SaveLocation(cfg.DataRoot) + } + return cfg, false, err + } + return Default(), true, nil } func Default() *Config { return &Config{ - DataRoot: DefaultDataRoot(), + DataRoot: CurrentDataRoot(), Locale: i18n.Detect(), AutoPinPCores: true, DefaultGPU: "auto", @@ -63,7 +163,7 @@ func Load(path string) (*Config, error) { return nil, err } if cfg.DataRoot == "" { - cfg.DataRoot = DefaultDataRoot() + cfg.DataRoot = filepath.Dir(path) } cfg.Locale = i18n.Normalize(string(cfg.Locale)) return cfg, nil @@ -83,7 +183,7 @@ func Save(path string, cfg *Config) error { return os.WriteFile(path, append(data, '\n'), 0o644) } -func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") } +func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") } func (c *Config) XDGConfigDir() string { return filepath.Join(c.DataRoot, "config") } func (c *Config) XDGDataDir() string { return filepath.Join(c.DataRoot, "data") } func (c *Config) XDGCacheDir() string { return filepath.Join(c.DataRoot, "cache") } diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..36780a3 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,80 @@ +package config + +import ( + "os" + "path/filepath" + "runtime" + "testing" +) + +// isolate points the user config dir and the legacy default at temp folders. +func isolate(t *testing.T) (legacy string) { + t.Helper() + cfgHome := t.TempDir() + if runtime.GOOS == "windows" { + t.Setenv("APPDATA", cfgHome) + } else { + t.Setenv("XDG_CONFIG_HOME", cfgHome) + t.Setenv("HOME", cfgHome) + } + t.Setenv("REIMS_GO_DATA_ROOT", "") + legacy = filepath.Join(t.TempDir(), "legacy") + old := legacyDataRoot + legacyDataRoot = func() string { return legacy } + t.Cleanup(func() { legacyDataRoot = old }) + return legacy +} + +func TestFirstLaunchNeedsSetupUntilAFolderIsChosen(t *testing.T) { + isolate(t) + _, needs, err := Resolve() + if err != nil || !needs { + t.Fatalf("fresh machine: needs=%v err=%v", needs, err) + } + chosen := filepath.Join(t.TempDir(), "Data", "reims-go") + cfg := Default() + cfg.DataRoot = chosen + if err := Save("", cfg); err != nil { + t.Fatal(err) + } + if err := SaveLocation(chosen); err != nil { + t.Fatal(err) + } + got, needs, err := Resolve() + if err != nil || needs || got.DataRoot != chosen { + t.Fatalf("after choosing: root=%q needs=%v err=%v", got.DataRoot, needs, err) + } + if CurrentDataRoot() != chosen { + t.Fatalf("CurrentDataRoot = %q", CurrentDataRoot()) + } +} + +func TestExistingInstallIsAdoptedWithoutAsking(t *testing.T) { + legacy := isolate(t) + cfg := Default() + cfg.DataRoot = legacy + cfg.ActiveRuntime = "3731afd" + if err := Save(filepath.Join(legacy, "reims-go.json"), cfg); err != nil { + t.Fatal(err) + } + got, needs, err := Resolve() + if err != nil || needs || got.ActiveRuntime != "3731afd" { + t.Fatalf("legacy: %+v needs=%v err=%v", got, needs, err) + } + if root, ok := ReadLocation(); !ok || root != legacy { + t.Fatalf("location not recorded: %q %v", root, ok) + } +} + +func TestEnvOverridesEverything(t *testing.T) { + isolate(t) + env := t.TempDir() + t.Setenv("REIMS_GO_DATA_ROOT", env) + cfg, needs, err := Resolve() + if err != nil || needs || cfg.DataRoot != env { + t.Fatalf("env: root=%q needs=%v err=%v", cfg.DataRoot, needs, err) + } + if _, err := os.Stat(LocationPath()); !os.IsNotExist(err) { + t.Fatal("env override must not write the location file") + } +} diff --git a/internal/host/drives_other.go b/internal/host/drives_other.go new file mode 100644 index 0000000..0e0d694 --- /dev/null +++ b/internal/host/drives_other.go @@ -0,0 +1,35 @@ +//go:build !windows + +package host + +import ( + "os" + "syscall" +) + +// Drive is a disk a data folder could go on. +type Drive struct { + Root string `json:"root"` + FreeGB float64 `json:"free_gb"` + System bool `json:"system"` + External bool `json:"external"` +} + +// ListDrives returns the home directory's volume on dev/preview hosts. +func ListDrives() []Drive { + home, err := os.UserHomeDir() + if err != nil { + return nil + } + free, _ := FreeGB(home) + return []Drive{{Root: home, FreeGB: free, System: true}} +} + +// FreeGB is the free space on the volume holding path. +func FreeGB(path string) (float64, bool) { + var st syscall.Statfs_t + if err := syscall.Statfs(path, &st); err != nil { + return 0, false + } + return float64(st.Bavail) * float64(st.Bsize) / (1 << 30), true +} diff --git a/internal/host/drives_windows.go b/internal/host/drives_windows.go new file mode 100644 index 0000000..5acd1b5 --- /dev/null +++ b/internal/host/drives_windows.go @@ -0,0 +1,96 @@ +//go:build windows + +package host + +import ( + "encoding/binary" + "os" + "strings" + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +var ( + procGetLogicalDrives = kernel32.NewProc("GetLogicalDrives") + procGetDriveTypeW = kernel32.NewProc("GetDriveTypeW") +) + +const driveFixed = 3 // DRIVE_FIXED + +// Drive is a local fixed disk a data folder could go on. +type Drive struct { + Root string `json:"root"` // `D:\` + FreeGB float64 `json:"free_gb"` // bytes available to this user + System bool `json:"system"` // holds Windows + External bool `json:"external"` // on a USB bus (Windows still calls USB disks "fixed") +} + +// ListDrives returns local fixed drives (no removable, network or optical). +func ListDrives() []Drive { + mask, _, _ := procGetLogicalDrives.Call() + sys := strings.ToUpper(strings.TrimSuffix(os.Getenv("SystemDrive"), `\`)) + if sys == "" { + sys = "C:" + } + var out []Drive + for i := 0; i < 26; i++ { + if mask&(1< 导入)", - "doctor.runtime.active": "当前激活:%s(%s)", - "runtime.installed": "便携运行时已安装:%s -> %s", - "runtime.activated": "已切换激活运行时:%s", - "runtime.empty": "尚未安装任何便携运行时。", - "vm.empty": "当前没有已创建的虚拟机。", - "vm.install_guide.title": "macOS 装机步骤(简体中文恢复界面):", - "vm.install_guide.step1": "1. 打开「磁盘工具」,选中「QEMU HARDDISK Media」并点「抹掉」(格式选 APFS)。", - "vm.install_guide.step2": "2. 退出磁盘工具,选择「重新安装 macOS Tahoe」并等待完成。", - "vm.install_guide.step3": "3. 进入桌面后,运行 `reims-go vm eject %s`(或在界面点击「弹出安装盘」)。", - "err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`", - "installer.paused": "已暂停。再次运行 `reims-go installer download %s` 会从中断处继续。", - "installer.done": "离线安装包已就绪:macOS %s -> %s", - "installer.cached.empty": "还没有下载任何安装包。", - "installer.cached.total": "共 %s,位于 %s", - "installer.partial": "(未下载完)", + "doctor.title": "reims-go 宿主机环境体检", + "doctor.os": "操作系统", + "doctor.cpu": "处理器与核心拓扑", + "doctor.pcores": "P-Core 性能核", + "doctor.ecores": "E-Core 能效核", + "doctor.ram": "宿主机内存", + "doctor.disk": "数据盘剩余空间", + "doctor.whpx": "Windows 虚拟机监控程序平台 (WHPX)", + "doctor.whpx.ok": "可用(WinHvPlatform.dll 已就绪,hypervisor 运行中)", + "doctor.whpx.no_hv": "已加载 WinHvPlatform.dll,但未检测到虚拟化(请在 BIOS 开启 VT-x/AMD-V)", + "doctor.whpx.missing": "未启用(请点击一键启用 HypervisorPlatform 并重启 Windows)", + "doctor.whpx.unsupported": "非 Windows 宿主(当前处于跨平台开发模式)", + "doctor.gpu": "Vulkan 显卡列表", + "doctor.gpu.none": "未检测到已注册的 Vulkan ICD 显卡驱动", + "doctor.gpu.recommended": "推荐独显", + "doctor.runtime": "便携运行时", + "doctor.runtime.none": "尚未安装(运行 reims-go runtime install <压缩包> 导入)", + "doctor.runtime.active": "当前激活:%s(%s)", + "runtime.installed": "便携运行时已安装:%s -> %s", + "runtime.activated": "已切换激活运行时:%s", + "runtime.empty": "尚未安装任何便携运行时。", + "vm.empty": "当前没有已创建的虚拟机。", + "vm.install_guide.title": "macOS 装机步骤(简体中文恢复界面):", + "vm.install_guide.step1": "1. 打开「磁盘工具」,选中「QEMU HARDDISK Media」并点「抹掉」(格式选 APFS)。", + "vm.install_guide.step2": "2. 退出磁盘工具,选择「重新安装 macOS Tahoe」并等待完成。", + "vm.install_guide.step3": "3. 进入桌面后,运行 `reims-go vm eject %s`(或在界面点击「弹出安装盘」)。", + "err.runtime_not_installed": "未找到已激活的便携运行时,请先执行 `reims-go runtime install <归档路径>`", + "installer.paused": "已暂停。再次运行 `reims-go installer download %s` 会从中断处继续。", + "installer.done": "离线安装包已就绪:macOS %s -> %s", + "installer.cached.empty": "还没有下载任何安装包。", + "installer.cached.total": "共 %s,位于 %s", + "installer.partial": "(未下载完)", + "runtime.remote.empty": "当前通道还没有发布运行时(候选版需要加 --candidate)。", + "runtime.remote.downloading": "下载运行时 %s(%s,%s)", + "runtime.remote.paused": "已暂停。再次运行同一命令会从中断处继续。", }, EnUS: { - "doctor.title": "reims-go Host Environment Check", - "doctor.os": "Operating System", - "doctor.cpu": "CPU & Core Topology", - "doctor.pcores": "P-Cores (Performance)", - "doctor.ecores": "E-Cores (Efficiency)", - "doctor.ram": "Host Memory", - "doctor.disk": "Data Drive Free Space", - "doctor.whpx": "Windows Hypervisor Platform (WHPX)", - "doctor.whpx.ok": "Ready (WinHvPlatform.dll active, hypervisor running)", - "doctor.whpx.no_hv": "WinHvPlatform.dll present, but no hypervisor detected (enable VT-x/AMD-V in BIOS)", - "doctor.whpx.missing": "Not enabled (enable Windows Hypervisor Platform and restart Windows)", - "doctor.whpx.unsupported": "Non-Windows host (cross-platform dev mode)", - "doctor.gpu": "Vulkan GPUs", - "doctor.gpu.none": "No registered Vulkan ICD driver found", - "doctor.gpu.recommended": "Recommended discrete GPU", - "doctor.runtime": "Portable Runtime", - "doctor.runtime.none": "Not installed (run `reims-go runtime install `)", - "doctor.runtime.active": "Active: %s (%s)", - "runtime.installed": "Portable runtime installed: %s -> %s", - "runtime.activated": "Active runtime switched to: %s", - "runtime.empty": "No portable runtimes installed.", - "vm.empty": "No virtual machines found.", - "vm.install_guide.title": "macOS Setup Steps (Recovery UI):", - "vm.install_guide.step1": "1. Open 'Disk Utility', select 'QEMU HARDDISK Media', and Erase as APFS.", - "vm.install_guide.step2": "2. Quit Disk Utility, choose 'Reinstall macOS Tahoe', and wait for completion.", - "vm.install_guide.step3": "3. Once on the desktop, run `reims-go vm eject %s` (or click 'Eject Installer').", - "err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install ` first", - "installer.paused": "Paused. Run `reims-go installer download %s` again to continue where it stopped.", - "installer.done": "Offline installer ready: macOS %s -> %s", - "installer.cached.empty": "No installers downloaded yet.", - "installer.cached.total": "%s in %s", - "installer.partial": "(partly downloaded)", + "doctor.title": "reims-go Host Environment Check", + "doctor.os": "Operating System", + "doctor.cpu": "CPU & Core Topology", + "doctor.pcores": "P-Cores (Performance)", + "doctor.ecores": "E-Cores (Efficiency)", + "doctor.ram": "Host Memory", + "doctor.disk": "Data Drive Free Space", + "doctor.whpx": "Windows Hypervisor Platform (WHPX)", + "doctor.whpx.ok": "Ready (WinHvPlatform.dll active, hypervisor running)", + "doctor.whpx.no_hv": "WinHvPlatform.dll present, but no hypervisor detected (enable VT-x/AMD-V in BIOS)", + "doctor.whpx.missing": "Not enabled (enable Windows Hypervisor Platform and restart Windows)", + "doctor.whpx.unsupported": "Non-Windows host (cross-platform dev mode)", + "doctor.gpu": "Vulkan GPUs", + "doctor.gpu.none": "No registered Vulkan ICD driver found", + "doctor.gpu.recommended": "Recommended discrete GPU", + "doctor.runtime": "Portable Runtime", + "doctor.runtime.none": "Not installed (run `reims-go runtime install `)", + "doctor.runtime.active": "Active: %s (%s)", + "runtime.installed": "Portable runtime installed: %s -> %s", + "runtime.activated": "Active runtime switched to: %s", + "runtime.empty": "No portable runtimes installed.", + "vm.empty": "No virtual machines found.", + "vm.install_guide.title": "macOS Setup Steps (Recovery UI):", + "vm.install_guide.step1": "1. Open 'Disk Utility', select 'QEMU HARDDISK Media', and Erase as APFS.", + "vm.install_guide.step2": "2. Quit Disk Utility, choose 'Reinstall macOS Tahoe', and wait for completion.", + "vm.install_guide.step3": "3. Once on the desktop, run `reims-go vm eject %s` (or click 'Eject Installer').", + "err.runtime_not_installed": "no active portable runtime found; run `reims-go runtime install ` first", + "installer.paused": "Paused. Run `reims-go installer download %s` again to continue where it stopped.", + "installer.done": "Offline installer ready: macOS %s -> %s", + "installer.cached.empty": "No installers downloaded yet.", + "installer.cached.total": "%s in %s", + "installer.partial": "(partly downloaded)", + "runtime.remote.empty": "No runtime is published on this channel yet (add --candidate for candidates).", + "runtime.remote.downloading": "Downloading runtime %s (%s, %s)", + "runtime.remote.paused": "Paused. Run the same command again to continue where it stopped.", }, } diff --git a/internal/runtime/remote.go b/internal/runtime/remote.go new file mode 100644 index 0000000..9dd0421 --- /dev/null +++ b/internal/runtime/remote.go @@ -0,0 +1,329 @@ +package runtime + +// Online install: runtime packages are GitHub Release assets of the reims-go +// repository (decided 2026-11-28, AGENTS.md). A runtime release is tagged +// "runtime-" and carries: +// +// reims-runtime-win-x64-.tar.zst +// reims-runtime-src-.tar.zst (matching sources, spec §7) +// SHA256SUMS.txt +// +// A GitHub prerelease is the candidate channel; a full release is stable +// (spec §6). The client lists stable only unless candidate is asked for. + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/config" +) + +const ( + DefaultReleasesRepo = "Nwflower/reims-go" + DefaultAPIBase = "https://api.github.com" + runtimeTagPrefix = "runtime-" + sumsAsset = "SHA256SUMS.txt" +) + +const ( + ChannelStable = "stable" + ChannelCandidate = "candidate" +) + +// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO +// overrides the repository (for forks and testing). +type Source struct { + APIBase string + Repo string + Client *http.Client +} + +func DefaultSource() Source { + repo := os.Getenv("REIMS_GO_RELEASES_REPO") + if repo == "" { + repo = DefaultReleasesRepo + } + return Source{APIBase: DefaultAPIBase, Repo: repo, Client: &http.Client{Timeout: 0}} +} + +// Remote is a runtime package published as a release. +type Remote struct { + Commit string `json:"commit"` + Tag string `json:"tag"` + Channel string `json:"channel"` + PublishedAt string `json:"published_at"` + PageURL string `json:"page_url"` + ArchiveName string `json:"archive_name"` + ArchiveURL string `json:"archive_url"` + ArchiveSize int64 `json:"archive_size"` + SumsURL string `json:"sums_url"` + SourceName string `json:"source_name,omitempty"` + SourceURL string `json:"source_url,omitempty"` +} + +type ghRelease struct { + TagName string `json:"tag_name"` + Draft bool `json:"draft"` + Prerelease bool `json:"prerelease"` + PublishedAt string `json:"published_at"` + HTMLURL string `json:"html_url"` + Assets []ghAsset `json:"assets"` +} + +type ghAsset struct { + Name string `json:"name"` + Size int64 `json:"size"` + URL string `json:"browser_download_url"` +} + +func (s Source) client() *http.Client { + if s.Client != nil { + return s.Client + } + return http.DefaultClient +} + +func newRequest(ctx context.Context, url string) (*http.Request, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + // A generic client name; nothing about the user (GitHub requires a User-Agent). + req.Header.Set("User-Agent", "reims-go") + return req, nil +} + +// ListRemote lists published runtime packages, newest first. Candidates are +// included only when includeCandidate is set. +func (s Source) ListRemote(ctx context.Context, includeCandidate bool) ([]Remote, error) { + url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", strings.TrimRight(s.APIBase, "/"), s.Repo) + req, err := newRequest(ctx, url) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/vnd.github+json") + resp, err := s.client().Do(req) + if err != nil { + return nil, fmt.Errorf("list runtime releases: %w", err) + } + 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) + } + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("list runtime releases: HTTP %d", resp.StatusCode) + } + var rels []ghRelease + if err := json.NewDecoder(resp.Body).Decode(&rels); err != nil { + return nil, fmt.Errorf("read runtime releases: %w", err) + } + var out []Remote + for _, r := range rels { + if r.Draft || !strings.HasPrefix(r.TagName, runtimeTagPrefix) { + continue + } + commit := strings.TrimPrefix(r.TagName, runtimeTagPrefix) + rem := Remote{Commit: commit, Tag: r.TagName, PublishedAt: r.PublishedAt, PageURL: r.HTMLURL, Channel: ChannelStable} + if r.Prerelease { + rem.Channel = ChannelCandidate + } + for _, a := range r.Assets { + switch { + case a.Name == "reims-runtime-win-x64-"+commit+".tar.zst": + rem.ArchiveName, rem.ArchiveURL, rem.ArchiveSize = a.Name, a.URL, a.Size + case a.Name == sumsAsset: + rem.SumsURL = a.URL + case strings.HasPrefix(a.Name, "reims-runtime-src-"): + rem.SourceName, rem.SourceURL = a.Name, a.URL + } + } + // A release without its sums or sources is incomplete: never offer it. + if rem.ArchiveURL == "" || rem.SumsURL == "" || rem.SourceURL == "" { + continue + } + if rem.Channel == ChannelCandidate && !includeCandidate { + continue + } + out = append(out, rem) + } + sort.SliceStable(out, func(i, j int) bool { return out[i].PublishedAt > out[j].PublishedAt }) + return out, nil +} + +// Pick finds a release by commit prefix, or the newest for "" / "latest". +func Pick(list []Remote, want string) (*Remote, error) { + want = strings.TrimSpace(want) + if len(list) == 0 { + return nil, errors.New("no runtime release is published for this channel") + } + if want == "" || strings.EqualFold(want, "latest") { + return &list[0], nil + } + for i := range list { + if strings.HasPrefix(list[i].Commit, want) || strings.HasPrefix(want, list[i].Commit) { + return &list[i], nil + } + } + return nil, fmt.Errorf("no runtime release for %q", want) +} + +// Progress reports bytes of the archive download. +type Progress func(done, total int64) + +// Download fetches r's archive into dir, continuing a partial download, and +// checks it against the release's SHA256SUMS.txt. It returns the archive path. +func (s Source) Download(ctx context.Context, r Remote, dir string, onProgress Progress) (string, error) { + if onProgress == nil { + onProgress = func(int64, int64) {} + } + want, err := s.expectedSum(ctx, r) + if err != nil { + return "", err + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", err + } + final := filepath.Join(dir, r.ArchiveName) + if got, err := fileSHA256(final); err == nil && strings.EqualFold(got, want) { + onProgress(r.ArchiveSize, r.ArchiveSize) + return final, nil + } + part := final + ".part" + + var have int64 + if st, err := os.Stat(part); err == nil { + have = st.Size() + } + req, err := newRequest(ctx, r.ArchiveURL) + if err != nil { + return "", err + } + if have > 0 { + req.Header.Set("Range", "bytes="+strconv.FormatInt(have, 10)+"-") + } + resp, err := s.client().Do(req) + if err != nil { + return "", fmt.Errorf("download %s: %w", r.ArchiveName, err) + } + defer resp.Body.Close() + + flags := os.O_CREATE | os.O_WRONLY + switch resp.StatusCode { + case http.StatusPartialContent: + flags |= os.O_APPEND + case http.StatusOK: + have = 0 // server ignored the range: start over + flags |= os.O_TRUNC + case http.StatusRequestedRangeNotSatisfiable: + os.Remove(part) + return s.Download(ctx, r, dir, onProgress) + default: + return "", fmt.Errorf("download %s: HTTP %d", r.ArchiveName, resp.StatusCode) + } + total := r.ArchiveSize + if total <= 0 && resp.ContentLength > 0 { + total = have + resp.ContentLength + } + + f, err := os.OpenFile(part, flags, 0o644) + if err != nil { + return "", err + } + done := have + onProgress(done, total) + buf := make([]byte, 256*1024) + last := time.Now() + for { + n, rerr := resp.Body.Read(buf) + if n > 0 { + if _, werr := f.Write(buf[:n]); werr != nil { + f.Close() + return "", werr + } + done += int64(n) + if time.Since(last) > 100*time.Millisecond { + onProgress(done, total) + last = time.Now() + } + } + if rerr == io.EOF { + break + } + if rerr != nil { + f.Close() + return "", fmt.Errorf("download %s: %w", r.ArchiveName, rerr) // .part kept for resume + } + } + if err := f.Close(); err != nil { + return "", err + } + onProgress(done, total) + + got, err := fileSHA256(part) + if err != nil { + return "", err + } + if !strings.EqualFold(got, want) { + os.Remove(part) + return "", fmt.Errorf("%s: SHA256 mismatch (expected %s, got %s); the download was discarded", r.ArchiveName, want, got) + } + if err := os.Rename(part, final); err != nil { + return "", err + } + return final, nil +} + +// expectedSum reads r's archive hash from the release's SHA256SUMS.txt +// (" " lines, as sha256sum writes them). +func (s Source) expectedSum(ctx context.Context, r Remote) (string, error) { + req, err := newRequest(ctx, r.SumsURL) + if err != nil { + return "", err + } + resp, err := s.client().Do(req) + if err != nil { + return "", fmt.Errorf("download %s: %w", sumsAsset, err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("download %s: HTTP %d", sumsAsset, resp.StatusCode) + } + sc := bufio.NewScanner(io.LimitReader(resp.Body, 1<<20)) + for sc.Scan() { + fields := strings.Fields(sc.Text()) + if len(fields) == 2 && strings.TrimPrefix(fields[1], "*") == r.ArchiveName && len(fields[0]) == 64 { + return strings.ToLower(fields[0]), nil + } + } + return "", fmt.Errorf("%s has no entry for %s", sumsAsset, r.ArchiveName) +} + +// DownloadsDir is where runtime archives are downloaded before install. +func DownloadsDir(cfg *config.Config) string { + return filepath.Join(cfg.DataRoot, "downloads") +} + +// IsInstalled reports whether commit is already unpacked under runtimes/. +func IsInstalled(cfg *config.Config, commit string) bool { + list, err := List(cfg) + if err != nil { + return false + } + for _, it := range list { + if strings.HasPrefix(it.Commit, commit) || strings.HasPrefix(commit, it.Commit) { + return true + } + } + return false +} diff --git a/internal/runtime/remote_test.go b/internal/runtime/remote_test.go new file mode 100644 index 0000000..7177d10 --- /dev/null +++ b/internal/runtime/remote_test.go @@ -0,0 +1,154 @@ +package runtime + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +type fakeGitHub struct { + srv *httptest.Server + archive []byte + sums string + hits map[string]int +} + +func newFakeGitHub(t *testing.T) *fakeGitHub { + t.Helper() + g := &fakeGitHub{archive: bytes.Repeat([]byte("reims-runtime-"), 50_000), hits: map[string]int{}} + sum := sha256.Sum256(g.archive) + g.sums = hex.EncodeToString(sum[:]) + " reims-runtime-win-x64-abc1234.tar.zst\n" + mux := http.NewServeMux() + mux.HandleFunc("/repos/o/r/releases", func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("User-Agent") != "reims-go" { + t.Errorf("User-Agent = %q", r.Header.Get("User-Agent")) + } + base := g.srv.URL + fmt.Fprintf(w, `[ + {"tag_name":"runtime-abc1234","prerelease":true,"published_at":"2026-11-28T10:00:00Z","assets":[ + {"name":"reims-runtime-win-x64-abc1234.tar.zst","size":%d,"browser_download_url":"%s/a/archive"}, + {"name":"reims-runtime-src-abc1234.tar.zst","size":5,"browser_download_url":"%s/a/src"}, + {"name":"SHA256SUMS.txt","size":90,"browser_download_url":"%s/a/sums"}]}, + {"tag_name":"runtime-0000old","prerelease":false,"published_at":"2026-10-01T00:00:00Z","assets":[ + {"name":"reims-runtime-win-x64-0000old.tar.zst","size":1,"browser_download_url":"%s/a/x"}, + {"name":"reims-runtime-src-0000old.tar.zst","size":1,"browser_download_url":"%s/a/x"}, + {"name":"SHA256SUMS.txt","size":1,"browser_download_url":"%s/a/x"}]}, + {"tag_name":"runtime-nosrc00","prerelease":false,"published_at":"2026-11-01T00:00:00Z","assets":[ + {"name":"reims-runtime-win-x64-nosrc00.tar.zst","size":1,"browser_download_url":"%s/a/x"}, + {"name":"SHA256SUMS.txt","size":1,"browser_download_url":"%s/a/x"}]}, + {"tag_name":"runtime-draft00","draft":true,"assets":[]}, + {"tag_name":"v0.1.0","prerelease":false,"assets":[]} +]`, len(g.archive), base, base, base, base, base, base, base, base) + }) + mux.HandleFunc("/a/archive", func(w http.ResponseWriter, r *http.Request) { + g.hits["archive"]++ + if r.Header.Get("Range") != "" { + g.hits["range"]++ + } + http.ServeContent(w, r, "a.tar.zst", time.Time{}, bytes.NewReader(g.archive)) + }) + mux.HandleFunc("/a/sums", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, g.sums) }) + g.srv = httptest.NewServer(mux) + t.Cleanup(g.srv.Close) + return g +} + +func (g *fakeGitHub) source() Source { + return Source{APIBase: g.srv.URL, Repo: "o/r", Client: g.srv.Client()} +} + +func TestListRemoteFiltersChannelsAndIncompleteReleases(t *testing.T) { + g := newFakeGitHub(t) + stable, err := g.source().ListRemote(context.Background(), false) + if err != nil { + t.Fatal(err) + } + if len(stable) != 1 || stable[0].Commit != "0000old" || stable[0].Channel != ChannelStable { + t.Fatalf("stable only = %+v", stable) + } + all, err := g.source().ListRemote(context.Background(), true) + if err != nil { + t.Fatal(err) + } + if len(all) != 2 || all[0].Commit != "abc1234" || all[0].Channel != ChannelCandidate || all[0].SourceName == "" { + t.Fatalf("with candidate = %+v", all) + } + if r, err := Pick(all, "abc"); err != nil || r.Commit != "abc1234" { + t.Fatalf("pick prefix: %v %v", r, err) + } + if r, _ := Pick(all, "latest"); r.Commit != "abc1234" { + t.Fatalf("latest = %v", r) + } + if _, err := Pick(nil, ""); err == nil { + t.Fatal("empty list") + } +} + +func TestDownloadResumesAndVerifies(t *testing.T) { + g := newFakeGitHub(t) + src := g.source() + list, _ := src.ListRemote(context.Background(), true) + r := list[0] + dir := t.TempDir() + + // A previous run left the first 100 KB. + part := filepath.Join(dir, r.ArchiveName+".part") + os.WriteFile(part, g.archive[:100_000], 0o644) + + var last int64 + path, err := src.Download(context.Background(), r, dir, func(done, total int64) { + if total != int64(len(g.archive)) { + t.Errorf("total = %d", total) + } + last = done + }) + if err != nil { + t.Fatal(err) + } + if g.hits["range"] != 1 { + t.Fatalf("expected a ranged request, hits=%v", g.hits) + } + if last != int64(len(g.archive)) { + t.Fatalf("last progress = %d", last) + } + got, _ := os.ReadFile(path) + if !bytes.Equal(got, g.archive) { + t.Fatal("archive content differs") + } + if _, err := os.Stat(part); !os.IsNotExist(err) { + t.Fatal(".part left behind") + } + + // Already there and valid: no new request. + before := g.hits["archive"] + if _, err := src.Download(context.Background(), r, dir, nil); err != nil { + t.Fatal(err) + } + if g.hits["archive"] != before { + t.Fatal("re-downloaded a verified archive") + } +} + +func TestDownloadRejectsAWrongChecksum(t *testing.T) { + g := newFakeGitHub(t) + g.sums = strings.Repeat("0", 64) + " reims-runtime-win-x64-abc1234.tar.zst\n" + list, _ := g.source().ListRemote(context.Background(), true) + dir := t.TempDir() + _, err := g.source().Download(context.Background(), list[0], dir, nil) + if err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") { + t.Fatalf("err = %v", err) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 0 { + t.Fatalf("bad download kept: %v", entries) + } +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 2be3c99..1986920 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -32,6 +32,22 @@ type Manifest struct { DLLCount int `json:"dll_count"` RawBytes int64 `json:"raw_bytes"` SHA256 map[string]string `json:"sha256"` + + // Schema 2 (docs/portable-runtime-spec.md §3.1, §5, §7): what the package + // was really built from. A package with patches is not "pure upstream". + VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"` + UtilCommit string `json:"util_commit,omitempty"` + MetalCommit string `json:"metal2vulkan_commit,omitempty"` + Patches []Patch `json:"patches,omitempty"` + Channel string `json:"channel,omitempty"` // candidate | stable + SourcePackage string `json:"source_package,omitempty"` // file name of the matching source archive +} + +// Patch is one local patch applied on top of upstream. +type Patch struct { + Name string `json:"name"` + Target string `json:"target"` // e.g. "vendor/qemu" + SHA256 string `json:"sha256"` } type Installed struct { diff --git a/patches/README.md b/patches/README.md index 114a747..d1a9680 100644 --- a/patches/README.md +++ b/patches/README.md @@ -10,4 +10,5 @@ | 文件 | 目标仓库 / 基准 commit | 解决的问题 | 上游状态 | | :--- | :--- | :--- | :--- | +| `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` 补齐后即可删除 | | `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 | diff --git a/patches/reims-vgpu-cargo-lock.patch b/patches/reims-vgpu-cargo-lock.patch new file mode 100644 index 0000000..4efd9a2 --- /dev/null +++ b/patches/reims-vgpu-cargo-lock.patch @@ -0,0 +1,28 @@ +diff --git a/Cargo.lock b/Cargo.lock +index 106e75e..01bf052 100644 +--- a/Cargo.lock ++++ b/Cargo.lock +@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] + name = "metal2vulkan" + version = "0.2.0" ++source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" + dependencies = [ + "ash", + "metal2vulkan-air", +@@ -223,6 +224,7 @@ dependencies = [ + [[package]] + name = "metal2vulkan-air" + version = "0.2.0" ++source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" + dependencies = [ + "sha2 0.11.1", + ] +@@ -230,6 +232,7 @@ dependencies = [ + [[package]] + name = "metal2vulkan-runtime" + version = "0.2.0" ++source = "git+https://github.com/steelbrain/metal2vulkan?rev=0b0ac58eb0f69ed3b37007fbdf3b135a46f90699#0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" + dependencies = [ + "ash", + "libc", diff --git a/runtime_bindings.go b/runtime_bindings.go new file mode 100644 index 0000000..4b54ce0 --- /dev/null +++ b/runtime_bindings.go @@ -0,0 +1,147 @@ +package main + +// Online runtime install from GitHub Releases (internal/runtime/remote.go). +// Downloads run as "runtime-install" tasks, so progress shows in the status bar. + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/installer" + rt "github.com/Nwflower/reims-go/internal/runtime" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +func (a *App) baseCtx() context.Context { + if a.ctx != nil { + return a.ctx + } + return context.Background() +} + +func (a *App) includeCandidate() bool { + a.mu.Lock() + defer a.mu.Unlock() + return a.cfg.RuntimeChannel == rt.ChannelCandidate +} + +// ListRemoteRuntimes lists published runtimes for the configured channel. +func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) { + return rt.DefaultSource().ListRemote(a.baseCtx(), a.includeCandidate()) +} + +// SetRuntimeChannel picks "stable" or "candidate" for online installs. +func (a *App) SetRuntimeChannel(channel string) error { + if channel != rt.ChannelStable && channel != rt.ChannelCandidate { + return fmt.Errorf("unknown channel %q", channel) + } + a.mu.Lock() + defer a.mu.Unlock() + a.cfg.RuntimeChannel = channel + 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, +// which resumes on the next install. +func (a *App) InstallRuntimeOnline(commit string) (string, error) { + a.mu.Lock() + if a.needsSetup { + a.mu.Unlock() + return "", errors.New("choose a data folder first") + } + cfg := *a.cfg + a.mu.Unlock() + + subject := strings.TrimSpace(commit) + if subject == "" { + subject = "latest" + } + for _, t := range tasks.list() { + if t.Kind == "runtime-install" && t.Status == TaskRunning { + return t.ID, nil + } + } + a.ensureTaskEmitter() + ctx, cancel := context.WithCancel(a.baseCtx()) + id := tasks.start("runtime-install", subject, "", cancel) + go func() { + defer cancel() + res, err := a.installRuntime(ctx, &cfg, commit, id) + switch { + case err == nil: + tasks.finish(id, res, nil) + case ctx.Err() != nil: + a.emitLog("runtime", "Runtime download paused; installing again continues where it stopped") + tasks.finish(id, "", context.Canceled) + default: + a.emitLog("runtime", "Runtime install error: "+err.Error()) + tasks.finish(id, "", err) + } + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } + }() + return id, nil +} + +func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, taskID string) (string, error) { + src := rt.DefaultSource() + 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") + // An explicit commit may be a candidate even on the stable channel: the + // user asked for it by name. + list, err := src.ListRemote(ctx, cfg.RuntimeChannel == rt.ChannelCandidate || (commit != "" && commit != "latest")) + if err != nil { + return "", err + } + r, err := rt.Pick(list, commit) + if err != nil { + return "", err + } + + if !rt.IsInstalled(cfg, r.Commit) { + step("Downloading runtime " + r.Commit) + path, err := src.Download(ctx, *r, rt.DownloadsDir(cfg), func(done, total int64) { + tasks.update(taskID, installer.Update{ + Kind: installer.KindProgress, Step: "downloading runtime " + r.Commit, + Done: done, Total: total, Percent: percent(done, total), + }) + }) + if err != nil { + return "", err + } + step("Installing runtime " + r.Commit) + inst, err := rt.InstallFromArchive(cfg, path) + if err != nil { + return "", err + } + _ = os.Remove(path) // the unpacked runtime is what's kept + r.Commit = inst.Commit + } + + a.mu.Lock() + a.cfg.ActiveRuntime = r.Commit + err = config.Save("", a.cfg) + a.mu.Unlock() + if err != nil { + return "", err + } + a.emitLog("runtime", fmt.Sprintf("Runtime %s (%s) installed and active", r.Commit, r.Channel)) + return r.Commit, nil +} + +func percent(done, total int64) float64 { + if total <= 0 { + return -1 + } + return float64(done) * 100 / float64(total) +} diff --git a/scripts/pack-runtime.ps1 b/scripts/pack-runtime.ps1 index 756b817..5b7f34d 100644 --- a/scripts/pack-runtime.ps1 +++ b/scripts/pack-runtime.ps1 @@ -1,147 +1,290 @@ <# .SYNOPSIS - Pack a standalone, MSYS2-free portable reims-vgpu runtime bundle for Windows x64. + Pack a portable reims-vgpu runtime for Windows x64, its matching source + package, and SHA256SUMS.txt, ready to publish as a GitHub Release. .DESCRIPTION - Collects reims-ctl.exe, reims-util.exe, and the self-contained QEMU directory - (with its bundled CLANG64/libva DLLs and share/ data), generates manifest.json - with SHA-256 hashes, copies NOTICE.md and upstream LICENSE files, and compresses - the bundle into a .tar.zst archive (falling back to .zip if zstd is unavailable). + Outputs, in -OutDir: + reims-runtime-win-x64-.tar.zst runtime (bin/, qemu/, manifest.json, + NOTICE.md, licenses/, patches/, + MSYS2-PACKAGES.txt) + reims-runtime-src-.tar.zst corresponding source: pristine upstream + trees at the built commits + patches/ + SHA256SUMS.txt both archives + + manifest.json (schema 2) states what the package was really built from: + upstream commit, vendor/qemu commit, reims-util and metal2vulkan commits, + every local patch with its SHA256, and the channel. A package built with + patches is never described as pure upstream (AGENTS.md rule 5). + + Before packing, each patch in -Patches is checked against the build tree: + the tree's diff must equal the patch, so the source package matches the + binaries. A mismatch stops the script. .EXAMPLE - .\scripts\pack-runtime.ps1 - .\scripts\pack-runtime.ps1 -OutDir D:\Data\reims-go\releases -ZstdLevel 15 + pwsh -File scripts/pack-runtime.ps1 -Channel candidate #> [CmdletBinding()] param( - [string]$ReimsRepo = 'D:\DevTools\reims-vgpu', - [string]$CargoBin = 'D:\DevTools\cargo\bin', - [string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current', - [string]$OutDir = 'D:\Data\reims-go\releases', - [string]$TempRoot = 'D:\Build\Temp', - [int]$ZstdLevel = 15 + [string]$ReimsRepo = 'D:\DevTools\reims-vgpu', + [string]$CargoHome = 'D:\DevTools\cargo', + [string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current', + [string]$Msys2 = 'D:\DevTools\msys64', + [string]$OutDir = 'D:\Data\reims-go\releases', + [string]$TempRoot = 'D:\Build\Temp', + [ValidateSet('candidate', 'stable')] + [string]$Channel = 'candidate', + [int]$ZstdLevel = 15 ) $ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +$patchesDir = Join-Path $repoRoot 'patches' +$CargoBin = Join-Path $CargoHome 'bin' -function Resolve-Zstd { - $candidates = @( - (Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source), - 'D:\DevTools\msys64\usr\bin\zstd.exe', - 'D:\DevTools\msys64\clang64\bin\zstd.exe' - ) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } - return ($candidates | Select-Object -First 1) +function Invoke-Native([string]$exe, [string[]]$argv) { + & $exe @argv + if ($LASTEXITCODE -ne 0) { throw "$exe $($argv -join ' ') failed ($LASTEXITCODE)" } } -# 1. Verify inputs +function Get-Sha256([string]$path) { + (Get-FileHash -Algorithm SHA256 -LiteralPath $path).Hash.ToLowerInvariant() +} + +function Write-Utf8([string]$path, [string]$text) { + [IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false)) +} + +function Resolve-Zstd { + @( + (Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source), + (Join-Path $Msys2 'usr\bin\zstd.exe'), + (Join-Path $Msys2 'clang64\bin\zstd.exe') + ) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1 +} + +function New-TarZst([string]$parent, [string]$name, [string]$archive) { + $zstd = Resolve-Zstd + if (-not $zstd) { throw 'zstd not found (install MSYS2 zstd or put zstd.exe on PATH)' } + $tar = Join-Path $TempRoot "$name.tar" + Invoke-Native 'tar.exe' @('-cf', $tar, '-C', $parent, $name) + Invoke-Native $zstd @('-T0', "-$ZstdLevel", '-q', '-f', $tar, '-o', $archive) + Remove-Item -LiteralPath $tar -Force +} + +# ── 1. Inputs and provenance ───────────────────────────────── $ctlExe = Join-Path $CargoBin 'reims-ctl.exe' $utilExe = Join-Path $CargoBin 'reims-util.exe' $qemuExe = Join-Path $QemuDir 'bin\qemu-system-x86_64.exe' foreach ($p in @($ctlExe, $utilExe, $qemuExe)) { - if (-not (Test-Path -LiteralPath $p)) { - throw "Required runtime binary not found: $p" - } + if (-not (Test-Path -LiteralPath $p)) { throw "Required runtime binary not found: $p" } } -$commit = (git -C $ReimsRepo rev-parse --short HEAD).Trim() -$fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim() +$commit = (git -C $ReimsRepo rev-parse --short HEAD).Trim() +$fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim() +$qemuRepo = Join-Path $ReimsRepo 'vendor\qemu' +$qemuCommit = (git -C $qemuRepo rev-parse HEAD).Trim() + +# reims-util's pinned commit is a constant in reims-ctl (crates/reims-ctl/src/reims_util.rs, REV). +$utilSrc = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'crates\reims-ctl\src\reims_util.rs') +if ($utilSrc -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found in reims_util.rs' } +$utilCommit = $Matches[1] + +# metal2vulkan's git rev as built (Cargo.lock in the build tree). +$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock') +if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.lock' } +$m2vCommit = $Matches[1] + $qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim() $utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim() +# ── 2. Patches must equal the build tree's diffs ───────────── +$patchSpecs = @( + @{ Name = 'reims-vgpu-cargo-lock.patch'; Target = 'reims-vgpu'; Repo = $ReimsRepo; Paths = @('Cargo.lock') }, + @{ Name = 'qemu-whpx-win10-compat.patch'; Target = 'vendor/qemu'; Repo = $qemuRepo; Paths = @() } +) +$patches = @() +foreach ($ps in $patchSpecs) { + $file = Join-Path $patchesDir $ps.Name + if (-not (Test-Path -LiteralPath $file)) { throw "Patch missing: $file" } + $argv = @('-C', $ps.Repo, '-c', 'core.autocrlf=false', 'diff') + $ps.Paths + $treeDiff = (& git @argv | Out-String).Replace("`r`n", "`n") + $patchText = [IO.File]::ReadAllText($file).Replace("`r`n", "`n") + if ($treeDiff.TrimEnd() -ne $patchText.TrimEnd()) { + throw "$($ps.Name) does not match the build tree's diff in $($ps.Repo). Stop: don't edit patches automatically (AGENTS.md rule 4)." + } + $patches += [ordered]@{ name = $ps.Name; target = $ps.Target; sha256 = (Get-Sha256 $file) } +} +# Anything else changed in the build trees is undeclared: refuse. +$otherCtl = @(git -C $ReimsRepo status --porcelain --ignore-submodules=all | Where-Object { $_ -notmatch 'Cargo\.lock$' }) +$otherQemu = @(git -C $qemuRepo status --porcelain --untracked-files=no | Where-Object { $_ -notmatch 'target/i386/whpx/whpx-all\.c$' }) +if ($otherCtl.Count -or $otherQemu.Count) { + throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu -join "`n")" +} + $bundleName = "reims-runtime-win-x64-$commit" -$stageRoot = Join-Path $TempRoot "pack-$bundleName" +$srcName = "reims-runtime-src-$commit" +$stageRoot = Join-Path $TempRoot "pack-$commit" $bundleDir = Join-Path $stageRoot $bundleName - +$srcDir = Join-Path $stageRoot $srcName if (Test-Path -LiteralPath $stageRoot) { Remove-Item -Recurse -Force -LiteralPath $stageRoot } -New-Item -ItemType Directory -Force -Path "$bundleDir\bin", "$bundleDir\qemu", "$bundleDir\licenses", $OutDir | Out-Null +New-Item -ItemType Directory -Force -Path "$bundleDir\bin", "$bundleDir\qemu", "$bundleDir\licenses", "$bundleDir\patches", $srcDir, $OutDir | Out-Null -Write-Host "==> Staging $bundleName ..." +# ── 3. Runtime bundle ──────────────────────────────────────── +Write-Host "==> Staging $bundleName ($Channel)" Copy-Item -LiteralPath $ctlExe -Destination "$bundleDir\bin\reims-ctl.exe" Copy-Item -LiteralPath $utilExe -Destination "$bundleDir\bin\reims-util.exe" - -# Resolve junction target so robocopy/copy gets real files cleanly $resolvedQemu = (Get-Item -LiteralPath $QemuDir).Target if (-not $resolvedQemu) { $resolvedQemu = $QemuDir } Copy-Item -Path "$resolvedQemu\*" -Destination "$bundleDir\qemu" -Recurse -Force -# Copy NOTICE.md and upstream license(s) -$repoRoot = Split-Path -Parent $PSScriptRoot Copy-Item -LiteralPath (Join-Path $repoRoot 'NOTICE.md') -Destination "$bundleDir\NOTICE.md" -$upstreamLicense = Join-Path $ReimsRepo 'LICENSE' -if (Test-Path -LiteralPath $upstreamLicense) { - Copy-Item -LiteralPath $upstreamLicense -Destination "$bundleDir\licenses\reims-vgpu-LICENSE.txt" +foreach ($ps in $patchSpecs) { Copy-Item -LiteralPath (Join-Path $patchesDir $ps.Name) -Destination "$bundleDir\patches\" } +Copy-Item -LiteralPath (Join-Path $patchesDir 'README.md') -Destination "$bundleDir\patches\README.md" +$licenses = @{ + 'reims-vgpu-LICENSE.txt' = (Join-Path $ReimsRepo 'LICENSE') + 'qemu-COPYING.txt' = (Join-Path $qemuRepo 'COPYING') + 'qemu-COPYING.LIB.txt' = (Join-Path $qemuRepo 'COPYING.LIB') } -$qemuLicense = Join-Path $ReimsRepo 'vendor\qemu\COPYING' -if (Test-Path -LiteralPath $qemuLicense) { - Copy-Item -LiteralPath $qemuLicense -Destination "$bundleDir\licenses\qemu-COPYING.txt" +foreach ($k in $licenses.Keys) { + if (Test-Path -LiteralPath $licenses[$k]) { Copy-Item -LiteralPath $licenses[$k] -Destination (Join-Path "$bundleDir\licenses" $k) } +} +if (Test-Path -LiteralPath (Join-Path $ReimsRepo 'LICENSES')) { + Copy-Item -Path (Join-Path $ReimsRepo 'LICENSES\*') -Destination "$bundleDir\licenses\" -Recurse -Force } -# 2. Compute file inventory & key hashes +# MSYS2 CLANG64 DLLs: owning package and version, and where its source is. +Write-Host '==> Listing MSYS2 packages of bundled DLLs' +$bash = Join-Path $Msys2 'usr\bin\bash.exe' +$dlls = @(Get-ChildItem -LiteralPath "$bundleDir\qemu\bin" -Filter '*.dll' -File | Sort-Object Name) +$pkgLines = [Collections.Generic.List[string]]::new() +$pkgSet = [ordered]@{} +foreach ($d in $dlls) { + $owner = (& $bash -lc "LC_ALL=C pacman -Qqo /clang64/bin/$($d.Name) 2>/dev/null" | Select-Object -First 1) + if ($owner) { + $ver = (& $bash -lc "LC_ALL=C pacman -Q $owner" | Select-Object -First 1).Split(' ')[1] + $pkgLines.Add("$($d.Name)`t$owner`t$ver") + $pkgSet["$owner $ver"] = $true + } else { + $pkgLines.Add("$($d.Name)`t(not from an MSYS2 package: built with qemu, source in the source package)`t-") + } +} +$msysText = @" +# DLLs bundled in qemu/bin and the MSYS2 CLANG64 packages they come from +# (pacman -Qo on the build machine, $(Get-Date -Format 'yyyy-MM-dd')). +# +# Sources for each package version: +# https://repo.msys2.org/mingw/sources/ (-.src.tar.zst, by pkgbase) +# https://github.com/msys2/MINGW-packages (build recipes) +# Licenses: see each package's /clang64/share/licenses// in MSYS2. + +DLL`tPACKAGE`tVERSION +$($pkgLines -join "`n") + +# Packages ($($pkgSet.Count)) +$($pkgSet.Keys -join "`n") +"@ +Write-Utf8 "$bundleDir\MSYS2-PACKAGES.txt" $msysText + +# ── 4. Source bundle ───────────────────────────────────────── +Write-Host "==> Staging $srcName" +function Export-GitTree([string]$repo, [string]$rev, [string]$dest) { + New-Item -ItemType Directory -Force -Path $dest | Out-Null + $tar = Join-Path $TempRoot ("git-export-" + [guid]::NewGuid() + '.tar') + Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $rev) + Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $dest) + Remove-Item -LiteralPath $tar -Force +} +Export-GitTree $ReimsRepo $fullCommit (Join-Path $srcDir "reims-vgpu-$commit") +Export-GitTree $qemuRepo $qemuCommit (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu") +# QEMU's meson wraps downloaded for this build (dtc, keycodemapdb, ...): part of what was built. +Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory | + Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } | + ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force } + +$checkouts = Join-Path $CargoHome 'git\checkouts' +$utilTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'reims-util-*' | ForEach-Object { Join-Path $_.FullName $utilCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +$m2vTree = Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' | ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 +if (-not $utilTree) { throw "reims-util source at $utilCommit not found under $checkouts" } +if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found under $checkouts" } +Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))") +Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))") + +New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null +Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\" +Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt" +Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md" +Write-Utf8 "$srcDir\README.md" @" +# Source for $bundleName + +Corresponding source for the binaries in ``$bundleName.tar.zst``. + +| Directory | Upstream | Commit | +| :-- | :-- | :-- | +| ``reims-vgpu-$commit/`` | https://github.com/steelbrain/reims-vgpu | ``$fullCommit`` | +| ``reims-vgpu-$commit/vendor/qemu/`` | https://github.com/steelbrain/qemu-reims-vgpu | ``$qemuCommit`` | +| ``reims-util-$($utilCommit.Substring(0, 7))/`` | https://github.com/steelbrain/reims-util | ``$utilCommit`` | +| ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | https://github.com/steelbrain/metal2vulkan | ``$m2vCommit`` | + +The trees are pristine upstream. The binaries were built after applying the +patches in ``patches/``: + + cd reims-vgpu-$commit && git apply ../patches/reims-vgpu-cargo-lock.patch + cd vendor/qemu && git apply ../../../patches/qemu-whpx-win10-compat.patch + +(``patch -p1`` works too.) Then build as upstream documents (``scripts/install-ctl.sh`` +in an MSYS2 CLANG64 shell). The DLLs in ``qemu/bin`` come from the MSYS2 +packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources. +"@ + +# ── 5. Manifest (schema 2) ─────────────────────────────────── $allFiles = Get-ChildItem -LiteralPath $bundleDir -Recurse -File -$rawBytes = ($allFiles | Measure-Object Length -Sum).Sum -$dllCount = @(Get-ChildItem -Path "$bundleDir\qemu\bin\*.dll" -ErrorAction SilentlyContinue).Count - -$keyFiles = @( - 'bin/reims-ctl.exe', - 'bin/reims-util.exe', - 'qemu/bin/qemu-system-x86_64.exe', - 'qemu/bin/qemu-img.exe', - 'qemu/bin/reims-vgpu-compile.exe' -) +$keyFiles = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe', 'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe') $hashes = [ordered]@{} foreach ($rel in $keyFiles) { $fp = Join-Path $bundleDir ($rel -replace '/', '\') - if (Test-Path -LiteralPath $fp) { - $hashes[$rel] = (Get-FileHash -Algorithm SHA256 -LiteralPath $fp).Hash.ToLowerInvariant() - } + if (Test-Path -LiteralPath $fp) { $hashes[$rel] = Get-Sha256 $fp } } - $manifest = [ordered]@{ - schema_version = 1 - name = $bundleName - platform = 'windows-x86_64' - upstream_repo = 'https://github.com/steelbrain/reims-vgpu' - commit = $commit - full_commit = $fullCommit - qemu_version = $qemuVersionLine - util_version = $utilVersionLine - built_at = (Get-Date).ToString('o') - file_count = $allFiles.Count - dll_count = $dllCount - raw_bytes = $rawBytes - sha256 = $hashes + schema_version = 2 + name = $bundleName + platform = 'windows-x86_64' + upstream_repo = 'https://github.com/steelbrain/reims-vgpu' + commit = $commit + full_commit = $fullCommit + vendor_qemu_commit = $qemuCommit + util_commit = $utilCommit + metal2vulkan_commit = $m2vCommit + patches = $patches + channel = $Channel + source_package = "$srcName.tar.zst" + qemu_version = $qemuVersionLine + util_version = $utilVersionLine + built_at = (Get-Date).ToString('o') + file_count = $allFiles.Count + 1 + dll_count = $dlls.Count + raw_bytes = ($allFiles | Measure-Object Length -Sum).Sum + sha256 = $hashes } -$manifest | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath "$bundleDir\manifest.json" -Encoding utf8 +Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5) -# 3. Compress -$zstd = Resolve-Zstd -$archivePath = $null -if ($zstd) { - $tarPath = Join-Path $stageRoot "$bundleName.tar" - $archivePath = Join-Path $OutDir "$bundleName.tar.zst" - Write-Host "==> Creating tar archive..." - & tar.exe -cf $tarPath -C $stageRoot $bundleName - if ($LASTEXITCODE -ne 0) { throw "tar.exe failed with exit code $LASTEXITCODE" } - Write-Host "==> Compressing with zstd (level $ZstdLevel, multi-threaded)..." - & $zstd -T0 -$ZstdLevel -f $tarPath -o $archivePath - if ($LASTEXITCODE -ne 0) { throw "zstd failed with exit code $LASTEXITCODE" } -} else { - $archivePath = Join-Path $OutDir "$bundleName.zip" - Write-Host "==> zstd not found; compressing with Compress-Archive (.zip)..." - Compress-Archive -Path $bundleDir -DestinationPath $archivePath -Force -} +# ── 6. Archives and sums ───────────────────────────────────── +Write-Host '==> Compressing runtime' +$runtimeArchive = Join-Path $OutDir "$bundleName.tar.zst" +New-TarZst $stageRoot $bundleName $runtimeArchive +Write-Host '==> Compressing sources' +$srcArchive = Join-Path $OutDir "$srcName.tar.zst" +New-TarZst $stageRoot $srcName $srcArchive -$archiveSizeMB = [math]::Round((Get-Item -LiteralPath $archivePath).Length / 1MB, 1) -$rawSizeMB = [math]::Round($rawBytes / 1MB, 1) -$archiveHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $archivePath).Hash.ToLowerInvariant() -"$archiveHash $(Split-Path -Leaf $archivePath)" | Set-Content -LiteralPath "$archivePath.sha256" -Encoding ascii +$rtHash = Get-Sha256 $runtimeArchive +$srcHash = Get-Sha256 $srcArchive +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" -# 4. Clean staging dir Remove-Item -Recurse -Force -LiteralPath $stageRoot -Write-Host "" -Write-Host "==> Done!" -ForegroundColor Green -Write-Host " Archive : $archivePath" -Write-Host " Raw : $rawSizeMB MB ($($allFiles.Count) files, $dllCount DLLs)" -Write-Host " Packed : $archiveSizeMB MB (ratio $([math]::Round($archiveSizeMB / $rawSizeMB * 100, 1))%)" -Write-Host " SHA256 : $archiveHash" +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)" diff --git a/setup.go b/setup.go new file mode 100644 index 0000000..e5c9d0c --- /dev/null +++ b/setup.go @@ -0,0 +1,186 @@ +package main + +// First launch: the user picks the data folder before anything else is written +// (runtimes, VMs, installers and caches all live under it). + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/host" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +// DataRootChoice is a suggested data folder on one drive. +type DataRootChoice struct { + Path string `json:"path"` + FreeGB float64 `json:"free_gb"` + System bool `json:"system"` + External bool `json:"external"` // USB disk: may be unplugged while a VM runs + Recommended bool `json:"recommended"` +} + +// DataRootCheck describes a folder the user is about to choose. +type DataRootCheck struct { + Path string `json:"path"` + FreeGB float64 `json:"free_gb"` + System bool `json:"system"` + External bool `json:"external"` + HasConfig bool `json:"has_config"` // an earlier reims-go data folder: its VMs are kept + Error string `json:"error,omitempty"` +} + +// SuggestDataRoots offers \Data\reims-go on each fixed drive, the +// non-system drive with the most free space first. +func (a *App) SuggestDataRoots() []DataRootChoice { + var out []DataRootChoice + for _, d := range host.ListDrives() { + out = append(out, DataRootChoice{ + Path: filepath.Join(d.Root, "Data", "reims-go"), + FreeGB: d.FreeGB, + System: d.System, + External: d.External, + }) + } + // Internal non-system drives first, then the system drive, USB disks last; + // most free space first within each. A USB disk is never recommended. + rank := func(c DataRootChoice) int { + switch { + case c.External: + return 2 + case c.System: + return 1 + } + return 0 + } + sort.SliceStable(out, func(i, j int) bool { + if rank(out[i]) != rank(out[j]) { + return rank(out[i]) < rank(out[j]) + } + return out[i].FreeGB > out[j].FreeGB + }) + if len(out) > 0 && !out[0].External { + out[0].Recommended = true + } + return out +} + +// CheckDataRoot reports free space and whether dir already holds reims-go data. +func (a *App) CheckDataRoot(dir string) DataRootCheck { + dir = strings.TrimSpace(dir) + c := DataRootCheck{Path: dir} + if err := validateDataRoot(dir); err != nil { + c.Error = err.Error() + return c + } + c.FreeGB, _ = host.FreeGB(existingAncestor(dir)) + c.System = isSystemVolume(dir) + vol := strings.ToUpper(filepath.VolumeName(dir)) + for _, d := range host.ListDrives() { + if strings.EqualFold(d.Root[:2], vol) { + c.External = d.External + } + } + if _, err := os.Stat(filepath.Join(dir, "reims-go.json")); err == nil { + c.HasConfig = true + } + return c +} + +// CompleteSetup makes dir the data folder: creates its layout, keeps an +// existing reims-go config there (its runtimes and VMs), records the choice for +// the next launch and leaves first-launch setup. +func (a *App) CompleteSetup(dir string) error { + dir = filepath.Clean(strings.TrimSpace(dir)) + if err := validateDataRoot(dir); err != nil { + return err + } + a.mu.Lock() + locale := a.cfg.Locale + a.mu.Unlock() + + cfgPath := filepath.Join(dir, "reims-go.json") + cfg, err := config.Load(cfgPath) + if err != nil { + return fmt.Errorf("read %s: %w", cfgPath, err) + } + cfg.DataRoot = dir + if _, statErr := os.Stat(cfgPath); statErr != nil { + cfg.Locale = locale // a new folder keeps the language picked on this screen + } + if err := cfg.EnsureDirs(); err != nil { + return err + } + if err := writable(dir); err != nil { + return err + } + if err := config.Save(cfgPath, cfg); err != nil { + return err + } + if err := config.SaveLocation(dir); err != nil { + return err + } + a.mu.Lock() + a.cfg = cfg + a.needsSetup = false + a.mu.Unlock() + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } + return nil +} + +func validateDataRoot(dir string) error { + if dir == "" { + return errors.New("choose a folder") + } + if !filepath.IsAbs(dir) { + return fmt.Errorf("%s is not a full path", dir) + } + if filepath.Clean(dir) == filepath.VolumeName(dir)+string(filepath.Separator) || filepath.Dir(dir) == dir { + return errors.New("choose a folder, not a whole drive") + } + if strings.ContainsAny(dir, ",") { + // reims-ctl passes kext paths to reims-util as "PATH,MIN,MAX" and refuses ',' + // (upstream 3731afd reims_util.rs:308-317); the data folder holds them. + return errors.New("the folder path can't contain ','") + } + if info, err := os.Stat(dir); err == nil && !info.IsDir() { + return fmt.Errorf("%s is a file", dir) + } + return nil +} + +// existingAncestor is dir or its nearest existing parent (for free-space checks +// before the folder exists). +func existingAncestor(dir string) string { + for d := dir; ; d = filepath.Dir(d) { + if _, err := os.Stat(d); err == nil { + return d + } + if filepath.Dir(d) == d { + return d + } + } +} + +func isSystemVolume(dir string) bool { + sys := os.Getenv("SystemDrive") + vol := filepath.VolumeName(dir) + return sys != "" && vol != "" && strings.EqualFold(sys, vol) +} + +func writable(dir string) error { + f, err := os.CreateTemp(dir, ".write-test-*") + if err != nil { + return fmt.Errorf("can't write to %s: %w", dir, err) + } + name := f.Name() + f.Close() + return os.Remove(name) +}