Compare commits

..
Author SHA1 Message Date
AxTps eabac1f11e docs: 补充 1.0.2-beta5 公告
Sync source to CNB / Sync Git ref (push) Skipped
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Prepare pnpm cache / prepare (push) Canceled after 0s
Starlight release / Release preflight (push) Canceled after 0s
Starlight release / Build (Linux arm64) (push) Canceled after 0s
Starlight release / Build (Linux x64) (push) Canceled after 0s
Starlight release / Build (macOS universal) (push) Canceled after 0s
Starlight release / Verify and publish (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
Starlight release / Build (Windows x64) (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
2026-10-11 07:06:54 +08:00
Ax_Tps b776b99f26 Merge pull request #12 from ApTx2012/feat/ui
Sync source to CNB / Sync Git ref (push) Skipped
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
feat: 接入皮肤站公告 API
2026-10-11 06:13:00 +08:00
Ax_Tps daeedc4951 Merge pull request #10 from ApTx2012/feat/launch-customization
Sync source to CNB / Sync Git ref (push) Skipped
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
feat: 支持自定义 Minecraft 窗口标题
2026-10-11 06:12:25 +08:00
AxTps cadb7bbdcd feat: 接入皮肤站公告 API
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-10 22:34:00 +08:00
AxTps 7f3ab9d79b fix: 补 EditInstance DTO 缺失的 window_title 字段与透传
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-10 22:23:49 +08:00
AxTps 037bff2db3 Merge branch 'main' into feat/launch-customization
Sync source to CNB / Sync Git ref (push) Skipped
解决 en-US/zh-CN locale JSON 的末尾追加冲突:窗口标题键与公告中心键均保留。
2026-10-10 22:07:19 +08:00
AxTps 1406f7ded3 fix: 补 ProcessMetadata 测试构造点缺失的 window_title
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-10 22:01:42 +08:00
Ap_Tx c54acd2e36 fix: 补齐盔甲预览的中文翻译 (#11)
Sync source to CNB / Sync Git ref (push) Skipped
Repository checks / typos (push) Canceled after 0s
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
皮肤编辑器盔甲面板的 46 条文案此前只有英文,补上 packages/ui 的中英对照。
2026-10-10 21:54:50 +08:00
AxTps 1b6534ad8c fix: changelog 评论 workflow 补 pull-requests write 权限
Sync source to CNB / Sync Git ref (push) Skipped
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
2026-10-10 21:53:05 +08:00
AxTps 2477fc62ca fix: 补窗口标题字段缺失的构造点
Sync source to CNB / Sync Git ref (push) Skipped
修 E0063:InstanceLaunchOverridesPatch 和 InstanceLaunchOverrides 的两处完整构造漏了 window_title。
2026-10-10 21:48:20 +08:00
Ap_Tx 3f6678ac2f feat: 移植远程公告中心 (#9)
Sync source to CNB / Sync Git ref (push) Skipped
Rust checks / shear (push) Canceled after 0s
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
从 Axolotl 搬 RemoteAnnouncements.vue,顶栏加公告铃铛。远程拉取先禁用,等接口。
2026-10-10 21:32:11 +08:00
AxTps e36329ff0e style: 窗口标题改动的 cargo fmt 格式修正
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-10 21:30:15 +08:00
AxTps c718d75774 feat: 支持自定义 Minecraft 窗口标题
Sync source to CNB / Sync Git ref (push) Skipped
全局开关 + 默认标题,实例可覆盖;Win32 重命名窗口。前端设置页同步。
2026-10-10 21:02:34 +08:00
AxTps 544611738d docs: 1.0.2-beta4 公告并入盔甲预览
Sync source to CNB / Sync Git ref (push) Skipped
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Starlight release / Release preflight (push) Canceled after 0s
Starlight release / Build (Linux arm64) (push) Canceled after 0s
Starlight release / Build (Linux x64) (push) Canceled after 0s
Starlight release / Build (macOS universal) (push) Canceled after 0s
Starlight release / Verify and publish (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Prepare pnpm cache / prepare (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
Starlight release / Build (Windows x64) (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
beta4 此前未打 tag,本次发布将其与皮肤编辑器盔甲预览
移植(PR #8)合并发布,故在 beta4 公告条目补充:
- 皮肤预览新增盔甲与盔甲纹饰渲染
- 盔甲预览选择的本地持久化
2026-10-10 19:25:39 +08:00
AxTps 403a883e0b fix: CI 钉住 cargo-shear 版本为 1.13.4
Sync source to CNB / Sync Git ref (push) Skipped
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
check-rust.yml 的 shear 任务在 Rust 1.95 工具链下装最新
cargo-shear(1.14.0) 失败:其依赖 ra_ap_syntax 0.0.352 要求
rustc >= 1.98。且 binstall 走 GitHub release 下载时遭遇
api.github.com 403,回退源码编译后同样因版本过高而失败。

钉到 cargo-shear@1.13.4(依赖 ra_ap_syntax 0.0.347,要求
rustc 1.95),与 CI 的 stable 工具链兼容。
2026-10-09 22:20:48 +08:00
AxTps 53c749aaea fix: 补齐 skin-rendering barrel 的盔甲导出
Sync source to CNB / Sync Git ref (push) Skipped
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
PR #8 合并后 CI 打包报 MISSING_EXPORT:ArmorTrimPanel.vue 与
SkinPreviewRenderer.vue 从 #ui/composables/skin-rendering 导入
ARMOR_SLOTS / ARMOR_TRIM_MATERIALS / ARMOR_TRIM_PATTERNS /
armorMaterialsForSlot / createDefaultArmorPreviewConfig /
useArmorPreview,但该 barrel 未导出这些符号。

补上 armor-preview-types 与 use-armor-preview 的导出。
本地 pnpm --filter @modrinth/app-frontend build 已通过。
2026-10-09 22:12:41 +08:00
Ap_Tx addc31c7c1 Merge pull request #8 from ApTx2012/feat/axolotl-port
feat: 移植 Axolotl 皮肤盔甲预览(Armor Preview)
2026-10-09 21:50:24 +08:00
AxTps 25978bcd8f Merge remote-tracking branch 'origin2/main'
Sync source to CNB / Sync Git ref (push) Skipped
Repository checks / typos (push) Canceled after 0s
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
2026-10-09 21:46:12 +08:00
AxTps 117eaad9ff style: 对分组修复涉及的 Rust 文件补 cargo fmt 2026-10-09 21:44:22 +08:00
Disy 91e2c369f5 fix: 优化下载并发调度,发布 1.0.2-beta4
Sync source to CNB / Sync Git ref (push) Skipped
Axolotl desktop CI / guardrails (push) Canceled after 0s
Axolotl desktop CI / desktop (macos-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (ubuntu-latest) (push) Canceled after 0s
Axolotl desktop CI / desktop (windows-latest) (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
2026-10-08 12:10:54 +08:00
AxTps ae2992d7f8 feat: 移植 Axolotl 皮肤盔甲预览(Armor Preview)
Sync source to CNB / Sync Git ref (push) Canceled after 0s
从 Axolotl 1.9.7 移植皮肤编辑器的盔甲/盔甲纹饰预览功能,
让玩家在皮肤选择页可试穿盔甲并调整纹饰。

新增:
- 前端组件 ArmorTrimTab / SkinListSkeleton 及 skin-armor-preview helper
- packages/ui 组件 ArmorPreviewControls / ArmorTrimPanel
- packages/ui armor 预览 composable(armor-preview-assets/types、use-armor-preview)
- packages/ui webgl 盔甲渲染(armor-geometry / armor-preview-object / armor-rendering)
- packages/ui/src/assets/minecraft-armor 盔甲素材

改动:
- SkinPreviewRenderer 增加 armorPreview/armorControls props、
  armorConfig model 与 useArmorPreview 集成
- Skins.vue 增加盔甲 tab、状态逻辑与模板接入
- 补齐 skin/composables/utils 的导出

适配说明:ArmorPreviewControls 原版依赖 reka-ui 的 popover,
Starlight 无该依赖且只用 external 模式,故改写为 external-only,
去除 reka-ui 与 overlays.css 依赖。
2026-10-07 20:01:19 +08:00
AxTps 20d5d2baab fix: 修复实例分组无法保存的问题
direct-link(外部 .minecraft 关联)同步逻辑会把来源路径当作分组名
写入 instance_groups 表,每次同步都覆盖用户手动设置的分组,导致
分组当场生效、重启丢失。

移除三处 direct-link 相关的来源分组写入,使 instance_groups 表
专属于用户分组:
- sync_direct_link_instances: 同步时不再覆盖 groups
- create_direct_link_instance: 建实例时不再写来源分组
- launcher::promote_external_instance_link: 提升外部实例时不再写分组
2026-10-06 09:50:01 +08:00
AxTps 748d24b264 fix: 修复周年庆横幅被标题栏遮挡与背景遮字问题,发布 1.0.2-beta3
Axolotl desktop CI / guardrails (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Prepare pnpm cache / prepare (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Starlight release / Build (Windows x64) (push) Has been cancelled
Starlight release / Build (Linux x64) (push) Has been cancelled
Starlight release / Build (macOS universal) (push) Has been cancelled
Starlight release / Verify and publish (push) Has been cancelled
Starlight release / Release preflight (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
Starlight release / Build (Linux arm64) (push) Has been cancelled
Sync LobeHub models / sync (push) Has been cancelled
2026-10-04 15:06:20 +08:00
AxTps bb0b094002 fix: migration guard 豁免删除分支
Axolotl desktop CI / guardrails (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Prepare pnpm cache / prepare (push) Has been cancelled
Starlight release / Build (Windows x64) (push) Has been cancelled
Starlight release / Build (Linux x64) (push) Has been cancelled
Starlight release / Build (macOS universal) (push) Has been cancelled
Starlight release / Verify and publish (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
Starlight release / Release preflight (push) Has been cancelled
Starlight release / Build (Linux arm64) (push) Has been cancelled
2026-10-04 13:39:09 +08:00
AxTps 386db4bdb5 fix: 豁免被删除的 000050 迁移文件
Axolotl desktop CI / guardrails (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Starlight release / Build (Windows x64) (push) Has been cancelled
Starlight release / Build (Linux x64) (push) Has been cancelled
Starlight release / Build (macOS universal) (push) Has been cancelled
Starlight release / Verify and publish (push) Has been cancelled
Prepare pnpm cache / prepare (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
Starlight release / Release preflight (push) Has been cancelled
Starlight release / Build (Linux arm64) (push) Has been cancelled
2026-10-04 13:36:53 +08:00
AxTps f98dbf1592 fix: migration guard 豁免补建表引发的删除与分歧
Axolotl desktop CI / guardrails (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Starlight release / Build (Windows x64) (push) Has been cancelled
Starlight release / Build (Linux x64) (push) Has been cancelled
Starlight release / Build (macOS universal) (push) Has been cancelled
Starlight release / Verify and publish (push) Has been cancelled
Prepare pnpm cache / prepare (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
Starlight release / Release preflight (push) Has been cancelled
Starlight release / Build (Linux arm64) (push) Has been cancelled
2026-10-04 13:26:59 +08:00
AxTps 48aff7550a fix: 补建 synced_pack_catalog / synced_pack_instances,发布 1.0.2-beta2
Axolotl desktop CI / guardrails (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Starlight release / Build (Windows x64) (push) Has been cancelled
Starlight release / Build (Linux x64) (push) Has been cancelled
Starlight release / Build (macOS universal) (push) Has been cancelled
Starlight release / Verify and publish (push) Has been cancelled
Prepare pnpm cache / prepare (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
Starlight release / Release preflight (push) Has been cancelled
Starlight release / Build (Linux arm64) (push) Has been cancelled
把两张同步包表的建表语句并入 20261003000000(原 000050 会触发 migration guard 的 out-of-order);给 check-migrations.mjs 增加 allowedHistoricalFixes 豁免;更新 catalog 到 1.0.2-beta2。
2026-10-04 13:16:34 +08:00
AxTps c000e6a535 fix: 补建跨实例同步缺失的 synced_pack_catalog / synced_pack_instances 表
Axolotl desktop CI / guardrails (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Prepare pnpm cache / prepare (push) Has been cancelled
Starlight release / Build (Windows x64) (push) Has been cancelled
Starlight release / Build (Linux x64) (push) Has been cancelled
Starlight release / Build (macOS universal) (push) Has been cancelled
Starlight release / Verify and publish (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
Starlight release / Release preflight (push) Has been cancelled
Starlight release / Build (Linux arm64) (push) Has been cancelled
移植跨实例同步时遗漏了这两张表,导致 20261003000200_synced-pack-selection.sql 对不存在的 synced_pack_catalog 执行 ALTER 而迁移失败、启动器无法初始化。新增 20261003000050_synced-pack-tables.sql(顺序位于 feature-tables 之后、pack-selection 之前)补建。
2026-10-04 12:46:12 +08:00
AxTps 2ed2791316 docs: 1.0.2-beta1 更新日志补充跨实例同步
Axolotl desktop CI / guardrails (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Starlight release / Build (Windows x64) (push) Has been cancelled
Starlight release / Build (Linux x64) (push) Has been cancelled
Starlight release / Build (macOS universal) (push) Has been cancelled
Starlight release / Verify and publish (push) Has been cancelled
Prepare pnpm cache / prepare (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
Starlight release / Release preflight (push) Has been cancelled
Starlight release / Build (Linux arm64) (push) Has been cancelled
2026-10-04 11:27:16 +08:00
AxTps d422f3aeaf docs: 补充 1.0.2-beta1 更新日志(周年庆彩蛋)
Axolotl desktop CI / guardrails (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Starlight release / Build (Windows x64) (push) Has been cancelled
Starlight release / Build (Linux x64) (push) Has been cancelled
Starlight release / Build (macOS universal) (push) Has been cancelled
Starlight release / Verify and publish (push) Has been cancelled
Prepare pnpm cache / prepare (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
Starlight release / Release preflight (push) Has been cancelled
Starlight release / Build (Linux arm64) (push) Has been cancelled
2026-10-04 11:26:45 +08:00
AxTps a21fe3750b feat: 新增 Starlight 周年庆彩蛋(每年 10 月 4 日)
Axolotl desktop CI / guardrails (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
10 月 4 日(Starlight 首个发布日 2014-10-04)当天,启动器顶部显示周年横幅并飘落蛋糕/彩带,周年数按年份-2014 计算。新增 helpers/anniversary.ts 与 AnniversaryCelebration.vue;开发者页加入 force_anniversary_celebration 功能开关用于随时预览。
2026-10-04 11:23:27 +08:00
Ap_Tx 8a447f33f6 Merge pull request #7 from ApTx2012/feat/instance-sync
Axolotl desktop CI / guardrails (push) Has been cancelled
Axolotl desktop CI / desktop (macos-latest) (push) Has been cancelled
Axolotl desktop CI / desktop (windows-latest) (push) Has been cancelled
Repository checks / typos (push) Has been cancelled
Repository checks / tombi (push) Has been cancelled
Rust checks / shear (push) Has been cancelled
Sync source to CNB / Sync Git ref (push) Has been cancelled
Axolotl desktop CI / desktop (ubuntu-latest) (push) Has been cancelled
Axolotl desktop CI / website (push) Has been cancelled
Sync LobeHub models / sync (push) Has been cancelled
Axolotl→Starlight 的跨实例同步移植,含后端命令层 + 前端 UI。
2026-10-04 10:59:58 +08:00
201 changed files with 4100 additions and 213 deletions

No files matched your search

+2 -2
View File
@@ -12,7 +12,7 @@ on:
permissions:
issues: write
pull-requests: read
pull-requests: write
jobs:
comment:
@@ -21,7 +21,7 @@ jobs:
permissions:
issues: write
pull-requests: read
pull-requests: write
contents: read
steps:
+1 -1
View File
@@ -22,5 +22,5 @@ jobs:
node-version-file: .nvmrc
- uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
- uses: cargo-bins/cargo-binstall@dc19f1e48450eefe5a29b8da6c6b00a87d730b37 # v1.18.1
- run: cargo binstall --no-confirm cargo-shear
- run: cargo binstall --no-confirm cargo-shear@1.13.4
- run: cargo shear
Generated
+2 -2
View File
@@ -6841,7 +6841,7 @@ dependencies = [
[[package]]
name = "theseus"
version = "1.0.0-beta15"
version = "1.0.2-beta4"
dependencies = [
"ariadne",
"async-minecraft-ping",
@@ -6945,7 +6945,7 @@ dependencies = [
[[package]]
name = "theseus_gui"
version = "1.0.0-beta15"
version = "1.0.2-beta4"
dependencies = [
"ashpd",
"async_zip",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@modrinth/app-frontend",
"private": true,
"version": "1.0.0-beta15",
"version": "1.0.2-beta4",
"type": "module",
"scripts": {
"dev": "vite",
+4
View File
@@ -72,6 +72,7 @@ import InstancePlayerModal from '@/components/instance/InstancePlayerModal.vue'
import TaggedModDownloadsModal from '@/components/instance/TaggedModDownloadsModal.vue'
import InstanceExportModal from '@/components/lab/recipe-generator/InstanceExportModal.vue'
import AccountsCard from '@/components/ui/AccountsCard.vue'
import AnniversaryCelebration from '@/components/ui/AnniversaryCelebration.vue'
import AppActionBar from '@/components/ui/AppActionBar.vue'
import AxolotlLogo from '@/components/ui/AxolotlLogo.vue'
import Breadcrumbs from '@/components/ui/Breadcrumbs.vue'
@@ -94,6 +95,7 @@ import NavRail from '@/components/ui/NavRail.vue'
import OnboardingOverlay from '@/components/ui/onboarding/OnboardingOverlay.vue'
import QuickInstanceSwitcher from '@/components/ui/QuickInstanceSwitcher.vue'
import SkinSiteSessionFrame from '@/components/ui/SkinSiteSessionFrame.vue'
import RemoteAnnouncements from '@/components/ui/RemoteAnnouncements.vue'
import StartupAnnouncementModal from '@/components/ui/StartupAnnouncementModal.vue'
import SplashScreen from '@/components/ui/SplashScreen.vue'
import WindowControls from '@/components/ui/WindowControls.vue'
@@ -2221,10 +2223,12 @@ provideAppUpdateDownloadProgress(appUpdateDownload)
</script>
<template>
<AnniversaryCelebration />
<SplashScreen v-if="!stateFailed" ref="splashScreen" data-tauri-drag-region />
<SkinSiteSessionFrame v-if="stateInitialized" />
<InstancePlayerModal v-if="stateInitialized" />
<StartupAnnouncementModal ref="startupAnnouncementModal" />
<RemoteAnnouncements :ready="stateInitialized && !showOnboarding && !stateFailed" />
<div id="teleports"></div>
<div
v-if="stateInitialized && themeStore.customBackgroundPath && !themeStore.transparentBackground"
@@ -32,6 +32,129 @@ export const ANNOUNCEMENT_CHANGE_TYPES: readonly AnnouncementChangeType[] = [
]
export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
{
id: 'launcher-1.0.2-beta5',
version: '1.0.2-beta5',
publishedAt: '2026-10-11',
title: {
'en-US': 'Starlight Launcher 1.0.2-beta5',
'zh-CN': 'Starlight Launcher 1.0.2-beta5',
},
changes: {
added: [
{
'en-US': 'Added a remote announcements center: a bell in the top bar opens a panel listing launcher announcements fetched from the Starlight skin site.',
'zh-CN': '新增远程公告中心:顶栏的铃铛可打开公告面板,展示从 Starlight 皮肤站拉取的启动器公告。',
},
{
'en-US': 'Added a custom Minecraft window title option: set a global toggle and default title, and let each instance override it. The game window is renamed on Windows.',
'zh-CN': '新增自定义 Minecraft 窗口标题:可设置全局开关与默认标题,并允许各实例单独覆盖;Windows 下会重命名游戏窗口。',
},
],
fixed: [
{
'en-US': 'Completed the Chinese translations for the armor preview feature.',
'zh-CN': '补齐盔甲预览功能的中文翻译。',
},
],
},
},
{
id: 'launcher-1.0.2-beta4',
version: '1.0.2-beta4',
publishedAt: '2026-10-08',
title: {
'en-US': 'Starlight Launcher 1.0.2-beta4',
'zh-CN': 'Starlight Launcher 1.0.2-beta4',
},
changes: {
added: [
{
'en-US': 'Added armor and armor-trim rendering to the skin preview, letting you try on armor pieces and trim patterns directly in the skin editor.',
'zh-CN': '皮肤预览新增盔甲与盔甲纹饰渲染,可在皮肤编辑器内直接试穿各部位盔甲并调整纹饰图案。',
},
{
'en-US': 'Armor preview selections in the skin editor are now saved locally, so they persist across sessions.',
'zh-CN': '皮肤编辑器中的盔甲预览选择现在会保存在本地,跨会话保留。',
},
],
changed: [
{
'en-US': 'Improved download scheduling to reduce concurrency automatically when tasks are waiting for capacity, making large Minecraft installations more reliable on constrained connections.',
'zh-CN': '优化下载任务调度:任务因容量不足排队时会自动降低并发,提升大型 Minecraft 版本在受限网络环境下的安装稳定性。',
},
],
fixed: [
{
'en-US': 'Fixed downloads timing out while waiting for internal connection capacity, which could cause Minecraft installations to fail even when the network was available.',
'zh-CN': '修复下载任务等待内部连接容量时过早超时,导致网络正常的情况下 Minecraft 安装仍可能失败的问题。',
},
{
'en-US': 'Fixed instance group changes not saving for some instances.',
'zh-CN': '修复部分实例的分组修改无法保存的问题。',
},
],
},
},
{
id: 'launcher-1.0.2-beta3',
version: '1.0.2-beta3',
publishedAt: '2026-10-04',
title: {
'en-US': 'Starlight Launcher 1.0.2-beta3',
'zh-CN': 'Starlight Launcher 1.0.2-beta3',
},
changes: {
fixed: [
{
'en-US': 'Fixed the anniversary celebration banner not showing above the window title bar, and made the banner background semi-transparent so the content behind it stays visible.',
'zh-CN': '修复周年庆庆祝横幅被窗口标题栏遮挡、无法显示的问题,并将横幅背景改为半透明,避免遮住下方内容。',
},
],
},
},
{
id: 'launcher-1.0.2-beta2',
version: '1.0.2-beta2',
publishedAt: '2026-10-04',
title: {
'en-US': 'Starlight Launcher 1.0.2-beta2',
'zh-CN': 'Starlight Launcher 1.0.2-beta2',
},
changes: {
fixed: [
{
'en-US': 'Fixed the launcher failing to start with "no such table: synced_pack_catalog": the cross-instance sync migration was missing the synced_pack_catalog and synced_pack_instances tables.',
'zh-CN': '修复启动器因 "no such table: synced_pack_catalog" 无法启动的问题:跨实例同步迁移遗漏了 synced_pack_catalog 与 synced_pack_instances 两张表。',
},
],
},
},
{
id: 'launcher-1.0.2-beta1',
version: '1.0.2-beta1',
publishedAt: '2026-10-04',
title: {
'en-US': 'Starlight Launcher 1.0.2-beta1',
'zh-CN': 'Starlight Launcher 1.0.2-beta1',
},
changes: {
added: [
{
'en-US': 'Cross-instance sync: share game options, resource packs, data packs, multiplayer servers, command history, and creative hotbars across instances, with per-option toggles and a fine-grained game-settings editor.',
'zh-CN': '跨实例同步:可跨实例共享游戏选项、资源包、数据包、多人服务器、命令历史与创造模式快捷栏,支持逐项开关与精细的游戏设置编辑器。',
},
{
'en-US': 'Starlight turns 12! On October 4th every year the launcher now shows a celebration banner and falling confetti. The anniversary number is computed from 2014.',
'zh-CN': 'Starlight 十二周年!每年 10 月 4 日,启动器会显示庆祝横幅与飘落的彩带、蛋糕,周年数按 2014 年起算。',
},
{
'en-US': 'Added a developer feature flag to preview the anniversary celebration at any time.',
'zh-CN': '新增开发者功能开关,可随时预览周年庆效果。',
},
],
},
},
{
id: 'launcher-1.0.1',
version: '1.0.1',
@@ -0,0 +1,246 @@
<script setup lang="ts">
import { defineMessages, useVIntl } from '@modrinth/ui'
import { computed, onUnmounted, ref, watch } from 'vue'
import { anniversaryYear, ordinal, shouldCelebrate } from '@/helpers/anniversary'
import { useTheming } from '@/store/state'
const { formatMessage } = useVIntl()
const themeStore = useTheming()
const messages = defineMessages({
banner: {
id: 'app.anniversary.banner',
defaultMessage: 'Happy {ordinal} Anniversary, Starlight!',
},
})
/** Emoji that drift down from the top of the window. */
const CONFETTI_EMOJI = ['🎂', '🎉', '🎊', '🎈', '✨', '🧁', '🍰']
type Confetti = {
id: number
emoji: string
left: number
delay: number
duration: number
size: number
drift: number
}
const visible = ref(false)
const years = ref(0)
const confetti = ref<Confetti[]>([])
let spawnTimer: number | undefined
let nextId = 0
function spawnConfetti(): void {
const emoji = CONFETTI_EMOJI[Math.floor(Math.random() * CONFETTI_EMOJI.length)]
confetti.value.push({
id: nextId++,
emoji,
left: Math.random() * 100,
delay: 0,
duration: 6 + Math.random() * 5,
size: 1 + Math.random() * 1.4,
drift: (Math.random() - 0.5) * 160,
})
// Keep the DOM small; drop the oldest once we exceed a cap.
if (confetti.value.length > 60) confetti.value.splice(0, 10)
}
const forced = computed(() => themeStore.getFeatureFlag('force_anniversary_celebration'))
function startCelebration(): void {
if (spawnTimer !== undefined) return
years.value = anniversaryYear()
visible.value = true
// Seed a few so the screen is not empty on the first frame.
for (let i = 0; i < 12; i++) spawnConfetti()
spawnTimer = window.setInterval(spawnConfetti, 700)
}
function stopCelebration(): void {
if (spawnTimer !== undefined) {
window.clearInterval(spawnTimer)
spawnTimer = undefined
}
confetti.value = []
visible.value = false
}
watch(
() => shouldCelebrate(forced.value),
(active) => (active ? startCelebration() : stopCelebration()),
{ immediate: true },
)
onUnmounted(stopCelebration)
const bannerText = computed(() =>
formatMessage(messages.banner, { ordinal: ordinal(years.value) }),
)
</script>
<template>
<Transition name="anniversary-fade">
<div v-if="visible" class="anniversary-root" aria-live="polite">
<!-- Falling confetti layer (click-through). -->
<div class="anniversary-confetti" aria-hidden="true">
<span
v-for="piece in confetti"
:key="piece.id"
class="anniversary-piece"
:style="{
left: piece.left + '%',
fontSize: piece.size + 'rem',
animationDelay: piece.delay + 's',
animationDuration: piece.duration + 's',
'--drift': piece.drift + 'px',
}"
>
{{ piece.emoji }}
</span>
</div>
<!-- Top banner. -->
<div class="anniversary-banner">
<span class="anniversary-banner-emoji">🎂</span>
<span class="anniversary-banner-text">{{ bannerText }}</span>
<span class="anniversary-banner-emoji">🎉</span>
</div>
</div>
</Transition>
</template>
<style scoped>
.anniversary-root {
position: fixed;
inset: 0;
/* Above content, below modals/drag overlays (which use z-[200]). */
z-index: 150;
pointer-events: none;
}
.anniversary-confetti {
position: absolute;
inset: 0;
overflow: hidden;
}
.anniversary-piece {
position: absolute;
top: -3rem;
will-change: transform;
animation-name: anniversary-fall;
animation-timing-function: linear;
animation-iteration-count: 1;
animation-fill-mode: forwards;
}
@keyframes anniversary-fall {
0% {
transform: translate3d(0, 0, 0) rotate(0deg);
opacity: 0;
}
10% {
opacity: 1;
}
100% {
transform: translate3d(var(--drift, 0), 110vh, 0) rotate(360deg);
opacity: 0.85;
}
}
.anniversary-banner {
position: absolute;
/* 避开原生窗口标题栏(Windows/macOS 系统装饰条会盖住 top:0 的内容);
titlebar-area-height 是 Tauri 暴露的标题栏高度变量,不支持时降级为 0 */
top: env(titlebar-area-height, 0px);
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.4rem 1rem;
font-weight: 700;
font-size: 0.95rem;
letter-spacing: 0.02em;
color: #fff;
/* 半透明深色兜底:即使下面的渐变背景失效,白字也不会在浅色页面上隐形 */
background-color: rgba(20, 16, 28, 0.35);
/* 半透明彩色渐变:让窗口下方的内容能透出来 */
background-image: linear-gradient(
90deg,
rgba(244, 114, 182, 0.8),
rgba(250, 204, 21, 0.8),
rgba(74, 222, 128, 0.8),
rgba(56, 189, 248, 0.8),
rgba(167, 139, 250, 0.8),
rgba(244, 114, 182, 0.8)
);
background-size: 300% 100%;
animation: anniversary-gradient 8s linear infinite;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25);
text-shadow:
0 1px 2px rgba(0, 0, 0, 0.55),
0 0 4px rgba(0, 0, 0, 0.35);
}
.anniversary-banner-text {
animation: anniversary-pulse 1.8s ease-in-out infinite;
}
.anniversary-banner-emoji {
animation: anniversary-bounce 1.4s ease-in-out infinite;
}
@keyframes anniversary-gradient {
0% {
background-position: 0% 50%;
}
100% {
background-position: 300% 50%;
}
}
@keyframes anniversary-pulse {
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.06);
}
}
@keyframes anniversary-bounce {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-3px);
}
}
.anniversary-fade-enter-active,
.anniversary-fade-leave-active {
transition: opacity 0.6s ease;
}
.anniversary-fade-enter-from,
.anniversary-fade-leave-to {
opacity: 0;
}
@media (prefers-reduced-motion: reduce) {
.anniversary-piece,
.anniversary-banner,
.anniversary-banner-text,
.anniversary-banner-emoji {
animation: none;
}
}
</style>
@@ -67,6 +67,23 @@
</div>
</template>
</Dropdown>
<ButtonStyled
v-tooltip="formatMessage(messages.announcements)"
type="transparent"
circular
>
<button
:aria-label="formatMessage(messages.announcements)"
class="relative"
@click="openAnnouncementCenter"
>
<NewspaperIcon />
<span
v-if="announcementUnreadCount"
class="absolute right-0 top-0 size-2 rounded-full bg-red ring-2 ring-bg-raised"
/>
</button>
</ButtonStyled>
<ButtonStyled
v-if="!isDownloadsPage && hasActiveDownloads && !hasVisibleActiveDownloadToasts"
color="brand"
@@ -190,6 +207,7 @@
<script setup lang="ts">
import {
BellIcon,
NewspaperIcon,
DownloadIcon,
DropdownIcon,
OnlineIndicatorIcon,
@@ -211,7 +229,7 @@ import {
} from '@modrinth/ui'
import { convertFileSrc } from '@tauri-apps/api/core'
import { Dropdown } from 'floating-vue'
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AppUpdateButton from '@/components/ui/app-update-button/index.vue'
@@ -222,6 +240,10 @@ import { get_many as getInstances } from '@/helpers/instance'
import { get_all as getRunningProcesses, kill as killProcess } from '@/helpers/process'
import type { LoadingBar } from '@/helpers/state'
import { progress_bars_list } from '@/helpers/state'
import {
OPEN_REMOTE_ANNOUNCEMENT_CENTER_EVENT,
REMOTE_ANNOUNCEMENTS_UPDATED_EVENT,
} from '@/helpers/remote-announcements'
import type { GameInstance } from '@/helpers/types'
import { downloadBarTypes, injectDownloadManager } from '@/providers/download-manager'
@@ -231,6 +253,25 @@ const popupNotificationManager = injectPopupNotificationManager()
const downloadManager = injectDownloadManager()
const { formatMessage } = useVIntl()
const announcementUnreadCount = ref(0)
function openAnnouncementCenter() {
window.dispatchEvent(new CustomEvent(OPEN_REMOTE_ANNOUNCEMENT_CENTER_EVENT))
}
function updateAnnouncementCount(event: Event) {
const detail = (event as CustomEvent<{ unreadKeys?: string[] }>).detail
announcementUnreadCount.value = detail?.unreadKeys?.length ?? 0
}
onMounted(() => {
window.addEventListener(REMOTE_ANNOUNCEMENTS_UPDATED_EVENT, updateAnnouncementCount)
})
onBeforeUnmount(() => {
window.removeEventListener(REMOTE_ANNOUNCEMENTS_UPDATED_EVENT, updateAnnouncementCount)
})
type NotificationHistoryItem = {
key: string
createdAt?: number
@@ -370,6 +411,10 @@ const messages = defineMessages({
id: 'app.action-bar.notifications',
defaultMessage: 'Notifications',
},
announcements: {
id: 'app.action-bar.announcements',
defaultMessage: 'Announcements',
},
clearNotifications: {
id: 'app.action-bar.notifications.clear',
defaultMessage: 'Clear all',
@@ -0,0 +1,420 @@
<script setup lang="ts">
import {
Button,
commonMessages,
defineMessages,
NewModal,
useModalStack,
useVIntl,
} from '@modrinth/ui'
import { renderString } from '@modrinth/utils'
import { fetch as tauriFetch } from '@tauri-apps/plugin-http'
import { openUrl } from '@tauri-apps/plugin-opener'
import { computed, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import {
announcementKey,
isAnnouncementActive,
mapBroadcastAnnouncements,
OPEN_REMOTE_ANNOUNCEMENT_CENTER_EVENT,
parseAnnouncements,
REMOTE_ANNOUNCEMENTS_UPDATED_EVENT,
type RemoteAnnouncement,
safeAnnouncementUrl,
} from '@/helpers/remote-announcements'
import {
requestSkinSiteDownloadToken,
skinSiteStatus,
waitForSkinSiteSession,
} from '@/composables/skin-site-session.ts'
const props = defineProps<{ ready: boolean; previewOnly?: boolean }>()
const { formatMessage } = useVIntl()
const { hasModal } = useModalStack()
const messages = defineMessages({
view: { id: 'app.remote-announcements.view', defaultMessage: 'View announcement' },
unread: { id: 'app.remote-announcements.unread', defaultMessage: 'Unread' },
readAll: {
id: 'app.remote-announcements.read-all',
defaultMessage: 'Mark all announcements as read',
},
centerTitle: { id: 'app.remote-announcements.center-title', defaultMessage: 'Announcements' },
empty: { id: 'app.remote-announcements.empty', defaultMessage: 'No announcements' },
previewTitle: {
id: 'app.remote-announcements.preview-title',
defaultMessage: 'Announcement style preview',
},
previewSummary: {
id: 'app.remote-announcements.preview-summary',
defaultMessage:
'This is a local preview. Select View announcement to preview the full Markdown content.',
},
previewContent: {
id: 'app.remote-announcements.preview-content',
defaultMessage:
'## Announcement preview\n\nThis is **sample content**, not a published announcement.\n\n- Supports headings, lists, and links\n- Close buttons are always available\n\n> Previewing does not change real announcement read status.\n\n| Type | Display |\n| --- | --- |\n| Modal | Full Markdown content |\n| Popup | Summary, then full content |\n\n[Visit the website](https://skin.starlight.cool/)',
},
previewAction: { id: 'app.remote-announcements.preview-action', defaultMessage: 'Visit website' },
})
const modal = ref<InstanceType<typeof NewModal>>()
const selected = ref<RemoteAnnouncement | null>(null)
const active = ref(false)
const centerOpen = ref(false)
const startupNotice = ref<RemoteAnnouncement | null>(null)
const html = computed(() => renderString(selected.value?.content ?? ''))
const stateKey = 'starlight-remote-announcements-v2'
const read = reactive(new Set<string>())
const queuedThisSession = new Set<string>()
const startupNotified = new Set<string>()
let items: RemoteAnnouncement[] = []
let pending: RemoteAnnouncement[] = []
let cacheKey = 'starlight-remote-announcements-cache-v1'
let cacheLoaded = false
let disposed = false
let interval: ReturnType<typeof setInterval> | undefined
let advanceTimer: ReturnType<typeof setTimeout> | undefined
function persist() {
if (props.previewOnly) return
try {
localStorage.setItem(
stateKey,
JSON.stringify({
read: [...read].slice(-1000),
}),
)
} catch {
// localStorage may be unavailable (private mode / quota)
}
}
function emitState() {
window.dispatchEvent(
new CustomEvent(REMOTE_ANNOUNCEMENTS_UPDATED_EVENT, {
detail: {
items,
unreadKeys: items.filter((item) => !read.has(announcementKey(item))).map(announcementKey),
},
}),
)
}
function openCenter(item?: RemoteAnnouncement) {
if (!props.ready || disposed) return
centerOpen.value = true
if (item) {
startupNotice.value = null
selectAnnouncement(item)
} else if (!selected.value && items.length) {
selectAnnouncement(items[0])
}
void nextTick(() => modal.value?.show())
}
function handleOpenCenter() {
if (props.previewOnly) return
openCenter()
}
async function show(item: RemoteAnnouncement) {
if (
disposed ||
!props.ready ||
!isAnnouncementActive(item) ||
(hasModal.value && !active.value && !centerOpen.value)
)
return
centerOpen.value = true
active.value = true
selectAnnouncement(item)
await nextTick()
if (!disposed) modal.value?.show()
}
function selectAnnouncement(item: RemoteAnnouncement) {
selected.value = item
const key = announcementKey(item)
read.add(key)
pending = pending.filter((entry) => announcementKey(entry) !== key)
persist()
emitState()
}
function markAllRead() {
for (const item of items) {
read.add(announcementKey(item))
}
pending = []
persist()
emitState()
}
function advance() {
if (disposed || !props.ready || hasModal.value || active.value) return
const next = pending.shift()
if (next) {
void show(next)
return
}
for (const item of items) {
const key = announcementKey(item)
if (
item.type === 'notification' &&
!startupNotified.has(key) &&
!read.has(key) &&
isAnnouncementActive(item)
) {
startupNotice.value = item
startupNotified.add(key)
setTimeout(() => {
if (startupNotice.value === item) {
startupNotice.value = null
advance()
}
}, 8000)
break
}
}
}
function closed() {
active.value = false
centerOpen.value = false
if (advanceTimer) clearTimeout(advanceTimer)
advanceTimer = setTimeout(advance, 350)
}
function sync(next: RemoteAnnouncement[], fresh: boolean) {
items = next.filter((item) => isAnnouncementActive(item))
const keys = new Set(items.map(announcementKey))
pending = pending.filter((item) => keys.has(announcementKey(item)))
if (selected.value && !keys.has(announcementKey(selected.value))) selected.value = null
emitState()
if (fresh) {
for (const item of items) {
const key = announcementKey(item)
if (
item.type === 'modal' &&
!queuedThisSession.has(key) &&
(!read.has(key) || item.priority === 'critical')
) {
queuedThisSession.add(key)
pending.push(item)
}
}
advance()
}
}
function loadCache() {
if (cacheLoaded || !cacheKey) return
cacheLoaded = true
try {
const cached = JSON.parse(localStorage.getItem(cacheKey) ?? 'null')
if (cached && typeof cached.savedAt === 'number' && Date.now() - cached.savedAt < 86400000) {
const parsed = parseAnnouncements(cached.items)
if (parsed) sync(parsed, false)
}
} catch {
// Ignore malformed or expired cache payloads
}
}
function saveCache(next: RemoteAnnouncement[]) {
if (!cacheKey) return
try {
localStorage.setItem(cacheKey, JSON.stringify({ savedAt: Date.now(), items: next }))
} catch {
// localStorage may be unavailable (private mode / quota)
}
}
async function refresh() {
if (disposed) return
loadCache()
if (skinSiteStatus.value !== 'signed-in') return
try {
await waitForSkinSiteSession()
const token = await requestSkinSiteDownloadToken()
const response = await tauriFetch('https://skin.starlight.cool/starlight/skin/broadcast/all', {
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
})
if (!response.ok) return
const data = await response.json()
const parsed = mapBroadcastAnnouncements((data as { payload?: unknown } | null)?.payload)
if (parsed && !disposed) {
sync(parsed, true)
saveCache(parsed)
}
} catch {
// Remote fetch failed; previously cached items remain displayed
}
}
async function openLink(value: unknown) {
const url = safeAnnouncementUrl(value)
if (!url) return
try {
await openUrl(url)
} catch {
// Opener may reject unknown schemes
}
}
function contentClick(event: MouseEvent) {
const link = event.target instanceof Element ? event.target.closest('a') : null
if (!link) return
event.preventDefault()
event.stopPropagation()
void openLink(link.getAttribute('href'))
}
function preview(type: RemoteAnnouncement['type'], withAction = false) {
if (!props.previewOnly || !props.ready || hasModal.value || disposed) return
const now = new Date().toISOString()
const item: RemoteAnnouncement = {
id: 'local-preview-' + type,
title: formatMessage(messages.previewTitle),
summary: formatMessage(messages.previewSummary),
content: formatMessage(messages.previewContent),
type,
priority: 'normal',
starts_at: now,
ends_at: null,
published_at: now,
action_label: withAction ? formatMessage(messages.previewAction) : null,
action_url: withAction ? 'https://skin.starlight.cool/' : null,
}
read.clear()
queuedThisSession.clear()
sync([item], true)
}
defineExpose({ preview })
onMounted(() => {
if (props.previewOnly) return
try {
const saved = JSON.parse(localStorage.getItem(stateKey) ?? 'null')
if (saved && Array.isArray(saved.read))
for (const key of saved.read) if (typeof key === 'string') read.add(key)
} catch {
// Ignore malformed local read-state
}
window.addEventListener(OPEN_REMOTE_ANNOUNCEMENT_CENTER_EVENT, handleOpenCenter)
const start = () => {
if (disposed) return
void refresh()
interval = setInterval(() => {
sync(items, false)
advance()
}, 15000)
}
// Defer the startup request until after first paint.
if (typeof requestIdleCallback === 'function') {
requestIdleCallback(start, { timeout: 2000 })
} else {
setTimeout(start, 500)
}
})
watch([() => props.ready, hasModal], () => {
if (advanceTimer) clearTimeout(advanceTimer)
advanceTimer = setTimeout(advance, 350)
})
onUnmounted(() => {
disposed = true
if (interval) clearInterval(interval)
if (advanceTimer) clearTimeout(advanceTimer)
window.removeEventListener(OPEN_REMOTE_ANNOUNCEMENT_CENTER_EVENT, handleOpenCenter)
})
</script>
<template>
<div
v-if="startupNotice"
class="fixed right-4 top-16 z-50 w-[22rem] max-w-[calc(100vw-2rem)] rounded-xl border border-surface-5 bg-surface-3 p-3 shadow-lg"
>
<button class="w-full text-left" @click="startupNotice && openCenter(startupNotice)">
<div class="mb-1 text-xs font-semibold uppercase text-brand">
{{ formatMessage(messages.unread) }}
</div>
<div class="font-semibold text-[var(--color-text-primary)]">{{ startupNotice.title }}</div>
<div
v-if="startupNotice.summary"
class="mt-1 line-clamp-2 text-sm text-[var(--color-text-tertiary)]"
>
{{ startupNotice.summary }}
</div>
</button>
</div>
<NewModal
ref="modal"
:header="formatMessage(messages.centerTitle)"
:on-hide="closed"
max-width="80vw"
width="80vw"
max-content-height="calc(80vh - 8rem)"
scrollable
>
<div class="flex h-[calc(80vh-8rem)] min-h-0 gap-3">
<aside class="flex min-h-0 w-[32%] min-w-[14rem] flex-col border-r border-surface-5 pr-3">
<div class="mb-2 flex items-center justify-between">
<span class="font-semibold text-[var(--color-text-primary)]">{{
formatMessage(messages.centerTitle)
}}</span>
<Button
v-if="items.some((item) => !read.has(announcementKey(item)))"
@click="markAllRead"
>{{ formatMessage(messages.readAll) }}</Button
>
</div>
<div
v-if="!items.length"
class="py-8 text-center text-sm text-[var(--color-text-tertiary)]"
>
{{ formatMessage(messages.empty) }}
</div>
<div v-else class="flex min-h-0 flex-col gap-1 overflow-auto">
<button
v-for="item in items"
:key="announcementKey(item)"
class="flex items-start gap-2 rounded-lg p-2 text-left hover:bg-surface-4"
:class="{
'bg-surface-4': selected && announcementKey(selected) === announcementKey(item),
}"
@click="selectAnnouncement(item)"
>
<span
class="mt-1.5 size-2 shrink-0 rounded-full"
:class="read.has(announcementKey(item)) ? 'opacity-0' : 'bg-red'"
/>
<span class="min-w-0 flex-1">
<span class="block truncate font-medium text-[var(--color-text-primary)]">{{
item.title
}}</span>
<span class="block line-clamp-2 text-xs text-[var(--color-text-tertiary)]">{{
item.summary || item.content
}}</span>
</span>
</button>
</div>
</aside>
<section v-if="selected" class="min-h-0 min-w-0 flex-1 overflow-auto px-1">
<h2 class="mb-4 text-xl font-semibold text-[var(--color-text-primary)]">
{{ selected.title }}
</h2>
<div
class="markdown-body break-words"
@click="contentClick"
@auxclick="contentClick"
v-html="html"
/>
<div class="mt-4 flex justify-end">
<Button
v-if="selected.action_url && selected.action_label"
type="colored"
color="brand"
@click="openLink(selected.action_url)"
>{{ selected.action_label }}</Button
>
</div>
</section>
<div
v-else
class="flex flex-1 items-center justify-center text-sm text-[var(--color-text-tertiary)]"
>
{{ formatMessage(messages.empty) }}
</div>
</div>
<template #actions>
<div class="flex flex-wrap justify-end gap-2">
<Button @click="modal?.hide()">{{ formatMessage(commonMessages.closeButton) }} </Button>
</div>
</template>
</NewModal>
</template>
@@ -36,24 +36,29 @@ const fullscreenSetting: Ref<boolean> = ref(
instance.value.force_fullscreen ?? globalSettings.force_fullscreen,
)
const maximizeWindowSetting = ref(instance.value.maximize_window ?? globalSettings.maximize_window)
const windowTitle = ref(instance.value.window_title ?? '')
const editInstanceObject = computed(() => {
const title = windowTitle.value.trim() ? windowTitle.value.trim() : null
if (!overrideWindowSettings.value) {
return {
force_fullscreen: null,
maximize_window: null,
game_resolution: null,
// The title is independent of the window-size override checkbox.
window_title: title,
}
}
return {
force_fullscreen: fullscreenSetting.value,
maximize_window: maximizeWindowSetting.value,
game_resolution: fullscreenSetting.value ? null : resolution.value,
window_title: title,
}
})
watch(
[overrideWindowSettings, resolution, fullscreenSetting, maximizeWindowSetting],
[overrideWindowSettings, resolution, fullscreenSetting, maximizeWindowSetting, windowTitle],
async () => {
await edit(instance.value.id, editInstanceObject.value)
},
@@ -109,6 +114,18 @@ const messages = defineMessages({
id: 'instance.settings.tabs.window.height.enter',
defaultMessage: 'Enter height...',
},
windowTitle: {
id: 'instance.settings.tabs.window.window-title',
defaultMessage: 'Window title',
},
windowTitleDescription: {
id: 'instance.settings.tabs.window.window-title.description',
defaultMessage: 'Customize the Minecraft window title. Leave empty to keep the default.',
},
enterWindowTitle: {
id: 'instance.settings.tabs.window.window-title.enter',
defaultMessage: 'Enter window title...',
},
})
</script>
@@ -200,5 +217,25 @@ const messages = defineMessages({
:placeholder="formatMessage(messages.enterHeight)"
/>
</div>
<div
v-if="globalSettings.custom_window_title_enabled"
class="flex items-center gap-4 justify-between"
>
<div class="flex flex-col gap-1">
<h2 class="m-0 inline-flex items-center gap-2 text-lg font-semibold text-contrast">
{{ formatMessage(messages.windowTitle) }}
</h2>
<p class="m-0">
{{ formatMessage(messages.windowTitleDescription) }}
</p>
</div>
<StyledInput
id="window-title"
v-model="windowTitle"
autocomplete="off"
type="text"
:placeholder="formatMessage(messages.enterWindowTitle)"
/>
</div>
</div>
</template>
@@ -38,6 +38,26 @@ const messages = defineMessages({
id: 'app.settings.defaults.maximize-window.unsupported',
defaultMessage: 'Not supported on this operating system.',
},
windowTitleEnabled: {
id: 'app.settings.defaults.window-title.enabled',
defaultMessage: 'Custom Minecraft window title',
},
windowTitleEnabledDescription: {
id: 'app.settings.defaults.window-title.enabled-description',
defaultMessage: 'Allow instances to customize the Minecraft window title.',
},
defaultWindowTitle: {
id: 'app.settings.defaults.window-title.default',
defaultMessage: 'Default window title',
},
defaultWindowTitleDescription: {
id: 'app.settings.defaults.window-title.default-description',
defaultMessage: 'Used when an instance leaves its window title empty.',
},
defaultWindowTitlePlaceholder: {
id: 'app.settings.defaults.window-title.default-placeholder',
defaultMessage: 'Enter default window title...',
},
width: { id: 'app.settings.defaults.width', defaultMessage: 'Width' },
widthDescription: {
id: 'app.settings.defaults.width-description',
@@ -212,6 +232,36 @@ watch(
/>
</template>
</SettingsRow>
<SettingsRow>
<template #label>
<span id="settings-target-defaults-window-title" tabindex="-1">
{{ formatMessage(messages.windowTitleEnabled) }}
</span>
</template>
<template #description>{{
formatMessage(messages.windowTitleEnabledDescription)
}}</template>
<template #control>
<Toggle id="custom-window-title-enabled" v-model="settings.custom_window_title_enabled" />
</template>
</SettingsRow>
<SettingsRow stacked>
<template #label>{{ formatMessage(messages.defaultWindowTitle) }}</template>
<template #description>{{
formatMessage(messages.defaultWindowTitleDescription)
}}</template>
<template #control>
<StyledInput
id="default-window-title"
v-model="settings.default_window_title"
:disabled="!settings.custom_window_title_enabled"
autocomplete="off"
type="text"
:placeholder="formatMessage(messages.defaultWindowTitlePlaceholder)"
wrapper-class="w-full"
/>
</template>
</SettingsRow>
</SettingsSection>
<SettingsSection>
@@ -71,6 +71,7 @@ const featureFlagLabels: Record<FeatureFlag, string> = {
advanced_filters_collapsed: '高级筛选默认折叠',
multiplayer_in_app: '多人联机',
auto_install_dependencies: '自动安装依赖',
force_anniversary_celebration: '强制显示周年庆庆祝(调试)',
}
const settings = ref(await getSettings())
@@ -0,0 +1,123 @@
<script setup lang="ts">
import { CheckIcon, RotateCounterClockwiseIcon, XIcon } from '@modrinth/assets'
import {
type ArmorPreviewConfig,
ArmorTrimPanel,
Button,
defineMessages,
useVIntl,
} from '@modrinth/ui'
import { computed, onMounted, onUnmounted } from 'vue'
const messages = defineMessages({
title: { id: 'app.skins.armor.title', defaultMessage: 'Armour and trims' },
description: {
id: 'app.skins.armor.description',
defaultMessage: 'Try armour and trims on your skin. Nothing is stored until you save it.',
},
unsaved: { id: 'app.skins.armor.unsaved', defaultMessage: 'Unsaved changes' },
resetToSaved: { id: 'app.skins.armor.reset-to-saved', defaultMessage: 'Reset to saved' },
restoreDefaults: {
id: 'app.skins.armor.restore-defaults',
defaultMessage: 'Restore defaults',
},
save: { id: 'app.skins.armor.save', defaultMessage: 'Save' },
close: { id: 'app.skins.armor.close', defaultMessage: 'Close' },
})
const draft = defineModel<ArmorPreviewConfig>({ required: true })
const props = defineProps<{
saved: ArmorPreviewConfig
/** Stable id shared with the toggle so it can point `aria-controls` here. */
panelId: string
}>()
const emit = defineEmits<{
save: []
reset: []
defaults: []
close: []
}>()
const { formatMessage } = useVIntl()
/**
* The tab is mounted only while it is showing, so this listens exactly for that
* window. It listens in the capture phase because the app's own global
* shortcuts listen on `window` the same way, and a bubble-phase listener here
* would be skipped as soon as anything closer stopped the event. A modal on top
* of the page owns Escape while it is up, and focus sits inside it, so the key
* is left to it.
*/
function handleKeydown(event: KeyboardEvent) {
if (event.key !== 'Escape') return
if (
event.target instanceof Element &&
event.target.closest('[role="dialog"], [role="alertdialog"], [aria-modal="true"]')
) {
return
}
emit('close')
}
onMounted(() => window.addEventListener('keydown', handleKeydown, true))
onUnmounted(() => window.removeEventListener('keydown', handleKeydown, true))
const isDirty = computed(() =>
Object.entries(draft.value).some(([slot, piece]) => {
const applied = props.saved[slot as keyof ArmorPreviewConfig]
return (
!applied ||
applied.material !== piece.material ||
applied.trimPattern !== piece.trimPattern ||
applied.trimMaterial !== piece.trimMaterial
)
}),
)
</script>
<template>
<div
:id="panelId"
role="region"
:aria-label="formatMessage(messages.title)"
class="flex min-h-[24rem] flex-col gap-4 rounded-2xl border border-solid border-surface-5 bg-surface-2 p-4"
>
<header class="flex flex-wrap items-start justify-between gap-3">
<div class="min-w-0">
<h2 class="m-0 text-lg font-bold text-[var(--color-text-primary)]">
{{ formatMessage(messages.title) }}
</h2>
<p class="m-0 mt-1 text-sm leading-6 text-[var(--color-text-tertiary)]">
{{ formatMessage(messages.description) }}
</p>
</div>
<div class="flex shrink-0 flex-wrap items-center gap-2">
<span v-if="isDirty" class="text-sm font-semibold text-[var(--color-text-tertiary)]">
{{ formatMessage(messages.unsaved) }}
</span>
<Button type="outlined" @click="emit('close')"
><XIcon />{{ formatMessage(messages.close) }}</Button
>
</div>
</header>
<ArmorTrimPanel v-model="draft" />
<footer
class="mt-auto flex flex-wrap items-center justify-between gap-2 border-0 border-t border-solid border-surface-5 pt-3"
>
<div class="flex flex-wrap items-center gap-2">
<Button type="outlined" :disabled="!isDirty" @click="emit('reset')"
><RotateCounterClockwiseIcon />{{ formatMessage(messages.resetToSaved) }}</Button
>
<Button type="outlined" @click="emit('defaults')">{{
formatMessage(messages.restoreDefaults)
}}</Button>
</div>
<Button type="colored" color="brand" :disabled="!isDirty" @click="emit('save')"
><CheckIcon />{{ formatMessage(messages.save) }}</Button
>
</footer>
</div>
</template>
@@ -0,0 +1,28 @@
<script setup lang="ts">
const { sections = 2, cards = 12 } = defineProps<{
sections?: number
cards?: number
}>()
</script>
<template>
<!--
Shaped after VirtualSkinSectionList: the same grid breakpoints and card
ratio, so the swap to real content does not move anything. Decorative, so
it stays out of the accessibility tree.
-->
<div class="flex flex-col gap-8" aria-hidden="true">
<div v-for="section in sections" :key="section" class="flex flex-col gap-4">
<div class="h-7 w-44 animate-pulse rounded-lg bg-surface-4" />
<div
class="grid w-full grid-cols-3 gap-3 min-[1300px]:grid-cols-4 min-[1750px]:grid-cols-5 min-[2050px]:grid-cols-6"
>
<div
v-for="card in cards"
:key="card"
class="aspect-[31/40] w-full animate-pulse rounded-[20px] bg-surface-4"
/>
</div>
</div>
</div>
</template>
@@ -0,0 +1,61 @@
/**
* Starlight anniversary helpers.
*
* Starlight's first release was on 2014-10-04, so every October 4th the
* launcher shows a small celebration. The anniversary number is simply
* `currentYear - 2014`.
*/
/** Year of Starlight's first release. */
export const STARLIGHT_FOUNDING_YEAR = 2014
/** Month (1-12) of Starlight's anniversary. */
export const STARLIGHT_ANNIVERSARY_MONTH = 10
/** Day of month of Starlight's anniversary. */
export const STARLIGHT_ANNIVERSARY_DAY = 4
/**
* Whether the given date falls on Starlight's anniversary (October 4th).
* Uses the local timezone, which is what the launcher user experiences.
*/
export function isAnniversary(date: Date = new Date()): boolean {
return (
date.getMonth() + 1 === STARLIGHT_ANNIVERSARY_MONTH &&
date.getDate() === STARLIGHT_ANNIVERSARY_DAY
)
}
/**
* The anniversary number for the given date (e.g. 12 for 2026).
* Not clamped: callers decide whether to guard against pre-2014 dates.
*/
export function anniversaryYear(date: Date = new Date()): number {
return date.getFullYear() - STARLIGHT_FOUNDING_YEAR
}
/**
* Whether the celebration should currently be shown.
*
* Normally this is only true on October 4th, but the developer-page
* `force_anniversary_celebration` feature flag forces it on for previewing.
*/
export function shouldCelebrate(force = false, date: Date = new Date()): boolean {
return force || isAnniversary(date)
}
/** English ordinal suffix for a number (1 -> "1st", 12 -> "12th"). */
export function ordinal(n: number): string {
const mod100 = n % 100
if (mod100 >= 11 && mod100 <= 13) return `${n}th`
switch (n % 10) {
case 1:
return `${n}st`
case 2:
return `${n}nd`
case 3:
return `${n}rd`
default:
return `${n}th`
}
}
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { mapBroadcastAnnouncements } from './remote-announcements.ts'
test('maps a broadcast entry into a remote announcement', () => {
const result = mapBroadcastAnnouncements([
{
id: 1,
title: '维护通知',
subtitle: '今晚停机',
content: '服务器将于今晚维护。',
updateAt: 1791640873710,
star: true,
importantLevel: 9,
source: 'SKIN',
},
])
assert.equal(result?.length, 1)
const item = result?.[0]
assert.equal(item?.id, '1')
assert.equal(item?.title, '维护通知')
assert.equal(item?.summary, '今晚停机')
assert.equal(item?.priority, 'critical')
assert.equal(item?.pinned, true)
assert.equal(item?.type, 'modal')
assert.equal(item?.published_at, new Date(1791640873710).toISOString())
assert.equal(item?.ends_at, null)
})
test('empty or blank subtitle becomes null summary', () => {
const result = mapBroadcastAnnouncements([
{ id: 2, title: '公告', subtitle: ' ', content: '内容', updateAt: 1000 },
])
assert.equal(result?.[0]?.summary, null)
})
test('skips entries missing required fields', () => {
const result = mapBroadcastAnnouncements([
{ id: 3, title: '有效', content: '内容', updateAt: 1000 },
{ id: 4, title: '', content: '内容', updateAt: 1000 },
{ title: '无 id', content: '内容', updateAt: 1000 },
{ id: 5, title: '无时间', content: '内容' },
null,
'不是对象',
])
assert.equal(result?.length, 1)
assert.equal(result?.[0]?.id, '3')
})
test('clamps importantLevel and maps priority boundaries', () => {
const result = mapBroadcastAnnouncements([
{ id: 6, title: 'a', content: 'x', updateAt: 1000, importantLevel: 0 },
{ id: 7, title: 'b', content: 'x', updateAt: 1000, importantLevel: 3 },
{ id: 8, title: 'c', content: 'x', updateAt: 1000, importantLevel: 6 },
{ id: 9, title: 'd', content: 'x', updateAt: 1000, importantLevel: 999 },
])
const byId = new Map(result?.map((item) => [item.id, item.priority]))
assert.equal(byId.get('6'), 'low')
assert.equal(byId.get('7'), 'normal')
assert.equal(byId.get('8'), 'high')
assert.equal(byId.get('9'), 'critical')
})
test('returns null for non-array payloads', () => {
assert.equal(mapBroadcastAnnouncements(null), null)
assert.equal(mapBroadcastAnnouncements({ payload: [] }), null)
assert.equal(mapBroadcastAnnouncements('nope'), null)
})
test('pinned announcements sort first', () => {
const result = mapBroadcastAnnouncements([
{ id: 10, title: '普通', content: 'x', updateAt: 2000, importantLevel: 9 },
{ id: 11, title: '置顶', content: 'x', updateAt: 1000, star: true },
])
assert.equal(result?.[0]?.id, '11')
assert.equal(result?.[1]?.id, '10')
})
@@ -5,6 +5,7 @@ export type RemoteAnnouncement = {
content: string
type: 'modal' | 'notification'
priority: 'low' | 'normal' | 'high' | 'critical'
pinned?: boolean
starts_at: string
ends_at: string | null
published_at: string
@@ -32,18 +33,28 @@ export function parseAnnouncements(value: unknown): RemoteAnnouncement[] | null
if (!entry || typeof entry !== 'object') continue
const item = entry as Record<string, unknown>
if (
typeof item.id !== 'string' || item.id.length > 100 || ids.has(item.id) ||
typeof item.title !== 'string' || !item.title.trim() || item.title.length > 120 ||
typeof item.content !== 'string' || item.content.length > 20000 ||
typeof item.id !== 'string' ||
item.id.length > 100 ||
ids.has(item.id) ||
typeof item.title !== 'string' ||
!item.title.trim() ||
item.title.length > 120 ||
typeof item.content !== 'string' ||
item.content.length > 20000 ||
(item.summary != null && (typeof item.summary !== 'string' || item.summary.length > 300)) ||
!['modal', 'notification'].includes(String(item.type)) ||
!['low', 'normal', 'high', 'critical'].includes(String(item.priority)) ||
typeof item.starts_at !== 'string' || !Number.isFinite(Date.parse(item.starts_at)) ||
typeof item.published_at !== 'string' || !Number.isFinite(Date.parse(item.published_at)) ||
(item.ends_at != null && (typeof item.ends_at !== 'string' || !Number.isFinite(Date.parse(item.ends_at)))) ||
(item.action_label != null && (typeof item.action_label !== 'string' || item.action_label.length > 80)) ||
typeof item.starts_at !== 'string' ||
!Number.isFinite(Date.parse(item.starts_at)) ||
typeof item.published_at !== 'string' ||
!Number.isFinite(Date.parse(item.published_at)) ||
(item.ends_at != null &&
(typeof item.ends_at !== 'string' || !Number.isFinite(Date.parse(item.ends_at)))) ||
(item.action_label != null &&
(typeof item.action_label !== 'string' || item.action_label.length > 80)) ||
(item.action_url != null && !safeAnnouncementUrl(item.action_url))
) continue
)
continue
ids.add(item.id)
items.push({
...item,
@@ -54,7 +65,12 @@ export function parseAnnouncements(value: unknown): RemoteAnnouncement[] | null
} as RemoteAnnouncement)
}
const rank = { low: 0, normal: 1, high: 2, critical: 3 }
return items.sort((first, second) => rank[second.priority] - rank[first.priority] || Date.parse(second.published_at) - Date.parse(first.published_at))
return items.sort(
(first, second) =>
Number(second.pinned ?? false) - Number(first.pinned ?? false) ||
rank[second.priority] - rank[first.priority] ||
Date.parse(second.published_at) - Date.parse(first.published_at),
)
}
export function isAnnouncementActive(item: RemoteAnnouncement, now = Date.now()) {
@@ -64,3 +80,76 @@ export function isAnnouncementActive(item: RemoteAnnouncement, now = Date.now())
export function announcementKey(item: RemoteAnnouncement) {
return item.id + ':' + item.published_at
}
export const REMOTE_ANNOUNCEMENTS_UPDATED_EVENT = 'starlight:remote-announcements-updated'
export const OPEN_REMOTE_ANNOUNCEMENT_CENTER_EVENT = 'starlight:open-remote-announcement-center'
type BroadcastAnnouncementEntry = {
title?: unknown
subtitle?: unknown
content?: unknown
updateAt?: unknown
star?: unknown
importantLevel?: unknown
id?: unknown
}
function broadcastPriority(level: number): RemoteAnnouncement['priority'] {
if (level >= 9) return 'critical'
if (level >= 6) return 'high'
if (level >= 3) return 'normal'
return 'low'
}
export function mapBroadcastAnnouncements(payload: unknown): RemoteAnnouncement[] | null {
if (!Array.isArray(payload) || payload.length > 200) return null
const items: RemoteAnnouncement[] = []
const seen = new Set<string>()
for (const entry of payload) {
if (!entry || typeof entry !== 'object') continue
const item = entry as BroadcastAnnouncementEntry
if (
typeof item.id !== 'number' ||
!Number.isFinite(item.id) ||
typeof item.title !== 'string' ||
!item.title.trim() ||
item.title.length > 120 ||
typeof item.content !== 'string' ||
item.content.length > 20000 ||
typeof item.updateAt !== 'number' ||
!Number.isFinite(item.updateAt) ||
(item.subtitle != null && typeof item.subtitle !== 'string')
)
continue
const id = String(item.id)
if (seen.has(id)) continue
seen.add(id)
const level =
typeof item.importantLevel === 'number' && Number.isFinite(item.importantLevel)
? Math.max(0, Math.min(10, Math.floor(item.importantLevel)))
: 0
const starred = item.star === true
const published = new Date(item.updateAt).toISOString()
const summary = typeof item.subtitle === 'string' && item.subtitle.trim() ? item.subtitle : null
items.push({
id,
title: item.title,
summary,
content: item.content,
type: starred || level >= 8 ? 'modal' : 'notification',
priority: broadcastPriority(level),
pinned: starred,
starts_at: published,
ends_at: null,
published_at: published,
action_url: null,
action_label: null,
})
}
const rank = { low: 0, normal: 1, high: 2, critical: 3 }
return items.sort(
(first, second) =>
Number(second.pinned ?? false) - Number(first.pinned ?? false) ||
rank[second.priority] - rank[first.priority] ||
Date.parse(second.published_at) - Date.parse(first.published_at),
)
}
@@ -0,0 +1,60 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { loadSkinArmorPreview, saveSkinArmorPreview } from './skin-armor-preview.ts'
const originalStorage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
function withStorage(run: (values: Map<string, string>) => void): void {
const values = new Map<string, string>()
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
value: {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
},
})
try {
run(values)
} finally {
if (originalStorage) Object.defineProperty(globalThis, 'localStorage', originalStorage)
else delete (globalThis as { localStorage?: Storage }).localStorage
}
}
test('armor preview selections survive storage round trips', () => {
withStorage(() => {
const config = loadSkinArmorPreview()
config.helmet.material = 'diamond'
config.helmet.trimPattern = 'sentry'
config.helmet.trimMaterial = 'gold'
saveSkinArmorPreview(config)
assert.deepEqual(loadSkinArmorPreview(), config)
})
})
test('invalid stored armor values fall back per slot and field', () => {
withStorage((values) => {
values.set(
'axolotl:skin-armor-preview',
JSON.stringify({
helmet: { material: 'diamond', trimPattern: 'invalid', trimMaterial: 'gold' },
boots: { material: 'turtle', trimPattern: 'sentry', trimMaterial: 'invalid' },
}),
)
const config = loadSkinArmorPreview()
assert.deepEqual(config.helmet, {
material: 'diamond',
trimPattern: null,
trimMaterial: 'gold',
})
assert.deepEqual(config.boots, {
material: null,
trimPattern: 'sentry',
trimMaterial: 'iron',
})
assert.equal(config.chestplate.material, null)
})
})
@@ -0,0 +1,47 @@
import {
ARMOR_SLOTS,
ARMOR_TRIM_MATERIALS,
ARMOR_TRIM_PATTERNS,
armorMaterialsForSlot,
type ArmorPreviewConfig,
createDefaultArmorPreviewConfig,
} from '@modrinth/ui'
const STORAGE_KEY = 'axolotl:skin-armor-preview'
function includes<T extends string>(values: readonly T[], value: unknown): value is T {
return typeof value === 'string' && values.some((item) => item === value)
}
export function loadSkinArmorPreview(): ArmorPreviewConfig {
const config = createDefaultArmorPreviewConfig()
try {
const saved = JSON.parse(globalThis.localStorage?.getItem(STORAGE_KEY) ?? 'null')
if (!saved || typeof saved !== 'object' || Array.isArray(saved)) return config
for (const slot of ARMOR_SLOTS) {
const piece = saved[slot]
if (!piece || typeof piece !== 'object' || Array.isArray(piece)) continue
if (piece.material === null || includes(armorMaterialsForSlot(slot), piece.material)) {
config[slot].material = piece.material
}
if (piece.trimPattern === null || includes(ARMOR_TRIM_PATTERNS, piece.trimPattern)) {
config[slot].trimPattern = piece.trimPattern
}
if (includes(ARMOR_TRIM_MATERIALS, piece.trimMaterial)) {
config[slot].trimMaterial = piece.trimMaterial
}
}
} catch {
// Invalid or unavailable local storage falls back to a fresh preview.
}
return config
}
export function saveSkinArmorPreview(config: ArmorPreviewConfig): void {
try {
globalThis.localStorage?.setItem(STORAGE_KEY, JSON.stringify(config))
} catch {
// The preview remains usable when local storage is unavailable.
}
}
+3
View File
@@ -55,6 +55,7 @@ export type GameInstance = {
force_fullscreen?: boolean
maximize_window?: boolean
game_resolution?: [number, number]
window_title?: string | null
launch_preparation_timeout?: number | null
hooks: Hooks
}
@@ -239,6 +240,8 @@ type AppSettings = {
force_fullscreen: boolean
maximize_window: boolean
game_resolution: [number, number]
custom_window_title_enabled: boolean
default_window_title: string
hide_on_process_start: boolean
enter_lightweight_mode_on_game_launch: boolean
auto_set_java_high_performance_mode: boolean
+58 -1
View File
@@ -11428,5 +11428,62 @@
},
"app.settings.synced-options.game-settings.value-unset": {
"message": "Choose a value"
},
"app.anniversary.banner": {
"message": "Happy {ordinal} Anniversary, Starlight!"
},
"instance.settings.tabs.window.window-title": {
"message": "Window title"
},
"instance.settings.tabs.window.window-title.description": {
"message": "Customize the Minecraft window title. Leave empty to keep the default."
},
"instance.settings.tabs.window.window-title.enter": {
"message": "Enter window title..."
},
"app.settings.defaults.window-title.enabled": {
"message": "Custom Minecraft window title"
},
"app.settings.defaults.window-title.enabled-description": {
"message": "Allow instances to customize the Minecraft window title."
},
"app.settings.defaults.window-title.default": {
"message": "Default window title"
},
"app.settings.defaults.window-title.default-description": {
"message": "Used when an instance does not provide its own title."
},
"app.settings.defaults.window-title.default-placeholder": {
"message": "Enter the default window title..."
},
"app.action-bar.announcements": {
"message": "Announcements"
},
"app.remote-announcements.center-title": {
"message": "Announcements"
},
"app.remote-announcements.empty": {
"message": "No announcements"
},
"app.remote-announcements.view": {
"message": "View announcement"
},
"app.remote-announcements.unread": {
"message": "Unread"
},
"app.remote-announcements.read-all": {
"message": "Mark all announcements as read"
},
"app.remote-announcements.preview-title": {
"message": "Announcement style preview"
},
"app.remote-announcements.preview-summary": {
"message": "This is a local preview notification. Select View announcement to see the full Markdown content."
},
"app.remote-announcements.preview-content": {
"message": "## Announcement preview\n\nThis is **sample content**, not a published announcement.\n\n- Supports headings, lists, and links\n- Close buttons are always available\n\n> Previewing does not change real announcement read status.\n\n| Type | Display |\n| --- | --- |\n| Modal | Full Markdown content |\n| Popup | Summary, then full content |\n\n[Visit the website](https://skin.starlight.cool/)"
},
"app.remote-announcements.preview-action": {
"message": "Visit website"
}
}
}
+14 -2
View File
@@ -11350,5 +11350,17 @@
"app.settings.synced-options.game-settings.value-mixed": { "message": "各实例不同" },
"app.settings.synced-options.game-settings.value-off": { "message": "关闭" },
"app.settings.synced-options.game-settings.value-on": { "message": "开启" },
"app.settings.synced-options.game-settings.value-unset": { "message": "选择一个值" }
}
"app.settings.synced-options.game-settings.value-unset": { "message": "选择一个值" },
"app.anniversary.banner": { "message": "Starlight {ordinal} 周年快乐!" },
"instance.settings.tabs.window.window-title": { "message": "窗口标题" },
"instance.settings.tabs.window.window-title.description": { "message": "自定义 Minecraft 窗口标题。留空则使用默认标题。" },
"instance.settings.tabs.window.window-title.enter": { "message": "输入窗口标题..." },
"app.settings.defaults.window-title.enabled": { "message": "自定义 Minecraft 窗口标题" },
"app.settings.defaults.window-title.enabled-description": { "message": "允许实例自定义 Minecraft 窗口标题。" },
"app.settings.defaults.window-title.default": { "message": "默认窗口标题" },
"app.settings.defaults.window-title.default-description": { "message": "当实例未提供自己的标题时使用。" },
"app.settings.defaults.window-title.default-placeholder": { "message": "输入默认窗口标题..." },
"app.action-bar.announcements": { "message": "公告" },
"app.remote-announcements.center-title": { "message": "公告" },
"app.remote-announcements.empty": { "message": "暂无公告" }
}
+143 -29
View File
@@ -9,9 +9,13 @@ import {
SpinnerIcon,
} from '@modrinth/assets'
import {
type ArmorPreviewConfig,
ArmorPreviewControls,
ButtonStyled,
cloneArmorPreviewConfig,
commonMessages,
ConfirmModal,
createDefaultArmorPreviewConfig,
defineMessages,
injectNotificationManager,
NavTabs,
@@ -24,12 +28,14 @@ import { invoke } from '@tauri-apps/api/core'
import type { DragDropEvent } from '@tauri-apps/api/webview'
import { getCurrentWebview } from '@tauri-apps/api/webview'
import { computedAsync } from '@vueuse/core'
import type { Ref } from 'vue'
import type { ComponentPublicInstance, Ref } from 'vue'
import { computed, inject, onMounted, onUnmounted, ref, useTemplateRef, watch } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
import type AccountsCard from '@/components/ui/AccountsCard.vue'
import ArmorTrimTab from '@/components/ui/skin/ArmorTrimTab.vue'
import EditSkinModal from '@/components/ui/skin/EditSkinModal.vue'
import SkinListSkeleton from '@/components/ui/skin/SkinListSkeleton.vue'
import VirtualSkinSectionList from '@/components/ui/skin/VirtualSkinSectionList.vue'
import {
openSkinSiteLogin,
@@ -45,6 +51,7 @@ import { useNetworkStatus } from '@/composables/useNetworkStatus'
import { check_reachable, get_default_user, users } from '@/helpers/auth'
import type { RenderResult } from '@/helpers/rendering/batch-skin-renderer.ts'
import { skinBlobUrlMap } from '@/helpers/rendering/batch-skin-renderer.ts'
import { loadSkinArmorPreview, saveSkinArmorPreview } from '@/helpers/skin-armor-preview'
import type { Cape, Skin, SkinTextureUrl } from '@/helpers/skins.ts'
import {
determineModelType,
@@ -252,6 +259,8 @@ const editSkinModal = useTemplateRef('editSkinModal')
const addSkinFileInput = useTemplateRef<HTMLInputElement>('addSkinFileInput')
const skinSectionList = useTemplateRef<VirtualSkinSectionListExpose>('skinSectionList')
const skinPreviewArea = useTemplateRef<HTMLElement>('skinPreviewArea')
const armorTrimTab = useTemplateRef<ComponentPublicInstance>('armorTrimTab')
const armorPreviewControls = useTemplateRef<ComponentPublicInstance>('armorPreviewControls')
const { formatMessage } = useVIntl()
const router = useRouter()
@@ -391,7 +400,8 @@ const isAddSkinButtonDragActive = ref(false)
const deleteSkinModal = ref()
const skinToDelete = ref<Skin | null>(null)
const skinListTab = ref<'saved' | 'default'>('saved')
const lastSkinListTab = ref<'saved' | 'default'>('saved')
const skinListTab = ref<'saved' | 'default' | 'armor'>('saved')
const skinListTabLinks = computed(() => [
{
@@ -403,6 +413,70 @@ const skinListTabLinks = computed(() => [
label: formatMessage(messages.defaultTab),
},
])
const ARMOR_TRIM_PANEL_ID = 'skins-armor-trim-panel'
const savedArmorPreview = ref<ArmorPreviewConfig>(loadSkinArmorPreview())
const armorPreviewConfig = ref<ArmorPreviewConfig>(cloneArmorPreviewConfig(savedArmorPreview.value))
function saveArmorPreview() {
savedArmorPreview.value = cloneArmorPreviewConfig(armorPreviewConfig.value)
saveSkinArmorPreview(savedArmorPreview.value)
}
function resetArmorPreviewToSaved() {
armorPreviewConfig.value = cloneArmorPreviewConfig(savedArmorPreview.value)
}
function restoreDefaultArmorPreview() {
armorPreviewConfig.value = createDefaultArmorPreviewConfig()
}
/** A third tab behind the two list tabs, opened from the preview's action row. */
function openArmorTab() {
if (skinListTab.value !== 'armor') lastSkinListTab.value = skinListTab.value
skinListTab.value = 'armor'
}
/**
* Whether an element belongs to the armour surface: somewhere inside the open
* armour tab or the button that toggles it. Only those hold a focus ring that
* would be left behind when the tab closes.
*/
function isArmorPreviewElement(element: Element) {
const tabElement: unknown = armorTrimTab.value?.$el
const toggleElement: unknown = armorPreviewControls.value?.$el
return (
(tabElement instanceof Element && tabElement.contains(element)) ||
(toggleElement instanceof Element && toggleElement.contains(element))
)
}
function closeArmorTab() {
// Leaving the tab drops whatever was not saved on purpose.
resetArmorPreviewToSaved()
skinListTab.value = lastSkinListTab.value
// Escape and the toggle both leave the armour button holding focus, which
// keeps its focus ring drawn until something else is clicked. Only drop that
// ring when the focus sits on the armour surface, never on an unrelated
// control that happened to hold it when Escape was pressed.
const focused = document.activeElement
if (focused instanceof HTMLElement && isArmorPreviewElement(focused)) focused.blur()
}
/**
* The tab bar keeps the last list tab highlighted while the armour tab shows, so
* picking one of them leaves the armour tab. That transition has to drop the
* draft exactly like the toggle and Escape paths do, or it lingers on the model
* while the panel is gone.
*/
function selectSkinListTab(index: number) {
if (skinListTab.value === 'armor') resetArmorPreviewToSaved()
lastSkinListTab.value = index === 0 ? 'saved' : 'default'
skinListTab.value = lastSkinListTab.value
}
function confirmDeleteSkin(skin: Skin) {
if (isSkinManagementReadOnly.value) return
@@ -1211,6 +1285,9 @@ await loadSkins()
class="ml-5 mt-4 flex h-[calc(80vh-1rem)] items-center justify-center max-[700px]:h-[calc(50vh-1rem)]"
>
<SkinPreviewRenderer
v-model:armor-config="armorPreviewConfig"
armor-preview
:armor-controls="false"
:cape-src="capeTexture"
:texture-src="skinTexture || ''"
:variant="skinVariant"
@@ -1257,6 +1334,16 @@ await loadSkins()
<EditIcon />
{{ formatMessage(messages.editSkinButton) }}
</button>
<ArmorPreviewControls
v-if="!isSkinSiteProfile"
ref="armorPreviewControls"
v-model="armorPreviewConfig"
panel="external"
:panel-id="ARMOR_TRIM_PANEL_ID"
:open="skinListTab === 'armor'"
@open="openArmorTab"
@close="closeArmorTab"
/>
</template>
</SkinPreviewRenderer>
</div>
@@ -1265,14 +1352,10 @@ await loadSkins()
<div class="pt-2">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<NavTabs
:active-index="skinListTab === 'saved' ? 0 : 1"
:active-index="lastSkinListTab === 'saved' ? 0 : 1"
:links="skinListTabLinks"
mode="local"
@tab-click="
(index: number) => {
skinListTab = index === 0 ? 'saved' : 'default'
}
"
@tab-click="selectSkinListTab"
/>
<ButtonStyled v-if="!isSkinSiteProfile" color="brand">
<button @click="router.push('/lab/skin-editor')">
@@ -1281,27 +1364,45 @@ await loadSkins()
</button>
</ButtonStyled>
</div>
<VirtualSkinSectionList
ref="skinSectionList"
:active-tab="skinListTab"
:saved-skins="savedSkins"
:default-skin-sections="defaultSkinSections"
:get-baked-skin-textures="getBakedSkinTextures"
:is-skin-selected="isSkinSelected"
:is-skin-active="isSkinActive"
:is-add-skin-button-drag-active="isAddSkinButtonDragActive"
:read-only="isSkinManagementReadOnly"
:manage-saved-skins="!isSkinSiteProfile"
@select="changeSkin"
@edit="(skin, event) => !isSkinSiteProfile && editSkinModal?.show(event, skin)"
@delete="confirmDeleteSkin"
@reorder-saved-skins="reorderSavedSkins"
@add-skin="openAddSkinFileBrowser"
@add-skin-dragenter="onAddSkinDragOver"
@add-skin-dragover="onAddSkinDragOver"
@add-skin-dragleave="onAddSkinDragLeave"
@add-skin-drop="onAddSkinDrop"
/>
<Transition name="armor-tab" mode="out-in">
<div v-if="skinListTab !== 'armor'" key="list">
<SkinListSkeleton v-if="isSkinListBuffering" />
<VirtualSkinSectionList
v-show="!isSkinListBuffering"
ref="skinSectionList"
:active-tab="skinListTab"
:saved-skins="savedSkins"
:default-skin-sections="defaultSkinSections"
:get-baked-skin-textures="getBakedSkinTextures"
:is-skin-selected="isSkinSelected"
:is-skin-active="isSkinActive"
:is-add-skin-button-drag-active="isAddSkinButtonDragActive"
:read-only="isSkinManagementReadOnly"
:manage-saved-skins="!isSkinSiteProfile"
@select="changeSkin"
@edit="(skin, event) => !isSkinSiteProfile && editSkinModal?.show(event, skin)"
@delete="confirmDeleteSkin"
@reorder-saved-skins="reorderSavedSkins"
@add-skin="openAddSkinFileBrowser"
@add-skin-dragenter="onAddSkinDragOver"
@add-skin-dragover="onAddSkinDragOver"
@add-skin-dragleave="onAddSkinDragLeave"
@add-skin-drop="onAddSkinDrop"
/>
</div>
<ArmorTrimTab
v-else
ref="armorTrimTab"
key="armor"
v-model="armorPreviewConfig"
:panel-id="ARMOR_TRIM_PANEL_ID"
:saved="savedArmorPreview"
@save="saveArmorPreview"
@reset="resetArmorPreviewToSaved"
@defaults="restoreDefaultArmorPreview"
@close="closeArmorTab"
/>
</Transition>
</div>
</div>
@@ -1382,4 +1483,17 @@ await loadSkins()
grid-template-columns: 1fr;
}
}
// The armour tab crossfades with the skin list it replaces.
.armor-tab-enter-active,
.armor-tab-leave-active {
transition:
opacity 180ms ease,
transform 180ms ease;
}
.armor-tab-enter-from,
.armor-tab-leave-to {
opacity: 0;
transform: translateY(0.5rem);
}
</style>
+1
View File
@@ -25,6 +25,7 @@ export const DEFAULT_FEATURE_FLAGS = {
page_transitions: true,
advanced_filters_collapsed: true,
auto_install_dependencies: true,
force_anniversary_celebration: false,
}
export const THEME_OPTIONS = ['dark', 'light', 'oled', 'system'] as const
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "theseus_gui"
# The actual version is set by the theseus-build workflow on tagging
version = "1.0.0-beta15"
version = "1.0.2-beta4"
edition.workspace = true
description = "Axolotl Launcher is a cross-platform Minecraft launcher"
homepage = "https://www.ghs.red"
+9 -1
View File
@@ -333,6 +333,12 @@ pub struct EditInstance {
)]
pub launch_preparation_timeout: Option<Option<u64>>,
pub hooks: Option<Hooks>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "serde_with::rust::double_option"
)]
pub window_title: Option<Option<String>>,
#[serde(
default,
@@ -531,7 +537,8 @@ fn edit_to_core(edit_instance: EditInstance) -> Result<CoreEditInstance> {
|| edit_instance.maximize_window.is_some()
|| edit_instance.game_resolution.is_some()
|| edit_instance.launch_preparation_timeout.is_some()
|| edit_instance.hooks.is_some();
|| edit_instance.hooks.is_some()
|| edit_instance.window_title.is_some();
if has_launch_change {
Some(InstanceLaunchOverridesPatch {
player: None,
@@ -546,6 +553,7 @@ fn edit_to_core(edit_instance: EditInstance) -> Result<CoreEditInstance> {
launch_preparation_timeout: edit_instance
.launch_preparation_timeout,
hooks: edit_instance.hooks,
window_title: edit_instance.window_title,
})
} else {
None
+79 -1
View File
@@ -253,6 +253,14 @@ impl LightweightMode {
if payload.maximize_window {
maximize_minecraft_window(payload.pid).await;
}
if let Some(title) = payload
.window_title
.as_ref()
.map(|value| value.trim())
.filter(|value| !value.is_empty())
{
rename_minecraft_window(payload.pid, title).await;
}
let settings = match theseus::settings::get().await {
Ok(settings) => settings,
Err(error) => {
@@ -332,6 +340,8 @@ struct ProcessEventPayload {
pid: u32,
#[serde(default)]
maximize_window: bool,
#[serde(default)]
window_title: Option<String>,
event: String,
crashed: Option<bool>,
#[serde(default)]
@@ -339,7 +349,7 @@ struct ProcessEventPayload {
}
#[cfg(target_os = "windows")]
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU32, Ordering};
#[cfg(target_os = "windows")]
static MAXIMIZE_PROCESS_ID: AtomicU32 = AtomicU32::new(0);
@@ -400,6 +410,74 @@ async fn maximize_minecraft_window(pid: u32) {
#[cfg(not(target_os = "windows"))]
async fn maximize_minecraft_window(_pid: u32) {}
#[cfg(target_os = "windows")]
static RENAME_WINDOW_HANDLE: AtomicIsize = AtomicIsize::new(0);
#[cfg(target_os = "windows")]
unsafe extern "system" fn rename_if_owned_by_process(
hwnd: windows::Win32::Foundation::HWND,
_: windows::Win32::Foundation::LPARAM,
) -> windows::core::BOOL {
use windows::Win32::UI::WindowsAndMessaging::{
GetWindowThreadProcessId, IsWindowVisible,
};
use windows::core::BOOL;
let mut window_pid = 0;
unsafe { GetWindowThreadProcessId(hwnd, Some(&mut window_pid)) };
if window_pid == MAXIMIZE_PROCESS_ID.load(Ordering::Relaxed)
&& unsafe { IsWindowVisible(hwnd).as_bool() }
{
RENAME_WINDOW_HANDLE.store(hwnd.0 as isize, Ordering::Relaxed);
return BOOL(0);
}
BOOL(1)
}
#[cfg(target_os = "windows")]
async fn rename_minecraft_window(pid: u32, title: &str) {
if pid == 0 || title.is_empty() {
return;
}
// PCL keeps re-applying the title: FML/Quilt and some mods reset it
// while the game boots, so a one-shot rename is not enough.
let deadline =
tokio::time::Instant::now() + std::time::Duration::from_secs(45);
let mut applied = false;
loop {
let found = {
let _guard = MAXIMIZE_WINDOW_ENUMERATION.lock();
MAXIMIZE_PROCESS_ID.store(pid, Ordering::Relaxed);
RENAME_WINDOW_HANDLE.store(0, Ordering::Relaxed);
unsafe {
use windows::Win32::Foundation::LPARAM;
use windows::Win32::UI::WindowsAndMessaging::EnumWindows;
let _ =
EnumWindows(Some(rename_if_owned_by_process), LPARAM(0));
}
RENAME_WINDOW_HANDLE.load(Ordering::Relaxed)
};
if found != 0 {
let hwnd = windows::Win32::Foundation::HWND(found as *mut _);
let wide: Vec<u16> = title.encode_utf16().chain(Some(0)).collect();
unsafe {
use windows::Win32::UI::WindowsAndMessaging::SetWindowTextW;
let _ =
SetWindowTextW(hwnd, windows::core::PCWSTR(wide.as_ptr()));
}
applied = true;
}
if tokio::time::Instant::now() >= deadline {
return;
}
let _ = applied;
tokio::time::sleep(std::time::Duration::from_millis(400)).await;
}
}
#[cfg(not(target_os = "windows"))]
async fn rename_minecraft_window(_pid: u32, _title: &str) {}
#[tauri::command]
pub fn lightweight_mode_frontend_ready(
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "theseus"
# The actual version is set by the theseus-build workflow on tagging
version = "1.0.0-beta15"
version = "1.0.2-beta4"
edition.workspace = true
[dependencies]
@@ -186,4 +186,32 @@ CREATE TABLE instance_server_pack_state (
FOREIGN KEY (instance_id) REFERENCES instances (id) ON DELETE CASCADE
);
-- Synced pack catalog tables (ported alongside the sync feature tables).
CREATE TABLE synced_pack_catalog (
id TEXT PRIMARY KEY NOT NULL,
project_type TEXT NOT NULL CHECK (project_type IN ('resourcepack', 'datapack')),
file_name TEXT NOT NULL,
sha1 TEXT NOT NULL UNIQUE,
size INTEGER NOT NULL CHECK (size >= 0),
game_versions_json TEXT NOT NULL DEFAULT '[]',
enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1)),
created_at INTEGER NOT NULL,
modified_at INTEGER NOT NULL
);
CREATE INDEX synced_pack_catalog_type ON synced_pack_catalog(project_type, modified_at);
CREATE TABLE synced_pack_instances (
pack_id TEXT NOT NULL,
instance_id TEXT NOT NULL,
excluded INTEGER NOT NULL DEFAULT 0 CHECK (excluded IN (0, 1)),
materialized_path TEXT,
modified_at INTEGER NOT NULL,
PRIMARY KEY (pack_id, instance_id),
FOREIGN KEY (pack_id) REFERENCES synced_pack_catalog(id) ON DELETE CASCADE,
FOREIGN KEY (instance_id) REFERENCES instances(id) ON DELETE CASCADE
);
CREATE INDEX synced_pack_instances_instance ON synced_pack_instances(instance_id, excluded);
ALTER TABLE settings ADD COLUMN sync_features_across_devices INTEGER NOT NULL DEFAULT FALSE;
@@ -0,0 +1,2 @@
ALTER TABLE settings ADD COLUMN custom_window_title_enabled INTEGER NOT NULL DEFAULT FALSE;
ALTER TABLE settings ADD COLUMN default_window_title TEXT NOT NULL DEFAULT 'Minecraft';
+12
View File
@@ -250,6 +250,17 @@ async fn run_credentials(
.launch_overrides
.maximize_window
.unwrap_or(settings.maximize_window);
let window_title = settings
.custom_window_title_enabled
.then(|| {
context
.launch_overrides
.window_title
.clone()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| settings.default_window_title.clone())
})
.filter(|value| !value.trim().is_empty());
let env_args = context
.launch_overrides
.custom_env_vars
@@ -319,6 +330,7 @@ async fn run_credentials(
&memory,
&resolution,
maximize_window,
window_title,
credentials,
post_exit_hook,
&context,
@@ -157,6 +157,7 @@ pub(crate) async fn import_axolotl(
),
maximize_window: Some(config.launch_overrides.maximize_window),
game_resolution: Some(config.launch_overrides.game_resolution),
window_title: None,
launch_preparation_timeout: Some(
config.launch_overrides.launch_preparation_timeout,
),
+2
View File
@@ -400,6 +400,7 @@ pub async fn emit_process(
uuid: Uuid,
pid: u32,
maximize_window: bool,
window_title: Option<String>,
event: ProcessPayloadType,
message: &str,
crashed: Option<bool>,
@@ -416,6 +417,7 @@ pub async fn emit_process(
uuid,
pid,
maximize_window,
window_title,
event,
message: message.to_string(),
crashed,
+2
View File
@@ -336,6 +336,8 @@ pub struct ProcessPayload {
pub uuid: Uuid,
pub pid: u32,
pub maximize_window: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub window_title: Option<String>,
pub event: ProcessPayloadType,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
+4 -4
View File
@@ -1947,9 +1947,9 @@ pub async fn download_assets(
// failures. Runs concurrently (same budget as the original scheduler) so
// import flows are not serialised.
if !fallback_assets.is_empty() {
let limit = crate::util::download::task_concurrency_limit(st)
.map(|limit| limit.saturating_mul(2))
.unwrap_or(ASSET_BATCH_CONCURRENCY);
let limit =
crate::util::download::single_authority_task_concurrency_limit(st)
.unwrap_or(ASSET_BATCH_CONCURRENCY);
futures::stream::iter(fallback_assets)
.map(Ok::<FallbackAsset, crate::Error>)
.try_for_each_concurrent(limit, |item| {
@@ -2123,7 +2123,7 @@ pub async fn download_libraries(
let num_files = tasks.len();
loading_try_for_each_concurrent(
stream::iter(tasks).map(Ok::<LibraryDownloadTask<'_>, crate::Error>),
crate::util::download::task_concurrency_limit(&st).map(|limit| limit.saturating_mul(2)),
crate::util::download::task_concurrency_limit(&st),
loading_bar,
loading_amount,
num_files,
+2 -9
View File
@@ -1,5 +1,4 @@
//! Logic for launching Minecraft
use crate::api::pack::import::direct_link::direct_link_group;
use crate::data::ModLoader;
use crate::event::emit::{emit_instance, emit_loading, init_loading};
use crate::event::{InstancePayloadType, LoadingBarType};
@@ -717,14 +716,6 @@ async fn promote_external_instance_link(
&mut tx,
)
.await?;
if let Some(group) = direct_link_group(&direct.dot_minecraft) {
crate::state::instances::adapters::sqlite::instance_rows::replace_instance_groups(
&instance.id,
&[group],
&mut tx,
)
.await?;
}
tx.commit().await?;
emit_instance(&instance.id, InstancePayloadType::Edited).await?;
Ok(())
@@ -1529,6 +1520,7 @@ pub async fn launch_minecraft(
memory: &MemorySettings,
resolution: &WindowSize,
maximize_window: bool,
window_title: Option<String>,
credentials: &Credentials,
post_exit_hook: Option<String>,
context: &InstanceLaunchContext,
@@ -2400,6 +2392,7 @@ pub async fn launch_minecraft(
command,
post_exit_hook,
maximize_window,
window_title,
instance_path.clone(),
logs_folder,
version_info.logging.is_some(),
@@ -1,6 +1,5 @@
use crate::api::pack::import::{
ImportLauncherType,
direct_link::{direct_link_group, resolve_direct_link},
ImportLauncherType, direct_link::resolve_direct_link,
};
use crate::launcher::ExternalGameDirMode;
use crate::state::instances::{
@@ -156,11 +155,6 @@ pub(crate) async fn create_direct_link_instance(
&mut tx,
)
.await?;
let groups = direct_link_group(&resolved.dot_minecraft)
.into_iter()
.collect::<Vec<_>>();
instance_rows::replace_instance_groups(&instance_id, &groups, &mut tx)
.await?;
instance_rows::upsert_instance_launch_overrides(&launch_overrides, &mut tx)
.await?;
tx.commit().await?;
@@ -103,6 +103,12 @@ pub struct InstanceLaunchOverridesPatch {
skip_serializing_if = "Option::is_none",
with = "serde_with::rust::double_option"
)]
pub window_title: Option<Option<String>>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "serde_with::rust::double_option"
)]
pub launch_preparation_timeout: Option<Option<u64>>,
pub hooks: Option<Hooks>,
}
@@ -371,6 +377,10 @@ fn apply_launch_overrides_patch(
if let Some(game_resolution) = patch.game_resolution {
overrides.game_resolution = game_resolution;
}
if let Some(window_title) = patch.window_title {
overrides.window_title =
window_title.filter(|value| !value.trim().is_empty());
}
if let Some(mode) = patch.instance_mode {
overrides.instance_mode = Some(mode);
}
@@ -1,7 +1,7 @@
use super::create_direct_link_instance::create_direct_link_instance;
use crate::api::pack::import::direct_link::{
detect_direct_link_source, direct_link_group,
has_minecraft_version_manifest, resolve_direct_link,
detect_direct_link_source, has_minecraft_version_manifest,
resolve_direct_link,
};
use crate::event::{InstancePayloadType, emit::emit_instance};
use crate::launcher::ExternalGameDirMode;
@@ -163,11 +163,7 @@ pub(crate) async fn sync_direct_link_instances(
let content_changed = metadata.applied_content_set.game_version
!= resolved.game_version
|| metadata.applied_content_set.loader != resolved.loader;
let groups = direct_link_group(&resolved.dot_minecraft)
.into_iter()
.collect::<Vec<_>>();
let groups_changed = metadata.groups != groups;
if fields_changed || content_changed || groups_changed {
if fields_changed || content_changed {
if content_changed {
crate::state::edit_instance(
&instance.id,
@@ -216,12 +212,6 @@ pub(crate) async fn sync_direct_link_instances(
&mut tx,
)
.await?;
instance_rows::replace_instance_groups(
&instance.id,
&groups,
&mut tx,
)
.await?;
tx.commit().await?;
let _ = emit_instance(
&instance.id,
@@ -38,6 +38,8 @@ pub struct InstanceLaunchOverrides {
pub maximize_window: Option<bool>,
pub game_resolution: Option<WindowSize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub window_title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub launch_preparation_timeout: Option<u64>,
pub hooks: Hooks,
}
@@ -55,6 +57,7 @@ impl InstanceLaunchOverrides {
force_fullscreen: None,
maximize_window: None,
game_resolution: None,
window_title: None,
launch_preparation_timeout: None,
hooks: Hooks {
pre_launch: None,
@@ -86,6 +89,8 @@ pub(crate) struct InstanceLaunchOverridesData {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub game_resolution: Option<WindowSize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub window_title: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub launch_preparation_timeout: Option<u64>,
#[serde(default)]
pub hooks: Hooks,
@@ -107,6 +112,7 @@ impl InstanceLaunchOverridesData {
force_fullscreen: self.force_fullscreen,
maximize_window: self.maximize_window,
game_resolution: self.game_resolution,
window_title: self.window_title,
launch_preparation_timeout: self.launch_preparation_timeout,
hooks: self.hooks,
}
@@ -125,6 +131,7 @@ impl From<&InstanceLaunchOverrides> for InstanceLaunchOverridesData {
force_fullscreen: overrides.force_fullscreen,
maximize_window: overrides.maximize_window,
game_resolution: overrides.game_resolution,
window_title: overrides.window_title.clone(),
launch_preparation_timeout: overrides.launch_preparation_timeout,
hooks: overrides.hooks.clone(),
}
@@ -621,6 +621,7 @@ where
force_fullscreen: input.force_fullscreen,
maximize_window: None,
game_resolution: input.game_resolution,
window_title: None,
launch_preparation_timeout: None,
hooks: input.hooks,
};
+39
View File
@@ -118,6 +118,7 @@ pub struct State {
download_sample_requests: AtomicU64,
download_sample_errors: AtomicU64,
download_sample_throttles: AtomicU64,
download_sample_queue_waits: AtomicU64,
pub(crate) install_job_semaphore: Semaphore,
pub(crate) install_db_semaphore: Semaphore,
pub(crate) install_job_cancellations: DashMap<Uuid, CancellationToken>,
@@ -196,6 +197,7 @@ struct AutoConcurrencySample {
requests: u64,
errors: u64,
throttles: u64,
queue_waits: u64,
}
/// Per-instance lock registry with task-local reentrancy.
@@ -399,6 +401,15 @@ impl AutoConcurrencyController {
} else {
sample.errors as f64 / sample.requests as f64
};
if sample.queue_waits > 0 {
self.high_utilization_windows = 0;
self.pressure_windows = 0;
self.probe = None;
self.cooldown_until = Some(now + AUTO_DOWNLOAD_PROBE_COOLDOWN);
return current
.saturating_sub(current.div_ceil(4))
.max(AUTO_DOWNLOAD_CONCURRENCY_MIN);
}
// A single throttled window is handled by the per-host limiter; the
// global concurrency only backs off when pressure persists across
// several samples, and then in small steps instead of a big cut.
@@ -677,6 +688,11 @@ impl State {
self.download_sample_errors.fetch_add(1, Ordering::AcqRel);
}
pub(crate) fn record_download_queue_wait(&self) {
self.download_sample_queue_waits
.fetch_add(1, Ordering::AcqRel);
}
pub(crate) fn update_download_settings(
self: &Arc<Self>,
settings: &Settings,
@@ -735,6 +751,7 @@ impl State {
self.download_sample_requests.swap(0, Ordering::AcqRel);
self.download_sample_errors.swap(0, Ordering::AcqRel);
self.download_sample_throttles.swap(0, Ordering::AcqRel);
self.download_sample_queue_waits.swap(0, Ordering::AcqRel);
continue;
}
let sample = AutoConcurrencySample {
@@ -749,6 +766,9 @@ impl State {
throttles: self
.download_sample_throttles
.swap(0, Ordering::AcqRel),
queue_waits: self
.download_sample_queue_waits
.swap(0, Ordering::AcqRel),
};
let current = self.download_concurrency();
let ceiling =
@@ -771,6 +791,7 @@ impl State {
requests = sample.requests,
errors = sample.errors,
throttles = sample.throttles,
queue_waits = sample.queue_waits,
"Adjusted automatic download concurrency"
);
self.resize_download_concurrency(target);
@@ -935,6 +956,7 @@ impl State {
download_sample_requests: AtomicU64::new(0),
download_sample_errors: AtomicU64::new(0),
download_sample_throttles: AtomicU64::new(0),
download_sample_queue_waits: AtomicU64::new(0),
install_job_semaphore: Semaphore::new(MAX_CONCURRENT_INSTALL_JOBS),
install_db_semaphore: Semaphore::new(1),
install_job_cancellations: DashMap::new(),
@@ -1024,6 +1046,7 @@ pub(crate) async fn test_state(
download_sample_requests: AtomicU64::new(0),
download_sample_errors: AtomicU64::new(0),
download_sample_throttles: AtomicU64::new(0),
download_sample_queue_waits: AtomicU64::new(0),
install_job_semaphore: Semaphore::new(1),
install_db_semaphore: Semaphore::new(1),
install_job_cancellations: DashMap::new(),
@@ -1053,9 +1076,24 @@ mod auto_concurrency_tests {
requests: 100,
errors: 0,
throttles: 0,
queue_waits: 0,
}
}
#[test]
fn queue_pressure_backs_off_immediately_and_repeatedly() {
let mut controller = AutoConcurrencyController::default();
let now = Instant::now();
let congested = AutoConcurrencySample {
queue_waits: 1,
..healthy(8, 100)
};
assert_eq!(controller.next_target(now, 128, 128, congested), 96);
assert_eq!(controller.next_target(now, 96, 128, congested), 72);
assert_eq!(controller.next_target(now, 16, 128, congested), 16);
}
#[test]
fn probes_up_after_two_saturated_windows_and_respects_ceiling() {
let mut controller = AutoConcurrencyController::default();
@@ -1130,6 +1168,7 @@ mod auto_concurrency_tests {
requests: 100,
errors: 5,
throttles: 0,
queue_waits: 0,
};
assert_eq!(controller.next_target(Instant::now(), 16, 128, sample), 16);
}
+6
View File
@@ -312,6 +312,7 @@ impl ProcessManager {
mut mc_command: Command,
post_exit_command: Option<String>,
maximize_window: bool,
window_title: Option<String>,
game_dir: PathBuf,
logs_folder: PathBuf,
xml_logging: bool,
@@ -336,6 +337,7 @@ impl ProcessManager {
uuid: Uuid::new_v4(),
pid: mc_proc.id().unwrap_or_default(),
maximize_window,
window_title: window_title.clone(),
start_time: Utc::now(),
instance_id: instance_id.to_string(),
instance_path: instance_path.to_string(),
@@ -509,6 +511,7 @@ impl ProcessManager {
metadata.uuid,
metadata.pid,
metadata.maximize_window,
metadata.window_title.clone(),
ProcessPayloadType::Launched,
"Launched Minecraft",
None,
@@ -586,6 +589,7 @@ pub struct ProcessMetadata {
pub uuid: Uuid,
pub pid: u32,
pub maximize_window: bool,
pub window_title: Option<String>,
pub instance_id: String,
pub instance_path: String,
pub instance_name: String,
@@ -1311,6 +1315,7 @@ impl Process {
uuid,
pid,
false,
None,
ProcessPayloadType::Finished,
"Exited process",
Some(!mc_exit_status.success() && !manually_killed),
@@ -1451,6 +1456,7 @@ mod post_upgrade_tests {
uuid,
pid: child.id().unwrap(),
maximize_window: false,
window_title: None,
instance_id: "first".into(),
instance_path: "first".into(),
instance_name: "First".into(),
+32
View File
@@ -176,6 +176,10 @@ pub struct Settings {
pub force_fullscreen: bool,
pub maximize_window: bool,
#[serde(default)]
pub custom_window_title_enabled: bool,
#[serde(default = "default_window_title")]
pub default_window_title: String,
#[serde(default)]
pub force_unicode_font: bool,
pub game_resolution: WindowSize,
pub hide_on_process_start: bool,
@@ -198,6 +202,10 @@ pub struct Settings {
pub version: usize,
}
fn default_window_title() -> String {
"Minecraft".to_string()
}
fn default_true() -> bool {
true
}
@@ -328,6 +336,16 @@ impl Settings {
)
.fetch_one(exec)
.await?;
let custom_window_title_enabled: bool = sqlx::query_scalar(
"SELECT custom_window_title_enabled FROM settings WHERE id = 0",
)
.fetch_one(exec)
.await?;
let default_window_title: String = sqlx::query_scalar(
"SELECT default_window_title FROM settings WHERE id = 0",
)
.fetch_one(exec)
.await?;
let settings = Self {
max_concurrent_downloads: res.max_concurrent_downloads as usize,
max_concurrent_writes: res.max_concurrent_writes as usize,
@@ -415,6 +433,8 @@ impl Settings {
},
force_fullscreen: res.mc_force_fullscreen == 1,
maximize_window: res.mc_maximize_window == 1,
custom_window_title_enabled,
default_window_title,
force_unicode_font: sqlx::query_scalar(
"SELECT mc_force_unicode_font FROM settings WHERE id = 0",
)
@@ -663,6 +683,18 @@ impl Settings {
.bind(self.ignore_ssl_errors)
.execute(exec)
.await?;
sqlx::query(
"UPDATE settings SET custom_window_title_enabled = ? WHERE id = 0",
)
.bind(self.custom_window_title_enabled)
.execute(exec)
.await?;
sqlx::query(
"UPDATE settings SET default_window_title = ? WHERE id = 0",
)
.bind(self.default_window_title.trim())
.execute(exec)
.await?;
sqlx::query("UPDATE settings SET mc_memory_optimize = ? WHERE id = 0")
.bind(self.memory.optimize_before_launch)
.execute(exec)
@@ -62,6 +62,7 @@ pub(crate) enum H2DownloadOutcome {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum H2DownloadFailure {
Ineligible(&'static str),
Capacity,
Connect,
Tls,
Protocol,
@@ -76,6 +77,7 @@ impl H2DownloadFailure {
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::Ineligible(reason) => reason,
Self::Capacity => "HTTP/2 connection capacity is unavailable",
Self::Connect => "HTTP/2 TCP connection failed",
Self::Tls => "HTTP/2 TLS connection failed",
Self::Protocol => "HTTP/2 protocol failed",
@@ -104,6 +106,7 @@ impl H2DownloadFailure {
pub(crate) async fn try_download_via_h2(
request: &DownloadRequest,
route: &DownloadRoute,
semaphore: &fetch::FetchSemaphore,
destination: &Path,
part_path: &Path,
policy: super::native::NativeH2Policy,
@@ -122,13 +125,19 @@ pub(crate) async fn try_download_via_h2(
preserve_partial: false,
};
}
let connection = match connect_authority(
route,
true,
policy.allow_cold_connection,
)
.await
let connection_wait =
connect_authority(route, true, policy.allow_cold_connection);
let connection_result = if let Some(cancellation) =
request.cancellation.as_ref()
{
tokio::select! {
_ = cancellation.cancelled() => return H2DownloadOutcome::Canceled,
result = connection_wait => result,
}
} else {
connection_wait.await
};
let connection = match connection_result {
Ok(connection) => connection,
Err(failure) => {
return H2DownloadOutcome::Fallback {
@@ -137,6 +146,30 @@ pub(crate) async fn try_download_via_h2(
};
}
};
// The shared connection reserves native capacity when it is created.
// Acquire the per-download permit afterwards so every native path uses
// the same native-then-fetch order and cannot form a circular wait.
let fetch_permit_wait =
fetch::acquire_fetch_permit_with_pressure(semaphore);
let fetch_permit_result = if let Some(cancellation) =
request.cancellation.as_ref()
{
tokio::select! {
_ = cancellation.cancelled() => return H2DownloadOutcome::Canceled,
result = fetch_permit_wait => result,
}
} else {
fetch_permit_wait.await
};
let _fetch_permit = match fetch_permit_result {
Ok(permit) => permit,
Err(_) => {
return H2DownloadOutcome::Fallback {
failure: H2DownloadFailure::Connect,
preserve_partial: false,
};
}
};
let Ok(uri) = route.url.parse::<Uri>() else {
return H2DownloadOutcome::Fallback {
failure: H2DownloadFailure::Http,
@@ -156,14 +189,20 @@ pub(crate) async fn try_download_via_h2(
let total_size = if let Some(size) = expected_size {
size
} else {
let _probe_stream_permit = match tokio::time::timeout(
ASSET_RESOURCE_WAIT_TIMEOUT,
super::h2_stream_budget::acquire(route),
)
.await
let probe_wait = super::h2_stream_budget::acquire_with_pressure(route);
let probe_result = if let Some(cancellation) =
request.cancellation.as_ref()
{
Ok(Ok(permit)) => permit,
Ok(Err(_)) | Err(_) => {
tokio::select! {
_ = cancellation.cancelled() => return H2DownloadOutcome::Canceled,
result = probe_wait => result,
}
} else {
probe_wait.await
};
let _probe_stream_permit = match probe_result {
Ok(permit) => permit,
Err(_) => {
return H2DownloadOutcome::Fallback {
failure: H2DownloadFailure::Connect,
preserve_partial: false,
@@ -239,10 +278,7 @@ pub(crate) async fn try_download_via_h2(
crate::install::DownloadItemStatus::WaitingForResource,
)
.await;
let stream_wait = tokio::time::timeout(
ASSET_RESOURCE_WAIT_TIMEOUT,
super::h2_stream_budget::acquire(route),
);
let stream_wait = super::h2_stream_budget::acquire_with_pressure(route);
let stream_wait_started = Instant::now();
let stream_result = if let Some(cancellation) =
request.cancellation.as_ref()
@@ -255,8 +291,8 @@ pub(crate) async fn try_download_via_h2(
stream_wait.await
};
let _stream_permit = match stream_result {
Ok(Ok(permit)) => permit,
Ok(Err(_)) | Err(_) => {
Ok(permit) => permit,
Err(_) => {
return H2DownloadOutcome::Fallback {
failure: H2DownloadFailure::Connect,
preserve_partial: false,
@@ -327,6 +363,7 @@ async fn connect_authority(
"Failed to establish shared HTTP/2 connection"
);
Err(match error.kind {
H2ConnectFailureKind::Capacity => H2DownloadFailure::Capacity,
H2ConnectFailureKind::Tcp => H2DownloadFailure::Connect,
H2ConnectFailureKind::Tls => H2DownloadFailure::Tls,
H2ConnectFailureKind::Protocol => H2DownloadFailure::Protocol,
@@ -771,6 +808,12 @@ mod tests {
use super::*;
use bytes::Bytes;
#[test]
fn capacity_wait_is_not_classified_as_a_transport_failure() {
assert!(!H2DownloadFailure::Capacity.is_transfer_failure());
assert!(!H2DownloadFailure::Capacity.should_cooldown_authority());
}
#[tokio::test]
async fn single_stream_reports_bytes_before_the_response_finishes() {
let size = 512 * 1024;
@@ -1183,28 +1226,6 @@ async fn download_asset_item(
"timed out waiting for asset destination lock".to_string(),
)
})?;
let fetch_permit = if apply_native_policy {
let Some(semaphore) = native_semaphore else {
return Err(crate::ErrorKind::OtherError(
"native asset batch is missing fetch budget".to_string(),
)
.into());
};
Some(
tokio::time::timeout(
ASSET_RESOURCE_WAIT_TIMEOUT,
semaphore.0.acquire(),
)
.await
.map_err(|_| {
crate::ErrorKind::NetworkError(
"timed out waiting for asset fetch permit".to_string(),
)
})??,
)
} else {
None
};
// A different downloader may have committed the object while this item
// waited for the destination lock. Reuse it instead of opening another
// stream, which also prevents cross-engine `.part`/rename races.
@@ -1243,24 +1264,26 @@ async fn download_asset_item(
return Ok(AssetBatchItemOutcome::LocalObjectFailed { error });
}
};
let _stream_permit = if apply_native_policy {
Some(
tokio::time::timeout(
ASSET_RESOURCE_WAIT_TIMEOUT,
super::h2_stream_budget::acquire_asset(route),
// Resolve the primary or lazily expanded sibling before taking the fetch
// permit. Shared connections reserve native capacity, so this preserves
// the native-then-fetch order used by every other native path.
let connection = connections.connection(rescue).await;
let fetch_permit = if apply_native_policy {
let Some(semaphore) = native_semaphore else {
return Err(crate::ErrorKind::OtherError(
"native asset batch is missing fetch budget".to_string(),
)
.await
.map_err(|_| {
crate::ErrorKind::NetworkError(
"timed out waiting for asset HTTP/2 stream permit"
.to_string(),
)
})??,
)
.into());
};
Some(fetch::acquire_fetch_permit_with_pressure(semaphore).await?)
} else {
None
};
let _stream_permit = if apply_native_policy {
Some(super::h2_stream_budget::acquire_asset_with_pressure(route).await?)
} else {
None
};
let connection = connections.connection(rescue).await;
let _connection_stream = connection.track_stream();
let mut headers = HeaderMap::new();
headers.insert(
+63 -32
View File
@@ -34,6 +34,7 @@ const CONNECTION_WAIT_TIMEOUT: Duration = Duration::from_secs(45);
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) enum H2ConnectFailureKind {
Capacity,
Tcp,
Tls,
Protocol,
@@ -357,9 +358,41 @@ async fn connect_tcp(host: &str, port: u16) -> std::io::Result<TcpStream> {
}
/// Connects a new shared HTTP/2 connection to `authority` (host[:port]).
async fn establish(
async fn reserve_physical_budget(
route: &DownloadRoute,
reserve_native_budget: bool,
) -> Result<Option<super::native_budget::NativeBudgetPermit>, H2ConnectError> {
Ok(if reserve_native_budget {
Some(
crate::util::fetch::wait_for_download_resource(
super::native_budget::acquire(route),
)
.await
.map_err(|_| {
H2ConnectError::new(
H2ConnectFailureKind::Capacity,
"HTTP/2 connection capacity remained stalled for 5 minutes"
.to_string(),
)
})?
.map_err(|error| {
H2ConnectError::new(
H2ConnectFailureKind::Capacity,
format!(
"failed to reserve HTTP/2 connection capacity: {error}"
),
)
})?,
)
} else {
None
})
}
/// Connects a new shared HTTP/2 connection to `authority` (host[:port]).
async fn establish(
route: &DownloadRoute,
physical_budget: Option<super::native_budget::NativeBudgetPermit>,
) -> Result<Arc<SharedH2Connection>, H2ConnectError> {
let authority =
crate::util::fetch::url_authority(&route.url).ok_or_else(|| {
@@ -368,16 +401,6 @@ async fn establish(
"HTTP/2 route has no authority".to_string(),
)
})?;
let physical_budget = if reserve_native_budget {
Some(super::native_budget::acquire(route).await.map_err(|error| {
H2ConnectError::new(
H2ConnectFailureKind::Tcp,
format!("failed to reserve HTTP/2 connection capacity: {error}"),
)
})?)
} else {
None
};
let (host, port) = authority
.rsplit_once(':')
.map(|(host, port)| (host, port.parse::<u16>().unwrap_or(443)))
@@ -487,16 +510,16 @@ pub(crate) async fn shared_connection(
)
})?;
let slot = connection_slot(&authority).await;
let mut cached = tokio::time::timeout(CONNECTION_WAIT_TIMEOUT, slot.lock())
.await
.map_err(|_| {
H2ConnectError::new(
H2ConnectFailureKind::Protocol,
format!(
"timed out waiting for HTTP/2 connection slot {authority}"
),
)
})?;
let mut cached = crate::util::fetch::wait_for_download_resource(
slot.lock(),
)
.await
.map_err(|_| {
H2ConnectError::new(
H2ConnectFailureKind::Capacity,
format!("HTTP/2 connection slot remained stalled for {authority}"),
)
})?;
if let Some(connection) = cached.as_ref().filter(|connection| {
!connection.is_dead() && !connection.is_idle_expired()
}) {
@@ -525,9 +548,11 @@ pub(crate) async fn shared_connection(
));
}
tracing::debug!(authority, "Establishing cold shared HTTP/2 connection");
let physical_budget =
reserve_physical_budget(route, reserve_native_budget).await?;
let connection = tokio::time::timeout(
CONNECTION_WAIT_TIMEOUT,
establish(route, reserve_native_budget),
establish(route, physical_budget),
)
.await
.map_err(|_| {
@@ -555,15 +580,16 @@ pub(crate) async fn shared_batch_connection(
)
})?;
let slot = batch_connection_slot(&authority).await;
let mut cached = tokio::time::timeout(
CONNECTION_WAIT_TIMEOUT,
let mut cached = crate::util::fetch::wait_for_download_resource(
slot.lock(),
)
.await
.map_err(|_| {
H2ConnectError::new(
H2ConnectFailureKind::Protocol,
format!("timed out waiting for asset HTTP/2 connection slot {authority}"),
H2ConnectFailureKind::Capacity,
format!(
"asset HTTP/2 connection slot remained stalled for {authority}"
),
)
})?;
if let Some(connection) = cached.as_ref().filter(|connection| {
@@ -591,9 +617,11 @@ pub(crate) async fn shared_batch_connection(
*cached = None;
}
tracing::debug!(authority, "Establishing sibling HTTP/2 asset connection");
let physical_budget =
reserve_physical_budget(route, reserve_native_budget).await?;
let connection = tokio::time::timeout(
CONNECTION_WAIT_TIMEOUT,
establish(route, reserve_native_budget),
establish(route, physical_budget),
)
.await
.map_err(|_| {
@@ -614,10 +642,13 @@ pub(crate) async fn has_live_connection(authority: &str) -> bool {
return false;
};
drop(connections);
let live = slot
.lock()
.await
let Ok(cached) = slot.try_lock() else {
// This is only an eligibility probe. A busy slot means another task
// is establishing or refreshing the connection; do not queue this
// caller behind that work before its cancellation-aware download path.
return false;
};
cached
.as_ref()
.is_some_and(|connection| !connection.is_dead());
live
.is_some_and(|connection| !connection.is_dead())
}
@@ -218,13 +218,9 @@ async fn download_range(
crate::install::DownloadItemStatus::WaitingForResource,
)
.await;
let _permit = tokio::time::timeout(
Duration::from_secs(45),
super::h2_stream_budget::acquire(route),
)
.await
.map_err(|_| H2DownloadFailure::Connect)?
.map_err(|_| H2DownloadFailure::Connect)?;
let _permit = super::h2_stream_budget::acquire_with_pressure(route)
.await
.map_err(|_| H2DownloadFailure::Connect)?;
super::h2_download::record_install_stage(
request,
crate::install::DownloadItemStatus::Downloading,
@@ -104,6 +104,20 @@ pub(crate) async fn acquire(
}
}
pub(crate) async fn acquire_with_pressure(
route: &DownloadRoute,
) -> crate::Result<H2StreamPermit> {
crate::util::fetch::wait_for_download_resource(acquire(route))
.await
.map_err(|_| {
crate::Error::from(crate::ErrorKind::NetworkError(
"HTTP/2 stream permit remained stalled for 5 minutes"
.to_string(),
))
})?
.map_err(Into::into)
}
/// Acquires a stream for the Minecraft asset batch. Assets retain a large
/// logical worker window, but use a separate physical stream pool so they
/// cannot consume the ordinary native content share.
@@ -134,10 +148,25 @@ pub(crate) async fn acquire_asset(
}
}
pub(crate) async fn acquire_asset_with_pressure(
route: &DownloadRoute,
) -> crate::Result<H2StreamPermit> {
crate::util::fetch::wait_for_download_resource(acquire_asset(route))
.await
.map_err(|_| {
crate::Error::from(crate::ErrorKind::NetworkError(
"asset HTTP/2 stream permit remained stalled for 5 minutes"
.to_string(),
))
})?
.map_err(Into::into)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::util::fetch::DownloadRouteSource;
use std::sync::atomic::{AtomicUsize, Ordering};
fn route() -> DownloadRoute {
DownloadRoute {
@@ -190,4 +219,40 @@ mod tests {
MAX_H2_STREAMS_PER_AUTHORITY
);
}
#[tokio::test]
async fn contended_stream_wait_reports_pressure_and_resumes() {
let route = DownloadRoute {
url: "https://h2-pressure.example/file".to_string(),
source: DownloadRouteSource::Official,
is_mirror: false,
allow_sensitive_headers: true,
supports_range: true,
proxy: ProxyPolicy::Direct,
};
let mut held = Vec::new();
for _ in 0..MAX_H2_STREAMS_PER_AUTHORITY {
held.push(acquire(&route).await.unwrap());
}
let pressure = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&pressure);
let release = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(35)).await;
drop(held);
});
let permit = crate::util::fetch::wait_for_resource_with_pressure(
acquire(&route),
Duration::from_millis(5),
Duration::from_millis(100),
move || {
observed.fetch_add(1, Ordering::Relaxed);
},
)
.await;
release.await.unwrap();
assert!(permit.is_ok());
assert!(pressure.load(Ordering::Relaxed) >= 1);
}
}
+14 -1
View File
@@ -73,6 +73,19 @@ pub(crate) fn task_concurrency_limit(state: &crate::State) -> Option<usize> {
if active_engine() == DownloadEngine::XmclCompat {
None
} else {
Some(state.download_concurrency())
Some(native_budget::task_limit(
state.download_concurrency(),
usize::MAX,
))
}
}
pub(crate) fn single_authority_task_concurrency_limit(
state: &crate::State,
) -> Option<usize> {
if active_engine() == DownloadEngine::XmclCompat {
None
} else {
Some(native_budget::task_limit(state.download_concurrency(), 1))
}
}
@@ -144,6 +144,15 @@ pub(crate) fn available(route: &DownloadRoute) -> usize {
.unwrap_or(MAX_CONNECTIONS_PER_AUTHORITY)
}
pub(crate) fn task_limit(
configured_limit: usize,
authority_count: usize,
) -> usize {
configured_limit.max(1).min(MAX_NATIVE_CONNECTIONS).min(
MAX_CONNECTIONS_PER_AUTHORITY.saturating_mul(authority_count.max(1)),
)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -174,4 +183,11 @@ mod tests {
drop(permits);
assert!(try_acquire(&route).is_ok());
}
#[test]
fn task_limit_matches_native_connection_capacity() {
assert_eq!(task_limit(128, 1), 8);
assert_eq!(task_limit(128, 4), 32);
assert_eq!(task_limit(4, 1), 4);
}
}
+126 -24
View File
@@ -85,6 +85,8 @@ const MAX_REDIRECT_LOCATION_BYTES: usize = 8 * 1024;
const FILE_TRANSFER_CONNECT_TIMEOUT: time::Duration =
time::Duration::from_secs(20);
const RESOURCE_WAIT_TIMEOUT: time::Duration = time::Duration::from_secs(45);
const RESOURCE_PRESSURE_INTERVAL: time::Duration = time::Duration::from_secs(3);
const RESOURCE_STALL_TIMEOUT: time::Duration = time::Duration::from_secs(300);
#[cfg(not(test))]
const FILE_TRANSFER_READ_TIMEOUT: time::Duration =
time::Duration::from_secs(60);
@@ -3894,6 +3896,73 @@ struct NativeConnectionPermit<'a> {
_native: crate::util::download::native_budget::NativeBudgetPermit,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ResourceWaitError {
TimedOut,
}
pub(crate) async fn wait_for_resource_with_pressure<F, T, P>(
future: F,
pressure_interval: time::Duration,
stall_timeout: time::Duration,
mut on_pressure: P,
) -> Result<T, ResourceWaitError>
where
F: Future<Output = T>,
P: FnMut(),
{
let pressure_interval =
pressure_interval.max(time::Duration::from_millis(1));
let pressure_timer = tokio::time::sleep(pressure_interval);
let stall_timer = tokio::time::sleep(stall_timeout);
tokio::pin!(future, pressure_timer, stall_timer);
loop {
tokio::select! {
result = &mut future => return Ok(result),
_ = &mut stall_timer => return Err(ResourceWaitError::TimedOut),
_ = &mut pressure_timer => {
on_pressure();
pressure_timer.as_mut().reset(
tokio::time::Instant::now() + pressure_interval,
);
}
}
}
}
pub(crate) async fn wait_for_download_resource<F, T>(
future: F,
) -> Result<T, ResourceWaitError>
where
F: Future<Output = T>,
{
wait_for_resource_with_pressure(
future,
RESOURCE_PRESSURE_INTERVAL,
RESOURCE_STALL_TIMEOUT,
|| {
if let Some(state) = crate::State::get_if_initialized() {
state.record_download_queue_wait();
}
},
)
.await
}
pub(crate) async fn acquire_fetch_permit_with_pressure(
semaphore: &FetchSemaphore,
) -> crate::Result<SemaphorePermit<'_>> {
wait_for_download_resource(semaphore.0.acquire())
.await
.map_err(|_| {
crate::Error::from(ErrorKind::NetworkError(
"download permit remained stalled for 5 minutes".to_string(),
))
})?
.map_err(Into::into)
}
async fn acquire_native_connection<'a>(
route: &DownloadRoute,
semaphore: &'a FetchSemaphore,
@@ -3906,6 +3975,20 @@ async fn acquire_native_connection<'a>(
})
}
async fn acquire_native_connection_with_pressure<'a>(
route: &DownloadRoute,
semaphore: &'a FetchSemaphore,
) -> crate::Result<NativeConnectionPermit<'a>> {
wait_for_download_resource(acquire_native_connection(route, semaphore))
.await
.map_err(|_| {
crate::Error::from(ErrorKind::NetworkError(
"native download resources remained stalled for 5 minutes"
.to_string(),
))
})?
}
fn try_acquire_native_connection<'a>(
route: &DownloadRoute,
semaphore: &'a FetchSemaphore,
@@ -5703,19 +5786,11 @@ async fn download_to_path_inner(
None
};
if let Some((h2_route, h2_policy)) = h2_selection {
let h2_permit =
tokio::time::timeout(RESOURCE_WAIT_TIMEOUT, semaphore.0.acquire())
.await
.map_err(|_| {
ErrorKind::NetworkError(
"timed out waiting for HTTP/2 download permit"
.to_string(),
)
})??;
let h2_started = Instant::now();
match crate::util::download::h2_download::try_download_via_h2(
&request,
&h2_route,
semaphore,
destination,
&part_path,
h2_policy,
@@ -5808,7 +5883,6 @@ async fn download_to_path_inner(
.await?;
}
}
drop(h2_permit);
}
let mut official_integrity_retry = h2_failed_nonofficial.is_some();
@@ -6147,8 +6221,6 @@ async fn download_to_path_inner(
} else {
0
};
let mut activity = crate::State::get_if_initialized()
.map(|state| state.begin_download_connection());
record_install_download_started(
&request,
route,
@@ -6161,25 +6233,21 @@ async fn download_to_path_inner(
DownloadItemStatus::WaitingForResource,
)
.await;
let permit_wait = tokio::time::timeout(
RESOURCE_WAIT_TIMEOUT,
acquire_native_connection(route, semaphore),
);
let permit_wait =
acquire_native_connection_with_pressure(route, semaphore);
let resource_wait_started = Instant::now();
let permit = if let Some(cancellation) = request.cancellation.as_ref() {
let permit = if let Some(cancellation) =
request.cancellation.as_ref()
{
tokio::select! {
_ = cancellation.cancelled() => return Err(ErrorKind::OtherError("download canceled while waiting for native resources".to_string()).into()),
result = permit_wait => result,
}
} else {
permit_wait.await
}
.map_err(|_| {
ErrorKind::NetworkError(
"timed out waiting for native download resources"
.to_string(),
)
})??;
}?;
let mut activity = crate::State::get_if_initialized()
.map(|state| state.begin_download_connection());
tracing::debug!(
route = %sanitize_url_for_log(&route.url),
resource = "native_connection_and_fetch",
@@ -7135,6 +7203,40 @@ mod tests {
static H2_FALLBACK_TEST_LOCK: LazyLock<std::sync::Mutex<()>> =
LazyLock::new(|| std::sync::Mutex::new(()));
#[tokio::test]
async fn resource_wait_reports_pressure_without_losing_queue_position() {
let pressure_events = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&pressure_events);
let result = wait_for_resource_with_pressure(
async {
tokio::time::sleep(Duration::from_millis(35)).await;
7
},
Duration::from_millis(5),
Duration::from_millis(100),
move || {
observed.fetch_add(1, Ordering::Relaxed);
},
)
.await;
assert_eq!(result, Ok(7));
assert!(pressure_events.load(Ordering::Relaxed) >= 1);
}
#[tokio::test]
async fn resource_wait_keeps_a_final_stall_guard() {
let result = wait_for_resource_with_pressure(
std::future::pending::<()>(),
Duration::from_millis(5),
Duration::from_millis(25),
|| {},
)
.await;
assert_eq!(result, Err(ResourceWaitError::TimedOut));
}
async fn spawn_range_server(
data: Arc<Vec<u8>>,
wrong_content_range: bool,
Binary file not shown.

After

Width:  |  Height:  |  Size: 251 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 423 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 434 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 424 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 413 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 467 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 261 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 243 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 180 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 267 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 203 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 161 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 B

Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff. Show more