diff --git a/.github/workflows/build_ios.yml b/.github/workflows/build_ios.yml
index d0539e474..51813a8c6 100644
--- a/.github/workflows/build_ios.yml
+++ b/.github/workflows/build_ios.yml
@@ -25,6 +25,9 @@ on:
permissions:
contents: read
+env:
+ SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64: ${{ vars.SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64 }}
+
jobs:
build_ios:
name: Build_iOS
diff --git a/.github/workflows/build_publish.yml b/.github/workflows/build_publish.yml
index 3ee1449a7..7258930d1 100644
--- a/.github/workflows/build_publish.yml
+++ b/.github/workflows/build_publish.yml
@@ -14,6 +14,9 @@ on:
permissions:
contents: read
+env:
+ SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64: ${{ vars.SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64 }}
+
jobs:
# Release publication is gated on metadata.yaml: clients resolve a channel to a release tag there
# and reject the release manifest when its tag/channel disagree, so a stale channel entry
diff --git a/.github/workflows/codeQL.yml b/.github/workflows/codeQL.yml
index 40a107950..73a82f3b0 100644
--- a/.github/workflows/codeQL.yml
+++ b/.github/workflows/codeQL.yml
@@ -6,6 +6,9 @@ on:
schedule:
- cron: "0 3 * * 1"
+env:
+ SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64: ${{ vars.SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64 }}
+
jobs:
analyze:
name: CodeQL 分析
diff --git a/AGENTS.md b/AGENTS.md
index eec8c4e9b..7043b98bb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -15,7 +15,7 @@ Maintenance contract:
- `docs/project_rules.md` is the source of truth when a convention conflicts with this summary.
-->
-**Last Update:** 2026-11-01
+**Last Update:** 2026-11-21
**Last Submit:** 51f7f7fd
**Last modified model:** MiMoCode
@@ -75,14 +75,16 @@ Nested instruction files:
| Settings navigation | `SecRandom/Views/SettingsView.axaml.cs` | Default page `settings.overview`; has back stack + restart dialog. General group now includes `settings.general.basic`, `settings.general.privacy`, `settings.general.backup`, and `settings.general.control`. |
| Page registration helpers | `SecRandom.Core/Extensions/Registry/` | `AddMainPage`, `AddSettingsPage`, group, and separator helpers. |
| ClassIsland notifications | `SecRandom/Services/Notification/`, `SecRandom4Ci.Interface/` | Typed v2 IPC client for the installed SecRandom4Ci ClassIsland plugin. |
-| Control-plane node (集控) | `docs/client-protocol.md`, `SecRandom.Core/Services/ControlNode/`, `SecRandom/Services/ControlNode/`, `SecRandom/Views/SettingsPages/General/ControlSettingsPage.axaml(.cs)` | v4.1 集控节点:WebSocket 打 `wss://sectl.cn/control/ws`(凭据放首帧 `hello.payload`,不在 URL/请求头),三分信封 `req`/`res`/`evt`;命令是 `evt cmd` + 两帧回执 `req cmd.ack`/`req cmd.result`(`id` 回填 `command_id`),`expires_at` 为 Unix 毫秒、过期即丢且不补投;期望状态 `evt desired_state` 带单调 `revision` 与 `draw_locked`(缺失按 true),客户端只接受严格更新的 revision 并把 `applied_state_revision` 落盘;接入是双因子「地点ID + 配对码」(`POST /control/api/enroll`),之后 `POST /control/api/device/tree` 拉年级/班级、`POST /control/api/device/assign` 保存,握手成功后用 `class.select`/`class.release` 占班(占班=上课=允许抽取);本地开关 `RemoteControlEnabled`(默认关)仍是最终否决权。协议规范、命令表与错误码以 `../SECTL-auth/docs/control-center-protocol-v4.md` 为唯一事实源;v1 的 `srn_` 令牌 / `group_id` / 单码接入已断代。 |
+| Official SDK integration | `SecRandom/Services/Integration/`, `SecRandom/Views/SettingsPages/Linkage/`, `../SecRandom-Integration-SDK/docs/integration-v1.md` | Local signed-SDK discovery, user-approved result channels, and floating-window linkage leases; verification requires the compiled ECDSA public key and a matching live IPC peer process. |
+| Control-plane node (集控) | `docs/client-protocol.md`, `SecRandom.Core/Services/ControlNode/`, `SecRandom/Services/ControlNode/`, `SecRandom/Views/SettingsPages/General/ControlSettingsPage.axaml(.cs)` | v4.1 集控节点:WebSocket 打 `wss://sectl.cn/control/ws`(凭据放首帧 `hello.payload`,不在 URL/请求头),三分信封 `req`/`res`/`evt`;命令是 `evt cmd` + 两帧回执 `req cmd.ack`/`req cmd.result`(`id` 回填 `command_id`),`expires_at` 为 Unix 毫秒、过期即丢且不补投;期望状态 `evt desired_state` 带单调 `revision` 与 `draw_locked`(缺失按 true),客户端只接受严格更新的 revision 并把 `applied_state_revision` 落盘;桌面被控节点有两条接入通道:双因子「地点ID + 配对码」(`POST /control/api/enroll`),或登录 SECTL 账号(`POST /control/api/device/enroll`,JWT + `device.enroll`;首次 operator、同机接管需 admin),两者写同一条接入记录;之后 `POST /control/api/device/tree` 拉年级/班级、`POST /control/api/device/assign` 保存,握手成功后用 `class.select`/`class.release` 占班(占班=上课=允许抽取);本地开关 `RemoteControlEnabled`(默认关)仍是最终否决权。平板与手机是纯账号控制台(`ControlCenterClient` 固定 `https://sectl.cn/control/api`,无配对码入口、无集控设置页),远程抽取页按 地点→年级→班级→该班 `occupancy["secrandom"]` 的在线占班设备下发 `draw.trigger`/`draw.reset`,结果只读回执 `payload.drawn`;点名/抽奖与名单下拉由只回名称的 `roster.list`(operator,v4.5)填充,设备不支持时回落默认名单。协议规范、命令表与错误码以 `../SECTL-auth/docs/control-center-protocol-v4.md` 为唯一事实源;v1 的 `srn_` 令牌 / `group_id` / 单码接入已断代。 |
| Crash recovery | `SecRandom/Services/CrashRecovery/`, `SecRandom/Views/CrashRecoveryWindow.axaml.cs` | Fatal/dispatcher crash report prompt, guarded auto-restart, and shared desktop relaunch logic. |
| Page registry state | `SecRandom.Core/Services/PagesRegistryService.cs` | Main/settings/group collections. |
| Cross-platform view engine | `SecRandom.Core/Views/` | Logical view/session contracts; desktop and mobile shells provide DI-registered physical hosts. |
| Fair draw logic | `SecRandom.Core/Services/Draw/` | Partial `DrawEngine`, weighted draw, filters, crypto RNG, plus `DrawCommitCoordinator` (`IDrawCommitService`) transactional commits and shared `DrawRepeatPolicy`/`DrawCandidateFilter`. |
-| History record groups (历史记录组) | `SecRandom.Core/Services/Profiles/HistoryGroupCatalog.cs`, `HistoryGroupName.cs`, `SecRandom/ViewModels/MainPages/{RollCall,Lottery}PageViewModel.cs`, `SecRandom/Views/SettingsPages/Picking/DefaultDrawSettingsPage.axaml(.cs)` | Optional per-purposes split of the same profile history: a draw can be locked to one record group so weights only read that group's records and new records land in it. `HistoryItem.HistoryGroup` (empty = default group) is orthogonal to `CourseName`, so the two filters intersect; `StudentHistory`/`PrizeHistory` keep the registered group list in `HistoryGroups`, and the group *selection* on a main page is transient UI state that is never persisted (a page starts from the persisted default record group — `RollCallSettingsConfig.HistoryGroup` / `LotterySettingsConfig.HistoryGroup`, empty = 默认记录组 — and then only the visible `ComboBox` changes during that session, so a stale selection can never silently keep filtering); hiding the selector always means "no group scope" (`null`). The configuration value and the runtime scope are separated by `HistoryGroupScope.Resolve` (`SecRandom.Core/Services/Profiles/HistoryGroupScope.cs`): feature off ⇒ `null`, blank ⇒ `""` (默认记录组), an existing name ⇒ that name, a deleted/renamed name ⇒ `""` plus a "原组已不存在" hint (deletion only moves records back to the default group), and an unreadable catalogue ⇒ `null` rather than narrowing weights to an unverifiable group. Off by default (`General.HistoryGroups.Enabled`), readable-but-not-writable through the control plane, and deliberately not a protected operation. |
+| Orchestrated draw (编排抽取) | `SecRandom.Core/Models/Orchestration/OrchestrationModels.cs`, `SecRandom.Core/Services/Orchestration/` (`OrchestrationOrdering`, `OrchestrationScheduler`, `OrchestrationStore`, `OrchestrationVerification`), `SecRandom.Core/Services/Draw/DrawModeSelection.cs`, `SecRandom/Views/SettingsPages/Picking/OrchestrationSettingsPage.axaml(.cs)`, `OrchestrationRulePageBase.axaml(.cs)`, `OrchestrationRulePages.cs`, `OrchestrationEditingSession.cs`, `SecRandom/Services/Draw/SharedDrawServices.cs`, `docs/orchestrated-draw.md` | `DrawMode.Orchestrated` is neither a page nor a repeat policy: the order is decided *before* the draw, so a round is "take the next participant" instead of sampling. It is therefore the third choice of each channel's 「抽取方式」 dropdown (随机抽取 / 公平抽取 / 编排抽取, id `DrawModeCatalog.OrchestratedOptionId = "builtin.orchestrated"`, deliberately not a registered sampling algorithm) and is gone from the 「抽取模式」 repeat dropdown. Selecting it still persists `DrawMode.Orchestrated`, because the draw side reads only that; `DrawModeSelection.SelectOrchestrated` first records the channel's previous repeat policy in `OverridableDrawSettings.SampledDrawMode`, and `LeaveOrchestrated` restores it when the user picks a sampling method again — without that, one spell of orchestration would silently flatten a 半重复 setting to 不重复. While orchestrated the channel pages keep the 抽取模式 card visible — its three-item dropdown is bound to `SampledDrawMode` (the remembered repeat policy, always a valid 0..2 index) rather than to the four-valued `DrawMode`, so picking 编排抽取 can never push `SelectedIndex` to an out-of-range 3 and blank the selection — and hide only the 公平抽取策略 card; `S_DrawMode`/`S_FairDrawMode` keep their x:Names for settings search. An 编排名单 is its own entity (`OrchestrationProfile`, `data/config/orchestration/{id}.json`, runtime in `runtime/{id}.json`, both atomic replaces, `FormatVersion = 2`) bound to one `(target, source list)` pair, keyed by roster `RecordId`; only one list per pair is active, and a missing source record is flagged `IsSourceMissing` instead of deleted. The profile is edited as **five separate lists**, not one mixed grid: 「排斥」is global (`OrchestrationMember.IsExcluded`), while 「权重」/「延后」/「顺序」/「必中」 are per round (`OrchestrationRound.Weights`/`Skipped`/`Order`/`Guaranteed`, sparse, up to 10 rounds). `OrchestrationProfile.Rules` holds one switch per list and is the only place the lists can be muted: a list switched off keeps its data but stops participating, and 「顺序」and 「必中」are **mutually exclusive switches** (`SetEnabled` turns the other off) because both answer "who goes first" — with both populated in a hand-edited file, 必中 wins and the queue only seats the remainder, so nobody is seated twice. Ordering is a **queue**, not a set of absolute slots: `OrchestrationOrdering.Resolve` drops excluded/deferred/already-drawn members, puts the guaranteed group (internally by effective weight, stable) or else the round queue in front, then fills the rest by weighted sampling without replacement (`DrawEngine.CalculateStudentWeight`, manual weight is a multiplier clamped 0–100 that never changes the zero set) and finally the zero-weight tail by draw count descending, so nobody is ever dropped from a round. Because every draw re-resolves with the round's already-drawn members, a member queued third really comes out third after the first two leave, instead of being re-seated third inside the shrinking remainder. The old absolute-position `Pins` list survives only as a migration input: `OrchestrationStore.Normalize` (called on load and save) folds its positions into `Order` in pin order and then drops the field; it also clamps `RoundCount`, fills missing lists, and filters ids whose member is gone. The settings page is an **overview**, not an editor: command bar (当前名单 drawer / 新建 / 同步 / 名单设置 / 启用·停用), round row, channel-status strip, five `FASettingsExpander` cards that only carry a one-line summary each plus a 设置 button, and a separate `FASettingsExpander` of five `ToggleSwitch` rows for the rule switches. Each card jumps to its own **hidden** sub-page (`settings.picking.orchestration.{exclude,weight,defer,order,guarantee}`, `isHide: true`, never in the sidebar or settings search), and the five sub-pages share `OrchestrationRulePageBase` (`OrchestrationRulePages.cs` declares the five `[PageInfo]` classes): header + round picker + rule hint + search/count toolbar + a member list whose rows are toggles, a weight box, or position numbers with up/down buttons — so a member's 排斥/延后/权重/位置 is edited in exactly one place and `OrchestrationMemberDrawer` no longer exists. The overview hands `(profileId, round)` to the sub-page through `OrchestrationEditingSession` instead of letting a hidden page guess its context, and reloads on return so a sub-page save is visible immediately. The editor drawer (`OrchestrationEditorDrawer.axaml(.cs)`) still creates/rebinds a profile and immediately imports the source roster's members. A channel-status strip names the bound channel's draw mode through the same `Effective*Settings` the draw itself reads, warns when the selected list is not active, and offers 切换为编排抽取 that goes through `DrawModeSelection.SelectOrchestrated` on `RollCallSettingsConfig`/`LotterySettingsConfig` (so the previous repeat policy is kept for when the user switches back) — a list whose channel is not orchestrated would otherwise look perfectly enabled and never be read. 随机顺序 / 复制到其他轮 / 清空名单 live on the 顺序 sub-page (clear removes only that one list), and every write goes through the profile mutators (`SetExcluded`/`SetSkipped`/`SetGuaranteed`/`SetOrder`/`SetWeight`) so the cross-list invariants hold even in a hand-edited file. Because those mutators silently dissolve a conflicting entry in another list, every click that would do so asks first: a `FAContentDialog` lists the lists (and rounds) that will be cancelled, 取消 restores the `OneWay`-bound checkbox, 随机顺序 / 复制到其他轮 warn when 必中 members would be moved out, and the overview's 顺序/必中 switches say which sibling they will close. The proof is still generated: `SequentialOrder`(4) sampling with `StudentOrchestrated`(19)/`LotteryOrchestrated`(20) commits the positions in the candidate weight slot, and the audit carries only `fairness.orchestration = {round, roundCount}` (e.g. engine v3.6.0, see `docs/proof-orchestration-protocol.md`). Roll call, quick draw, and lottery all take the same branch and advance the round when the round is exhausted or reset; with no active 编排名单 the channel falls back silently to the ordinary random draw, and the main pages expose no orchestration state. |
+| Random-number draw settings (随机数抽取) | `SecRandom.Core/Models/SubConfigs/Picking/RandomNumberSettingsConfig.cs`, `SecRandom/Views/SettingsPages/Picking/RandomNumberSettingsPage.axaml(.cs)`, `SecRandom.Core/Services/Stats/RandomNumberStatisticsService.cs`, `SecRandom/Views/SettingsPages/HomeSettingsPage.axaml(.cs)` | The independent page for the former 不使用名单 mode: it owns only the two default ranges and the reset behavior, never roster history. Number draws write no `HistoryItem`; the only durable record is `data/history/random-number/stats.json` (`SecRandomRandomNumberStats/v1`), written after a successful number commit. Its `Ranges` list accumulates a draw count and last-draw time per `(start,end)` range; the 100-row `Recent` list is retained only for compatibility and legacy derivation. The overview reads `Ranges` and shows one row per range (range, draw count, last draw) — never individual drawn numbers or per-draw results. `RandomNumberResetBehavior.TemporaryOnly` (default) clears only `__number_list__`/`__number_prize_pool__`; `TemporaryAndStatistics` also clears that stats file, while roster history is never touched. Ranges are clamped to `RosterSelection.MaxNumberRangeSpan` and the main pages apply the configured defaults at construction. |
+| History record groups (历史记录组) | `SecRandom.Core/Services/Profiles/HistoryGroupCatalog.cs`, `HistoryGroupName.cs`, `SecRandom/ViewModels/MainPages/{RollCall,Lottery}PageViewModel.cs`, `SecRandom/Views/SettingsPages/Picking/DefaultDrawSettingsPage.axaml(.cs)` | Optional per-purposes split of the same profile history: a draw can be locked to one record group so weights only read that group's records and new records land in it. `HistoryItem.HistoryGroup` (empty = default group) is orthogonal to `CourseName`, so the two filters intersect; `StudentHistory`/`PrizeHistory` keep the registered group list in `HistoryGroups`, and the group *selection* on a main page is transient UI state that is never persisted (a page starts from the persisted default record group — `RollCallSettingsConfig.HistoryGroup` / `LotterySettingsConfig.HistoryGroup`, empty = 默认记录组 — and then only the visible `ComboBox` changes during that session, so a stale selection can never silently keep filtering); hiding the selector always means "no group scope" (`null`). The configuration value and the runtime scope are separated by `HistoryGroupScope.Resolve` (`SecRandom.Core/Services/Profiles/HistoryGroupScope.cs`): feature off ⇒ `null`, blank ⇒ `""` (默认记录组), an existing name ⇒ that name, a deleted/renamed name ⇒ `""` plus a "原组已不存在" hint (deletion only moves records back to the default group), and an unreadable catalogue ⇒ `null` rather than narrowing weights to an unverifiable group. Off by default (`General.HistoryGroups.Enabled`), readable-but-not-writable through the control plane, and deliberately not a protected operation. The scope above is a **read** decision only: `HistoryGroupScope.ResolveRecordGroup` (same file, and deliberately **without** the feature switch) decides the marker each channel *writes*, so a channel whose draw is not group-scoped still stamps its own configured default group — turning the feature off must never fold 点名/闪抽/抽奖/编排 into the default group, because switching it back on could not undo that. |
| Config persistence | `SecRandom.Core/Services/Config/`, `SecRandom.Core/Services/HistoryStore/` | `FileConfigService` and handlers are host-internal Core runtime services; desktop keeps its existing package-root data path. v3 backup/archive transfer lives in `SecRandom.Core/Services/Archive/` (`DataArchiveService`). **Profile history is the one exception to JSON**: each list/pool history is a small SQLite database (`data/history/{roll_call_history,lottery_history}/{name}.srhdb`) read and written by `ProfileHistoryDatabase`, because a history file grows without bound while the JSON handler rewrote the whole file on every save (three times per draw). `StudentHistoryConfig`/`PrizeHistoryConfig` only override the `ConfigHandlerBase` storage seams (`LoadData`/`SaveData`/`DeleteData`); every path decision (exists / enumerate / rename / delete) must go through `ProfileHistoryPaths`, never a hand-built `{name}.json`. Saves are incremental — each record row carries a content fingerprint (`row_hash`), so a draw only writes the changed member plus its new rows. The switch is transparent: the first read of a profile imports its legacy `{name}.json` into the database and renames it to `{name}.json.migrated`, which no `*.json` reader matches, so archives stay readable and the old file survives as a one-time rollback copy. |
-| Account cloud backup | `SecRandom/Services/ImportExport/CloudBackupService.cs`, `SecRandom/Services/ImportExport/CloudAutomaticBackupService.cs`, `SecRandom/Services/Auth/SectlCloudStorageClient.cs`, `SecRandom.Core/Services/Archive/CloudBackupPackage.cs` | Desktop and mobile account cloud sync over the SECTL personal cloud API: `CloudBackup` archives split into verified parts plus a trailing manifest, cloud listing/delete, and verified download before the normal v3 restore. Every upload carries a device alias (`BackupConfig.CloudDeviceAlias`; when empty, the mobile heads' device label — Android/iOS report `localhost` as their host name — and otherwise the host name) that labels the cloud list and scopes retention per device. `CloudAutomaticBackupService` is the hosted service behind the separate `BackupConfig.CloudAutoBackup*` cadence and retention settings. Cloud backups are uploaded as the plain v3 archive: there is deliberately no client-side encryption and no passphrase, so account access is the only key and any signed-in device can restore every backup. |
| Audit tooling | `scripts/FairnessAudit/` | Standalone fairness/performance validation script and HTML report generator. |
| Release history dataset | `scripts/ReleaseHistory/`, `docs/release-history/` | Multi-sheet XLSX over GitHub Releases + `CHANGELOG/` + local git: version timeline, per-release highlights, adjacent-version deltas, removed/downgraded features, contributors, star growth, asset download counts. Refresh with `powershell -File scripts/ReleaseHistory/update-release-history.ps1`, then `verify_workbook.py`. Star timelines need a logged-in `gh` CLI; manual conclusions live in `docs/release-history/curated/annotations.json`. |
| Release update signing | `scripts/ReleaseManifest/`, `scripts/validate-release-metadata.ps1`, `.github/workflows/build_publish.yml`, `.github/workflows/build_ios.yml` | Ed25519 key-generation helper and CI manifest signer; private key is Actions-secret-only. Release intermediates and final artifacts are grouped under `artifacts/release/`. The channel gate validates `metadata.yaml` against the release tag before every build. iOS builds out of band and then attaches the IPA, a re-signed manifest, and a refreshed release note to the release the publish job created (`scripts/ReleaseManifest/Update-ReleaseManifest.ps1`). |
@@ -113,6 +115,7 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo
| `CrashRecoveryRuntime` | app service helper | `SecRandom/Services/CrashRecovery/CrashRecoveryRuntime.cs` | Reads crash recovery mode, writes bounded crash reports, and builds restart process plans. |
| `ISecurityService` | app service contract | `SecRandom/Services/Security/` | Owns credential verification, lockout policy, selected-factor authorization, and protected-operation gating. |
| `ProtocolCommandRouter` | app service | `SecRandom/Services/Ipc/ProtocolCommandRouter.cs` | Normalizes URL/IPC routes, routes protected commands, and returns structured IPC results. |
+| `IntegrationChannelService` | app service | `SecRandom/Services/Integration/IntegrationChannelService.cs` | Verifies official SDK process proofs, discovers/persists approved local notification channels, forwards committed draws, and tracks IPC linkage leases. |
| `DeviceUuidStore` | app service | `SecRandom/Services/Config/DeviceUuidStore.cs` | Persists the pseudo-anonymous device UUID separately in `data/config/device-uuid.json` and migrates legacy settings values. |
| `AttachedSettingsRegistryService` | registry | `SecRandom.Core/Services/AttachedSettingsRegistryService.cs` | Static collections for attached-settings controls. |
| `ViewModelBase` | base VM | `SecRandom/ViewModels/ViewModelBase.cs` | Base VM exposing `MainConfig`; inherits `ObservableRecipient`. |
@@ -135,9 +138,6 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo
| `LoopbackAuthCallbackPage` | app renderer | `SecRandom/Services/Auth/LoopbackAuthCallbackPage.cs` | The one browser page the desktop loopback broker answers the OAuth redirect with: a self-contained document (inline CSS, inline 96×96 app icon as base64, no script, no second request) whose light/dark follows the **browser** through `prefers-color-scheme`, because it is not an Avalonia window and cannot read the in-app theme. Its copy lives in `SecRandom/Langs/Auth/` (three languages, `C_` keys) and says "back in SecRandom", never "signed in": `SectlAuthService` writes this response *before* it validates `state` and exchanges the code. Only a short lowercase `error` code is echoed, and only on the failure state. |
| `SectlHeartbeatService` | hosted app service | `SecRandom/Services/Auth/SectlHeartbeatService.cs` | OAuth device heartbeat for desktop and mobile: reports immediately for a signed-in session and then every five minutes. |
| `SectlCloudStorageClient` | app service | `SecRandom/Services/Auth/SectlCloudStorageClient.cs` | Typed client for the SECTL personal cloud API (`/api/cloud/*`): platform-scoped listing, base64 upload, short-lived download URLs, delete, and quota, with service error codes preserved. |
-| `CloudBackupService` | app service | `SecRandom/Services/ImportExport/CloudBackupService.cs` | Account cloud-sync orchestration: packages a `CloudBackup` archive, uploads verified parts plus a trailing manifest, lists/groups cloud backups, verifies and rebuilds a download, deletes parts before the manifest, and purges incomplete backups. Every upload stamps this device's alias into the backup id, retention keeps only this device's own surplus, and `UploadAutomaticAsync` is the only path that frees account space. It uploads the archive as produced — client-side encryption was removed, so account access is the only key — and exposes `DeviceTag`/`IsOwnBackup` so a consumer can tell this device's backups from another machine's. A package the removed feature uploaded keeps its `IsEncrypted` name marker: it stays listed (and deletable) but `CanRestore` is false, because this build holds no way to derive its key. |
-| `CloudAutomaticBackupService` | hosted app service | `SecRandom/Services/ImportExport/CloudAutomaticBackupService.cs` | Automatic cloud backup on the `BackupConfig.CloudAutoBackup*` cadence, on desktop and mobile; follows this device's own newest cloud upload and keeps each signed-in device inside its own retention limit, while an exhausted quota still removes the account-wide oldest backup. |
-| `CloudBackupPackage` | domain helper | `SecRandom.Core/Services/Archive/CloudBackupPackage.cs` | Cloud backup part/manifest format: file naming, backup-id generation with the optional device alias, backup-id safety and alias parsing, splitting, manifest validation, and per-part plus whole-archive SHA-256 merging. Schema 1 is the only supported version: the parts carry the v3 ZIP archive itself. The removed feature's `-enc` name marker is still parsed so a schema-2 package from an older build is recognised and refused (its manifest is rejected by the schema check) instead of being mis-grouped as a current backup. |
| `PlatformUsageReportService` | app service | `SecRandom/Services/PlatformUsageReportService.cs` | Hosted reporter for the SECTL usage counters (`daily_roll_call_count` family); counts draws after a successful commit and app launches at startup, gated by `OnlineStatusMode`, and posts through the aggregate reporting entrance `PlatformStatsApi.ReportUri`. |
| `UsageMetricCounter` | domain helper | `SecRandom.Core/Services/Stats/UsageMetricCounter.cs` | Pure current-local-day event counters plus the pinned `platform_id`/`field_key`/`delta` increment payload shape (no time field: the service stamps receive time; no `value`, which would be judged as a last-value field report). |
| `PlatformVersionReportService` | hosted app service | `SecRandom/Services/PlatformVersionReportService.cs` | Hosted version-usage reporter: one best-effort report per start carrying the build version plus the device UUID only, posted to the aggregate reporting entrance (where `version` is what makes it a version report), run on the thread pool so startup is never delayed, and deliberately not gated by `OnlineStatusMode`. |
@@ -151,6 +151,7 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo
- Selecting `TopmostMode.UiAccess` for the primary or floating window persists the setting and requests a restart. `SecRandom.Desktop/UiAccessStartup` is the Windows-only pre-Avalonia launcher boundary: following `killtimer0/uiaccess`, it elevates a bootstrap process, impersonates same-session `winlogon.exe`, sets `TokenUIAccess` on a duplicate of the bootstrap's current token, and starts the UIAccess replacement before Avalonia initializes. The original process waits only for the bootstrap to create the replacement, never for Avalonia or Host initialization; denied elevation, preparation failure, or timeout keeps the original process in ordinary topmost and preserves the configured mode for a later retry.
- Windows UIAccess topmost builds may use `SecRandom.Desktop/app.uiaccess.manifest` when `EnableUiAccess=true`; that manifest requires Authenticode signing and installation under Program Files. Independently, the runtime `UiAccessStartup` token preparation follows `killtimer0/uiaccess` and works from the ordinary manifest after UAC authorization, so debug and portable Windows builds can exercise UIAccess as well. The release workflow enables the manifest only when Windows code-signing secrets are available.
- Point-call students and lottery prizes use `RecordId` as the internal stable identity for history/fairness. The visible `Id` field is optional display metadata only and must not be required by import, draw, or history logic.
+- Zero lists is a normal state, not an error: every list and prize pool may be deleted, including the last one. `ProfileService` seeds one blank `default` list/pool only on the first run (`MainConfigModel.General.Basic.GuideCompleted == false`) and only while that directory has no `*.json`; once the guide is complete an empty directory stays empty across restarts, because `ResolveProfileName` returns `null` instead of falling back to `"default"`. With no lists, `StudentListConfig`/`StudentHistoryConfig`/`PrizeListConfig`/`PrizeHistoryConfig` are all `null` (so `Current*` are `null` too); `Load*Profile(string.Empty)` means "detach the active profile" (`Clear*Profile`), `ProfileCatalogManager.Delete{Student,Prize}List` calls it when the deleted profile was the last one, and `SetDefault{StudentList,PrizePool}` accepts an empty name to clear a default that pointed at a deleted list. All consumers must keep working through the nullable `IProfileService` contract (`?.`/`?? []`); never reintroduce a "at least one list must remain" guard. UI consequence: list-management pages show their `C_NoList`/`C_NoList_D` empty state, and the draw-settings default roster/pool cards hide themselves (`DefaultRosterSettingSource.HasRosters`) instead of offering an empty picker.
- A roll-call student or lottery prize candidate must be enabled and have a nonblank `Id` or `Name`. Import may map either column and excludes rows where both are blank.
- Picking `ClearRecord` controls temporary draw records only; do not clear persistent profile histories from that setting. RollCall and QuickDraw share the same student temporary record store, while Lottery uses prize temporary records.
- Privacy settings split Sentry upload from online status reporting: `SentryTelemetryEnabled` only controls `SecRandom/Services/Telemetry/`, while `OnlineStatusMode` gates the SECTL online-status and usage-counter channels (`SecRandom/Services/OnlineStatusService.cs`, `PlatformUsageReportService`) but deliberately not `PlatformVersionReportService`.
@@ -159,27 +160,27 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo
- All SECTL statistics reporting goes through the one aggregate entrance `PlatformStatsApi.ReportUri` (`POST /api/stats/report`), never a per-type endpoint: the four old endpoints (`/api/stats/online`, `/api/stats/usage/increment`, `/api/stats/version`, `/api/fields/values`) are compatibility-only and must not be reintroduced. The service judges the report type from the payload keys and stops at the first hit — (1) `field_key` **and** `value` → field, (2) `version`/`app_version` → version, (3) `metrics`/`increments`/`usage`/`delta`/`metric_key` → usage, (4) anything else carrying `platform_id`/`device_uuid` → online — and answers `400` when nothing matches. That judgment is why the payload shapes are load-bearing rather than cosmetic: posting the right fields to the wrong old endpoint, or adding a field of an earlier rule (a `value` in an increment, a `version` in a heartbeat), does not fail, it silently books the number under another figure. Keep `PlatformStatsReportEntranceTests` matching the documented order if the API's rule ever changes.
- Telemetry access is seam-based: runtime code depends on `ITelemetryTransaction` / `ITelemetrySdkAdapter` and must not reference Sentry types directly (the DSN lives in `GlobalConstants.SentryDsn`). `TelemetryRuntimeService` is Sentry-free; the desktop-only `TelemetryTransactionSentryExtensions` shim is excluded from mobile builds, while mobile links the same telemetry sources, adds `MobileProfilingIntegrationStub`, and owns its Sentry DI/init/shutdown plus Android/iOS unhandled-exception hooks.
- The pseudo-anonymous device UUID belongs in `data/config/device-uuid.json`; legacy settings values are migration-only and must not be serialized back into `settings.json`. Full-data and configuration backups include this file, while settings-only exports do not overwrite a device identity.
-- ClassIsland notifications require the installed `SecRandom4Ci` v2 plugin. `NotificationService` uses the local `SecRandom4Ci.Interface` contract and `ClassIsland.IPC.v2.Server`; it must not use loopback TCP. SecRandom's built-in notification channel is the existing QuickDraw result window, shared by roll-call, QuickDraw, and lottery notifications. Each draw channel only controls whether it is enabled; `NotificationSettings.Default` owns the one global service, duration, threshold, fallback, and built-in auto-close configuration. `UseBuiltInOnServiceFailure` is the backend-neutral fallback policy for a selected external notification service and defaults to enabled; current ClassIsland-only delivery uses it when v2 IPC fails. For automatic QuickDraw delivery, the built-in or dual service opens this window before the draw to show the rolling animation and then its result; external-only delivery must not open the QuickDraw window unless the fallback runs. Notification settings must not duplicate the QuickDraw window's placement, opacity, or draw-animation controls.
+- ClassIsland notifications require the installed `SecRandom4Ci` v2 plugin. `NotificationService` uses the local `SecRandom4Ci.Interface` contract and `ClassIsland.IPC.v2.Server`; it must not use loopback TCP. SecRandom's built-in notification channel is the existing QuickDraw result window, shared by roll-call, QuickDraw, and lottery notifications. Each draw channel only controls whether it is enabled; `NotificationSettings.Default` owns the one global service, duration, threshold, fallback, and built-in auto-close configuration. `UseBuiltInOnServiceFailure` is the backend-neutral fallback policy for a selected external notification service and defaults to enabled; current ClassIsland-only delivery uses it when v2 IPC fails. For automatic QuickDraw delivery, the built-in or dual service opens this window before the draw to show the rolling animation and then its result; external-only delivery must not open the QuickDraw window unless the fallback runs. Notification settings must not duplicate the QuickDraw window's draw-animation controls. The built-in notification floating window's geometry — position, monitor, horizontal/vertical offset, and opacity — is global, edited only on the separate `settings.notification.floatingWindow` page (`NotificationFloatingWindowSettingsPage`, registered directly above `settings.notification.fullscreen`) and stored once on `NotificationSettings.Default`; channel pages keep only enable, animation, notification service, display duration, and the main-window threshold. The position row on that page is a dropdown field (`SecRandom.Core/Controls/AnchorGridDropDown`) whose collapsed text is the current position's localized name and whose flyout holds the 3×3 dot grid (`SecRandom.Core/Controls/AnchorGridPicker`, styled by the paired `Controls/AnchorGridPicker.axaml` and `Controls/AnchorGridDropDown.axaml`) instead of a list of five text options: `NotificationWindowPosition` defines nine anchors — `Center`/`Top`/`Bottom`/`Left`/`Right` keep the legacy values 0–4 and the four corners are appended as 5–8, so no saved position ever moves to another cell — and both that page and `App.TryResolveQuickDrawNotificationTargetRect` read `NotificationWindowAnchorLayout` (`GridOrder` for the cell order, `Resolve` for the horizontal/vertical anchor), so the grid order and the window geometry cannot drift apart. Picking a dot writes the anchor back into the field's text and closes the flyout (arrow keys browse the grid while it stays open), and the offsets still fine-tune any anchor. Its auto-close countdown presentation is global on that same default channel too: `CountdownStyle` picks the text hint or the default outline, and the outline is one continuous 6px rounded ring that starts on the top edge just after the top-left corner and is eaten clockwise as the remaining time runs out — the same start point and sweep direction as the floating window's long-press progress ring (`BorderedProgressRing`), never four separately shrinking bars. The outline's colors are edited as three sibling cards on that page (color mode, gradient, single color): the gradient card holds exactly two `ColorPicker`s — `CountdownGradientStart` and `CountdownGradientEnd`, laid side by side with no connector glyph and no add/remove affordance — and fills every ring segment from the window's horizontal position so the self-coloured loop has no seam; `CountdownSolidColor` is the uniform alternative with no preview swatch of its own, and both color cards are hidden while the text hint is selected. The per-channel `OverridableNotificationChannelSettings.OverrideNotificationWindowSettings` is a legacy field that `FloatingWindowSettingsUnifiedInitialized` folds back to `false` when the settings file loads, so no channel can hold a window geometry the user can no longer see or edit.
- Crash recovery mode lives under `MainConfigModel.General.CrashRecovery`; prompt startup handling must run before single-instance acquisition, while normal restart must release the single-instance service before relaunch. `CrashRecoverySettingsConfig.DisableCrashedPlugin` (default enabled) gates the plugin crash auto-disable path: when a dispatcher unhandled exception stack belongs to a plugin load context, that plugin is marked `.disabled` for the next startup; the toggle lives beside the crash-recovery mode in the basic settings page.
- First-run OOBE is a top-level window shown immediately after `BuildHost()` and before floating-window/main-app initialization. Its carousel begins with a non-blocking, centered welcome screen with the application icon; it is outside the eight configuration pages, whose first item places the collapsed-by-default verifiable-draw notice before the privacy-policy and GPLv3 acknowledgement controls, and whose last three are desktop integration, 集控 (control node), and privacy in that order. The control-node page sits between desktop integration and privacy on purpose: it and desktop integration are both device-local "how this machine is reached" settings that never touch `settings.json`, while privacy is "what this machine sends out" and must stay the final page that asks the user to decide something. That page binds the device-owned switch, display name, node ID, and group ID straight through `IControlNodeStateStore` (`data/config/control/node-state.json`, so an import can never turn remote control on) plus the control-platform link, and it deliberately shows **no** live connection status — the node's hosted service only starts after the OOBE closes and the Host starts, so the page states when the node connects instead of pretending to know. Each acknowledgement requires explicit confirmation. The welcome page owns the lower-left language selector; changing it persists the language, refreshes ViewModel-derived localized values, then recreates only the OOBE visual tree into localized resources without restarting or leaving the first-run flow. An active import drawer defers the visual replacement until its preview/mapping flow closes. `GuideCompleted`, `AcceptedVerificationNoticeVersion`, `AcceptedPrivacyPolicyVersion`, and `AcceptedGplVersion` determine whether an OOBE acknowledgement is required. After the full guide has completed, a verifiable-draw notice, privacy-policy, or GPL version update opens only the acknowledgement page and its privacy controls, not unrelated setup pages. OOBE class/prize spreadsheet imports reuse the list-management import controls in its own right-side drawer, so their file mapping, preview, duplicate handling, and cancel behavior stay aligned with the settings list pages. Completing OOBE continues into normal startup and explicitly opens the primary main window; it must not exit merely because the OOBE window closes. Verifiable-draw notice, privacy-policy, and GPL changes increment their app-layer OOBE versions independently.
-- Floating-window startup visibility is owned by `App.ApplyFloatingWindowStartupVisibility()` and must never be left to the Avalonia lifetime. `ClassicDesktopStyleApplicationLifetime.StartCore` shows `MainWindow` **exactly once, unconditionally** (`ShowMainWindow()` is called only there and does not check visibility), so normal startup depends on that single show — while the deferred paths (first-run OOBE, settings-integrity gate) reach `App.ContinueDesktopStartup` *after* the lifetime already started and therefore get no show at all, which is how the floating window silently stayed invisible after the OOBE. Turning 启动时显示悬浮窗 off cannot be expressed by `Hide()` before `Start()` either, because `Window.Hide()` returns immediately for a window that was never shown; the hide is instead posted after the lifetime's show and gated on `UserWantsVisible`, so a tray re-open during that instant is respected and a course-linkage-hidden window is not restored. 左右两侧同时显示(默认关闭,`FloatingWindowSettings.ShowOnBothSides`)由 `App.ApplyFloatingWindowLayout()` 在运行时布置:开启后主窗钉右、副窗钉左,两扇窗都只能纵向移动,关掉开关后保留右侧那扇主窗,副窗的纵向锚点单独持久化在 `FloatingWindowSettings.SecondaryAnchorCenterY`(绝不写共享的 `FloatPosition`),且副窗跟随主窗的显示/隐藏与课程联动状态;设置改变或配置 `Reloaded` 后都会重新布置。两侧高度统一(默认开启,`FloatingWindowSettings.SyncBothSidesAnchor`,只在左右两侧同时显示开启时才出现)让两扇窗共用同一个纵向锚点:`App.AlignFloatingWindowAnchors()` 在布置与开关切换后把一侧的锚点对齐给另一侧,拖动过程中由 `App.SyncFloatingWindowAnchor()` 调 `FloatingWindow.ApplyUnifiedAnchor()` 实时跟随;关闭后两侧各记各的高度。
+- Floating-window startup visibility is owned by `App.ApplyFloatingWindowStartupVisibility()` and must never be left to the Avalonia lifetime. `ClassicDesktopStyleApplicationLifetime.StartCore` shows `MainWindow` **exactly once, unconditionally** (`ShowMainWindow()` is called only there and does not check visibility), so normal startup depends on that single show — while the deferred paths (first-run OOBE, settings-integrity gate) reach `App.ContinueDesktopStartup` *after* the lifetime already started and therefore get no show at all, which is how the floating window silently stayed invisible after the OOBE. Turning 启动时显示悬浮窗 off cannot be expressed by `Hide()` before `Start()` either, because `Window.Hide()` returns immediately for a window that was never shown; the hide is instead posted after the lifetime's show and gated on `UserWantsVisible`, so a tray re-open during that instant is respected and a course-linkage-hidden window is not restored. 左右两侧同时显示(默认关闭,`FloatingWindowSettings.ShowOnBothSides`)由 `App.ApplyFloatingWindowLayout()` 在运行时布置:开启后主窗钉在它原本那一侧、副窗补到另一侧(哪侧算"原本"由 `FloatingWindow.IsOnLeftSide` 按当前钉边/停靠状态或窗口中心与工作区中线判定),两扇窗都只能纵向移动,关掉开关后保留原本那一侧的主窗(原本在左就回左边、原本在右就留在右边),副窗的纵向锚点单独持久化在 `FloatingWindowSettings.SecondaryAnchorCenterY`(绝不写共享的 `FloatPosition`),且副窗跟随主窗的显示/隐藏与课程联动状态;设置改变或配置 `Reloaded` 后都会重新布置。两侧高度统一(默认开启,`FloatingWindowSettings.SyncBothSidesAnchor`,只在左右两侧同时显示开启时才出现)让两扇窗共用同一个纵向锚点:`App.AlignFloatingWindowAnchors()` 在布置与开关切换后把一侧的锚点对齐给另一侧,拖动过程中由 `App.SyncFloatingWindowAnchor()` 调 `FloatingWindow.ApplyUnifiedAnchor()` 实时跟随;关闭后两侧各记各的高度。
- Settings JSON, full-data ZIP, and backup restore only accept manifest/envelope exports produced by SecRandom v3. Validate `producer_version` before taking an import snapshot or changing data; unsupported sources must be explained in a modal dialog. `producer_version` is the raw `GlobalConstants.Version`, so it keeps a SemVer pre-release/build suffix (`v3.0.0-alpha.2`); the gate must strip that suffix and compare only the numeric core's major, never feed the raw value to `Version.TryParse` — otherwise a pre-release build rejects the archives it produced itself.
- Security credentials must never be stored in `MainConfigModel` or `settings.json`. Keep passwords, TOTP seeds, USB binding tokens, and lockout state in `SecRandom/Services/Security`'s separate credential store; ordinary settings only select factors and protected operations. The sole credential file is `data/config/security/credentials.json`: its internal `FormatVersion` is authoritative, uses Argon2id-derived key material plus AES-256-GCM for portable storage, and must not depend on DPAPI, Keychain, `secret-tool`, or a versioned filename. Do not read or migrate older credential files. `SecurityCredentialStore` restricts the whole `data/config/security` directory to the current user once per process and on every save (Unix `0700` directory with `0600` files and temporary files; Windows breaks ACL inheritance and keeps only the current user plus SYSTEM and Administrators), because that directory also holds the readable `totp-standalone.json` copy; the hardening is best-effort and must never leave the directory unreadable to the app itself. Lockout state deliberately stays outside the AES-GCM authenticated data — a failed attempt happens without the encryption key, so `FailedAttempts`/`LockedUntilUtc` must remain writable through `SaveMetadata`, which also means anyone who can rewrite the credential file can reset the lockout: the lockout only restrains callers that cannot write that file.
- The security settings themselves are no longer in `settings.json`. `SecuritySettingsConfig` (protection master switch, factor selection, protected operations, Sudo, integrity check) lives in `data/config/security/settings.json` through the app-layer `SecuritySettingsStore`: an AES-256-GCM envelope (`FormatVersion`/`Nonce`/`Tag`/`Ciphertext`, authenticated with the fixed `SecRandom/SecuritySettings/v1` associated data) plus a device-local random 256-bit key in the sibling `settings.key`. `MainConfigModel` no longer declares the property; a set-only `security_settings` bridge captures the legacy plaintext block once so the first run of this build migrates it and then rewrites `settings.json` to drop it. The read rules are load-bearing: a file that exists but cannot be decrypted, or a file that is gone while a security password is configured, must **not** fall back to "protection off" — the store returns maximal protection (`SecurityEnabled` plus every `Protect*`, with the factor flags left to the credential-derived `NormalizeSettings`) and sets `IsIntegrityCompromised`, so editing or deleting the file is never a way to turn protection off. A fresh install with no credentials still writes defaults with protection off, and the legacy bridge is consumed only while the encrypted file is absent, so neither a later `settings.json` edit nor an imported archive can re-specify these switches. The device key is what makes this work without a password prompt at startup — "should this operation verify?" must be answerable before any verification happens — so it shares the credential directory's owner-only hardening instead of the password-derived key; anyone who can read that directory can forge the settings, the same boundary as rewriting `credentials.json` to reset the lockout.
- Because the protection switches left `settings.json`, `ControlSettingsCatalog` no longer describes a `security` category at all (it used to be described-but-read-only), so the control plane can neither read nor write them. The archive pre-import gate was reworked to match: `IArchivePreImportGuard.AuthorizeImport()` takes no candidate and asks the host for one fresh verification (no sudo state counts) whenever protection is active, so importing a settings file or restoring a backup stays a protected operation even though no archive can carry the switches any more. Export is deliberately not gated: automatic and cloud backups run in the background where no dialog can be raised. The whole `data/config/security` directory — now also holding the protection switches — stays excluded from every export, cloud backup, and the Android provider.
- While `SecuritySettingsConfig.RequireAllSelectedFactors` is off ("any selected method" mode) every selected factor verifies on its own, and TOTP cannot be checked without its seed, so that mode keeps a password-free seed copy in the sibling `data/config/security/totp-standalone.json` (written only while the mode is off and TOTP is configured; deleted when the mode turns on or the password is removed). The directory stays excluded from every export, cloud backup, and the Android provider, and the settings description discloses the trade-off. Never move that copy into `credentials.json`: its AES-GCM authentication data covers only `FormatVersion`, the password credential, `HasTotp`, and USB bindings, so a readable seed field there would be read before any authentication and would silently bypass the existing tamper detection.
-- `SecuritySettingsConfig.SettingsIntegrityCheckEnabled` (desktop-only, password-gated) records a SHA-256 fingerprint of the whole `data/config/settings.json` in the credential envelope's plaintext `SettingsIntegrity` record on every `MainConfigHandler.Save()`/`Reload()`, and `App` verifies it before desktop startup. A mismatch routes through `SettingsIntegrityAction`: `Confirm` (the default) keeps the confirmation gate that requires the security password before the app continues, otherwise it exits; `AutoRestore` hands startup to `SettingsIntegrityRecoveryService`, which walks the newest `data/backup/*.zip` and/or account cloud backups per the separately configured `SettingsIntegrityRestoreSource` (`Local` / `LocalThenCloud` / `CloudThenLocal`), takes `config/settings.json` from the first supported v3 archive that actually carries a loadable settings payload, copies the current file to `data/backup/integrity/settings_before_restore_*.json`, atomically replaces it, reloads the handler (which refreshes the fingerprint), and restarts the app; only the settings file is touched, and a failed recovery keeps the original file and falls back to the password gate with the failure reason. Cloud candidates go through `SettingsIntegrityRecoveryService.OrderCloudCandidates`, which keeps *only* backups uploaded by this device (`CloudBackupService.IsOwnBackup`, newest first) and drops every other machine's: a settings file describes the machine it came from, so another device's backup is never a restore source, not even as a last resort. When this device has no own cloud backup the cloud source yields nothing (the skip is logged), recovery stays with `data/backup`, and otherwise the original file is kept and startup falls back to the password gate. The fingerprint needs existing security credentials as its anchor, is cleared when protection is turned off, and — because it lives outside the AES-GCM authenticated data — detects accidental or casual edits rather than a determined local attacker who can rewrite both files. Because the switch itself now lives in the encrypted security-settings file, `SettingsIntegrityService` also subscribes to `SecuritySettingsStore.Saved`: toggling the check no longer writes `settings.json`, so that event is what records or clears the fingerprint — without it the check could be turned on and still never have a recorded digest.
- OmniTTS cloud speech API keys are credentials too: they live in `data/config/voice/omnitts-keys.json` via `OmniTtsCredentialStore` (app-layer, atomic replace), never in `VoiceSettingsConfig`/`settings.json`, IPC payloads, logs, telemetry, backups, or the Android DocumentsProvider. OmniTTS is voice engine 2 (`OmniTtsSpeechProvider.OmniEngine`), sits beside System SAPI (0) and Edge TTS (1), and is a unified cloud TTS engine whose providers are OpenAI, Gemini, FishAudio, MiMo, and Custom OpenAI-compatible. OpenAI, Gemini, and MiMo voice choices use documented preset sets; Gemini uses native `/v1beta/interactions` synthesis and wraps its 24 kHz PCM response as WAV. MiMo voice-design and voice-clone models use model-specific chat-completions payloads; clone references are WAV files kept privately under `data/config/voice/mimo-voice-reference.wav`, identified by a hash, and excluded from settings, archives, IPC, and logs. Models are fetched from provider APIs or typed manually. The voice settings page shows OmniTTS-specific rows (provider, base URL, key, model, voice, batch cache) only while `VoiceEngine == 2`. `data/config/voice/` is excluded from archives and protected from the Android provider/directory launcher. iOS keeps the voice settings page unregistered (`!OperatingSystem.IsIOS()`); OmniTTS targets Windows, Linux, macOS, and Android.
- Security authorization always flows through `ISecurityService`; do not add direct validation checks to tray handlers, windows, ViewModels, or linkage code. Passwords require at least 6 characters, with no artificial character-class rule. Strength feedback is advisory only: the password editor renders `PasswordStrengthEvaluator` (`SecRandom.Core/Services/Security/PasswordStrength/`, zxcvbn-style dictionary/pattern guess-count bands), and that score must never become a save gate — a rule-shaped "must contain X" meter is the same artificial constraint this section forbids.
- Sudo mode is opt-in but on by default (`SecuritySettingsConfig.SudoModeEnabled`); turning it off makes every protected operation verify again. While it is on, a successful verification skips re-verification for `SudoModeDurationSeconds` (default 20s, 10–600s in the security page). The global timer covers draw/window/restart/exit/shortcut/IPC operations, while the settings window keeps a separate timer that is renewed by every verified settings update and ends when the duration elapses **or** the settings window closes, whichever comes first. Sudo never covers protection-loosening changes: `UpdateSecuritySettingsAsync` diffs the security settings with `SecuritySettingsSnapshot.IsProtectionDowngrade`, and a downgrade (turning security off, clearing a factor, disabling the settings-integrity check, switching the integrity action to automatic restore, turning a protection off, or lengthening the sudo duration) requires a fresh password verification that neither the settings-window sudo nor the global timer can satisfy; that fresh verification then authorizes further downgrades for one sudo duration so a single editing session does not re-prompt for every switch. `BypassClassTimeRestriction` and `ChangeSecuritySettings` are deliberately immune to every sudo state, so a confirmed non-class-time restriction can never be bypassed by an open sudo window. TOTP setup (`BeginTotpSetupAsync`), TOTP removal (`RemoveTotpAsync`, which clears the seed from the credential envelope, deletes the `totp-standalone.json` copy, discards any unconfirmed pending setup, and turns the factor off), password changes, and USB binding always require fresh verification too. The tray menu exposes an "Exit Sudo Mode" option (visible while any sudo state is active) that calls `DeactivateSudoMode()` and therefore clears both the global timer and the settings-window authorization. Every security-setting control on the security page — including the Sudo switch and duration — must write through `UpdateSecuritySettingsAsync`; never mutate the security-settings model directly and save it, because `UpdateSecuritySettingsAsync` is what performs the fresh verification and `SecuritySettingsStore` is what writes the encrypted file.
- Full IPC/URL compatibility is app-layer routed through `ProtocolCommandRouter`: structured current-user named-pipe IPC is additive to legacy `ShowMainWindow`/`Restart`/`Url:` delivery, and all external mutations must use `ISecurityService`. `data/*` queries must use non-mutating profile snapshots, never active-profile loading APIs.
- `HistoryItem.DrawRoundId` identifies every record committed by one logical draw. Populate it for new history writes; IPC history projections group by it and must never expose internal `RecordId`.
-- History record groups (历史记录组) are an optional second history dimension beside `HistoryItem.CourseName`, never a replacement: on the record `HistoryGroup` (empty marker = the default group) is set when the record is written and both filters apply together, so a gated draw reads and writes the intersection. The scope parameter is deliberately **tri-state** (`string? historyGroup`): `null` means do not filter on the group axis at all (feature off or selector hidden = the pre-#294 behaviour, every record counts), `""` means the default group only (records whose marker is empty, which is what the panel's 默认记录组 option selects), and a name means that one group. Collapsing `null` and `""` re-introduces the original unfairness in the other direction, because the option labelled 默认记录组 would then count records that were explicitly sorted into another group. `DrawEngine`'s history caches, `IProfileService.Record*History`, `IDrawCommitService` commit records, and `VerificationDrawCoordinator` carry the value as a trailing optional parameter — nothing in the weight calculator changes, because filtering the cache already yields the group-local counts. Deliberate limits: temporary draw records are bucketed per history record group (one bucket for "not scoped by a group", one for the default group, one per group name), so a group-scoped draw's repeat limit counts exactly the records it can see and switching groups never inherits another group's counts; renaming a group merges its bucket and deleting one folds it into the default bucket, while prize temporary records stay per prize pool because they carry physical inventory. The group name is the identity (renaming rewrites markers, and `HistoryGroupName` rejects blank/over-long/control/reserved names such as the `__break__` course sentinel), and the group *selection* is transient UI state — it is never persisted, and hiding the selector always means "no group scope" (`null`, i.e. every record counts again), so a stale selection can never silently keep filtering. The switch and the group create/rename/delete management live on the history-management settings page (`SecRandom/Views/SettingsPages/History/HistoryManagementSettingsPage.axaml(.cs)`), not on a draw-settings page, and the main panels expose only the selector. Moving records between groups goes through `IProfileCatalogManager.Move{Student,Prize}HistoryGroup` (marker-only, no new record, no `DrawRoundId`) and never through `IDrawCommitService`. Enabling the feature is not a protected operation, the switch is readable-but-not-writable through the control plane, and downgrading to a build without it silently folds grouped records back into the global history.
+- History record groups (历史记录组) are an optional second history dimension beside `HistoryItem.CourseName`, never a replacement: on the record `HistoryGroup` (empty marker = the default group) is set when the record is written and both filters apply together, so a gated draw reads and writes the intersection. The scope parameter is deliberately **tri-state** (`string? historyGroup`): `null` means do not filter on the group axis at all (feature off or selector hidden = the pre-#294 behaviour, every record counts), `""` means the default group only (records whose marker is empty, which is what the panel's 默认记录组 option selects), and a name means that one group. Collapsing `null` and `""` re-introduces the original unfairness in the other direction, because the option labelled 默认记录组 would then count records that were explicitly sorted into another group. `DrawEngine`'s history caches, `IProfileService.Record*History`, `IDrawCommitService` commit records, and `VerificationDrawCoordinator` carry the value as a trailing optional parameter — nothing in the weight calculator changes, because filtering the cache already yields the group-local counts. Deliberate limits: temporary draw records are bucketed per history record group (one bucket for "not scoped by a group", one for the default group, one per group name), so a group-scoped draw's repeat limit counts exactly the records it can see and switching groups never inherits another group's counts; renaming a group merges its bucket and deleting one folds it into the default bucket, while prize temporary records stay per prize pool because they carry physical inventory. The group name is the identity (renaming rewrites markers, and `HistoryGroupName` rejects blank/over-long/control/reserved names such as the `__break__` course sentinel), and the group *selection* is transient UI state — it is never persisted, and hiding the selector always means "no group scope" (`null`, i.e. every record counts again), so a stale selection can never silently keep filtering. The switch and the group create/rename/delete management live on the history-management settings page (`SecRandom/Views/SettingsPages/History/HistoryManagementSettingsPage.axaml(.cs)`), not on a draw-settings page, and the main panels expose only the selector. Moving records between groups goes through `IProfileCatalogManager.Move{Student,Prize}HistoryGroup` (marker-only, no new record, no `DrawRoundId`) and never through `IDrawCommitService`. Enabling the feature is not a protected operation, the switch is readable-but-not-writable through the control plane, and downgrading to a build without it silently folds grouped records back into the global history. Read scope and write marker are separate values on every commit: `HistoryGroup` stays the tri-state **read** scope, while `RecordGroup` (and `StudentRecordGroup` for the students assigned by a lottery round, whose records live in the student history rather than the prize history) is the **write** marker and is resolved by `HistoryGroupScope.ResolveRecordGroup`, which never takes the feature switch — `DrawCommitCoordinator` uses `RecordGroup ?? HistoryGroup`, so every existing caller keeps its old behaviour byte-for-byte, and `RollCallSession`/`LotterySession` (mobile), `RollCallDrawService`/`LotteryDrawService` and `QuickDrawPageViewModel` always pass one, so a channel that is not group-scoped still writes its own configured default group instead of collapsing into the default one.
+- Moving records between groups (`IProfileCatalogManager.Move{Student,Prize}HistoryGroup`) is a marker-only operation and must never go through `IDrawCommitService`. Its optional trailing `sourceGroup` scopes the rewrite to one record group (`null` = every record of the selected member, `""` = only the default group, a name = that group), because a history page filtered to a group must not silently rewrite the member's records sitting in other groups; the returned count is the number of `HistoryItem`s whose marker changed, and `0` leaves the file byte-identical. The selection unit is the member's `RecordId` — every record of one member shares it — so a summary/overview row is movable too, which is why `HistoryDisplayRow.RecordId` is populated for overview rows as well. Creating a group is not part of moving: the move flyout offers only the default group plus existing groups, and create/rename/delete stays on `HistoryManagementSettingsPage`. The lottery page shows its record-group selector even without an assigned student list: nothing is isolated then, but the chosen name still tags the prize records it writes (a number-only draw writes no history at all and therefore hides the selector).
- Draw commits must go through `IDrawCommitService` (`DrawCommitCoordinator`): one logical draw gets exactly one `DrawRoundId` (a caller may supply one), temporary records commit before persistent history, a mid-commit failure rolls back through snapshot compensation, and commits serialize behind the coordinator gate. Never reintroduce bare two-step writes of `IProfileService.Record*History` plus temporary-record calls; the optional `drawRoundId` parameter (and `drawMethod` on `RecordPrizeHistory`) exists for coordinator use. Preview frames write no temporary record and no history: the coordinator is the only writer of the fairness surface, and the weight/filter/verification layers read persistent history only, so an animation that flickers through a hundred names can neither record a hit nor shift a weight. A preview shuffles with `Random.Shared` while the draw samples through the injected `IRandomSource` (`CryptoRandomSource`), so animation frames cannot consume or bias the draw's random stream. `SecRandom.Core.Tests/PreviewAnimationFairnessTests.cs` pins all three claims, including a reflection guard that the presentation contracts expose no commit or temporary-record surface.
- File persistence saves are atomic replacements: `FileConfigService.SaveConfig` and `DrawTemporaryRecordService.SaveState` write a temporary file and atomically replace the target; new file-persistence code must follow the same pattern instead of overwriting files in place. Profile history is stored in SQLite (`ProfileHistoryDatabase`) instead: it saves inside one transaction, so a crash rolls back to the previous complete history, and it never needs the temp-file dance. Do not hand-build history paths — `ProfileHistoryPaths` owns the database, the not-yet-migrated JSON and the `.json.migrated` backup for a profile.
-- Draw proofs use the SecRandom v3 algorithm ID and an `algorithmEngineVersion`. Engine v3.1 commits the sampling mode into the request: student draws use history-balanced weighted sampling, count-based lottery inventory uses equal-probability partial permutation when no internal rule applies, and pan or internal-rule lottery draws use weighted sampling without replacement. Keep the verifier's replay logic byte-compatible with each supported proof engine version. Engine v3.4.0 does not change the replay mathematics at all — it only marks that the `fairness` block may carry `historyScope` — but the service side must be deployed **before** a client build sends that generation, exactly like a new audit field: a 3.3-generation verifier replays the same proof and reads the narrowed per-candidate `historyCount` values as global history. `fair.sectl.cn` accepts 3.4/3.3/3.2 as the current algorithm family, 3.1 as the previous family, and 3.0 as the oldest, and keeps replaying every previously issued generation.
+- Draw proofs use the SecRandom v3 algorithm ID and an `algorithmEngineVersion`. Engine v3.1 commits the sampling mode into the request: student draws use history-balanced weighted sampling, count-based lottery inventory uses equal-probability partial permutation when no internal rule applies, and pan or internal-rule lottery draws use weighted sampling without replacement. Keep the verifier's replay logic byte-compatible with each supported proof engine version. Engine v3.4.0 does not change the replay mathematics at all — it only marks that the `fairness` block may carry `historyScope` — but the service side must be deployed **before** a client build sends that generation, exactly like a new audit field: a 3.3-generation verifier replays the same proof and reads the narrowed per-candidate `historyCount` values as global history. `fair.sectl.cn` accepts 3.6/3.5/3.4/3.3/3.2 as the current algorithm family, 3.1 as the previous family, and 3.0 as the oldest, and keeps replaying every previously issued generation. Engine v3.6.0 adds the orchestrated generation: `samplingMode` 4 (`SequentialOrder`) reads the arranged position out of the weight slot (`weightMicros = 1..count`, dense and unique, no random material consumed), `algorithmProfile` 19/20 (`StudentOrchestrated`/`LotteryOrchestrated`) is compatible only with that sampler, and the anonymous audit declares the mode as `fairness.repeatMode = "orchestrated"` plus `fairness.orchestration = { round, roundCount }` — counters only, never the schedule, positions, names, or weights. Deploy the service before a client build sends 3.6: an older version chain rejects it outright. The four draw-mode tokens live in `SecRandom.Core/Enums/Configs/DrawModeCatalog.cs`, which is the only client-side spelling of them.
- Ordinary draws immediately save an `OfflineReproducible` proof, then submit that newly generated proof to `fair.sectl.cn` for background replay/signing. A submission must use the proof object captured at draw time and never a re-read of the proof file: `DrawProofAttestationService` keeps the pending item in memory, persists only its path, proof ID, and canonical proof hash to `data/proofs/attestation-queue.json`, retries failures with bounded exponential backoff, resumes queued items after a restart, and refuses plus reports an item whose file no longer matches the recorded hash (it then keeps the receipt in the queue instead of overwriting the changed file). Startup must never scan or re-attest historical proof files that were never queued. A current server receipt signs a canonical hash of all proof fields except the receipt itself, plus the proof ID, input hash, payload hash, anonymous audit-payload hash, and mode; public sharing requires that receipt. This detects changes after the signed submission, but it does not attest to an unmodified local executable, an authentic real-world candidate pool, or absence of pre-draw result selection. Do not call it a pre-draw server witness. Local proof retention applies both the configured age and total storage limits; after every new save, delete oldest `.srproof.json` files until the configured storage cap is met.
-- `data/proofs` carries a local append-only evidence chain: `DrawProof.Chain` stores `index`/`prevHash`/`selfHash` (`selfHash = SHA256("SecRandomProof/v3/chain" ‖ index ‖ prevHash ‖ canonicalProofHash)`), and `ProofChainStore` keeps the head plus a `retainedFromIndex` floor in `data/proofs/chain-head.json`. Retention and storage-limit cleanup must record every proof they delete through `RecordRemovedIndices`, so an absence below the floor is explained and only an unrecorded prefix/interior gap is reported; the floor may only advance across a contiguous prefix of recorded removals, because a sparse deletion (removing index 10 while 1-9 survive) would otherwise explain away every hole below it; storage-limit cleanup must also never delete the proof the same save just wrote, since that leaves the chain head pointing at a file that never landed and hands the attestation queue a path that no longer exists; `ProofIntegrityVerifier` is the only reader that judges the chain. Chain fields and `witness.timestampToken` must never enter `WitnessClient.ComputeAttestedProofHash` — the server recomputes that hash, so adding fields there invalidates every receipt. A local chain buys visibility, not protection: an attacker who controls the machine can rebuild chain and head consistently.
+- Proof files under `data/proofs` are plain `OfflineReproducible` `.srproof.json` documents. The local append-only evidence chain was removed: `DrawProof.Chain`, `ProofChainStore` (`data/proofs/chain-head.json`), `RecordRemovedIndices` cleanup notes, and `ProofIntegrityVerifier`. Receipts issued before the removal stay valid because `WitnessClient.ComputeAttestedProofHash` never covered chain fields — so never add them back to that hash, and do not re-introduce a chain reader or a verification-page chain button.
- The anonymous audit payload is validated by `fair.sectl.cn` against a fixed property allow-list (`ValidateAnonymousAuditPayload` / `ValidateFairness`), so adding a field there requires the server change to land first — the client must never ship a new audit field before the service accepts it, or every ordinary attestation fails with `audit_payload_invalid`. `rosterDigest` was added that way: `RosterDigest.Compute` hashes the canonical RecordId-to-display mapping (entries sorted by record id, so reordering is not a change while renaming, renumbering, regrouping, or disabling is) of the roster the draw was taken from, and `VerificationDrawCoordinator` omits it when the active profile is not the drawn list. It is the only commitment that ties a winning record id back to a person, because the candidate pool itself is anonymous — without it, editing the list after the draw silently re-points a winning record id at someone else while every receipt, replay check, and time stamp still validates. Only the digest leaves the device, never names or numbers; the digest of a low-entropy roster does allow someone who already knows nearly the whole list to confirm a membership guess. RFC 3161 time stamping is always on and has no user-facing setting: `TimestampAuthorityClient` sends only the canonical proof hash to the fixed authority `https://tsa.wotrus.com/`, stores the returned token in `witness.timestampToken`, and validates its signature plus the certificate chain, accepting either the operating-system trust store or the pinned WoTrus (沃通) root it embeds (revocation is not checked so validation stays offline-capable). The authority is deliberately not configurable — a user-facing URL would let a broken or hostile endpoint silently disable the anchor — and it is reachable from mainland networks, unlike the free public authorities. A time stamp proves the digest existed no later than the stamped time and never that the draw happened then. `historyScope` follows the same allow-list rule: `ValidateFairness` accepts `global`/`course`/`history-group`/`course-and-history-group`, and the client declares only the scope — **never** the group name, which is user-authored free text that can name a class or a person. The service cannot verify the claim either, because it only replays the recorded per-candidate `historyCount` values, so `historyScope` is a declaration attached to the proof, not an attestation of how the history was filtered.
- `fair.sectl.cn` anchors the local proof chain: `DrawProofAttestationService` submits the proof including `chain`, and the attest response's `chain.status` (`genesis`/`continuous`/`duplicate`/`broken`/`gap`/`behind`/`conflict`) is surfaced as `ProofAttestationStatus.ChainAlertCount` and logged. A `behind` status means the service already holds a higher chain position for this device, which is how a deleted-and-rebuilt local chain becomes visible; the server-side anchor never moves backwards. Receipt and time-stamp failures are counted separately (`ReceiptFailedCount`/`TimestampFailedCount`) so an unavailable third-party authority never reads as a failed attestation.
- Formal notarization is the explicit alternative to ordinary replay attestation: the client sends a zero-seed anonymous request, `fair.sectl.cn` durably locks it, persists server random material after the lock, calculates the result, and returns an immutable `OnlineWitnessed` proof. Formal mode waits for that response and must never substitute a local draw after an error; its ledger is independent of retention-limited public proof sharing. It protects the locked flow against local code/seed/proof replacement, but cannot establish real-world roster authenticity, completeness, or pre-submission pool integrity.
@@ -193,7 +194,6 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo
- The desktop loopback redirect is answered with `LoopbackAuthCallbackPage` rather than a bare `
`. Its wording must never claim a finished sign-in — `SectlAuthService` writes and closes that response *before* it validates `state` and exchanges the code — and its light/dark follows the browser's `prefers-color-scheme`, because a page in the browser cannot read the app theme. `LoopbackAuthRedirectBroker` keeps answering requests that carry neither `code` nor `error` (a browser asking for `/favicon.ico`, a reload) instead of spending its one read on them, and a browser that closes the tab mid-write must not turn an already-received callback into a failure. Responses carry `default-src 'none'` CSP, `no-store`, and `nosniff`, and the page stays static — no entrance animation, because a background tab or a screenshot must never catch it invisible.
- The settings title bar account flyout and the mobile cloud tab use `SectlAuthService` and SECTL OAuth Authorization Code + PKCE. Desktop receives the redirect on a loopback callback; a mobile head receives it through the app's custom scheme (`cn.sectl.secrandom.mobile://oauth/callback`, registered on the SECTL authorization service for the shared client id), delivered by `MobileAuthCallbackRouter` — Android through the system browser and an intent filter, iOS through `ASWebAuthenticationSession`, which captures the redirect itself because a suspended iOS app cannot be handed a deep link. Tokens are stored only in `data/config/sectl-auth.json` through `SectlTokenStore`; the client ID is centralized in `SectlAuthService.ClientId`, and a mobile attempt records its PKCE verifier in `data/config/sectl-auth-pending.json` so a redirect that arrives after the process was reclaimed is still exchanged (`SectlAuthService.ResumePendingAuthorizationAsync`, never a second authorization prompt). The refresh endpoint rotates a **single-use** refresh token on every success and invalidates the previous one immediately, so the client contract is: `SectlTokenStore.SaveAsync` replaces the file atomically (temporary file + flush to disk + rename) and a rotation is persisted *before* the new access token is used — never memory-first, never in place; all concurrent refreshes collapse into one single-flight task (callers await it with their own cancellation token, so one caller giving up cannot abort a rotation the others need) under a cross-process lock file (`sectl-auth.lock`) that also makes a second process re-read and adopt a pair another process already rotated. Outcomes are classified instead of retried blindly: `400` (`invalid_grant`/`invalid_request`/`unsupported_grant_type`) and `401 invalid_client` are terminal — the local pair is cleared, `RequiresReauthorization` is set, `StateChanged` fires, and the dead refresh token is never submitted again; `429 rate_limited` retries the *same* refresh after its `retry_after_ms`; `503 temporarily_unavailable` retries with exponential backoff plus jitter; an unknown network outcome first re-reads the token file (adopting another process's rotation) and then retries once, and keeps the session when it still cannot tell whether the server rotated. Access tokens carry a locally stamped `access_token_expires_at` and are refreshed five minutes early (`expires_in` from the response, 3600s fallback), while `refresh_token_issued_at` records the first authorization because the fixed 180-day window is never extended by rotation. `SectlHeartbeatService` calls `/api/oauth/heartbeat` with the active Bearer token immediately after startup/sign-in and then every five minutes, independent of the anonymized online-status policy. `SectlAuthService.SendAuthorizedAsync` is the one authorized-request boundary for other SECTL APIs: it attaches the bearer token, refreshes it once on `401`, and treats `error_description: Access token has been revoked` as a reason to re-authorize rather than to rotate the refresh token. `SectlAuthService.InitializeAsync` must stay local-only: it loads the token file and raises `StateChanged`, while the `/api/oauth/userinfo` profile and avatar download run on an unobserved background task that reports through the same event. `App.StartRuntimeServicesAsync` awaits account initialization before `Host.StartAsync()`, and `ShowSettingsWindowCoreAsync` awaits that startup task, so awaiting the account network calls there makes a slow SECTL API stall every window that follows — the settings window must never depend on account network latency. The `/api/oauth/token` and `/api/oauth/refresh` payloads carry only the grant fields plus the device UUID: the client must not resolve its own public IP (the former third-party lookup call is gone for good) nor upload an `ip_address`, because the service derives the address from the connection itself.
- SECTL OAuth tokens never expire by time: the service keeps `ACCESS_TOKEN_TTL_SECONDS` and `REFRESH_TOKEN_TTL_SECONDS` at `-1`, reports `expires_in = 315360000` (ten years) only so a generic OAuth client can still compute a far-away absolute expiry, and `/api/oauth/introspect` answers `expires_at: "-1"` with `exp: null`. No local age check may therefore end a session: `SectlAuthService.ResolveAccessTokenLifetime` maps a negative or absent lifetime to `UnlimitedExpiresInSeconds`, and revocation is the only end — an explicit logout/revocation, a reused refresh token (family revocation), or a deleted account. `SectlAuthService.InitializeAsync` confirms the stored session in the background with `POST /api/oauth/introspect` (`token` + `client_id`, mapped by `SectlTokenIntrospection` in `SecRandom/Services/Auth/SectlTokenIntrospection.cs`) and never on the awaited startup path: `active: false` clears the pair, sets `RequiresReauthorization`, and raises `StateChanged`, while an unreachable endpoint, a non-success status, or a malformed body keeps the session — a flaky network must never read as a revoked session. `SectlTokenIntrospection.NeverExpires` documents the `"-1"` marker so nobody parses it as a date, which would read as 2000-12-31 and discard a fresh session. The `85.137.245.159` host in the developer `~/.ssh/config` is the separate sync server, not the auth or cloud service, so no API origin may be derived from it.
-- Account cloud backup is an app-layer feature on desktop and mobile, built on the SECTL personal cloud API (`/api/cloud/*`), and is separate from the anonymous SecRandom Sync channel, which stays encrypted, short-lived, and 1 MiB-capped. `DataArchiveService.ExportCloudBackupAsync` produces a `CloudBackup` archive whose root set is picked from the dedicated `CloudInclude*` selection but never leaves `CloudBackupRoots`, so `config/device-uuid.json`, `audio/voice`, `theme`/`themes`, and `logs` can never be uploaded (plugins, credentials, backups, and staging were already excluded for every archive kind), while `proofs` is uploadable only when `BackupConfig.CloudIncludeProofs` is on — default off, because a cloud copy is the last resort once local proofs were deleted; `ImportCloudBackupAsync` accepts only that kind and filters the device identity out of its commit roots. One backup is uploaded as 512 KiB verified parts plus a trailing manifest, cloud state is always rediscovered by listing (`SecRandom-cloud-` prefix, parts grouped per backup) instead of being cached in configuration, and a download must pass per-part and whole-archive SHA-256 verification before the normal v3 inspection, recovery snapshot, staging commit, and restart request. Client-side encryption and its passphrase were removed on purpose: the archive is uploaded as produced, so account access is the only key and any signed-in device can list and restore any backup — the platform can read a cloud backup, which is the accepted trade-off for recoverability. A package the removed feature uploaded is still recognised by its `-enc` file-name marker and stays listed with a 旧版加密,无法恢复 label, but `CloudBackupService.CanRestore` is false for it and its schema-2 manifest is rejected by `ValidateManifest`, because this build holds no way to derive its key. The cleartext manifest still reveals which content categories a backup carries and its size. Automatic cloud backup is opt-in and separate from the local backup cadence (`BackupConfig.CloudAutoBackupEnabled`/`IntervalDays`/`MaxCount`); the `CloudAutomaticBackupService` runs it while an account is signed in and follows this device's own newest upload, and only `CloudBackupService.UploadAutomaticAsync` may delete cloud backups. Every upload stamps a device alias into its backup id (`CloudBackupPackage.CreateBackupId`, `_`, ASCII-safe and at most `MaxDeviceTagLength` characters, taken from `BackupConfig.CloudDeviceAlias` or the host name, with a short digest when neither is ASCII-safe), so the cloud listing shows which machine a backup came from without downloading its manifest; the alias is a display label rather than an identity, so `config/device-uuid.json` still never leaves the device. Retention is per device: `UploadAutomaticAsync` trims only this device's surplus beyond `MaxCount` and never deletes a backup it cannot attribute (ids uploaded before aliases existed stay untrimmed), while an exhausted quota is the one account-wide deletion and removes the oldest backup of the whole account. The manual upload path never deletes implicit backups.
- Desktop plugins use `.srpx` ZIP packages with a root `manifest.yml`; the entry assembly contains one non-abstract `PluginBase` implementation. Plugins are discovered from `data/plugins`, pending packages are staged in `data/cache/plugin-packages`, and plugin initialization runs before Host construction. Plugin page IDs follow the `plugin..*` namespace, are owned by the plugin, and must be unique at the application registry level. External dynamic plugins are desktop-only for now; mobile hosts do not load them.
- Plugin API surface: `PluginBase` implements `IAsyncDisposable`; the host disposes each entrance (`DisposePluginsAsync`) before Host shutdown, and forwards application start/stop to the `PluginBase.OnAppStarted` / `OnAppStopping` overrides through the `PluginLifecycleBridge` hosted service (no plugin-registered hosted service needed just for lifecycle). Stable plugin-facing contracts resolve through DI from `SecRandom.Core/Abstraction/Services/`: `IMainView`/`ISettingsView`/`IDrawerView` (under `Views/`, wrapping `MainView.Current`/`SettingsView.Current` with UI-thread marshaling and empty-shell no-ops), `IAppNavigationService` (wraps `App.ShowMainWindow`/`ShowSettingsWindow`/`ShowQuickDrawWindow` and preserves the settings authorization gate), `IAppLifecycleService` (forwards `App.AppStarted`/`AppStopping`; primary use is plugin lifecycle hooks), `IFloatingWindowButtonRegistry` + `FloatingWindowButtonDescriptor` (runtime-only floating-window button registration; visibility is picked in the floating-window settings MultiComboBox and persisted as `FloatingWindowSettingsConfig.VisiblePluginButtonIds`, pruned at refresh when a registration disappears), and `IPluginDrawService` (controlled draw facade). Plugin draws must go through `IPluginDrawService`, which authorizes via `LinkageDrawCoordinator` and reuses `RollCallDrawService`/`LotteryDrawService`; plugins must never call `IDrawCommitService`, `IRollCallSession`/`ILotterySession`, or `IProfileService.Record*History` directly. Plugin management supports uninstall markers (`.uninstall`, config dir preserved), crash auto-disable (`.disabled` written when an unhandled exception stack belongs to a plugin load context), and external dev plugin directories via repeatable `--epp`/`--externalPluginPath` startup args. `PluginManager` is registered as both `IPluginManager` and its concrete type. The srpx packaging target excludes host-provided assemblies (SecRandom/Avalonia/FluentAvalonia/Microsoft.Extensions/runtimes/resources) so plugin packages stay host-free even with the local SDK reference. The full guide is `docs/plugins.md`.
- Plugin SDK packaging and release: `SecRandom.PluginSdk` tracks the application version. `PluginApiVersions.Current` in the SDK defines the minimum host API version and its major must equal the application major version (enforced by the `build_pluginsdk` CI job). `SecRandom.Shared`, `SecRandom.Core`, and `SecRandom.PluginSdk` are packed together on every CI run (`-p:PackageVersion=`) and uploaded as the `pluginsdk` artifact; only the release `publish` job pushes them to NuGet.org using `NuGet/login@v1` (OIDC Trusted Publishing, `user=${{ secrets.NUGET_USER }}`). The host rejects plugins whose `manifest.yml` `apiVersion` major is below `PluginApiVersions.Current.Major`. Local pack workflow: `scripts/publish-pluginsdk.ps1`.
@@ -218,9 +218,10 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo
- Managed draw music uses a platform-specific runtime boundary: desktop `settings.personalized.music` imports/deletes/previews MP3/WAV/FLAC files through `MusicLibraryService`/private SoundFlow playback, while mobile `MobileMediaLibraryService` uses StorageProvider streams into `data/audio/music` and `IMobileMediaPlayer` supplied by Android/iOS heads. Draw-settings and student/prize attached settings use the same managed IDs, no-music, or random-play options; the first drawn record supplies both overrides for a multi-record result. Deleting a managed track clears global and per-record references. Mobile display images likewise import through StorageProvider streams into `data/images`; image/music/voice failures must not invalidate a committed draw.
- Course linkage uses fixed v2 data-source values: `0=Off`, `1=CSES`, `2=ClassIsland`. CSES schedules live at `data/CSES/cses_schedule.yml`; ClassIsland is accessed only through the app-layer official IPC adapter. Only a confirmed course break restricts local draw/reset or hides the floating window. Missing/invalid CSES data, ClassIsland connection loss, or an unknown state must permit normal operation. ClassIsland reports a confirmed non-class period as `Breaking`, `AfterSchool`, `PrepareOnClass`, or `None` (today's plan loaded but no current time point, i.e. before the first class or a gap); `IsLessonConfirmed` is only true inside a class/break time point and must never be used as an availability gate, because before-school and after-school hours are exactly the periods the linkage restriction must cover. A day without a loaded plan (`IsClassPlanLoaded == false`) stays permissive.
- CSES schedule errors follow the “`InvalidDataException` + `Data` error code” convention: `CsesScheduleException` is a static factory that throws `InvalidDataException` (sealed, so it cannot be subclassed) with a `CsesScheduleError` code and optional argument stored in `Exception.Data`; UI retrieves them through `CsesScheduleException.TryGetError` and localizes from resources.
-- `LinkageSettings.VerificationRequired` governs the course-time bypass prompt and is distinct from `SecuritySettings.ProtectLinkage`, which continues to protect only external SecRandom URL/IPC mutations. Student course history uses `HistoryItem.CourseName` with `RecordId` identity; empty legacy course values remain global history.
-- File/data paths should go through `Utils.GetFilePath(...)`. Desktop and portable deployments keep mutable data under the package root's `data/` directory. The shared `App` mobile branch is the controlled exception: before any path is read, it sets `Utils` once to its app-private local-data root; no Core service, view, or desktop code may redirect it later. `data/config` keeps its stable name for compatibility but is hidden at the filesystem level where supported (Windows `Hidden|System`; Unix-like hosts use the parent `.hidden` convention as a fallback), and hiding failures must not block config I/O.
-- Desktop startup calls `Utils.PrepareDesktopDataRoot()` before reading settings. Installed packages use `/data` when it passes a real write probe and otherwise use `LocalApplicationData/SecRandom/data`; portable ZIP packages never fall back to a per-user directory, and a failed write probe blocks startup with the transient `SecRandomTmpRootWindow`/`FATaskDialog` warning host.
+- `LinkageSettings.VerificationRequired` governs the course-time bypass prompt and is distinct from `SecuritySettings.ProtectLinkage`, which continues to protect only external SecRandom URL/IPC mutations. That bypass is only a bypass if something can actually verify: `SecurityService.AuthorizeAsync` runs the action unchecked when `RequiresVerification` is false (security protection off, or no configured factor), so `LinkageDrawCoordinator` must ask `RequiresVerification(SecurityOperation.BypassClassTimeRestriction)` first and hard-block — including the `ClassTimeDrawRestrictionNotice` toast — instead of delegating, or the break ban and `LinkageSettings.RestrictWhenUnavailable` fail open. `EvaluateGate` mirrors the same test and answers `BlockedByClassTime`. Student course history uses `HistoryItem.CourseName` with `RecordId` identity; empty legacy course values remain global history.
+- File/data paths should go through `Utils.GetFilePath(...)`. The desktop data root is resolved in `SecRandom.Shared/DataRoot/` (`DesktopDataRootResolver`) with one fixed precedence: `--data-root` > `SECRANDOM_DATA_ROOT` > the anchor file `data-root.json` > legacy-location adoption > mode default. Portable packages default to `/data`; installed packages default to a per-user standard root (`%LOCALAPPDATA%\SecRandom\data`, macOS `~/Library/Application Support/SecRandom/data`, Linux `${XDG_CONFIG_HOME:-~/.config}/secrandom/data`) and never to the install directory. The anchor lives outside the data root (`/data-root.json` for portable, the standard anchor directory for installed). A user-chosen root is a `Custom` mode stored in that anchor; a root inside an activated `app-*` payload is never a valid destination. The shared `App` mobile branch is the controlled exception: before any path is read, it sets `Utils` once to its app-private local-data root; no Core service, view, or desktop code may redirect it later. `data/config` keeps its stable name for compatibility but is hidden at the filesystem level where supported (Windows `Hidden|System`; Unix-like hosts use the parent `.hidden` convention as a fallback), and hiding failures must not block config I/O.
+- Desktop startup calls `Utils.PrepareDesktopDataRoot(GlobalConstants.IsDevelopment, commandLineDataRoot)` before reading settings. The resolver adopts legacy layouts (`/data`, a writable install directory's `data`, a stray `app-*/data`) and repairs payload-resident data by moving it to the package root; a failed write probe blocks startup with the transient `SecRandomTmpRootWindow`/`FATaskDialog` host (`M_DataRootUnavailable*`, or the portable-specific message). The anchor is persisted whenever the mode came from a default/legacy/adopted location, and is not written for a command-line/environment override or for development builds already resolving the package directory.
+- Changing the data root is a two-process transaction: the storage settings page validates the target, writes `data-root-journal.json` (next to the anchor), and restarts with `--data-root-migration `; that launch skips normal data-root preparation and shows `DataRootMigrationWindow`, which runs `DataRootMigrationEngine` (copy to `.migrating-` on the target volume, rewrite root-relative paths, verify, rename to the target, write the anchor, then keep the old root as `.migrated-`). Writing the anchor is the single commit point: if it fails the target is rolled back and the source stays intact.
- Desktop builds copy `SecRandom/Assets` beside the executable and bind `OverlayAssetLoader` so existing `avares://SecRandom/Assets/...` URIs load physical files first, including Debug builds. Android and iOS keep the same assets embedded. `Assets/Updates/release-public-key.txt` and `Assets/Plugins/plugin-market-public-key.txt` are embedded on every target and must never be resolved from the physical overlay. `System.Uri` lower-cases the authority of an absolute `avares` URI while the scheme is unregistered (as it is for the `GlobalConstants` static font families created before Avalonia starts), so the overlay must compare that authority case-insensitively, or the first layout asking for the `Assets/Fonts/` font collection throws `Could not create glyphTypeface`.
- Portable ZIP updates use `SecRandom.Launcher` at the stable package root and activated `app-*` payload directories. The application, not Launcher, validates/downloads/extracts/activates a complete ZIP; `Utils.PackageRoot` / `DataRoot` keep user data stable across payload versions. Every entry that outlives the process — autostart and `secrandom://`/URL-protocol registration — must launch that root Launcher (`Utils.TryGetPortableLauncherPath`) instead of an executable inside the activated payload, because an update replaces that directory; in-app restart and crash recovery keep using the running payload's executable.
- Update discovery uses a fixed GitHub mirror first, with GitHub direct access as fallback. A detached Ed25519-signed release manifest and each artifact's length/SHA-512 must verify before deployment or a system installer is started; signing keys remain outside the repository. Desktop artifacts, the signed Android arm64 APK, and the unsigned iOS arm64 IPA share this manifest. Android downloads its verified APK then delegates installation to the system package installer; iOS device distribution and in-app update delivery remain deferred.
diff --git a/CHANGELOG/v3/v3.2.0-beta.1/CHANGELOG.md b/CHANGELOG/v3/v3.2.0-beta.1/CHANGELOG.md
new file mode 100644
index 000000000..e1edb1618
--- /dev/null
+++ b/CHANGELOG/v3/v3.2.0-beta.1/CHANGELOG.md
@@ -0,0 +1,63 @@
+
+
+> [!caution]
+>
+> # 抢先体验 Beta 版
+>
+> 您正在使用我们的最新功能预览版。为了在正式版中给您带来更完美的体验,我们需要您的帮助与反馈。
+>
+> **⚠️ 风险提示**:此版本尚在打磨中,可能存在偶发异常或未知问题,**请务必避免用于关键业务或生产环境**。
+>
+> **📣 我们需要您**:如果发现任何 Bug,或有功能改进建议,欢迎随时前往 **GitHub Issues** 提交反馈。
+>
+> 感谢您成为我们的首批体验官!
+
+
+# v3.2.0 - Beta 1 - Nonomi (十六夜野宫)
+
+## 🚀 主要更新
+
+- 新增 **浮窗支持屏幕两侧**,开启后可以更方便的让你进行快速操作
+- 新增 **历史记录组**,开启后可以在点名/抽奖页面设置接下来抽取的历史记录存放在哪个历史记录组内。如果使用公平抽取模式,将会影响后续的公平性
+- 新增 **随机数模式**,可在点名/抽奖的名单中选择随机数给你,将可以直接进行随机数的抽取。随机数的默认值可在设置内调整
+- 新增 **简洁模式**,主要是部分用户想要一个最简单的抽取样式,你如果觉得你使用 SecRandom 只用了点名名单和闪抽,那你可以使用这个功能,当然没有多余的娱乐功能了
+- 新增 **全屏通知渠道**,可以全屏显示结果,并且有动画样式可以选择,而且可以配置背景图片,能让抽取更有意思。“打字机”动画支持文案库,你也可以手动添加,或者发送内置提示词给AI生成后进行粘贴导入
+- 新增 **浮窗通知设置页面**,可以配置浮窗的一些功能,以及样式
+- 新增 **浮窗组件可自定义**,可以自定义配置浮窗内的组件,并且支持打开其他文件/URL,支持自定义名称、图标
+- 新增 **浮窗收纳样式可自定义**,为了一些用户觉得“抽”和单一的图标觉得标识不明显,可以自行配置该样式
+- 新增 **课程联动严格限制功能**,可以防止IPC断联时依旧保持安全锁定状态,默认关闭
+- 新增 **浮窗通知自适应前景色**,支持自动根据背景调整浮窗通知的外观,大大提升了可读性。该功能默认开启,如果开启低配模式将会自动关闭
+- 新增 **更新源**,支持了思拓创联官方服务器分发源
+- 新增 **关于-本机信息**,可在关于页面查看本机的一些信息
+- 新增 **关于-抽取算法版本号**,支持在关于页面查看抽取算法的版本号
+- 新增 **浮窗支持无焦点**,为防止点击浮窗时出现焦点切换,导致影响PPT的放映,支持开启,如果在部分系统环境下有Bug可以自行关闭
+- 新增 **编排模式**,可以在部分场景(eg:公开课、演示等)进行一个固定顺序/权重修改/排除一些成员/延后一些成员滞后抽取,对部分不需要随机/公平抽取的场景进行支持
+- 新增 **闪抽长按支持抽多人**,默认开启,长按闪抽可出现数量显示组件在左侧/右侧,上下拖动后松手即可快速抽取多人(1~5人)
+- 新增 **公平抽取设置值**,可选择公平抽取算法倾向,分为 **均匀优先(默认)、随机优先**,修改为随机优先后可以有细微感知抽取的随机性会稍强,如果担心被台下的人骂,我建议还是均匀优先好一点
+- 新增 **浮窗通知关闭倒计时样式**,默认设置为“四周进度”,汇总浮窗通知的四周显示关闭倒计时,并且可以自定义颜色,默认为蓝红渐变
+- 新增 **数据储存**,可以手动修改数据默认保存的位置,并且支持一键迁移
+
+## 💡 功能优化
+
+- 优化 **名单管理增减成员/奖品体验**,单独添加/减少一位成员序号重叠/缺失会自动询问用户该执行推后/不动行为
+- 优化 **登录后授权的页面**,变得……好看了
+- 优化 **IPC接口**,拓展了部分接口的功能,并且优化了IPC部分管道名称
+- 优化 **部分名称优化**,将“SecRandom 文档站”改为“SecRandom 官网”、“SecRandom 内置通知”改为“SecRandom 浮窗通知”
+- 优化 **集控**,支持思拓创联官方集控API接口,旧的集控将不可使用,桌面端支持地点码+配对码/登录账号的形式进行连接集控;移动端登录账号后即可远程抽取对应设备上的特定名单
+- 优化 **历史记录**,将每种抽取模式的默认历史分开计算,避免影响公平抽取的计算
+- 优化 **CPU占用&RAM占用**,这一次只能说是降低了部分,下次再接再厉
+- 优化 **浮窗点击**,小修小补了浮窗的点击准确性
+
+## 🐛 修复问题
+
+- 修复 **便携版开机启动项指向版本文件夹**,便携包的自启动与 `secrandom://` 协议注册现在指向包根目录的 `SecRandomLauncher`,而不是 `app-*` 版本目录里的 `SecRandom.Desktop.exe`
+- 修复 **Edge TTS 生成报错**,更新库版本支持了v2版本
+- 修复 **默认数据目录存放位置**,修复在便携模式下和安装版本下的数据目录的默认存放位置不标准的情况
+
+## ❌ 移除功能
+
+- 移除 证明文件验证链、云服务自动备份、软件启动时检查文件是否被篡改功能(第一用处不大,第二有些功能有点 bug)
+
+---
+
+💝 **感谢所有贡献者为 SecRandom 项目付出的努力!**
diff --git a/CHANGELOG/v3/v3.2.0/CHANGELOG.md b/CHANGELOG/v3/v3.2.0/CHANGELOG.md
deleted file mode 100644
index 7a7a11b97..000000000
--- a/CHANGELOG/v3/v3.2.0/CHANGELOG.md
+++ /dev/null
@@ -1,43 +0,0 @@
-
-
-> [!note]
->
-> # v3.2.0 正式版发布
->
-> 感谢您一路以来的等待与支持,**v3.2.0 正式版**现已发布,可直接用于日常教学等正式场景。
->
-> **📣 我们需要您**:如果发现任何 Bug,或有功能改进建议,欢迎随时前往 **GitHub Issues** 提交反馈。
->
-> 感谢您陪伴 SecRandom 一路走到这里!
-
-
-# v3.2.0 - Nonomi (十六夜野宫)
-
-## 🚀 主要更新
-
-- 新增 **历史记录组**:同一个名单的历史可以被拆成互不干扰的若干组(例如「课堂提问」和「抽奖」),在点名、抽奖主页面选一个组即可把抽取锁定到该组——权重只参考这一组里已有的记录,本次记录也只写进这一组
-- 新增 **组管理**:在「设置 → 历史记录 → 历史记录管理」里可以新建、改名、删除记录组;删除只会把该组记录移回默认组,不会删除任何一条历史
-- 新增 **历史页的记录组列与筛选**,并支持把已有记录「移到另一组」,用来修复选错组的记录或把旧记录归档
-- 新增 **首页「默认记录组」选项**:点名页、抽奖页的记录组下拉里,第一项是「默认记录组」,选它表示只按未分组的记录计算权重——已经分到别的组的记录不会混进来;主页面只保留这一个下拉,不再有锁定提示或取消按钮
-- 新增 **导出包含记录组列**:导出的 XLSX/CSV 明细多一列记录组,便于按用途核对
-- 新增 **闪抽默认记录组**:闪抽没有自己的选择器,改为在「抽取设置 → 闪抽」里设一个默认组,之后每次闪抽都锁在该组(悬浮窗上会有一行提示说明当前锁定到哪个组)
-- 新增 **点名/抽奖的持久化默认记录组**:在两页各自「抽取设置」里可以指定下次打开时组下拉默认落在哪一组——下拉本身仍然只是本次会话的临时选择,改动设置里的默认组才会影响下一次打开;选「默认记录组」表示只算未分组的记录,与「不分组(全部历史)」不是一回事
-- 新增 **默认组失效回落**:设置里的组被删除或改名后,下一次抽取自动回落到「默认记录组」(删除组只会把它的记录移回默认组),闪抽提示里还会多一句说明原组已不存在
-- 新增 **证明声明整理范围**:可验证抽奖的证明里会写明本次权重用的是哪一个范围的历史(全局 / 课程 / 记录组 / 课程加记录组),验证端据此按同样的范围重放;证明引擎版本随之升到 3.4.0
-
-## 💡 功能优化
-
-- 优化 **课程过滤与记录组可以同时使用**:开了课程联动过滤时,两个维度取交集,互不覆盖
-- 优化 **抽奖页的分配学生权重**:抽奖页选择记录组后,分配给奖品的学生也按该组的历史计算权重
-- 优化 **重复抽取上限按记录组独立计数**:临时记录里的「已抽中次数」现在按记录组分开存(不分组、默认组、每个具名组各一份),换组不会再把上一组的计数带过来;改名组会把计数合并到新名字,删除组会把计数并入默认组。升级前的历史计数无法判断属于哪个组,统一归到「不分组」那一份,按组计数从零开始
-- 优化 **历史记录改用轻量数据库存储**:每个名单/奖池的历史现在是一个小的 SQLite 数据库(`data/history/**/*.srhdb`),保存只写本次变动的成员与记录,不再每次把整份历史重新序列化。以 60 人 × 300 轮(1.8 万条记录)为例:整份保存从约 112 ms 降到 35 ms、一次抽取的增量保存约 37 ms,文件体积从 9.4 MB 降到 1.9 MB,读取也略快;备份、云备份、还原与导入导出仍然按整个 `data/history` 目录处理,不需要额外操作
-- 新增 **历史记录无感迁移**:升级后第一次读取某个名单/奖池时,旧的历史 JSON 会自动导入新数据库,原文件改名成 `*.json.migrated` 留作一次性回滚副本(不再参与任何 JSON 读取)。不需要手动迁移,恢复旧版备份包(里面是 JSON)后同样会被自动导入
-- 注意 **降级需要手动换回 JSON**:旧版本只认识历史 JSON,回退到旧版本前请把 `data/history/**/*.json.migrated` 改名回 `*.json`,否则旧版本看不到这些名单的历史记录
-
-## 🐛 修复问题
-
-- 修复 **便携版开机启动项指向版本文件夹**:便携包的自启动与 `secrandom://` 协议注册现在指向包根目录的 `SecRandomLauncher`,而不是 `app-*` 版本目录里的 `SecRandom.Desktop.exe`;更新替换版本目录后开机启动不再失效,也无需重新设置,已有的旧条目会在下次启动时自动改写
-
----
-
-💝 **感谢所有贡献者为 SecRandom 项目付出的努力!**
diff --git a/SecRandom.Core.Tests/AdaptiveBackdropTests.cs b/SecRandom.Core.Tests/AdaptiveBackdropTests.cs
new file mode 100644
index 000000000..182f6226a
--- /dev/null
+++ b/SecRandom.Core.Tests/AdaptiveBackdropTests.cs
@@ -0,0 +1,233 @@
+using Avalonia.Media;
+using SecRandom.Core.Services.Presentation;
+
+namespace SecRandom.Core.Tests;
+
+public class AdaptiveBackdropTests
+{
+ [Theory]
+ [InlineData(0.00)]
+ [InlineData(0.10)]
+ [InlineData(0.35)]
+ [InlineData(0.50)]
+ [InlineData(0.65)]
+ [InlineData(0.90)]
+ [InlineData(1.00)]
+ public void KeepsReadableContrastAcrossTheWholeLuminanceRange(double median)
+ {
+ var theme = AdaptiveBackdropResolver.Resolve(
+ BackdropLuminance.FromPercentiles(median, median, median), appThemeIsDark: false);
+
+ Assert.True(
+ AdaptiveBackdropResolver.ContrastAgainstSurface(theme) >= AdaptiveBackdropResolver.MinimumContrastRatio,
+ $"median={median:0.00} contrast={AdaptiveBackdropResolver.ContrastAgainstSurface(theme):0.00}");
+ }
+
+ [Fact]
+ public void PicksWhiteTextOnADarkDesktop()
+ {
+ var theme = AdaptiveBackdropResolver.Resolve(
+ BackdropLuminance.FromPercentiles(0.01, 0.05, 0.09), appThemeIsDark: false);
+
+ Assert.True(theme.IsDarkBackdrop);
+ Assert.Equal(Colors.White, theme.Foreground);
+ }
+
+ [Fact]
+ public void PicksBlackTextOnABrightDesktop()
+ {
+ var theme = AdaptiveBackdropResolver.Resolve(
+ BackdropLuminance.FromPercentiles(0.85, 0.93, 0.99), appThemeIsDark: true);
+
+ Assert.False(theme.IsDarkBackdrop);
+ Assert.Equal(Colors.Black, theme.Foreground);
+ }
+
+ [Fact]
+ public void PressesTheSurfaceHarderWhenTheBackdropIsBusy()
+ {
+ var flat = AdaptiveBackdropResolver.Resolve(
+ BackdropLuminance.FromPercentiles(0.30, 0.35, 0.40), appThemeIsDark: false);
+ var busy = AdaptiveBackdropResolver.Resolve(
+ BackdropLuminance.FromPercentiles(0.02, 0.35, 0.95), appThemeIsDark: false);
+
+ Assert.True(busy.SurfaceAlpha > flat.SurfaceAlpha);
+ }
+
+ [Fact]
+ public void CardSurfaceIsAtLeastAsOpaqueAsTheRootSurface()
+ {
+ var theme = AdaptiveBackdropResolver.Resolve(
+ BackdropLuminance.FromPercentiles(0.2, 0.3, 0.4), appThemeIsDark: false);
+
+ Assert.True(theme.CardSurface.A >= theme.Surface.A);
+ Assert.True(theme.Surface.A < 255);
+ }
+
+ [Fact]
+ public void FallsBackToAnOpaqueCardMatchingTheAppTheme()
+ {
+ var dark = AdaptiveBackdropResolver.FromAppTheme(isDarkTheme: true);
+ var light = AdaptiveBackdropResolver.FromAppTheme(isDarkTheme: false);
+
+ Assert.Equal(255, dark.Surface.A);
+ Assert.Equal(255, light.Surface.A);
+ Assert.Equal(Colors.White, dark.Foreground);
+ Assert.Equal(Colors.Black, light.Foreground);
+ }
+
+ [Fact]
+ public void ContrastUsesTheWcagFormula()
+ {
+ Assert.Equal(21.0, AdaptiveBackdropResolver.ContrastRatio(0, Colors.White), 3);
+ Assert.Equal(1.0, AdaptiveBackdropResolver.ContrastRatio(0.0, Colors.Black), 3);
+ }
+
+ ///
+ /// 需求本身:浅底必须黑字、深底必须白字,判据是"画出来的卡片有多亮",不是"桌面深不深"。
+ ///
+ [Theory]
+ [InlineData(0.00)]
+ [InlineData(0.18)]
+ [InlineData(0.50)]
+ [InlineData(0.82)]
+ [InlineData(1.00)]
+ public void SelectsTheHigherContrastInkForTheDrawnSurface(double surfaceLuminance)
+ {
+ var ink = AdaptiveBackdropResolver.SelectForeground(surfaceLuminance);
+
+ Assert.True(
+ AdaptiveBackdropResolver.ContrastRatio(surfaceLuminance, ink) >=
+ AdaptiveBackdropResolver.ContrastRatio(
+ surfaceLuminance,
+ ink == Colors.Black ? Colors.White : Colors.Black));
+ Assert.Equal(surfaceLuminance >= 0.1792 ? Colors.Black : Colors.White, ink);
+ }
+
+ /// 整体不透明度也淡化文字:中灰桌面上的淡深色卡片仍以白字较清晰,但无法达到 AA。
+ [Fact]
+ public void WashedOutDarkCardComparesTheVisibleInkInsteadOfOpaqueInk()
+ {
+ var backdrop = BackdropLuminance.FromPercentiles(0.5, 0.5, 0.5);
+ var theme = AdaptiveBackdropResolver.Resolve(backdrop, appThemeIsDark: true, surfaceOpacity: 0.2);
+
+ Assert.True(theme.IsDarkBackdrop);
+ Assert.Equal(Colors.White, theme.Foreground);
+ Assert.Equal(1.0, theme.SurfaceAlpha);
+ // 独立数值:L(#1F)=0.0137020830472897,底=.2*L(#1F)+.8*.5,白字=.2+.8*.5。
+ Assert.Equal(0.402740416609458, theme.SurfaceLuminance, 12);
+ Assert.Equal(1.43570128964365, AdaptiveBackdropResolver.ContrastAgainstSurface(theme), 12);
+ Assert.Equal(1.43570128964365,
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop), 12);
+ Assert.Equal(1.00608981468768,
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme with { Foreground = Colors.Black }, backdrop), 12);
+ Assert.True(AdaptiveBackdropResolver.ContrastAgainstSurface(theme) < AdaptiveBackdropResolver.MinimumContrastRatio);
+ }
+
+ /// 合成亮度必须等于"卡片色 × 卡片不透明度 × 整块不透明度 + 剩下的桌面"。
+ [Theory]
+ [InlineData(1.0)]
+ [InlineData(0.8)]
+ [InlineData(0.5)]
+ [InlineData(0.2)]
+ public void SurfaceLuminanceMatchesTheCompositionOfTheDrawnCard(double opacity)
+ {
+ const double backdropLuminance = 1.0;
+ var theme = AdaptiveBackdropResolver.Resolve(
+ BackdropLuminance.FromPercentiles(backdropLuminance, backdropLuminance, backdropLuminance),
+ appThemeIsDark: false,
+ surfaceOpacity: opacity);
+
+ var expected = AdaptiveBackdropResolver.ComposeSurfaceLuminance(
+ theme.Surface, theme.SurfaceAlpha, backdropLuminance, opacity);
+
+ Assert.Equal(expected, theme.SurfaceLuminance, 12);
+ // 文字也乘整体不透明度,白桌面上的黑字亮度为 1-opacity。
+ var expectedContrast = (expected + 0.05) / (1 - opacity + 0.05);
+ Assert.Equal(expectedContrast, AdaptiveBackdropResolver.ContrastAgainstSurface(theme), 12);
+ if (opacity <= 0.5)
+ Assert.True(expectedContrast < AdaptiveBackdropResolver.MinimumContrastRatio);
+ }
+
+ ///
+ /// 卡片半透明压在一张花壁纸/PPT 上时,卡片两端会合成出不同的底色;字必须在两端都看得清,
+ /// 否则就是"左边看得见、右边消失"。
+ ///
+ [Theory]
+ [InlineData(0.02, 0.30, 0.62)]
+ [InlineData(0.05, 0.50, 0.98)]
+ [InlineData(0.10, 0.75, 0.95)]
+ public void KeepsTheInkReadableAtBothEndsOfABusyBackdrop(double p10, double median, double p90)
+ {
+ const double opacity = 0.9;
+ var backdrop = BackdropLuminance.FromPercentiles(p10, median, p90);
+ var theme = AdaptiveBackdropResolver.Resolve(backdrop, appThemeIsDark: false, surfaceOpacity: opacity);
+
+ var worst = AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop, opacity);
+
+ Assert.True(
+ worst >= AdaptiveBackdropResolver.MinimumContrastRatio,
+ $"p10={p10:0.00} median={median:0.00} p90={p90:0.00} worst={worst:0.00} " +
+ $"ink={(theme.Foreground == Colors.Black ? "black" : "white")} alpha={theme.SurfaceAlpha:0.00}");
+ }
+
+ ///
+ /// 不透明度低到"桌面透上来太多"时,任何纯色都达不到 4.5,此时只能选对比更高的那个,
+ /// 并且卡片底必须已经被压到不透明(在这条不透明度下已经无解,但仍要是最优解)。
+ ///
+ [Fact]
+ public void PicksTheBestAvailableInkWhenTheCardIsTooTransparentToBeReadable()
+ {
+ const double opacity = 0.75;
+ var backdrop = BackdropLuminance.FromPercentiles(0, 0.2, 1);
+ var theme = AdaptiveBackdropResolver.Resolve(backdrop, appThemeIsDark: false, surfaceOpacity: opacity);
+
+ Assert.Equal(1.0, theme.SurfaceAlpha, 3);
+ Assert.Equal(Colors.White, theme.Foreground);
+ // 整体透明度同时淡化文字,黑/白字在亮桌面端的可见对比度都不足 4.5。
+ Assert.Equal(3.384077715267313,
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop, opacity), 12);
+ Assert.Equal(1.0342552076182241,
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme with { Foreground = Colors.Black }, backdrop, opacity), 12);
+ Assert.True(
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop, opacity) >=
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(
+ theme with { Foreground = Colors.Black },
+ backdrop,
+ opacity));
+ Assert.True(
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop, opacity) >=
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(
+ theme with { Foreground = Colors.White },
+ backdrop,
+ opacity));
+ }
+
+ /// 整体透明度不改变桌面分类,但可能让较清晰的白字也达不到目标对比度。
+ [Fact]
+ public void SurfaceOpacityDoesNotReclassifyTheBackdrop()
+ {
+ var theme = AdaptiveBackdropResolver.Resolve(
+ BackdropLuminance.FromPercentiles(0.45, 0.45, 0.45), appThemeIsDark: true, surfaceOpacity: 0.05);
+
+ Assert.True(theme.IsDarkBackdrop);
+ Assert.Equal(Colors.White, theme.Foreground);
+ Assert.True(AdaptiveBackdropResolver.ContrastAgainstSurface(theme) < AdaptiveBackdropResolver.MinimumContrastRatio);
+ }
+
+ [Fact]
+ public void KeepsTheBetterTranslucentSurfaceWhenNoCandidateMeetsTheContrastTarget()
+ {
+ var backdrop = BackdropLuminance.FromPercentiles(0, 0.8, 1);
+ var theme = AdaptiveBackdropResolver.Resolve(backdrop, appThemeIsDark: false, surfaceOpacity: 0.75);
+
+ Assert.Equal(Colors.Black, theme.Foreground);
+ Assert.Equal(224, theme.Surface.A);
+ // 白底本身越实,亮桌面上的淡黑字反而越贴近底色;不能无条件返回 alpha=1。
+ Assert.Equal(3.4033140306651,
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop), 12);
+ var opaqueSurface = theme with { Surface = Color.FromRgb(0xFA, 0xFA, 0xFA) };
+ Assert.Equal(3.38993338312322,
+ AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(opaqueSurface, backdrop), 12);
+ }
+}
\ No newline at end of file
diff --git a/SecRandom.Core.Tests/AppHostServiceResolutionTests.cs b/SecRandom.Core.Tests/AppHostServiceResolutionTests.cs
new file mode 100644
index 000000000..b1f264779
--- /dev/null
+++ b/SecRandom.Core.Tests/AppHostServiceResolutionTests.cs
@@ -0,0 +1,80 @@
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using SecRandom.Core.Abstraction;
+
+namespace SecRandom.Core.Tests;
+
+///
+/// 的取服务边界。停机流程会先释放服务容器、再清空 Host,
+/// 这个窗口里错误处理路径仍会取服务;此时必须得到 null 而不是把 ObjectDisposedException 抛回去,
+/// 否则一次停机期的刷新(例如托盘 Sudo 菜单的 5 秒计时器)会二次击穿异常处理。
+///
+[Collection("AppHost")]
+public class AppHostServiceResolutionTests : IDisposable
+{
+ private readonly IHost? _originalHost = IAppHost.Host;
+
+ public void Dispose()
+ {
+ IAppHost.Host = _originalHost;
+ }
+
+ [Fact]
+ public void TryGetService_ReturnsNull_WhenHostIsNotBuilt()
+ {
+ IAppHost.Host = null;
+
+ Assert.Null(IAppHost.TryGetService());
+ }
+
+ [Fact]
+ public void TryGetService_ReturnsNull_WhenProviderIsDisposed()
+ {
+ var provider = new ServiceCollection().AddSingleton(new object()).BuildServiceProvider();
+ provider.Dispose();
+ IAppHost.Host = new StubHost(provider);
+
+ Assert.Null(IAppHost.TryGetService