Compare commits

...
Author SHA1 Message Date
AxTps 13a56f4200 fix: Linux 系统安装时游戏目录默认回退到用户主目录
Sync source to CNB / Sync Git ref (push) Skipped
从 deb 等系统包安装时,启动器可执行文件位于 /usr/bin,此前一键安装
StarLight 实例的"选择游戏目录"弹窗会默认到这个系统目录,普通用户既
无写权限,也不适合存放游戏数据。

将默认目录计算移入 theseus::default_game_dir_root():Linux 下若可执行
文件位于 /usr、/opt、/snap 等系统路径,回退到用户主目录;便携版与其
他平台仍使用可执行文件所在目录。
2026-10-17 16:12:28 +08:00
Disy 0f35a5f707 fix: 修复实时日志积压并更新至 1.0.2-beta7
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
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-12 20:00:25 +08:00
AxTps 6fb73490d3 chore: 发布 1.0.2-beta6
Sync source to CNB / Sync Git ref (push) Skipped
Repository checks / typos (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
Starlight release / Release preflight (push) Canceled after 0s
Starlight release / Build (Windows x64) (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
Prepare pnpm cache / prepare (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
Axolotl desktop CI / website (push) Canceled after 0s
- 版本号更新为 1.0.2-beta6(package.json / Cargo.toml / Cargo.lock)
- catalog 新增 1.0.2-beta6 更新公告:键盘快捷键、崩溃日志分享与 AI 分析、日志类型扩展、日志导出、实例分组拖拽,以及公告刷新与盔甲翻译修复
2026-10-11 15:53:34 +08:00
AxTps 2dcf26c9d9 Merge pull request #18 from ApTx2012/feat/backend-logtype
Sync source to CNB / Sync Git ref (push) Skipped
Repository checks / typos (push) Canceled after 0s
Repository checks / tombi (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
Axolotl desktop CI / website (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
feat: 扩展日志类型,支持 JVM 崩溃与启动器日志
2026-10-11 15:44:25 +08:00
AxTps 9ccacba3fd Merge remote-tracking branch 'origin/main' into feat/backend-logtype
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-11 15:42:28 +08:00
AxTps 54499dd9da Merge pull request #17 from ApTx2012/feat/backend
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
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
feat: 崩溃日志分享与 AI 分析
2026-10-11 15:41:23 +08:00
AxTps fce6c60759 Merge remote-tracking branch 'origin/main' into feat/backend
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-11 15:40:27 +08:00
AxTps dcbad9447d Merge remote-tracking branch 'origin/main' into feat/backend-logtype
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-11 15:08:59 +08:00
AxTps 4abf643852 Merge pull request #4 from ApTx2012/automation/sync-lobehub-models
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
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
chore(ai): sync LobeHub models
2026-10-11 15:07:54 +08:00
AxTps a8d8e1674b feat: 扩展日志类型,支持 JVM 崩溃与启动器日志
Sync source to CNB / Sync Git ref (push) Skipped
LogType 新增 JvmCrash 与 LauncherLog,使崩溃弹窗能列出
hs_err_pid*.log、launcher_log.txt、latest_stdout.log 等日志。

- 新增 log_directories_for_type 与 is_log_file_for_type,统一
  各日志类型的目录解析与文件名筛选
- 新增 isolated_minecraft_root,兼容 versions 版本隔离布局
- get_logs 追加 JvmCrash 与 LauncherLog 两类采集
- get_logs_by_filename / get_output_by_filename /
  delete_logs_by_filename 改用目录列表按存在性查找
- get_logs_from_type 遍历多目录并按文件名去重
2026-10-11 14:53:20 +08:00
AxTps 60f3fd8816 Merge pull request #16 from ApTx2012/feat/ui
Sync source to CNB / Sync Git ref (push) Skipped
Repository checks / typos (push) Canceled after 0s
Repository checks / tombi (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
Axolotl desktop CI / website (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
feat: 新增键盘快捷键设置
2026-10-11 14:09:48 +08:00
AxTps c71c220446 feat: 崩溃弹窗集成日志分享与 AI 分析
Sync source to CNB / Sync Git ref (push) Skipped
将崩溃弹窗替换为双栏布局:左侧展示诊断摘要与分享入口,
右侧提供日志文件浏览器与 LogAgent 流式分析输出。

- MinecraftCrashModal 改用新版的分享票据、结构化摘要与 AI 事件流
- 新增 minecraft-crash-logs 工具函数,用于筛选与合并崩溃日志
- 事件层新增 logshare_ai_listener 监听 AI 分析进度
- log-share 工具更新为支持 provider 路由的新版
- Button 组件对齐新版(补 icon-only、circular、2xs 与 chip/highlight 变体)
- console 导出 LogViewport,供日志浏览器复用
- 补齐 en-US / zh-CN 相关文案
2026-10-11 14:05:33 +08:00
AxTps a95153d0b1 fix: 补全崩溃日志分享命令层的类型导入
apps/app 命令层缺少 LogShareSettings、LogShareUploadResponse、
SharedLog 三个类型的导入,导致 desktop 编译报 E0425。
2026-10-11 14:04:52 +08:00
AxTps 853147b04d feat: 新增崩溃日志分享设置界面
Sync source to CNB / Sync Git ref (push) Skipped
- 设置页新增「日志分享」与「已分享日志」区块(默认实例设置内)
- 补齐 helpers/logs.js 的 logshare 调用(上传/分析/删除/记录)
- 日志分享设置支持分享服务、AI 来源、自动上传、多文件、不留存、进度等选项
- 已分享日志支持查看列表与删除
- 补 en-US / zh-CN 文案
- i18n 白名单补充 LogShare AI
2026-10-11 12:23:53 +08:00
AxTps 8d61826c5f feat: 新增崩溃日志分享与 AI 分析(后端)
Sync source to CNB / Sync Git ref (push) Skipped
- 新增 LogShare 接入:上传崩溃日志、查询结构化分析、SSE 流式 AI 解释、删除分享
- 新增本地已分享日志记录(shared_logs)与分享设置(log_share_settings)
- 日志上传来源标识为 starlight/<版本>
- 新增 logshare_ai 事件用于向前端推送 AI 流式输出
- 暴露 11 个 tauri 命令并补齐 ACL
2026-10-11 12:15:33 +08:00
AxTps 2e92887eb2 feat: 新增键盘快捷键设置
Sync source to CNB / Sync Git ref (push) Skipped
- 设置页新增「键盘快捷键」分类,可自定义快捷键绑定
- 支持快速滚动(Home/End/PageUp/PageDown)与导航跳转(Ctrl/Cmd+数字)
- 快捷键绑定与开关按动作独立持久化,默认关闭
- 新增 ui 包 keybinding 组件与工具(KeybindingModal/KeybindingChips 等)
2026-10-11 11:14:46 +08:00
AxTps 47bdb1e79c Merge pull request #15 from ApTx2012/fix/ui
Sync source to CNB / Sync Git ref (push) Skipped
Rust checks / shear (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Repository checks / tombi (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
Axolotl desktop CI / website (push) Canceled after 0s
fix: 修复远端公告不刷新与盔甲面板未翻译
2026-10-11 10:32:49 +08:00
AxTps d6fdb4f453 Merge remote-tracking branch 'origin/main' into fix/ui
Sync source to CNB / Sync Git ref (push) Skipped
# Conflicts:
#	apps/app-frontend/src/locales/en-US/index.json
#	apps/app-frontend/src/locales/zh-CN/index.json
2026-10-11 10:28:52 +08:00
AxTps 4ba1ed279f Merge pull request #14 from ApTx2012/feat/instance
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
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
feat: 实例分组增强(后端 JSON 存储 + 前端拖拽分组 UI)
2026-10-11 09:39:14 +08:00
AxTps afdd091971 fix: 修复远端公告不刷新与盔甲面板未翻译
Sync source to CNB / Sync Git ref (push) Skipped
Bug1 远端公告:公告只在启动时拉取一次,且点铃铛不触发刷新。
- openCenter 时补调 refresh(),点铃铛即拉最新
- watch skinSiteStatus,登录皮肤站后自动重试拉取

Bug2 盔甲翻译:补 7 个缺失的 app.skins.armor.* i18n 键
(title/save/close/description/unsaved/reset-to-saved/restore-defaults),
ui 包的 skin.preview.armor.* 46 个键已存在无需补。
2026-10-11 08:58:03 +08:00
AxTps 99e0aa9d14 Merge pull request #13 from ApTx2012/feat/backend
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
Axolotl desktop CI / website (push) Canceled after 0s
Repository checks / typos (push) Canceled after 0s
Repository checks / tombi (push) Canceled after 0s
Rust checks / shear (push) Canceled after 0s
feat: 导出启动器日志
2026-10-11 08:35:07 +08:00
AxTps 22bc631293 style: 对 emit.rs 的 import 补跑 cargo fmt
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-11 08:15:28 +08:00
AxTps 3d3682023e fix: 补回 emit.rs 缺失的 futures/serde_json import
Sync source to CNB / Sync Git ref (push) Skipped
阶段1搬运时漏了 `use futures::prelude::*;` 和 `use serde_json::Value;`,
导致 cargo test 编译 theseus lib test 时报 E0425(Value) / E0405(TryStream)。
cargo check 不编 test 路径故未暴露。
2026-10-11 08:08:40 +08:00
AxTps f253d5529b feat: 实例分组增强前端(拖拽分组 UI)
Sync source to CNB / Sync Git ref (push) Skipped
移植 Axolotl 的拖拽式实例分组界面到 Starlight,接入阶段1的规范化分组后端:

- 新增 helpers/analytics.ts(trackEvent 遥测桩)
- 补全 helpers/instance-groups.ts(6 个 invoke 包装)
- 新增 composables/useInstanceGroups.ts(分组状态 + 事件监听)
- 升级 composables/useGridGrouping.ts(排序方向 isSortAscending/toggleSortDirection)
- helpers/events.js 补 instance_groups_listener(对接 instance_groups_changed 事件)
- 新增 components/ui/library/DraggableInstanceCard.vue
- 新增 components/ui/library/InstanceGroup.vue(并补 group-drag-handle 修复组拖拽重排)
- 新增 components/ui/modal/InstanceGroupModal.vue
- GridDisplay.vue 替换为 Axolotl 拖拽版(DragDropProvider + vuedraggable)
- 补 en-US/zh-CN i18n 键各 39 条
2026-10-11 07:54:48 +08:00
AxTps 253141b6ff style: 补实例分组阶段1的 cargo fmt 格式
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-11 07:17:42 +08:00
AxTps 946a477397 feat: 实例分组增强阶段1(后端 JSON 存储与命令)
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-11 07:12:15 +08:00
AxTps c9a2eeb53d Merge branch 'main' into feat/backend
Sync source to CNB / Sync Git ref (push) Skipped
解决 zh-CN locale 末尾追加冲突:保留日志导出键。
2026-10-11 06:14:25 +08:00
AxTps 79addd4aba feat: 移植导出启动器日志
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-11 06:12:05 +08:00
github-actions[bot] 98396c6bcd chore(ai): sync LobeHub models at 6c7a6fb033e4
Sync source to CNB / Sync Git ref (push) Skipped
2026-10-10 09:55:54 +00:00
78 changed files with 9767 additions and 759 deletions

No files matched your search

Generated
+2 -2
View File
@@ -6841,7 +6841,7 @@ dependencies = [
[[package]]
name = "theseus"
version = "1.0.2-beta4"
version = "1.0.2-beta7"
dependencies = [
"ariadne",
"async-minecraft-ping",
@@ -6945,7 +6945,7 @@ dependencies = [
[[package]]
name = "theseus_gui"
version = "1.0.2-beta4"
version = "1.0.2-beta7"
dependencies = [
"ashpd",
"async_zip",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@modrinth/app-frontend",
"private": true,
"version": "1.0.2-beta4",
"version": "1.0.2-beta7",
"type": "module",
"scripts": {
"dev": "vite",
+3
View File
@@ -169,6 +169,7 @@ import { createServerInstall, provideServerInstall } from '@/providers/server-in
import { setupProviders } from '@/providers/setup'
import { setupAuthProvider } from '@/providers/setup/auth'
import { setupLoadingStateProvider } from '@/providers/setup/loading-state'
import { setupKeyboardShortcuts } from '@/composables/useKeyboardShortcuts'
import { useError } from '@/store/error.js'
import { useTheming } from '@/store/state'
@@ -184,6 +185,8 @@ const onSchematicWorkshopPage = computed(() => route.path === '/lab/schematic-pr
const isSchematicFile = (path: string) => /\.(litematic|schematic|schem)$/i.test(path)
const APP_LEFT_NAV_WIDTH = '4rem'
setupKeyboardShortcuts()
const discoverContentPath = computed(() => {
const projectType = route.params.projectType
if (
@@ -32,6 +32,55 @@ export const ANNOUNCEMENT_CHANGE_TYPES: readonly AnnouncementChangeType[] = [
]
export const launcherAnnouncements: readonly LauncherAnnouncement[] = [
{
id: 'launcher-1.0.2-beta6',
version: '1.0.2-beta6',
publishedAt: '2026-10-11',
title: {
'en-US': 'Starlight Launcher 1.0.2-beta6',
'zh-CN': 'Starlight Launcher 1.0.2-beta6',
},
changes: {
added: [
{
'en-US': 'Added keyboard shortcut settings: enable and rebind navigation and quick-scrolling shortcuts.',
'zh-CN': '新增键盘快捷键设置:可启用并自定义导航与快速滚动快捷键。',
},
{
'en-US': 'Added crash log sharing and AI analysis: share crash diagnostics to LogShare for a structured summary and optional AI analysis, with a rebuilt crash window that browses log files and streams the analysis.',
'zh-CN': '新增崩溃日志分享与 AI 分析:可将崩溃诊断分享到 LogShare 获取结构化摘要与 AI 分析;崩溃窗口重做为双栏布局,可浏览日志文件并流式查看分析结果。',
},
{
'en-US': 'Crash logs now also collect JVM crash reports (hs_err_pid*.log) and launcher logs.',
'zh-CN': '崩溃日志现在也会收集 JVM 崩溃报告(hs_err_pid*.log)与启动器日志。',
},
{
'en-US': 'Added a launcher log export entry.',
'zh-CN': '新增启动器日志导出入口。',
},
{
'en-US': 'Instance groups can now be reordered by dragging.',
'zh-CN': '实例分组支持拖拽重排。',
},
],
changed: [
{
'en-US': 'Synced the latest supported AI chat model list from LobeHub.',
'zh-CN': '同步 LobeHub 最新的 AI 聊天模型列表。',
},
],
fixed: [
{
'en-US': 'Fixed remote announcements not refreshing.',
'zh-CN': '修复远端公告不刷新的问题。',
},
{
'en-US': 'Completed the Chinese translations for the armor preview feature.',
'zh-CN': '补齐盔甲预览功能的中文翻译。',
},
],
},
},
{
id: 'launcher-1.0.2-beta5',
version: '1.0.2-beta5',
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -100,6 +100,7 @@ function emitState() {
}
function openCenter(item?: RemoteAnnouncement) {
if (!props.ready || disposed) return
void refresh()
centerOpen.value = true
if (item) {
startupNotice.value = null
@@ -302,6 +303,10 @@ onMounted(() => {
setTimeout(start, 500)
}
})
watch(skinSiteStatus, (status) => {
if (disposed || props.previewOnly) return
if (status === 'signed-in') void refresh()
})
watch([() => props.ready, hasModal], () => {
if (advanceTimer) clearTimeout(advanceTimer)
advanceTimer = setTimeout(advance, 350)
@@ -0,0 +1,92 @@
<script setup lang="ts">
import { KeyboardSensor, PointerSensor, useDraggable } from '@dnd-kit/vue'
import { useEventListener } from '@vueuse/core'
import { computed, ref } from 'vue'
import type { GameInstance } from '@/helpers/types'
const props = defineProps<{
instance: GameInstance
instanceGroupId: string
disabled: boolean
}>()
const emit = defineEmits<{
(e: 'contextmenu' | 'card-click', event: MouseEvent): void
(e: 'start-long-press' | 'cancel-long-press'): void
}>()
const cardElement = ref<HTMLElement>()
const instanceCardSensors = [
PointerSensor.configure({
preventActivation: () => false,
}),
KeyboardSensor,
]
const dragDisabled = computed(() => props.disabled)
const { isDragging } = useDraggable({
id: computed(() => `instance:${props.instanceGroupId}:${props.instance.id}`),
element: cardElement,
disabled: dragDisabled,
sensors: instanceCardSensors,
data: computed(() => ({
instanceId: props.instance.id,
fromGroup: props.instanceGroupId,
})),
})
let wantsClick = false
useEventListener(window, 'pointerdown', () => {
wantsClick = true
})
useEventListener(window, 'pointerup', () => {
if (isDragging.value) {
wantsClick = false
}
})
useEventListener(window, 'blur', () => {
wantsClick = false
})
function onCardClick(event: MouseEvent) {
if (!wantsClick || isDragging.value) return
wantsClick = false
emit('card-click', event)
}
function onContextMenu(event: MouseEvent) {
emit('contextmenu', event)
}
function onMouseDown() {
if (!dragDisabled.value) {
emit('start-long-press')
}
}
function onMouseUp() {
emit('cancel-long-press')
}
</script>
<template>
<div
ref="cardElement"
class="group relative min-w-0 w-full"
@click="onCardClick"
@mousedown="onMouseDown"
@mouseup="onMouseUp"
@mouseleave="onMouseUp"
@touchstart="!dragDisabled && onMouseDown()"
@touchend="onMouseUp"
@touchcancel="onMouseUp"
@contextmenu.prevent.stop="onContextMenu"
>
<slot :is-dragging="isDragging" />
<slot v-if="!isDragging" name="overlay" />
</div>
</template>
@@ -0,0 +1,521 @@
<script setup lang="ts">
import { useDroppable } from '@dnd-kit/vue'
import {
ArrowDownIcon,
ArrowUpIcon,
DropdownIcon,
EditIcon,
PlusIcon,
TrashIcon,
XIcon,
} from '@modrinth/assets'
import {
Button,
Checkbox,
commonMessages,
defineMessages,
IconButton,
InlineEditableText,
NewModal,
TagItem,
useVIntl,
} from '@modrinth/ui'
import { computed, nextTick, ref, watch } from 'vue'
import ContextMenu from '@/components/ui/ContextMenu.vue'
import Instance from '@/components/ui/Instance.vue'
import DraggableInstanceCard from '@/components/ui/library/DraggableInstanceCard.vue'
import { UNGROUPED_GROUP_KEY } from '@/composables/useGridGrouping'
import { FAVORITES_GROUP_ID } from '@/composables/useInstanceGroups'
import type { GameInstance } from '@/helpers/types'
const MAX_GROUP_NAME_LENGTH = 256
const { formatMessage } = useVIntl()
const messages = defineMessages({
ungrouped: { id: 'app.instances.group.ungrouped', defaultMessage: 'No group' },
pinned: { id: 'app.instances.group.pinned', defaultMessage: 'Pinned' },
emptyGroup: {
id: 'app.instances.group.empty',
defaultMessage: 'Drag and drop to add instances.',
},
editGroupName: {
id: 'app.instances.group.edit-name',
defaultMessage: 'Edit group name',
},
deleteGroup: {
id: 'app.instances.group.delete-group',
defaultMessage: 'Delete group',
},
deleteGroupDescription: {
id: 'app.instances.group.delete-description',
defaultMessage: 'Instances in this group will be ungrouped.',
},
moveGroupUp: {
id: 'app.instances.group.move-up',
defaultMessage: 'Move group up',
},
moveGroupDown: {
id: 'app.instances.group.move-down',
defaultMessage: 'Move group down',
},
addToGroup: {
id: 'app.instances.group.add-to-group',
defaultMessage: 'Add to group',
},
newInstance: {
id: 'app.instances.group.new-instance',
defaultMessage: 'New instance',
},
collapseGroup: {
id: 'app.instances.group.collapse',
defaultMessage: 'Collapse group',
},
expandGroup: {
id: 'app.instances.group.expand',
defaultMessage: 'Expand group',
},
renameGroup: {
id: 'app.instances.group.rename-group',
defaultMessage: 'Rename group',
},
groupNameEmpty: {
id: 'app.instances.group.name-empty',
defaultMessage: 'Group names cannot be empty.',
},
groupNameTooLong: {
id: 'app.instances.group.name-too-long',
defaultMessage: 'Group names cannot be longer than {maxLength} characters.',
},
})
const props = defineProps<{
sectionKey: string
groupName?: string
instances: GameInstance[]
grouping: string
isCollapsed: boolean
displayMode: string
selectMode: boolean
selectedInstanceIds: Set<string>
isSortAscending?: boolean
hideHeader?: boolean
canMoveUp?: boolean
canMoveDown?: boolean
groupPendingNameEdit?: string | null
}>()
// Events are grouped only where the payload shapes genuinely match; the
// per-event names are documentation, not part of the type.
const emit = defineEmits<{
(e: 'toggleCollapse' | 'deleteGroup' | 'addToGroup' | 'startLongPress', id: string): void
(e: 'handleCheckboxClick' | 'handleCardClick', instanceId: string, event: MouseEvent): void
(e: 'handleContextMenu', event: MouseEvent, instanceId: string, sectionKey: string): void
(e: 'renameGroup', oldKey: string, newKey: string): void
(e: 'cancelLongPress' | 'newInstance' | 'renameComplete'): void
(e: 'moveGroup', groupKey: string, direction: -1 | 1): void
}>()
const groupOptions = ref<InstanceType<typeof ContextMenu>>()
const groupContainerRef = ref<HTMLElement>()
const groupNameInput = ref<InstanceType<typeof InlineEditableText>>()
const deletingGroup = ref(false)
const confirmDeleteGroupModal = ref<InstanceType<typeof NewModal>>()
const groupName = ref(props.groupName ?? props.sectionKey)
const isUngrouped = computed(() => props.sectionKey === UNGROUPED_GROUP_KEY)
const isFavorites = computed(() => props.sectionKey === FAVORITES_GROUP_ID)
const isCustomGroup = computed(
() => props.grouping === 'Group' && !isUngrouped.value && !isFavorites.value,
)
const isGroupDragActive = computed(() => props.grouping === 'Group')
const effectiveCollapsed = computed(() => (props.hideHeader ? false : props.isCollapsed))
const { isDropTarget } = useDroppable({
id: computed(() => `instance-group:${props.sectionKey}`),
element: groupContainerRef,
disabled: computed(() => props.hideHeader || !isGroupDragActive.value),
data: computed(() => ({
groupId: props.sectionKey,
})),
})
watch(
() => [props.sectionKey, props.groupName],
() => {
groupName.value = props.groupName ?? props.sectionKey
},
)
watch(
() => props.groupPendingNameEdit,
async (pendingId) => {
if (pendingId !== props.sectionKey) return
await nextTick()
groupContainerRef.value?.scrollIntoView({ block: 'nearest' })
await groupNameInput.value?.startEditing()
emit('renameComplete')
},
{ immediate: true, flush: 'post' },
)
function validateGroupName(value: string) {
const normalized = value.trim()
if (normalized.length === 0) return false
if (normalized.length > MAX_GROUP_NAME_LENGTH) return false
return true
}
async function updateGroupName(value: string) {
const newName = value.trim()
if (!newName || newName === groupName.value) return false
emit('renameGroup', props.sectionKey, newName)
return true
}
function openGroupContextMenu(event: MouseEvent) {
groupOptions.value?.showMenu(
event,
props.sectionKey,
isCustomGroup.value
? [
{ name: 'new_instance' },
{ name: 'add_instances' },
{ name: 'edit_name' },
{ type: 'divider' },
{ name: 'delete_group', color: 'danger' },
]
: [{ name: 'new_instance' }],
)
}
async function handleGroupOption({ option }: { option: string }) {
if (option === 'new_instance') {
emit('newInstance')
} else if (option === 'add_instances') {
emit('addToGroup', props.sectionKey)
} else if (option === 'edit_name') {
groupNameInput.value?.startEditing()
} else if (option === 'delete_group') {
requestGroupDeletion()
}
}
function requestGroupDeletion() {
if (isUngrouped.value || isFavorites.value) return
if (props.instances.length > 0) {
confirmDeleteGroupModal.value?.show()
} else {
void removeGroup()
}
}
async function removeGroup() {
if (deletingGroup.value) return
deletingGroup.value = true
emit('deleteGroup', props.sectionKey)
setTimeout(() => {
deletingGroup.value = false
confirmDeleteGroupModal.value?.hide()
}, 300)
}
function onCardClick(instanceId: string, event: MouseEvent) {
emit('handleCardClick', instanceId, event)
}
function onStartLongPress(instanceId: string) {
emit('startLongPress', instanceId)
}
</script>
<template>
<div
ref="groupContainerRef"
class="instance-group group/instance-container relative select-none pb-3"
@contextmenu.prevent.stop="openGroupContextMenu"
>
<div
v-if="!hideHeader && isDropTarget && isGroupDragActive"
class="pointer-events-none absolute -inset-2 inset-y-0 z-20 rounded-xl border-2 border-dashed border-contrast opacity-40 bg-transparent transition-opacity duration-150"
/>
<div
v-if="!hideHeader && (grouping === 'Group' || sectionKey !== UNGROUPED_GROUP_KEY)"
class="group/header flex h-10 w-full items-center gap-2 border-0 border-b border-solid border-b-surface-5"
:class="{ 'group-drag-handle cursor-grab': isCustomGroup }"
>
<div
class="flex min-w-0 cursor-pointer items-center gap-2"
@click="emit('toggleCollapse', sectionKey)"
>
<button
class="flex shrink-0 items-center border-0 bg-transparent p-0 cursor-pointer"
type="button"
:aria-expanded="!effectiveCollapsed"
:aria-label="
formatMessage(effectiveCollapsed ? messages.expandGroup : messages.collapseGroup)
"
@click.stop="emit('toggleCollapse', sectionKey)"
>
<DropdownIcon
class="size-5 shrink-0 text-[var(--color-text-tertiary)] transition-transform duration-300"
:class="{ 'rotate-180': !effectiveCollapsed }"
/>
</button>
<InlineEditableText
v-if="!isUngrouped && !isFavorites"
ref="groupNameInput"
v-model="groupName"
activation-mode="manual"
class="text-base font-semibold !h-10 text-[var(--color-text-default)] select-none"
max-width="24rem"
:max-length="MAX_GROUP_NAME_LENGTH"
:on-change="updateGroupName"
:validate="validateGroupName"
/>
<span v-else class="text-base font-semibold text-[var(--color-text-default)] select-none">
{{ isFavorites ? formatMessage(messages.pinned) : formatMessage(messages.ungrouped) }}
</span>
<TagItem v-if="instances.length" class="shrink-0 border-surface-3 bg-surface-2">
{{ instances.length }}
</TagItem>
</div>
<div class="min-w-0 flex-1" />
<div
v-if="isCustomGroup"
class="flex shrink-0 items-center opacity-0 transition-opacity duration-250 group-hover/header:opacity-100 focus-within:opacity-100"
>
<IconButton
v-tooltip="formatMessage(messages.moveGroupUp)"
:label="formatMessage(messages.moveGroupUp)"
type="quiet"
size="sm"
:disabled="!canMoveUp"
@click.stop="emit('moveGroup', sectionKey, -1)"
>
<ArrowUpIcon />
</IconButton>
<IconButton
v-tooltip="formatMessage(messages.moveGroupDown)"
:label="formatMessage(messages.moveGroupDown)"
type="quiet"
size="sm"
:disabled="!canMoveDown"
@click.stop="emit('moveGroup', sectionKey, 1)"
>
<ArrowDownIcon />
</IconButton>
<IconButton
v-tooltip="formatMessage(messages.editGroupName)"
:label="formatMessage(messages.editGroupName)"
type="quiet"
size="sm"
@click.stop="groupNameInput?.startEditing()"
>
<EditIcon />
</IconButton>
<IconButton
v-tooltip="formatMessage(messages.addToGroup)"
:label="formatMessage(messages.addToGroup)"
type="quiet"
size="sm"
@click.stop="emit('addToGroup', sectionKey)"
>
<PlusIcon />
</IconButton>
<IconButton
v-tooltip="formatMessage(messages.deleteGroup)"
:label="formatMessage(messages.deleteGroup)"
type="quiet"
size="sm"
:disabled="deletingGroup"
@click.stop="handleGroupOption({ option: 'delete_group' })"
>
<TrashIcon />
</IconButton>
</div>
</div>
<div v-if="!effectiveCollapsed" class="mt-2.5">
<section
class="grid grid-cols-[repeat(auto-fill,minmax(16rem,1fr))] w-full gap-3 mr-auto scroll-smooth overflow-y-auto"
:class="{
'grid-cols-[repeat(auto-fill,minmax(13rem,1fr))] gap-4': displayMode === 'cards',
}"
>
<template v-for="instance in instances" :key="instance.id">
<DraggableInstanceCard
v-if="isGroupDragActive"
:instance="instance"
:instance-group-id="sectionKey"
:disabled="selectMode"
@card-click="(event: MouseEvent) => onCardClick(instance.id, event)"
@contextmenu="
(event: MouseEvent) => emit('handleContextMenu', event, instance.id, props.sectionKey)
"
@start-long-press="onStartLongPress(instance.id)"
@cancel-long-press="emit('cancelLongPress')"
>
<template #default="{ isDragging }">
<div
:class="{
'pointer-events-none': selectMode,
'relative cursor-pointer select-none rounded-lg transition-all hover:brightness-90 active:scale-[0.98]': true,
}"
@click.capture="
(event: MouseEvent) => {
if (event.shiftKey && !selectMode) {
event.stopPropagation()
emit('handleCardClick', instance.id, event)
}
}
"
>
<Instance
:instance="instance"
:disabled="selectMode || isDragging"
:variant="displayMode === 'cards' ? 'library' : 'standard'"
:class="{
'opacity-50': selectMode && !selectedInstanceIds.has(instance.id),
}"
/>
</div>
</template>
<template #overlay>
<div
class="absolute right-2 bottom-2 z-10 transition-opacity"
:class="
selectMode && selectedInstanceIds.has(instance.id)
? ''
: 'opacity-0 group-hover:opacity-100'
"
@click.stop="emit('handleCheckboxClick', instance.id, $event)"
>
<Checkbox :model-value="selectedInstanceIds.has(instance.id)" />
</div>
<div
v-if="!selectMode"
class="absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity"
@click.stop="
emit('handleContextMenu', $event as MouseEvent, instance.id, props.sectionKey)
"
>
<Button type="quiet" size="2xs" circular icon-only
><slot name="moreIcon" />
</Button>
</div>
</template>
</DraggableInstanceCard>
<div v-else class="group relative">
<div
class="relative cursor-pointer select-none rounded-lg transition-all hover:brightness-90 active:scale-[0.98]"
@click.capture="
(event: MouseEvent) => {
if (event.shiftKey && !selectMode) {
event.stopPropagation()
emit('handleCardClick', instance.id, event)
}
}
"
@click="emit('handleCardClick', instance.id, $event as MouseEvent)"
@mousedown="!selectMode && emit('startLongPress', instance.id)"
@mouseup="emit('cancelLongPress')"
@mouseleave="emit('cancelLongPress')"
@touchstart="!selectMode && emit('startLongPress', instance.id)"
@touchend="emit('cancelLongPress')"
@touchcancel="emit('cancelLongPress')"
>
<div :class="{ 'pointer-events-none': selectMode }">
<Instance
:instance="instance"
:disabled="selectMode"
:variant="displayMode === 'cards' ? 'library' : 'standard'"
:class="{
'opacity-50': selectMode && !selectedInstanceIds.has(instance.id),
}"
@contextmenu.prevent.stop="
(event: MouseEvent) =>
emit('handleContextMenu', event, instance.id, props.sectionKey)
"
/>
</div>
</div>
<div
class="absolute right-2 bottom-2 z-10 transition-opacity"
:class="
selectMode && selectedInstanceIds.has(instance.id)
? ''
: 'opacity-0 group-hover:opacity-100'
"
@click.stop="emit('handleCheckboxClick', instance.id, $event)"
>
<Checkbox :model-value="selectedInstanceIds.has(instance.id)" />
</div>
<div
v-if="!selectMode"
class="absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity"
@click.stop="
emit('handleContextMenu', $event as MouseEvent, instance.id, props.sectionKey)
"
>
<Button type="quiet" size="2xs" circular icon-only><slot name="moreIcon" /> </Button>
</div>
</div>
</template>
<p
v-if="instances.length === 0"
class="col-span-full m-0 pt-1 pl-0.5 text-base font-base text-[var(--color-text-tertiary)] opacity-80"
>
{{ formatMessage(messages.emptyGroup) }}
</p>
</section>
</div>
</div>
<ContextMenu ref="groupOptions" @option-clicked="handleGroupOption">
<template #new_instance>
<PlusIcon />
{{ formatMessage(messages.newInstance) }}
</template>
<template #add_instances>
<PlusIcon />
{{ formatMessage(messages.addToGroup) }}
</template>
<template #edit_name>
<EditIcon />
{{ formatMessage(messages.editGroupName) }}
</template>
<template #delete_group>
<TrashIcon />
{{ formatMessage(messages.deleteGroup) }}
</template>
</ContextMenu>
<NewModal
ref="confirmDeleteGroupModal"
:header="formatMessage(messages.deleteGroup)"
fade="danger"
width="500px"
>
<p class="m-0 text-base text-[var(--color-text-default)]">
{{ formatMessage(messages.deleteGroupDescription) }}
</p>
<template #actions>
<div class="flex justify-end gap-2">
<Button type="outlined" @click="confirmDeleteGroupModal?.hide()">
<XIcon />
{{ formatMessage(commonMessages.cancelButton) }}
</Button>
<Button type="colored" color="red" :disabled="deletingGroup" @click="removeGroup">
<TrashIcon />
{{ formatMessage(messages.deleteGroup) }}
</Button>
</div>
</template>
</NewModal>
</template>
@@ -0,0 +1,62 @@
export interface CrashLogFile {
age: number
filename: string
log_type: 'InfoLog' | 'CrashReport' | 'JvmCrash' | 'LauncherLog'
output?: string | null
}
const RUN_ASSOCIATION_WINDOW_SECONDS = 3 * 60
export function shouldUseLogShareAutoAnalysis(settings: {
ai_source: 'logshare' | 'custom'
auto_upload: boolean
no_storage?: boolean
}): boolean {
return settings.ai_source === 'logshare' && settings.auto_upload
}
function isRelevantLog(file: CrashLogFile): boolean {
const lower = file.filename.toLowerCase()
if (file.log_type === 'CrashReport') return lower.endsWith('.txt')
if (file.log_type === 'JvmCrash') return lower.startsWith('hs_err') && lower.endsWith('.log')
return ['latest.log', 'debug.log', 'launcher_log.txt', 'latest_stdout.log'].includes(lower)
}
export function selectCrashLogFiles(files: CrashLogFile[]): CrashLogFile[] {
const sorted = files.filter(isRelevantLog).sort((left, right) => right.age - left.age)
const anchor = sorted[0]?.age
if (anchor === undefined) return []
const singletonTypes = new Set<CrashLogFile['log_type']>()
return sorted.filter((file) => {
if (anchor - file.age > RUN_ASSOCIATION_WINDOW_SECONDS) return false
if (file.log_type !== 'CrashReport' && file.log_type !== 'JvmCrash') return true
if (singletonTypes.has(file.log_type)) return false
singletonTypes.add(file.log_type)
return true
})
}
export function crashLogKey(file: CrashLogFile): string {
return `${file.log_type}:${file.filename}`
}
export function crashLogLabel(file: CrashLogFile): string {
return file.log_type === 'CrashReport' ? `crash-reports/${file.filename}` : file.filename
}
export function preferredCrashLogKey(files: CrashLogFile[]): string {
const preferred =
files.find((file) => file.log_type === 'CrashReport') ??
files.find((file) => file.log_type === 'JvmCrash') ??
files.find((file) => file.filename.toLowerCase() === 'latest.log') ??
files[0]
return preferred ? crashLogKey(preferred) : ''
}
export function combineCrashLogs(files: CrashLogFile[]): string {
return files
.filter((file) => file.output)
.map((file) => `===== ${crashLogLabel(file)} =====\n${file.output}`)
.join('\n\n')
}
@@ -0,0 +1,313 @@
<template>
<NewModal ref="modal" no-padding scrollable actions-divider max-width="560px" width="560px">
<template #title>
<span class="text-2xl font-semibold text-[var(--color-text-primary)]">
{{
existingGroupName
? formatMessage(messages.addToGroupTitle, { groupName: existingGroupName })
: formatMessage(messages.header)
}}
</span>
</template>
<template v-if="!existingGroupName">
<div class="flex flex-col gap-2.5 p-6">
<label for="new-group-name" class="font-semibold text-[var(--color-text-primary)]">
{{ formatMessage(messages.groupName) }}
</label>
<StyledInput
id="new-group-name"
ref="groupNameInput"
v-model="newGroupName"
:placeholder="formatMessage(messages.groupNamePlaceholder)"
:maxlength="32"
@click="groupNameInput?.select()"
/>
</div>
<div class="h-px bg-divider" />
</template>
<div class="flex h-[400px] flex-col gap-3 overflow-y-auto bg-surface-2 py-4">
<div class="px-6">
<StyledInput
v-model="newGroupSearch"
:icon="SearchIcon"
:placeholder="formatMessage(messages.searchInstance)"
class="w-full"
/>
</div>
<div
v-if="newGroupInstances.length === 0"
class="flex items-center justify-center py-12 text-[var(--color-text-tertiary)]"
>
{{ formatMessage(messages.noInstancesFound) }}
</div>
<div v-else class="flex flex-col gap-1">
<div
v-for="instance in newGroupInstances"
:key="instance.id"
class="flex items-center justify-between gap-4 px-6 py-1.5 hover:bg-surface-3"
:class="{ 'opacity-60': selectedNewGroupInstanceIds.has(instance.id) }"
>
<div class="flex min-w-0 items-center gap-2.5">
<InstanceIcon
:icon-path="instance.icon_path"
:instance-id="instance.id"
:loader="instance.loader"
class="!size-[2rem] !rounded-md"
/>
<div class="flex min-w-0 items-center gap-2">
<span class="truncate font-semibold text-[var(--color-text-primary)]">{{
instance.name
}}</span>
<TagItem v-if="instance.groups && instance.groups.length > 0" class="shrink-0">
{{ getGroupName(instance.groups[0]) }}
</TagItem>
</div>
</div>
<Button
:type="selectedNewGroupInstanceIds.has(instance.id) ? 'outlined' : 'base'"
@click="toggleNewGroupInstance(instance.id)"
>
<CheckIcon v-if="selectedNewGroupInstanceIds.has(instance.id)" />
{{
formatMessage(
selectedNewGroupInstanceIds.has(instance.id) ? messages.added : messages.add,
)
}}
</Button>
</div>
</div>
</div>
<template #actions>
<div class="flex items-center justify-end gap-2">
<Button type="outlined" @click="modal?.hide()">
<XIcon />
{{ formatMessage(messages.cancel) }}
</Button>
<Button
type="colored"
color="brand"
:disabled="existingGroupName ? !canSaveGroups : !canCreateGroup"
@click="existingGroupName ? handleSaveGroups() : handleCreateGroup()"
>
<SpinnerIcon v-if="creatingGroup" class="animate-spin" />
<CheckIcon v-else-if="existingGroupName" />
<PlusIcon v-else />
{{ formatMessage(existingGroupName ? messages.saveChanges : messages.createGroup) }}
</Button>
</div>
</template>
</NewModal>
</template>
<script setup lang="ts">
import { CheckIcon, PlusIcon, SearchIcon, SpinnerIcon, XIcon } from '@modrinth/assets'
import { Button, defineMessages, NewModal, StyledInput, TagItem, useVIntl } from '@modrinth/ui'
import { computed, ref } from 'vue'
import InstanceIcon from '@/components/ui/InstanceIcon.vue'
import { FAVORITES_GROUP_ID } from '@/composables/useInstanceGroups'
import { list } from '@/helpers/instance'
import { create_group, list_groups, set_group_memberships } from '@/helpers/instance-groups'
import type { GameInstance } from '@/helpers/types'
const { formatMessage } = useVIntl()
const props = defineProps<{
instanceIds: string[]
existingGroupName?: string
existingGroupId?: string
}>()
const emit = defineEmits<{
(e: 'applied'): void
}>()
const messages = defineMessages({
header: {
id: 'app.instances.batch-edit-groups.header',
defaultMessage: 'Create group',
},
addToGroupTitle: {
id: 'app.instances.batch-edit-groups.add-to-group-title',
defaultMessage: 'Add instances to "{groupName}"',
},
groupName: {
id: 'app.instances.batch-edit-groups.group-name',
defaultMessage: 'Group name',
},
groupNamePlaceholder: {
id: 'app.instances.batch-edit-groups.group-name-placeholder',
defaultMessage: 'Enter group name',
},
searchInstance: {
id: 'app.instances.batch-edit-groups.search-instance',
defaultMessage: 'Search instances',
},
noInstancesFound: {
id: 'app.instances.batch-edit-groups.no-instances-found',
defaultMessage: 'No instances found',
},
add: {
id: 'app.instances.batch-edit-groups.add',
defaultMessage: 'Add',
},
added: {
id: 'app.instances.batch-edit-groups.added',
defaultMessage: 'Added',
},
cancel: {
id: 'app.instances.batch-edit-groups.cancel',
defaultMessage: 'Cancel',
},
createGroup: {
id: 'app.instances.batch-edit-groups.create',
defaultMessage: 'Create group',
},
pinnedGroupName: {
id: 'app.instances.group.pinned',
defaultMessage: 'Pinned',
},
saveChanges: {
id: 'app.instances.batch-edit-groups.save-changes',
defaultMessage: 'Save',
},
})
const modal = ref<InstanceType<typeof NewModal>>()
const groupNameInput = ref<InstanceType<typeof StyledInput>>()
const newGroupName = ref('')
const newGroupSearch = ref('')
const creatingGroup = ref(false)
const allInstances = ref<GameInstance[]>([])
const groupNameMap = ref(new Map<string, string>())
const selectedNewGroupInstanceIds = ref(new Set<string>())
const canCreateGroup = computed(() => newGroupName.value.trim().length > 0)
const canSaveGroups = computed(() => {
if (!props.existingGroupName) return false
const groupId = props.existingGroupId
if (!groupId) return false
return allInstances.value.some((instance) => {
const isSelected = selectedNewGroupInstanceIds.value.has(instance.id)
const hasGroup = (instance.groups || []).includes(groupId)
return isSelected !== hasGroup
})
})
const newGroupInstances = computed(() => {
const search = newGroupSearch.value.toLowerCase()
return allInstances.value.filter((instance) => {
if (!search) return true
return instance.name.toLowerCase().includes(search)
})
})
function getGroupName(groupId: string) {
if (groupId === FAVORITES_GROUP_ID) {
return formatMessage(messages.pinnedGroupName)
}
return groupNameMap.value.get(groupId) || groupId
}
function show(ids?: string[]) {
newGroupSearch.value = ''
creatingGroup.value = false
Promise.all([list(), list_groups()]).then(([instances, groups]) => {
allInstances.value = instances as GameInstance[]
const map = new Map<string, string>()
for (const g of groups) {
map.set(g.id, g.name)
}
groupNameMap.value = map
if (!props.existingGroupName) {
const customGroups = groups.filter((g: { id: string }) => g.id !== 'group:favorites')
let groupNumber = customGroups.length + 1
const existingNames = new Set(groups.map((g: { name: string }) => g.name.toLowerCase()))
while (existingNames.has(`group ${groupNumber}`)) {
groupNumber++
}
newGroupName.value = `Group ${groupNumber}`
}
if (props.existingGroupName) {
const groupId = props.existingGroupId
selectedNewGroupInstanceIds.value = new Set(
allInstances.value.filter((i) => (i.groups || []).includes(groupId || '')).map((i) => i.id),
)
} else {
selectedNewGroupInstanceIds.value = new Set(ids ?? props.instanceIds)
}
})
modal.value?.show()
}
function toggleNewGroupInstance(instanceId: string) {
const next = new Set(selectedNewGroupInstanceIds.value)
if (next.has(instanceId)) {
next.delete(instanceId)
} else {
next.add(instanceId)
}
selectedNewGroupInstanceIds.value = next
}
async function handleCreateGroup() {
const name = newGroupName.value.trim()
if (!name || selectedNewGroupInstanceIds.value.size === 0) return
creatingGroup.value = true
const group = await create_group(name).catch(() => null)
if (!group) {
creatingGroup.value = false
return
}
if (selectedNewGroupInstanceIds.value.size > 0) {
const updates = [...selectedNewGroupInstanceIds.value].map((instanceId) => ({
instance_id: instanceId,
group_ids: [group.id],
}))
await set_group_memberships(updates).catch(() => {})
}
creatingGroup.value = false
modal.value?.hide()
emit('applied')
}
async function handleSaveGroups() {
if (!props.existingGroupName) return
creatingGroup.value = true
const groupId = props.existingGroupId
const changedInstances = allInstances.value.filter((instance) => {
const isSelected = selectedNewGroupInstanceIds.value.has(instance.id)
const hasGroup = (instance.groups || []).includes(groupId || '')
return isSelected !== hasGroup
})
const updates = changedInstances.map((instance) => {
const isSelected = selectedNewGroupInstanceIds.value.has(instance.id)
return {
instance_id: instance.id,
group_ids: isSelected ? [groupId!] : [],
}
})
await set_group_memberships(updates).catch(() => {})
creatingGroup.value = false
modal.value?.hide()
emit('applied')
}
defineExpose({ show })
</script>
@@ -6,6 +6,8 @@ import { ref, watch } from 'vue'
import { get, set } from '@/helpers/settings.ts'
import CrashAnalysisAISettings from './CrashAnalysisAISettings.vue'
import LogShareSettings from './LogShareSettings.vue'
import SharedLogsSettings from './SharedLogsSettings.vue'
import SettingsRow from './SettingsRow.vue'
import SettingsSection from './SettingsSection.vue'
@@ -391,5 +393,7 @@ watch(
</SettingsSection>
<CrashAnalysisAISettings />
<LogShareSettings />
<SharedLogsSettings />
</div>
</template>
@@ -0,0 +1,231 @@
<script setup lang="ts">
import {
defineMessages,
type KeyBinding,
KeybindingChips,
KeybindingModal,
Toggle,
useVIntl,
} from '@modrinth/ui'
import { computed, ref } from 'vue'
import { getNavShortcutEnabled, setNavShortcutEnabled } from '@/helpers/nav-shortcut-state'
import { getQuickScrollEnabled, setQuickScrollEnabled } from '@/helpers/scroll-top-state'
import { NAV_ACTIONS, SCROLL_ACTIONS, type ShortcutAction } from '@/helpers/shortcut-actions'
import {
buildConflicts,
clearStoredBinding,
resolveAllBindings,
storeBinding,
} from '@/helpers/shortcut-bindings'
import { useTheming } from '@/store/theme'
import SettingsRow from './SettingsRow.vue'
import SettingsSection from './SettingsSection.vue'
const { formatMessage } = useVIntl()
const themeStore = useTheming()
themeStore.quickScrollEnabled = getQuickScrollEnabled()
themeStore.shortcutBindings = resolveAllBindings()
for (const action of NAV_ACTIONS) {
themeStore[action.enabledField] = getNavShortcutEnabled(action.id)
}
const messages = defineMessages({
scrollTitle: {
id: 'app.shortcut-settings.scroll-title',
defaultMessage: 'Quick scrolling',
},
scrollDescription: {
id: 'app.shortcut-settings.scroll-description',
defaultMessage: 'Move through long pages with the keyboard.',
},
enable: { id: 'app.shortcut-settings.enable', defaultMessage: 'Enable quick scrolling' },
navTitle: {
id: 'app.shortcut-settings.nav-title',
defaultMessage: 'Navigation shortcuts',
},
navDescription: {
id: 'app.shortcut-settings.nav-description',
defaultMessage: 'Jump to a menu item with its shortcut. Each shortcut is off until enabled.',
},
changeShortcut: {
id: 'app.shortcut-settings.change-shortcut',
defaultMessage: 'Change the shortcut for {action}',
},
})
function actionLabel(action: ShortcutAction) {
return formatMessage(action.label)
}
function actionDescription(action: ShortcutAction) {
return formatMessage(action.description)
}
function bindingFor(action: ShortcutAction): KeyBinding {
return themeStore.shortcutBindings[action.id] ?? action.defaultBinding
}
function sameBinding(left: KeyBinding, right: KeyBinding) {
return (
left.device === right.device &&
left.code === right.code &&
left.mod === right.mod &&
left.shift === right.shift &&
left.alt === right.alt
)
}
const editing = ref<ShortcutAction | null>(null)
const keybindingModal = ref<InstanceType<typeof KeybindingModal>>()
const editingLabel = computed(() => (editing.value ? actionLabel(editing.value) : undefined))
const editingBinding = computed(() => (editing.value ? bindingFor(editing.value) : null))
const editingDefault = computed(() => editing.value?.defaultBinding ?? null)
const editingConflicts = computed(() =>
editing.value
? buildConflicts(editing.value.id, (id) => {
const action = [...SCROLL_ACTIONS, ...NAV_ACTIONS].find((candidate) => candidate.id === id)
return action ? actionLabel(action) : id
})
: [],
)
function openShortcut(action: ShortcutAction) {
editing.value = action
keybindingModal.value?.show()
}
function saveShortcut(binding: KeyBinding) {
const action = editing.value
if (!action) return
// A combination matching the default is stored as "not changed", so a later
// change to the default still reaches this shortcut.
if (sameBinding(binding, action.defaultBinding)) clearStoredBinding(action.id)
else storeBinding(action.id, binding)
themeStore.shortcutBindings = { ...themeStore.shortcutBindings, [action.id]: binding }
}
function toggleQuickScroll(value: unknown) {
themeStore.quickScrollEnabled = !!value
setQuickScrollEnabled(themeStore.quickScrollEnabled)
}
function toggleNavShortcut(action: ShortcutAction, value: unknown) {
themeStore[action.enabledField] = !!value
setNavShortcutEnabled(action.id, !!value)
}
</script>
<template>
<div class="flex flex-col gap-6">
<SettingsSection>
<template #header>
<h2 class="m-0 text-lg font-semibold text-[var(--color-text-primary)]">
{{ formatMessage(messages.scrollTitle) }}
</h2>
<p class="m-0 mt-1 text-sm leading-relaxed text-[var(--color-text-tertiary)]">
{{ formatMessage(messages.scrollDescription) }}
</p>
</template>
<SettingsRow>
<template #label>
<span id="settings-target-shortcuts-enable" tabindex="-1">
{{ formatMessage(messages.enable) }}
</span>
</template>
<template #control>
<Toggle
id="quick-scroll-enabled"
:model-value="themeStore.quickScrollEnabled"
@update:model-value="toggleQuickScroll"
/>
</template>
</SettingsRow>
<SettingsRow v-for="action in SCROLL_ACTIONS" :key="action.id">
<template #label>
<span :id="`settings-target-${action.id}`" tabindex="-1">{{ actionLabel(action) }}</span>
</template>
<template #description>{{ actionDescription(action) }}</template>
<template #control>
<button
type="button"
class="keybinding-trigger"
:aria-label="formatMessage(messages.changeShortcut, { action: actionLabel(action) })"
@click="openShortcut(action)"
>
<KeybindingChips :binding="bindingFor(action)" />
</button>
</template>
</SettingsRow>
</SettingsSection>
<SettingsSection>
<template #header>
<h2
id="settings-target-shortcuts-nav"
tabindex="-1"
class="m-0 text-lg font-semibold text-[var(--color-text-primary)]"
>
{{ formatMessage(messages.navTitle) }}
</h2>
<p class="m-0 mt-1 text-sm leading-relaxed text-[var(--color-text-tertiary)]">
{{ formatMessage(messages.navDescription) }}
</p>
</template>
<SettingsRow v-for="action in NAV_ACTIONS" :key="action.id">
<template #label>{{ actionLabel(action) }}</template>
<template #description>{{ actionDescription(action) }}</template>
<template #control>
<div class="flex flex-wrap items-center justify-end gap-3">
<button
type="button"
class="keybinding-trigger"
:aria-label="formatMessage(messages.changeShortcut, { action: actionLabel(action) })"
@click="openShortcut(action)"
>
<KeybindingChips :binding="bindingFor(action)" />
</button>
<Toggle
:id="`nav-shortcut-${action.id}`"
:model-value="themeStore[action.enabledField]"
@update:model-value="(value) => toggleNavShortcut(action, value)"
/>
</div>
</template>
</SettingsRow>
</SettingsSection>
<KeybindingModal
ref="keybindingModal"
:action-label="editingLabel"
:binding="editingBinding"
:default-binding="editingDefault"
:conflicts="editingConflicts"
@save="saveShortcut"
/>
</div>
</template>
<style scoped>
.keybinding-trigger {
cursor: pointer;
border-radius: var(--radius-md);
border: 1px solid transparent;
background: transparent;
padding: 0.25rem 0.375rem;
transition:
background-color 0.15s ease,
border-color 0.15s ease;
}
.keybinding-trigger:hover,
.keybinding-trigger:focus-visible {
border-color: var(--surface-4);
background: var(--surface-3);
}
</style>
@@ -0,0 +1,192 @@
<script setup lang="ts">
import { DownloadIcon, FolderOpenIcon, XIcon } from '@modrinth/assets'
import {
Button,
Checkbox,
Combobox,
commonMessages,
defineMessages,
injectNotificationManager,
injectPopupNotificationManager,
NewModal,
useVIntl,
} from '@modrinth/ui'
import { computed, ref } from 'vue'
import { exportLauncherLogs, highlightInFolder } from '@/helpers/utils'
const { formatMessage } = useVIntl()
const { handleError } = injectNotificationManager()
const popupNotificationManager = injectPopupNotificationManager()
const modal = ref<InstanceType<typeof NewModal>>()
const exporting = ref(false)
const selectedRange = ref<'last30Minutes' | 'last2Hours' | 'all'>('last2Hours')
const selectedLevel = ref<'all' | 'debug' | 'info'>('all')
const includeSystemInfo = ref(true)
const includeInstanceLogs = ref(false)
const includeCrashAnalysis = ref(false)
const messages = defineMessages({
title: { id: 'app.settings.logs.export.modal.title', defaultMessage: 'Export logs' },
description: {
id: 'app.settings.logs.export.modal.description',
defaultMessage:
'Choose how much detail to include. Exported logs have access tokens, Minecraft tokens, and IP addresses replaced with placeholders.',
},
rangeLabel: { id: 'app.settings.logs.export.modal.range', defaultMessage: 'Time range' },
rangeLast30Minutes: {
id: 'app.settings.logs.export.modal.range.30-minutes',
defaultMessage: 'Last 30 minutes',
},
rangeLast2Hours: {
id: 'app.settings.logs.export.modal.range.2-hours',
defaultMessage: 'Last 2 hours',
},
rangeAll: { id: 'app.settings.logs.export.modal.range.all', defaultMessage: 'All sessions' },
levelLabel: { id: 'app.settings.logs.export.modal.level', defaultMessage: 'Log level' },
levelAll: { id: 'app.settings.logs.export.modal.level.all', defaultMessage: 'All levels' },
levelDebug: {
id: 'app.settings.logs.export.modal.level.debug',
defaultMessage: 'Debug and above',
},
levelInfo: { id: 'app.settings.logs.export.modal.level.info', defaultMessage: 'Info and above' },
extrasLabel: {
id: 'app.settings.logs.export.modal.extras',
defaultMessage: 'Additional information',
},
systemInfo: {
id: 'app.settings.logs.export.modal.system-info',
defaultMessage: 'System and environment summary',
},
instanceLogs: {
id: 'app.settings.logs.export.modal.instance-logs',
defaultMessage: 'Most recent instance log',
},
crashAnalysis: {
id: 'app.settings.logs.export.modal.crash-analysis',
defaultMessage: 'Crash analysis (when a crash is detected)',
},
cancel: { id: 'app.settings.logs.export.modal.cancel', defaultMessage: 'Cancel' },
confirm: { id: 'app.settings.logs.export.modal.confirm', defaultMessage: 'Export' },
exportedTitle: {
id: 'app.settings.logs.export.notification-title',
defaultMessage: 'Logs exported',
},
exportedText: {
id: 'app.settings.logs.export.notification-text',
defaultMessage: 'The log archive was saved to {path}',
},
})
const rangeOptions = computed(() => [
{ value: 'last30Minutes', label: formatMessage(messages.rangeLast30Minutes) },
{ value: 'last2Hours', label: formatMessage(messages.rangeLast2Hours) },
{ value: 'all', label: formatMessage(messages.rangeAll) },
])
const levelOptions = computed(() => [
{ value: 'all', label: formatMessage(messages.levelAll) },
{ value: 'debug', label: formatMessage(messages.levelDebug) },
{ value: 'info', label: formatMessage(messages.levelInfo) },
])
async function exportLogs() {
exporting.value = true
try {
const path = await exportLauncherLogs({
range: selectedRange.value,
level: selectedLevel.value,
includeSystemInfo: includeSystemInfo.value,
includeInstanceLogs: includeInstanceLogs.value,
includeCrashAnalysis: includeCrashAnalysis.value,
})
if (path) {
modal.value?.hide()
popupNotificationManager.addPopupNotification({
title: formatMessage(messages.exportedTitle),
text: formatMessage(messages.exportedText, { path }),
type: 'success',
buttons: [
{
label: formatMessage(commonMessages.openInFolderButton),
icon: FolderOpenIcon,
action: () => highlightInFolder(path).catch(handleError),
},
],
})
}
} catch (error) {
handleError(error)
} finally {
exporting.value = false
}
}
defineExpose({
show: () => modal.value?.show(),
hide: () => modal.value?.hide(),
})
</script>
<template>
<NewModal
ref="modal"
:header="formatMessage(messages.title)"
:closable="true"
:close-on-click-outside="true"
width="40rem"
scrollable
>
<div class="flex flex-col gap-4">
<p class="m-0">{{ formatMessage(messages.description) }}</p>
<div class="flex flex-col gap-2">
<span class="font-semibold text-[var(--color-text-primary)]">{{
formatMessage(messages.rangeLabel)
}}</span>
<Combobox
id="log-export-range"
v-model="selectedRange"
:name="formatMessage(messages.rangeLabel)"
:options="rangeOptions"
/>
</div>
<div class="flex flex-col gap-2">
<span class="font-semibold text-[var(--color-text-primary)]">{{
formatMessage(messages.levelLabel)
}}</span>
<Combobox
id="log-export-level"
v-model="selectedLevel"
:name="formatMessage(messages.levelLabel)"
:options="levelOptions"
/>
</div>
<div class="flex flex-col gap-2">
<span class="font-semibold text-[var(--color-text-primary)]">{{
formatMessage(messages.extrasLabel)
}}</span>
<Checkbox v-model="includeSystemInfo" :label="formatMessage(messages.systemInfo)" />
<Checkbox v-model="includeInstanceLogs" :label="formatMessage(messages.instanceLogs)" />
<Checkbox v-model="includeCrashAnalysis" :label="formatMessage(messages.crashAnalysis)" />
</div>
</div>
<template #actions>
<div class="flex justify-end gap-2">
<Button type="outlined" :disabled="exporting" @click="modal?.hide()"
><XIcon />
{{ formatMessage(messages.cancel) }}
</Button>
<Button type="colored" color="brand" :disabled="exporting" @click="exportLogs"
><DownloadIcon />
{{ formatMessage(messages.confirm) }}
</Button>
</div>
</template>
</NewModal>
</template>
@@ -0,0 +1,354 @@
<script setup lang="ts">
import { Combobox, defineMessages, injectNotificationManager, Toggle, useVIntl } from '@modrinth/ui'
import { computed, onMounted, ref } from 'vue'
import { type AIState, getAIState, sharedAIState } from '@/helpers/ai'
import {
get_crash_analysis_ai_settings,
get_log_share_settings,
update_crash_analysis_ai_settings,
update_log_share_settings,
} from '@/helpers/logs'
import SettingsRow from './SettingsRow.vue'
import SettingsSection from './SettingsSection.vue'
type CrashAISettings = {
enabled: boolean
provider_id: string
model_id: string
ai_source: 'logshare' | 'custom'
}
type LogShareSettings = {
share_provider: 'logshare' | 'mclogs'
ai_source: string
auto_upload: boolean
multi_file: boolean
no_storage: boolean
show_progress: boolean
}
const { formatMessage } = useVIntl()
const { handleError } = injectNotificationManager()
const settings = ref<LogShareSettings>({
share_provider: 'logshare',
ai_source: 'logshare',
auto_upload: true,
multi_file: true,
no_storage: false,
show_progress: true,
})
const aiSettings = ref<CrashAISettings>({
enabled: false,
provider_id: '',
model_id: '',
ai_source: 'logshare',
})
const loading = ref(true)
const saving = ref(false)
const messages = defineMessages({
title: { id: 'app.log-share.settings.title', defaultMessage: 'Log sharing & AI analysis' },
description: {
id: 'app.log-share.settings.description',
defaultMessage:
'Share crash diagnostics with LogShare for a structured summary and optional AI analysis. LogShare is preferred; mclo.gs is used as a fallback.',
},
shareProvider: {
id: 'app.log-share.settings.share-provider',
defaultMessage: 'Log sharing service',
},
shareProviderDescription: {
id: 'app.log-share.settings.share-provider-description',
defaultMessage: 'Where the diagnostic link is uploaded when you share it.',
},
aiSource: { id: 'app.log-share.settings.ai-source', defaultMessage: 'AI analysis source' },
aiSourceLogShare: {
id: 'app.log-share.settings.ai-source-logshare',
defaultMessage: 'LogShare AI',
},
aiSourceCustom: {
id: 'app.log-share.settings.ai-source-custom',
defaultMessage: 'Custom AI provider',
},
aiSourceDescription: {
id: 'app.log-share.settings.ai-source-description',
defaultMessage:
'Both sources send a sanitized and shortened crash context. AI output may be inaccurate.',
},
enabled: {
id: 'app.crash-analysis.ai.settings.enabled',
defaultMessage: 'Enable AI explanations',
},
enabledDescription: {
id: 'app.crash-analysis.ai.settings.enabled-description',
defaultMessage: 'Local rule-based crash analysis remains available without AI.',
},
provider: { id: 'app.crash-analysis.ai.settings.provider', defaultMessage: 'AI provider' },
model: { id: 'app.crash-analysis.ai.settings.model', defaultMessage: 'Text model' },
noProviders: {
id: 'app.crash-analysis.ai.settings.no-providers',
defaultMessage: 'Enable a provider and a text model above before using AI crash explanations.',
},
autoUpload: {
id: 'app.log-share.settings.auto-upload',
defaultMessage: 'Upload to get a structured summary automatically',
},
autoUploadDescription: {
id: 'app.log-share.settings.auto-upload-description',
defaultMessage: 'Only effective in LogShare AI mode.',
},
multiFile: { id: 'app.log-share.settings.multi-file', defaultMessage: 'Multi-file upload' },
multiFileDescription: {
id: 'app.log-share.settings.multi-file-description',
defaultMessage: 'Upload latest.log, crash reports, hs_err and launcher logs together.',
},
noStorage: {
id: 'app.log-share.settings.no-storage',
defaultMessage: 'Analyze without storing logs',
},
noStorageDescription: {
id: 'app.log-share.settings.no-storage-description',
defaultMessage:
'Submit content directly for analysis and skip the stored upload. Disables the automatic summary.',
},
showProgress: {
id: 'app.log-share.settings.show-progress',
defaultMessage: 'Show AI analysis progress',
},
showProgressDescription: {
id: 'app.log-share.settings.show-progress-description',
defaultMessage: 'Display thinking, tool and limit status while LogShare AI is working.',
},
})
const emptyState: AIState = { settings: { enabled: false }, catalog_source: '', providers: [] }
const aiState = computed(() => sharedAIState.value ?? emptyState)
const providers = computed(() =>
aiState.value.providers.filter(
(provider) => provider.enabled && provider.models.some((model) => model.enabled),
),
)
const providerOptions = computed(() =>
providers.value.map((provider) => ({
value: provider.provider_id,
label: provider.custom_name || provider.provider_id,
})),
)
const modelOptions = computed(
() =>
providers.value
.find((provider) => provider.provider_id === aiSettings.value.provider_id)
?.models.filter((model) => model.enabled)
.map((model) => ({ value: model.id, label: model.name || model.id })) ?? [],
)
const isCustom = computed(() => aiSettings.value.ai_source === 'custom')
const noStorageEnabled = computed(() => aiSettings.value.ai_source === 'logshare')
const shareProviderOptions = [
{ value: 'logshare', label: 'LogShare' },
{ value: 'mclogs', label: 'mclo.gs' },
]
const aiSourceOptions = [
{ value: 'logshare', label: formatMessage(messages.aiSourceLogShare) },
{ value: 'custom', label: formatMessage(messages.aiSourceCustom) },
]
async function saveShare(next: LogShareSettings): Promise<void> {
saving.value = true
try {
await update_log_share_settings(next)
settings.value = next
} catch (error) {
handleError(error)
} finally {
saving.value = false
}
}
async function saveAI(next: CrashAISettings): Promise<void> {
saving.value = true
try {
await update_crash_analysis_ai_settings(next)
aiSettings.value = next
settings.value = { ...settings.value, ai_source: next.ai_source }
} catch (error) {
handleError(error)
} finally {
saving.value = false
}
}
function updateShare(patch: Partial<LogShareSettings>): void {
void saveShare({ ...settings.value, ...patch })
}
function selectShareProvider(value: unknown): void {
const provider = value === 'mclogs' ? 'mclogs' : 'logshare'
updateShare({ share_provider: provider, ai_source: aiSettings.value.ai_source })
}
function selectAiSource(value: unknown): void {
const source = value === 'custom' ? 'custom' : 'logshare'
void saveAI({ ...aiSettings.value, ai_source: source })
}
function updateEnabled(enabled: boolean): void {
void saveAI({ ...aiSettings.value, enabled })
}
function updateProvider(providerId: string): void {
const provider = providers.value.find((item) => item.provider_id === providerId)
const modelId = provider?.models.find((model) => model.enabled)?.id ?? ''
void saveAI({ ...aiSettings.value, provider_id: providerId, model_id: modelId })
}
function updateModel(modelId: string): void {
void saveAI({ ...aiSettings.value, model_id: modelId })
}
onMounted(async () => {
try {
const [nextShare, nextAI] = await Promise.all([
get_log_share_settings(),
get_crash_analysis_ai_settings(),
getAIState(),
])
settings.value = { ...nextShare, ai_source: nextAI.ai_source }
aiSettings.value = nextAI
} catch (error) {
handleError(error)
} finally {
loading.value = false
}
})
</script>
<template>
<SettingsSection
v-if="!loading"
id="settings-target-log-share"
:title="formatMessage(messages.title)"
:description="formatMessage(messages.description)"
>
<SettingsRow>
<template #label>{{ formatMessage(messages.shareProvider) }}</template>
<template #description>{{ formatMessage(messages.shareProviderDescription) }}</template>
<template #control>
<Combobox
id="log-share-provider"
:model-value="settings.share_provider"
:options="shareProviderOptions"
:disabled="saving"
@update:model-value="selectShareProvider($event)"
/>
</template>
</SettingsRow>
<SettingsRow>
<template #label>{{ formatMessage(messages.aiSource) }}</template>
<template #description>{{ formatMessage(messages.aiSourceDescription) }}</template>
<template #control>
<Combobox
id="log-share-ai-source"
:model-value="aiSettings.ai_source"
:options="aiSourceOptions"
:disabled="saving"
@update:model-value="selectAiSource($event)"
/>
</template>
</SettingsRow>
<template v-if="isCustom">
<SettingsRow>
<template #label>{{ formatMessage(messages.enabled) }}</template>
<template #description>{{ formatMessage(messages.enabledDescription) }}</template>
<template #control>
<Toggle
id="crash-analysis-ai-enabled"
:model-value="aiSettings.enabled"
:disabled="saving || !aiState.settings.enabled || !providers.length"
@update:model-value="updateEnabled(!!$event)"
/>
</template>
</SettingsRow>
<template v-if="providers.length">
<SettingsRow>
<template #label>{{ formatMessage(messages.provider) }}</template>
<template #control>
<Combobox
id="crash-analysis-ai-provider"
:model-value="aiSettings.provider_id"
:options="providerOptions"
:disabled="saving"
@update:model-value="updateProvider(String($event))"
/>
</template>
</SettingsRow>
<SettingsRow>
<template #label>{{ formatMessage(messages.model) }}</template>
<template #control>
<Combobox
id="crash-analysis-ai-model"
:model-value="aiSettings.model_id"
:options="modelOptions"
:disabled="saving || !aiSettings.provider_id"
@update:model-value="updateModel(String($event))"
/>
</template>
</SettingsRow>
</template>
<p v-else class="m-0 p-4 text-sm text-[var(--color-text-tertiary)]">
{{ formatMessage(messages.noProviders) }}
</p>
</template>
<SettingsRow>
<template #label>{{ formatMessage(messages.autoUpload) }}</template>
<template #description>{{ formatMessage(messages.autoUploadDescription) }}</template>
<template #control>
<Toggle
id="log-share-auto-upload"
:model-value="settings.auto_upload"
:disabled="saving || !noStorageEnabled || settings.no_storage"
@update:model-value="updateShare({ auto_upload: !!$event })"
/>
</template>
</SettingsRow>
<SettingsRow>
<template #label>{{ formatMessage(messages.multiFile) }}</template>
<template #description>{{ formatMessage(messages.multiFileDescription) }}</template>
<template #control>
<Toggle
id="log-share-multi-file"
:model-value="settings.multi_file"
:disabled="saving"
@update:model-value="updateShare({ multi_file: !!$event })"
/>
</template>
</SettingsRow>
<SettingsRow>
<template #label>{{ formatMessage(messages.noStorage) }}</template>
<template #description>{{ formatMessage(messages.noStorageDescription) }}</template>
<template #control>
<Toggle
id="log-share-no-storage"
:model-value="settings.no_storage"
:disabled="saving || !noStorageEnabled"
@update:model-value="updateShare({ no_storage: !!$event })"
/>
</template>
</SettingsRow>
<SettingsRow>
<template #label>{{ formatMessage(messages.showProgress) }}</template>
<template #description>{{ formatMessage(messages.showProgressDescription) }}</template>
<template #control>
<Toggle
id="log-share-show-progress"
:model-value="settings.show_progress"
:disabled="saving"
@update:model-value="updateShare({ show_progress: !!$event })"
/>
</template>
</SettingsRow>
</SettingsSection>
</template>
@@ -0,0 +1,66 @@
<script setup lang="ts">
import { FolderOpenIcon, UploadIcon } from '@modrinth/assets'
import { Button, defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
import { ref } from 'vue'
import { showLauncherLogsFolder } from '@/helpers/utils'
import LogExportModal from './LogExportModal.vue'
import SettingsRow from './SettingsRow.vue'
import SettingsSection from './SettingsSection.vue'
const { formatMessage } = useVIntl()
const { handleError } = injectNotificationManager()
const exportModal = ref<InstanceType<typeof LogExportModal>>()
const messages = defineMessages({
exportTitle: { id: 'app.settings.logs.export.title', defaultMessage: 'Export logs' },
exportDescription: {
id: 'app.settings.logs.export.description',
defaultMessage:
'Package launcher logs with an optional environment summary, instance log, and crash analysis.',
},
exportButton: { id: 'app.settings.logs.export.button', defaultMessage: 'Export logs…' },
openFolder: { id: 'app.settings.logs.open-folder', defaultMessage: 'Open logs folder' },
})
async function openLogsFolder() {
try {
await showLauncherLogsFolder()
} catch (error) {
handleError(error)
}
}
</script>
<template>
<div class="flex flex-col gap-6">
<SettingsSection
:title="formatMessage(messages.exportTitle)"
:description="formatMessage(messages.exportDescription)"
title-id="settings-target-logs-export"
>
<SettingsRow stacked>
<template #label>
<span>{{ formatMessage(messages.exportTitle) }}</span>
</template>
<template #description>{{ formatMessage(messages.exportDescription) }}</template>
<template #control>
<div class="flex flex-wrap gap-2">
<Button type="colored" color="brand" @click="exportModal?.show()"
><UploadIcon />
{{ formatMessage(messages.exportButton) }}
</Button>
<Button @click="openLogsFolder"
><FolderOpenIcon />
{{ formatMessage(messages.openFolder) }}
</Button>
</div>
</template>
</SettingsRow>
</SettingsSection>
<LogExportModal ref="exportModal" />
</div>
</template>
@@ -0,0 +1,129 @@
<script setup lang="ts">
import { Button, defineMessages, injectNotificationManager, useVIntl } from '@modrinth/ui'
import { onMounted, ref } from 'vue'
import { delete_shared_log, list_shared_logs } from '@/helpers/logs'
import SettingsRow from './SettingsRow.vue'
import SettingsSection from './SettingsSection.vue'
type SharedLog = {
id: string
url: string
raw: string
token: string
provider: string
instance_id: string | null
instance_name: string | null
truncated: boolean
created_at: number
}
const { formatMessage } = useVIntl()
const { addNotification, handleError } = injectNotificationManager()
const logs = ref<SharedLog[]>([])
const loading = ref(true)
const deletingId = ref<string | null>(null)
const messages = defineMessages({
title: { id: 'app.log-share.shared-logs.title', defaultMessage: 'Shared logs' },
description: {
id: 'app.log-share.shared-logs.description',
defaultMessage:
'Every diagnostic you have shared is listed here. Delete an entry to remove it from your history and request its removal from the sharing service.',
},
empty: { id: 'app.log-share.shared-logs.empty', defaultMessage: 'No shared logs yet.' },
delete: { id: 'app.log-share.shared-logs.delete', defaultMessage: 'Delete' },
deleting: { id: 'app.log-share.shared-logs.deleting', defaultMessage: 'Deleting…' },
deleted: {
id: 'app.log-share.shared-logs.deleted',
defaultMessage: 'Shared log removed.',
},
deleteFailed: {
id: 'app.log-share.shared-logs.delete-failed',
defaultMessage: 'Failed to delete the shared log.',
},
truncated: { id: 'app.log-share.shared-logs.truncated', defaultMessage: 'Truncated' },
})
async function refresh(): Promise<void> {
try {
logs.value = await list_shared_logs()
} catch (error) {
handleError(error)
} finally {
loading.value = false
}
}
async function remove(log: SharedLog): Promise<void> {
if (deletingId.value) return
deletingId.value = log.id
try {
await delete_shared_log(log.id, log.token)
logs.value = logs.value.filter((item) => item.id !== log.id)
addNotification({ title: formatMessage(messages.deleted), type: 'success' })
} catch (error) {
handleError(error)
addNotification({ title: formatMessage(messages.deleteFailed), type: 'error' })
} finally {
deletingId.value = null
}
}
function formatDate(timestamp: number): string {
return new Date(timestamp * 1000).toLocaleString()
}
onMounted(refresh)
</script>
<template>
<SettingsSection
id="settings-target-shared-logs"
:title="formatMessage(messages.title)"
:description="formatMessage(messages.description)"
>
<SettingsRow stacked>
<template #control>
<div class="flex w-full min-w-0 flex-col gap-2">
<p v-if="loading" class="m-0 p-2 text-sm text-[var(--color-text-tertiary)]">…</p>
<p v-else-if="!logs.length" class="m-0 p-2 text-sm text-[var(--color-text-tertiary)]">
{{ formatMessage(messages.empty) }}
</p>
<ul v-else class="m-0 flex max-h-72 list-none flex-col gap-1 overflow-y-auto p-2">
<li
v-for="log in logs"
:key="log.id"
class="flex items-center gap-3 rounded-lg bg-surface-2 px-3 py-2"
>
<a
:href="log.url || `https://logshare.cn/${log.id}`"
target="_blank"
rel="noopener noreferrer"
class="min-w-0 flex-1 truncate text-[var(--color-text-default)] underline"
>
{{ log.url || log.id }}
</a>
<span class="shrink-0 text-xs text-[var(--color-text-tertiary)]">
{{ log.provider }}
<template v-if="log.truncated">
· {{ formatMessage(messages.truncated) }}
</template>
<template v-if="log.instance_name"> · {{ log.instance_name }} </template>
· {{ formatDate(log.created_at) }}
</span>
<Button type="outlined" :disabled="deletingId === log.id" @click="remove(log)"
>{{
deletingId === log.id
? formatMessage(messages.deleting)
: formatMessage(messages.delete)
}}
</Button>
</li>
</ul>
</div>
</template>
</SettingsRow>
</SettingsSection>
</template>
@@ -3,6 +3,7 @@ import type { MessageDescriptor } from '@modrinth/ui'
export type SettingsCategoryId =
| 'interface'
| 'home-navigation'
| 'shortcut-settings'
| 'language-translation'
| 'ai'
| 'java-performance'
@@ -13,6 +14,7 @@ export type SettingsCategoryId =
| 'updates'
| 'about'
| 'feature-flags'
| 'logs'
export type SettingsGroupId = 'launcher' | 'game' | 'data-privacy' | 'support' | 'developer'
@@ -44,6 +46,15 @@ export const settingsCategoryDefinitions: SettingsCategoryDefinition[] = [
group: 'launcher',
onboardingId: 'settings-tab-home-navigation',
},
{
id: 'shortcut-settings',
name: {
id: 'app.settings.tabs.shortcut-settings',
defaultMessage: 'Keyboard shortcuts',
},
group: 'launcher',
onboardingId: 'settings-tab-shortcut-settings',
},
{
id: 'language-translation',
name: {
@@ -116,6 +127,11 @@ export const settingsCategoryDefinitions: SettingsCategoryDefinition[] = [
name: { id: 'app.settings.tabs.about', defaultMessage: 'About' },
group: 'support',
},
{
id: 'logs',
name: { id: 'app.settings.tabs.logs', defaultMessage: 'Logs' },
group: 'support',
},
{
id: 'feature-flags',
name: {
@@ -3,9 +3,11 @@ import {
BotIcon,
CoffeeIcon,
CpuIcon,
FileTextIcon,
GameIcon,
GaugeIcon,
InfoIcon,
KeyboardIcon,
LanguagesIcon,
LayoutTemplateIcon,
PaintbrushIcon,
@@ -48,6 +50,10 @@ const categoryContent: Record<SettingsCategoryId, Pick<SettingsCategory, 'icon'
icon: LayoutTemplateIcon,
content: defineAsyncComponent(() => import('./HomeNavigationSettings.vue')),
},
'shortcut-settings': {
icon: KeyboardIcon,
content: defineAsyncComponent(() => import('./KeybindSettings.vue')),
},
'language-translation': {
icon: LanguagesIcon,
content: defineAsyncComponent(() => import('./LanguageTranslationSettings.vue')),
@@ -78,6 +84,10 @@ const categoryContent: Record<SettingsCategoryId, Pick<SettingsCategory, 'icon'
content: defineAsyncComponent(() => import('./UpdateSettings.vue')),
},
about: { icon: InfoIcon, content: defineAsyncComponent(() => import('./AboutSettings.vue')) },
logs: {
icon: FileTextIcon,
content: defineAsyncComponent(() => import('./LogsSettings.vue')),
},
'feature-flags': {
icon: ToggleRightIcon,
content: defineAsyncComponent(() => import('./FeatureFlagSettings.vue')),
@@ -384,6 +384,16 @@ export const settingsSearchEntries: SettingsSearchEntry[] = [
categoryId: 'feature-flags',
label: message('settings.feature-flags.title', 'Feature flags'),
},
{
id: 'logs-export',
categoryId: 'logs',
targetId: 'settings-target-logs-export',
label: message('app.settings.logs.export.title', 'Export logs'),
description: message(
'app.settings.logs.export.description',
'Package launcher logs with an optional environment summary, instance log, and crash analysis.',
),
},
]
export function validateSettingsSearchEntries(entries = settingsSearchEntries): string[] {
@@ -7,15 +7,22 @@ export const UNGROUPED_GROUP_KEY = '__ungrouped__'
export type GridGroupingOption = 'Group' | 'Loader' | 'Game version' | 'None'
export type GridSortOption =
| 'Name'
| 'Last played'
| 'Date created'
| 'Date modified'
| 'Game version'
'Name' | 'Last played' | 'Date created' | 'Date modified' | 'Game version'
export type GridSortDirection = 'asc' | 'desc'
export const defaultSortDirections: Record<GridSortOption, GridSortDirection> = {
Name: 'asc',
'Last played': 'desc',
'Date created': 'desc',
'Date modified': 'desc',
'Game version': 'asc',
}
export interface GridDisplayState {
group: GridGroupingOption
sortBy: GridSortOption
sortDirections: Partial<Record<GridSortOption, GridSortDirection>>
collapsedGroups: string[]
}
@@ -38,6 +45,7 @@ export function useGridGrouping<T extends Record<string, unknown>>(
{
group: 'Group',
sortBy: 'Name',
sortDirections: {},
collapsedGroups: [],
},
localStorage,
@@ -66,7 +74,7 @@ export function useGridGrouping<T extends Record<string, unknown>>(
state.value.collapsedGroups = [...collapsedSections]
}
function sortInstances(instances: T[], sortBy: GridSortOption): T[] {
function sortInstances(instances: T[], sortBy: GridSortOption, ascending: boolean): T[] {
const sorted = [...instances]
const getGameVersion = options.getGameVersion ?? ((i: T) => i.game_version ?? '')
const getLastPlayed = options.getLastPlayed ?? ((i: T) => i.last_played ?? 0)
@@ -83,16 +91,19 @@ export function useGridGrouping<T extends Record<string, unknown>>(
)
break
case 'Last played':
sorted.sort((a, b) => dayjs(getLastPlayed(b)).diff(dayjs(getLastPlayed(a))))
sorted.sort((a, b) => dayjs(getLastPlayed(a)).diff(dayjs(getLastPlayed(b))))
break
case 'Date created':
sorted.sort((a, b) => dayjs(getDateCreated(b)).diff(dayjs(getDateCreated(a))))
sorted.sort((a, b) => dayjs(getDateCreated(a)).diff(dayjs(getDateCreated(b))))
break
case 'Date modified':
sorted.sort((a, b) => dayjs(getDateModified(b)).diff(dayjs(getDateModified(a))))
sorted.sort((a, b) => dayjs(getDateModified(a)).diff(dayjs(getDateModified(b))))
break
}
if (!ascending) {
sorted.reverse()
}
return sorted
}
@@ -148,11 +159,25 @@ export function useGridGrouping<T extends Record<string, unknown>>(
function sortSections(
instanceMap: Map<string, T[]>,
group: GridGroupingOption,
sortBy: GridSortOption,
): Map<string, T[]> {
if (group !== 'Group' && group !== 'Game version') {
return instanceMap
}
if (group === 'Group' && sortBy !== 'Name') {
if (instanceMap.has(UNGROUPED_GROUP_KEY) && instanceMap.size > 1) {
const ungroupedInstances = instanceMap.get(UNGROUPED_GROUP_KEY)!
instanceMap.delete(UNGROUPED_GROUP_KEY)
const newMap = new Map<string, T[]>([[UNGROUPED_GROUP_KEY, ungroupedInstances]])
for (const [key, instances] of instanceMap) {
newMap.set(key, instances)
}
return newMap
}
return instanceMap
}
const sortedEntries = [...instanceMap.entries()].sort((a, b) => {
if (group === 'Group') {
if (a[0] === UNGROUPED_GROUP_KEY && b[0] !== UNGROUPED_GROUP_KEY) return -1
@@ -166,12 +191,30 @@ export function useGridGrouping<T extends Record<string, unknown>>(
return instanceMap
}
const sortDirection = computed<GridSortDirection>(() => {
return (
state.value.sortDirections[state.value.sortBy] ?? defaultSortDirections[state.value.sortBy]
)
})
const isSortAscending = computed(() => sortDirection.value === 'asc')
const toggleSortDirection = () => {
const current = sortDirection.value
const next: GridSortDirection = current === 'asc' ? 'desc' : 'asc'
state.value.sortDirections = {
...state.value.sortDirections,
[state.value.sortBy]: next,
}
}
const filteredResults = computed(() => {
const { group = 'Group', sortBy = 'Name' } = state.value
const ascending = isSortAscending.value
const sorted = sortInstances(instances.value, sortBy)
const sorted = sortInstances(instances.value, sortBy, ascending)
const grouped = groupInstances(sorted, group)
return sortSections(grouped, group)
return sortSections(grouped, group, sortBy)
})
return {
@@ -180,6 +223,9 @@ export function useGridGrouping<T extends Record<string, unknown>>(
filteredResults,
isSectionCollapsed,
setSectionCollapsed,
sortDirection,
isSortAscending,
toggleSortDirection,
UNGROUPED_GROUP_KEY,
}
}
}
@@ -0,0 +1,182 @@
import { computed, type Ref, ref, watch } from 'vue'
import { instance_groups_listener } from '@/helpers/events'
import {
create_group,
delete_group,
type InstanceGroupDefinition,
type InstanceGroupMembershipUpdate,
list_groups,
MAX_INSTANCE_GROUP_NAME_LENGTH,
rename_group,
set_group_memberships,
set_group_order,
} from '@/helpers/instance-groups'
export const FAVORITES_GROUP_ID = 'group:favorites'
export const UNGROUPED_GROUP_ID = 'group:none'
export { MAX_INSTANCE_GROUP_NAME_LENGTH }
export { type InstanceGroupDefinition, type InstanceGroupMembershipUpdate }
export interface InstanceGroupWithMembership {
key: string
name: string
instances: string[]
}
export function useInstanceGroups(instances: Ref<{ id: string; groups: string[] }[]>) {
const libraryGroups = ref<InstanceGroupDefinition[]>([])
const libraryGroupsLoaded = ref(false)
async function fetchGroups() {
libraryGroups.value = await list_groups()
libraryGroupsLoaded.value = true
}
fetchGroups()
instance_groups_listener(() => {
fetchGroups()
})
const orderedLibraryGroupIds = ref<string[]>([])
watch(
libraryGroups,
(groups) => {
orderedLibraryGroupIds.value = groups.map((g) => g.id)
},
{ immediate: true },
)
const instanceGroups = computed(() => {
if (!libraryGroupsLoaded.value) {
return []
}
const instanceGroupMap = new Map<string, string[]>()
for (const instance of instances.value) {
const groups = instance.groups ?? []
for (const groupId of groups) {
if (!instanceGroupMap.has(groupId)) {
instanceGroupMap.set(groupId, [])
}
instanceGroupMap.get(groupId)!.push(instance.id)
}
}
const allGroupIds = new Set<string>()
const groupMap = new Map<string, string[]>()
for (const groupId of orderedLibraryGroupIds.value) {
allGroupIds.add(groupId)
groupMap.set(groupId, instanceGroupMap.get(groupId) ?? [])
}
const ungroupedIds: string[] = []
for (const instance of instances.value) {
const instanceGroups = instance.groups ?? []
const isInAnyGroup = instanceGroups.some((g) => allGroupIds.has(g))
if (!isInAnyGroup) {
ungroupedIds.push(instance.id)
}
}
if (ungroupedIds.length > 0) {
groupMap.set(UNGROUPED_GROUP_ID, ungroupedIds)
}
return [...groupMap.entries()].map(([key, instances]) => ({
key,
name:
key === UNGROUPED_GROUP_ID
? 'Ungrouped'
: (libraryGroups.value.find((g) => g.id === key)?.name ?? key),
instances,
}))
})
const creatingGroup = ref(false)
const reorderingGroups = ref(false)
async function createNewGroup(name: string): Promise<string | null> {
creatingGroup.value = true
try {
const group = await create_group(name)
libraryGroups.value = [...libraryGroups.value, group]
orderedLibraryGroupIds.value = [...orderedLibraryGroupIds.value, group.id]
return group.id
} finally {
creatingGroup.value = false
}
}
async function renameGroupById(id: string, newName: string): Promise<boolean> {
if (id === FAVORITES_GROUP_ID) return false
const result = await rename_group(id, newName)
const idx = libraryGroups.value.findIndex((g) => g.id === id)
if (idx !== -1) {
libraryGroups.value = [
...libraryGroups.value.slice(0, idx),
result,
...libraryGroups.value.slice(idx + 1),
]
}
return true
}
async function deleteGroupById(id: string): Promise<boolean> {
if (id === FAVORITES_GROUP_ID) return false
await delete_group(id)
libraryGroups.value = libraryGroups.value.filter((g) => g.id !== id)
orderedLibraryGroupIds.value = orderedLibraryGroupIds.value.filter((gid) => gid !== id)
return true
}
async function reorderGroups(groupIds: string[]): Promise<boolean> {
reorderingGroups.value = true
try {
await set_group_order(groupIds)
// Favorites is rendered separately from draggable sections. Keep it in
// the local order after a drag even though the backend accepts only the
// reorderable group ids; otherwise it appears again as an ordinary
// section until the next full group refresh.
orderedLibraryGroupIds.value = [
FAVORITES_GROUP_ID,
...groupIds.filter((id) => id !== FAVORITES_GROUP_ID),
]
return true
} finally {
reorderingGroups.value = false
}
}
async function setMemberships(updates: InstanceGroupMembershipUpdate[]): Promise<boolean> {
await set_group_memberships(updates)
return true
}
function groupNameById(id: string): string | undefined {
if (id === UNGROUPED_GROUP_ID) return 'Ungrouped'
return libraryGroups.value.find((g) => g.id === id)?.name
}
return {
libraryGroups,
libraryGroupsLoaded,
orderedLibraryGroupIds,
instanceGroups,
creatingGroup,
reorderingGroups,
createGroup: createNewGroup,
renameGroupById,
deleteGroupById,
reorderGroups,
setMemberships,
groupNameById,
}
}
@@ -0,0 +1,215 @@
import {
type KeyBinding,
bindingMatchesKeyboardEvent,
bindingMatchesMouseEvent,
bindingMatchesWheelEvent,
useModalStack,
} from '@modrinth/ui'
import { computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useNetworkStatus } from '@/composables/useNetworkStatus'
import {
SCROLL_ACTIONS,
SHORTCUT_ACTIONS,
type ShortcutAction,
} from '@/helpers/shortcut-actions'
import { resolveAllBindings } from '@/helpers/shortcut-bindings'
import { getNavShortcutEnabled } from '@/helpers/nav-shortcut-state'
import { getQuickScrollEnabled } from '@/helpers/scroll-top-state'
import { useTheming } from '@/store/theme'
/** Editing surfaces keep these keys for themselves. */
function isEditableTarget(target: EventTarget | null) {
return (
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
(target instanceof HTMLElement && target.isContentEditable)
)
}
function scrollsAtOwnLevel(element: Element) {
const { overflowY } = getComputedStyle(element)
return /(auto|scroll|overlay)/.test(overflowY) && element.scrollHeight > element.clientHeight
}
/** A container that scrolls the page itself rather than a widget on it. */
function isPageScroller(element: Element) {
return scrollsAtOwnLevel(element) && element.clientHeight >= window.innerHeight / 2
}
/** Nearest scrolling ancestor, whatever its size. */
function nearestScrollContainer(target: EventTarget | null) {
let element = target instanceof Element ? target : null
while (element) {
if (scrollsAtOwnLevel(element)) return element
element = element.parentElement
}
return null
}
/**
* The page's own scroller. Most pages scroll inside `.app-viewport`, but some
* screens (settings, consoles, studios) turn that element's scrolling off and
* host a full-height container inside it, so fall back to whatever fills the
* middle of the viewport.
*/
function resolvePageScroller() {
const viewport = document.querySelector<HTMLElement>('.app-viewport')
if (!viewport) return null
if (isPageScroller(viewport)) return viewport
const bounds = viewport.getBoundingClientRect()
let element: Element | null = document.elementFromPoint(
bounds.left + bounds.width / 2,
bounds.top + bounds.height / 2,
)
while (element) {
if (isPageScroller(element)) return element
element = element.parentElement
}
return viewport
}
export function setupKeyboardShortcuts() {
const themeStore = useTheming()
const { hasModal } = useModalStack()
const route = useRoute()
const router = useRouter()
const { offline } = useNetworkStatus()
themeStore.quickScrollEnabled = getQuickScrollEnabled()
for (const shortcut of SHORTCUT_ACTIONS) {
if (shortcut.group === 'nav') themeStore[shortcut.enabledField] = getNavShortcutEnabled(shortcut.id)
}
themeStore.shortcutBindings = resolveAllBindings()
/** The combination an action answers to now: recorded if there is one, default otherwise. */
function bindingFor(action: ShortcutAction): KeyBinding {
return themeStore.shortcutBindings[action.id] ?? action.defaultBinding
}
/** Whether an action is switched on and reachable in the current state. */
function shortcutIsAvailable(action: ShortcutAction): boolean {
if (!themeStore[action.enabledField]) return false
return !action.unavailable?.({
worldsTabEnabled: themeStore.featureFlags.worlds_tab,
offline: offline.value,
})
}
function findShortcut<E extends Event>(
event: E,
matches: (binding: KeyBinding, event: E) => boolean,
{ includeDisabled = false }: { includeDisabled?: boolean } = {},
): ShortcutAction | null {
if (hasModal.value) return null
if (isEditableTarget(event.target)) return null
for (const action of SHORTCUT_ACTIONS) {
if (!includeDisabled && !shortcutIsAvailable(action)) continue
if (matches(bindingFor(action), event)) return action
}
return null
}
/** Does what an action is for. Scrolling actions move the page's own scroller. */
function runShortcut(action: ShortcutAction, event: Event) {
if (action.target) {
router.push(action.target(route))
return
}
const focusedContainer = nearestScrollContainer(event.target)
if (focusedContainer && !isPageScroller(focusedContainer)) return
const scroller = resolvePageScroller()
if (!scroller) return
action.applyScroll?.(scroller)
}
function handleScrollShortcutKey(event: KeyboardEvent) {
if (event.isComposing) return
const match = findShortcut(event, bindingMatchesKeyboardEvent, { includeDisabled: true })
if (match?.group !== 'scroll') return
const focusedContainer = nearestScrollContainer(event.target)
if (focusedContainer && !isPageScroller(focusedContainer)) return
const scroller = resolvePageScroller()
if (!scroller) return
event.preventDefault()
if (!shortcutIsAvailable(match)) return
match.applyScroll?.(scroller)
}
function handleNavShortcutKey(event: KeyboardEvent) {
if (event.isComposing) return
const match = findShortcut(event, bindingMatchesKeyboardEvent)
if (match?.group !== 'nav') return
event.preventDefault()
runShortcut(match, event)
}
const hasPointerBindings = computed(() =>
SHORTCUT_ACTIONS.some((action) => bindingFor(action).device === 'mouse'),
)
function handleShortcutMouse(event: MouseEvent) {
if (!hasPointerBindings.value) return
const match = findShortcut(event, bindingMatchesMouseEvent)
if (!match) return
event.preventDefault()
event.stopPropagation()
runShortcut(match, event)
}
function handleShortcutWheel(event: WheelEvent) {
if (!hasPointerBindings.value) return
const match = findShortcut(event, bindingMatchesWheelEvent)
if (!match) return
event.preventDefault()
event.stopPropagation()
runShortcut(match, event)
}
function handleGlobalKeydown(event: KeyboardEvent) {
const key = event.key.toLowerCase()
const isFindShortcut = key === 'f' && (event.ctrlKey || event.metaKey)
const isBlockedDevtoolsShortcut = event.key === 'F12' && !themeStore.devMode
if (isFindShortcut || isBlockedDevtoolsShortcut) {
event.preventDefault()
event.stopPropagation()
}
handleScrollShortcutKey(event)
handleNavShortcutKey(event)
}
window.addEventListener('keydown', handleGlobalKeydown, true)
window.addEventListener('mousedown', handleShortcutMouse, true)
// Not passive: a bound wheel direction has to keep the page from scrolling.
window.addEventListener('wheel', handleShortcutWheel, { capture: true, passive: false })
onUnmounted(() => {
window.removeEventListener('keydown', handleGlobalKeydown, true)
window.removeEventListener('mousedown', handleShortcutMouse, true)
window.removeEventListener('wheel', handleShortcutWheel, { capture: true, passive: false })
})
return { bindingFor, shortcutIsAvailable, SCROLL_ACTIONS }
}
@@ -0,0 +1,75 @@
interface InstanceProperties {
loader: string
game_version: string
}
interface ProjectProperties extends InstanceProperties {
id: string
project_type: string
}
type AnalyticsEventMap = {
Launched: { version: string; dev: boolean; onboarded: boolean }
PageView: { path: string; fromPath: string; failed: unknown }
InstanceCreate: { source: string }
InstanceCreateStart: { source: string }
InstanceStart: InstanceProperties & { source: string }
InstanceStop: Partial<InstanceProperties> & { source?: string }
InstanceDuplicate: InstanceProperties
InstanceRepair: InstanceProperties
InstanceSetIcon: Record<string, never>
InstanceRemoveIcon: Record<string, never>
InstanceUpdateAll: InstanceProperties & { count: number; selected: boolean }
InstanceProjectUpdate: InstanceProperties & { id: string; name: string; project_type: string }
InstanceProjectDisable: InstanceProperties & {
id: string
name: string
project_type: string
disabled: boolean
}
InstanceProjectRemove: InstanceProperties & { id: string; name: string; project_type: string }
ProjectInstall: ProjectProperties & { version_id: string; title: string; source: string }
ProjectInstallStart: { source: string }
PackInstall: { id: string; version_id: string; title: string; source: string }
PackInstallStart: Record<string, never>
AccountLogIn: { source?: string }
AccountLogOut: Record<string, never>
JavaTest: { path: string; success: boolean }
JavaManualSelect: { version: string }
JavaAutoDetect: { path: string; version: string }
GalleryImageNext: { project_id: string; url: string }
GalleryImagePrevious: { project_id: string; url: unknown }
GalleryImageExpand: { project_id: string; url: string }
}
export type AnalyticsEvent = keyof AnalyticsEventMap
let optedIn = false
let debugEnabled = false
export const initAnalytics = () => {
optedIn = true
}
export const debugAnalytics = () => {
debugEnabled = true
}
export const optOutAnalytics = () => {
optedIn = false
}
export const optInAnalytics = () => {
optedIn = true
}
type OptionalArgs<T> = Record<string, never> extends T ? [properties?: T] : [properties: T]
export const trackEvent = <E extends AnalyticsEvent>(
eventName: E,
...args: OptionalArgs<AnalyticsEventMap[E]>
) => {
if (optedIn && debugEnabled) {
console.debug('[Starlight telemetry disabled]', eventName, args[0])
}
}
+14
View File
@@ -82,6 +82,16 @@ export async function instance_bulk_update_progress_listener(callback) {
return await listen('instance_bulk_update_progress', (event) => callback(event.payload))
}
/// Payload for the 'instance_groups_changed' event
/*
InstanceGroupsChangedPayload {
instance_ids: string[]
}
*/
export async function instance_groups_listener(callback) {
return await listen('instance_groups_changed', (event) => callback(event.payload))
}
export async function install_job_listener(callback) {
return await listen('install_job', (event) => callback(event.payload))
}
@@ -150,6 +160,10 @@ export async function notification_listener(callback) {
return await listen('notification', (event) => callback(event.payload))
}
export async function logshare_ai_listener(callback) {
return await listen('logshare_ai', (event) => callback(event.payload))
}
/// Payload for the 'log' event
/*
LogPayload {
@@ -1 +1,46 @@
export const MAX_INSTANCE_GROUP_NAME_LENGTH = 256
import { invoke } from '@tauri-apps/api/core'
export const MAX_INSTANCE_GROUP_NAME_LENGTH = 256
export type InstanceGroupDefinition = {
id: string
name: string
}
export type InstanceGroupMembershipUpdate = {
instance_id: string
group_ids: string[]
}
export async function list_groups(): Promise<InstanceGroupDefinition[]> {
return await invoke('plugin:instance|instance_list_groups')
}
export async function create_group(name: string): Promise<InstanceGroupDefinition> {
return await invoke('plugin:instance|instance_create_group', { name })
}
export async function rename_group(id: string, newName: string): Promise<InstanceGroupDefinition> {
return await invoke('plugin:instance|instance_rename_group', {
id,
newName,
})
}
export async function delete_group(id: string): Promise<void> {
return await invoke('plugin:instance|instance_delete_group', { id })
}
export async function set_group_order(group_ids: string[]): Promise<void> {
return await invoke('plugin:instance|instance_set_group_order', {
groupIds: group_ids,
})
}
export async function set_group_memberships(
updates: InstanceGroupMembershipUpdate[],
): Promise<void> {
return await invoke('plugin:instance|instance_set_group_memberships', {
updates,
})
}
+44
View File
@@ -95,6 +95,50 @@ export async function undo_added_mod(instanceId, filename, expectedHash) {
return await invoke('plugin:logs|logs_undo_added_mod', { instanceId, filename, expectedHash })
}
export async function get_log_share_settings() {
return await invoke('plugin:logs|logs_get_log_share_settings')
}
export async function update_log_share_settings(settings) {
return await invoke('plugin:logs|logs_update_log_share_settings', { settings })
}
export async function logshare_upload_crash(instanceId) {
return await invoke('plugin:logs|logs_logshare_upload_crash', { instanceId })
}
export async function logshare_get_insights(id) {
return await invoke('plugin:logs|logs_logshare_get_insights', { id })
}
export async function logshare_analyse_crash_direct(instanceId) {
return await invoke('plugin:logs|logs_logshare_analyse_crash_direct', { instanceId })
}
export async function logshare_ai_analyze_stored(instanceId, id) {
return await invoke('plugin:logs|logs_logshare_ai_analyze_stored', { instanceId, id })
}
export async function logshare_ai_analyze_direct(instanceId) {
return await invoke('plugin:logs|logs_logshare_ai_analyze_direct', { instanceId })
}
export async function logshare_delete(id, token) {
return await invoke('plugin:logs|logs_logshare_delete', { id, token })
}
export async function list_shared_logs() {
return await invoke('plugin:logs|logs_list_shared_logs')
}
export async function record_shared_log(log) {
return await invoke('plugin:logs|logs_record_shared_log', { log })
}
export async function delete_shared_log(id, token) {
return await invoke('plugin:logs|logs_delete_shared_log', { id, token })
}
/// Export the censored files and local analysis from an instance's latest run.
export async function export_crash_context(instanceId, instanceName) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
@@ -0,0 +1,14 @@
const NAV_SHORTCUT_STORAGE_PREFIX = 'starlight-shortcut-nav-'
/**
* Whether a navigation shortcut is enabled. Shortcuts are off by default;
* each one is turned on individually from the Shortcut settings page.
*/
export function getNavShortcutEnabled(id: string): boolean {
const value = localStorage.getItem(NAV_SHORTCUT_STORAGE_PREFIX + id)
return value === 'true'
}
export function setNavShortcutEnabled(id: string, enabled: boolean) {
localStorage.setItem(NAV_SHORTCUT_STORAGE_PREFIX + id, String(enabled))
}
@@ -0,0 +1,20 @@
const SHOW_SCROLL_TOP_STORAGE_KEY = 'starlight-show-scroll-top'
const QUICK_SCROLL_ENABLED_STORAGE_KEY = 'starlight-quick-scroll-enabled'
export function getShowScrollTop(): boolean {
const value = localStorage.getItem(SHOW_SCROLL_TOP_STORAGE_KEY)
return value !== 'false'
}
export function setShowScrollTop(show: boolean) {
localStorage.setItem(SHOW_SCROLL_TOP_STORAGE_KEY, String(show))
}
export function getQuickScrollEnabled(): boolean {
const value = localStorage.getItem(QUICK_SCROLL_ENABLED_STORAGE_KEY)
return value === 'true'
}
export function setQuickScrollEnabled(enabled: boolean) {
localStorage.setItem(QUICK_SCROLL_ENABLED_STORAGE_KEY, String(enabled))
}
@@ -0,0 +1,309 @@
import { defineMessages, type KeyBinding, type MessageDescriptor } from '@modrinth/ui'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { getLastBrowseContentProjectType, isBrowseContentProjectType } from '@/helpers/settings'
/** Which half of the settings page an action belongs to. */
export type ShortcutGroupId = 'scroll' | 'nav'
/** Theme store fields that switch an action on. */
export type ShortcutEnabledField =
| 'quickScrollEnabled'
| 'shortcutNavHome'
| 'shortcutNavWorlds'
| 'shortcutNavDiscover'
| 'shortcutNavSkins'
| 'shortcutNavMultiplayer'
| 'shortcutNavLibrary'
| 'shortcutNavLab'
| 'shortcutNavDownloads'
| 'shortcutNavCreate'
| 'shortcutNavSettings'
export interface ShortcutContext {
worldsTabEnabled: boolean
offline: boolean
}
export interface ShortcutAction {
/** Stable id, used for the binding, the enable flag and the settings row. */
id: string
group: ShortcutGroupId
enabledField: ShortcutEnabledField
defaultBinding: KeyBinding
label: MessageDescriptor
description: MessageDescriptor
/** Navigation actions know where they lead. */
target?: (route: RouteLocationNormalizedLoaded) => string
/** Navigation actions that are not reachable right now. */
unavailable?: (context: ShortcutContext) => boolean
/** Scrolling actions move the page's own scroller. */
applyScroll?: (scroller: HTMLElement) => void
}
/**
* Declared here rather than assembled from the action ids, so the extractor can
* see them; an id built at runtime is one a translation pass would drop.
*/
const messages = defineMessages({
scrollTop: {
id: 'app.shortcut-settings.home-action',
defaultMessage: 'Scroll to the top',
},
scrollTopDescription: {
id: 'app.shortcut-settings.home-action-description',
defaultMessage: 'Moves the page you are reading to the top.',
},
scrollBottom: {
id: 'app.shortcut-settings.end-action',
defaultMessage: 'Scroll to the bottom',
},
scrollBottomDescription: {
id: 'app.shortcut-settings.end-action-description',
defaultMessage: 'Moves the page you are reading to the bottom.',
},
scrollUp: {
id: 'app.shortcut-settings.page-up-action',
defaultMessage: 'Scroll up one screen',
},
scrollUpDescription: {
id: 'app.shortcut-settings.page-up-action-description',
defaultMessage: 'Moves the page you are reading up by one screen.',
},
scrollDown: {
id: 'app.shortcut-settings.page-down-action',
defaultMessage: 'Scroll down one screen',
},
scrollDownDescription: {
id: 'app.shortcut-settings.page-down-action-description',
defaultMessage: 'Moves the page you are reading down by one screen.',
},
navHome: { id: 'app.shortcut-settings.nav-home', defaultMessage: 'Home' },
navHomeDescription: {
id: 'app.shortcut-settings.nav-home-description',
defaultMessage: 'Jump to the Home page.',
},
navWorlds: { id: 'app.shortcut-settings.nav-worlds', defaultMessage: 'Worlds' },
navWorldsDescription: {
id: 'app.shortcut-settings.nav-worlds-description',
defaultMessage: 'Jump to your worlds.',
},
navDiscover: {
id: 'app.shortcut-settings.nav-discover',
defaultMessage: 'Discover content',
},
navDiscoverDescription: {
id: 'app.shortcut-settings.nav-discover-description',
defaultMessage: 'Jump to browsing content.',
},
navSkins: { id: 'app.shortcut-settings.nav-skins', defaultMessage: 'Skin selector' },
navSkinsDescription: {
id: 'app.shortcut-settings.nav-skins-description',
defaultMessage: 'Jump to the skin selector.',
},
navMultiplayer: { id: 'app.shortcut-settings.nav-multiplayer', defaultMessage: 'Multiplayer' },
navMultiplayerDescription: {
id: 'app.shortcut-settings.nav-multiplayer-description',
defaultMessage: 'Jump to multiplayer.',
},
navLibrary: { id: 'app.shortcut-settings.nav-library', defaultMessage: 'Library' },
navLibraryDescription: {
id: 'app.shortcut-settings.nav-library-description',
defaultMessage: 'Jump to your library.',
},
navLab: { id: 'app.shortcut-settings.nav-lab', defaultMessage: 'Lab' },
navLabDescription: {
id: 'app.shortcut-settings.nav-lab-description',
defaultMessage: 'Jump to the Lab.',
},
navDownloads: { id: 'app.shortcut-settings.nav-downloads', defaultMessage: 'Downloads' },
navDownloadsDescription: {
id: 'app.shortcut-settings.nav-downloads-description',
defaultMessage: 'Jump to downloads.',
},
navCreate: { id: 'app.shortcut-settings.nav-create', defaultMessage: 'Create new instance' },
navCreateDescription: {
id: 'app.shortcut-settings.nav-create-description',
defaultMessage: 'Jump to creating a new instance.',
},
navSettings: { id: 'app.shortcut-settings.nav-settings', defaultMessage: 'Settings' },
navSettingsDescription: {
id: 'app.shortcut-settings.nav-settings-description',
defaultMessage: 'Jump to the settings.',
},
})
function keyboard(code: string, mod = false, alt = false, shift = false): KeyBinding {
return { device: 'keyboard', code, mod, alt, shift }
}
/**
* Resolves the Discover content target from the current route, so the nav
* button and the keyboard shortcut share one source of truth.
*/
export function discoverContentTarget(route: RouteLocationNormalizedLoaded): string {
const projectType = route.params.projectType
if (
!route.query.i &&
!route.query.sid &&
!route.query.wid &&
typeof projectType === 'string' &&
isBrowseContentProjectType(projectType)
) {
return `/browse/${projectType}`
}
return `/browse/${getLastBrowseContentProjectType()}`
}
/**
* Every shortcut the launcher answers to. The binding here is the one a fresh
* install uses; a recorded binding is stored separately and wins over it.
*/
export const SHORTCUT_ACTIONS: ShortcutAction[] = [
{
id: 'shortcutScrollTop',
group: 'scroll',
enabledField: 'quickScrollEnabled',
defaultBinding: keyboard('Home'),
label: messages.scrollTop,
description: messages.scrollTopDescription,
applyScroll: (scroller) => scroller.scrollTo({ top: 0, behavior: 'smooth' }),
},
{
id: 'shortcutScrollBottom',
group: 'scroll',
enabledField: 'quickScrollEnabled',
defaultBinding: keyboard('End'),
label: messages.scrollBottom,
description: messages.scrollBottomDescription,
applyScroll: (scroller) =>
scroller.scrollTo({ top: scroller.scrollHeight, behavior: 'smooth' }),
},
{
id: 'shortcutScrollUp',
group: 'scroll',
enabledField: 'quickScrollEnabled',
defaultBinding: keyboard('PageUp'),
label: messages.scrollUp,
description: messages.scrollUpDescription,
applyScroll: (scroller) => {
// Immediate scrolling keeps rapid key repeats responsive.
scroller.scrollTop = Math.max(0, scroller.scrollTop - scroller.clientHeight * 0.9)
},
},
{
id: 'shortcutScrollDown',
group: 'scroll',
enabledField: 'quickScrollEnabled',
defaultBinding: keyboard('PageDown'),
label: messages.scrollDown,
description: messages.scrollDownDescription,
applyScroll: (scroller) => {
scroller.scrollTop = Math.min(
scroller.scrollHeight,
scroller.scrollTop + scroller.clientHeight * 0.9,
)
},
},
{
id: 'shortcutNavHome',
group: 'nav',
enabledField: 'shortcutNavHome',
defaultBinding: keyboard('Digit1', true),
label: messages.navHome,
description: messages.navHomeDescription,
target: () => '/',
},
{
id: 'shortcutNavWorlds',
group: 'nav',
enabledField: 'shortcutNavWorlds',
defaultBinding: keyboard('Digit2', true),
label: messages.navWorlds,
description: messages.navWorldsDescription,
target: () => '/worlds',
unavailable: (context) => !context.worldsTabEnabled,
},
{
id: 'shortcutNavDiscover',
group: 'nav',
enabledField: 'shortcutNavDiscover',
defaultBinding: keyboard('Digit3', true),
label: messages.navDiscover,
description: messages.navDiscoverDescription,
target: (route) => discoverContentTarget(route),
unavailable: (context) => context.offline,
},
{
id: 'shortcutNavSkins',
group: 'nav',
enabledField: 'shortcutNavSkins',
defaultBinding: keyboard('Digit4', true),
label: messages.navSkins,
description: messages.navSkinsDescription,
target: () => '/skins',
},
{
id: 'shortcutNavMultiplayer',
group: 'nav',
enabledField: 'shortcutNavMultiplayer',
defaultBinding: keyboard('Digit5', true),
label: messages.navMultiplayer,
description: messages.navMultiplayerDescription,
target: () => '/multiplayer',
},
{
id: 'shortcutNavLibrary',
group: 'nav',
enabledField: 'shortcutNavLibrary',
defaultBinding: keyboard('Digit6', true),
label: messages.navLibrary,
description: messages.navLibraryDescription,
target: () => '/library',
},
{
id: 'shortcutNavLab',
group: 'nav',
enabledField: 'shortcutNavLab',
defaultBinding: keyboard('Digit7', true),
label: messages.navLab,
description: messages.navLabDescription,
target: () => '/lab',
},
{
id: 'shortcutNavDownloads',
group: 'nav',
enabledField: 'shortcutNavDownloads',
defaultBinding: keyboard('Digit8', true),
label: messages.navDownloads,
description: messages.navDownloadsDescription,
target: () => '/downloads',
},
{
id: 'shortcutNavCreate',
group: 'nav',
enabledField: 'shortcutNavCreate',
defaultBinding: keyboard('Digit9', true),
label: messages.navCreate,
description: messages.navCreateDescription,
target: () => '/create',
unavailable: (context) => context.offline,
},
{
id: 'shortcutNavSettings',
group: 'nav',
enabledField: 'shortcutNavSettings',
defaultBinding: keyboard('Comma', true),
label: messages.navSettings,
description: messages.navSettingsDescription,
target: () => '/settings',
},
]
export const SCROLL_ACTIONS = SHORTCUT_ACTIONS.filter((action) => action.group === 'scroll')
export const NAV_ACTIONS = SHORTCUT_ACTIONS.filter((action) => action.group === 'nav')
export function shortcutAction(id: string): ShortcutAction | undefined {
return SHORTCUT_ACTIONS.find((action) => action.id === id)
}
@@ -0,0 +1,120 @@
import type { BindingConflict, KeyBinding } from '@modrinth/ui'
import { SHORTCUT_ACTIONS, shortcutAction } from '@/helpers/shortcut-actions'
const BINDING_STORAGE_PREFIX = 'starlight-shortcut-binding-'
/**
* Combinations the shell or the operating system answers to before the launcher
* sees them. Saved shortcuts may not take these over.
*/
export const RESERVED_BINDINGS: BindingConflict[] = [
{
id: 'system-find',
label: 'Find in page (Ctrl/Cmd + F)',
binding: keyboard('KeyF', true),
reserved: true,
},
{
id: 'system-devtools',
label: 'Developer tools (F12)',
binding: keyboard('F12'),
reserved: true,
},
{
id: 'system-close',
label: 'Close window (Ctrl/Cmd + W)',
binding: keyboard('KeyW', true),
reserved: true,
},
{
id: 'system-quit',
label: 'Quit (Ctrl/Cmd + Q)',
binding: keyboard('KeyQ', true),
reserved: true,
},
{
id: 'system-reload',
label: 'Reload (Ctrl/Cmd + R)',
binding: keyboard('KeyR', true),
reserved: true,
},
{ id: 'system-refresh', label: 'Refresh (F5)', binding: keyboard('F5'), reserved: true },
{
id: 'system-exit',
label: 'Close window (Alt + F4)',
binding: keyboard('F4', false, true),
reserved: true,
},
]
function keyboard(code: string, mod = false, alt = false, shift = false): KeyBinding {
return { device: 'keyboard', code, mod, alt, shift }
}
function isKeyBinding(value: unknown): value is KeyBinding {
if (!value || typeof value !== 'object') return false
const candidate = value as Partial<KeyBinding>
return (
(candidate.device === 'keyboard' || candidate.device === 'mouse') &&
typeof candidate.code === 'string' &&
candidate.code.length > 0 &&
typeof candidate.mod === 'boolean' &&
typeof candidate.shift === 'boolean' &&
typeof candidate.alt === 'boolean'
)
}
/** The combination recorded for an action, if it has one. */
export function readStoredBinding(id: string): KeyBinding | null {
const raw = localStorage.getItem(BINDING_STORAGE_PREFIX + id)
if (!raw) return null
try {
const parsed = JSON.parse(raw)
return isKeyBinding(parsed) ? parsed : null
} catch {
// A value that cannot be read is treated as unset, so the action keeps
// working with its default rather than becoming unreachable.
return null
}
}
export function storeBinding(id: string, binding: KeyBinding) {
localStorage.setItem(BINDING_STORAGE_PREFIX + id, JSON.stringify(binding))
}
/** Drops the recorded combination, putting the action back on its default. */
export function clearStoredBinding(id: string) {
if (readStoredBinding(id)) localStorage.removeItem(BINDING_STORAGE_PREFIX + id)
}
/** The combination an action answers to now: the recorded one, or its default. */
export function resolveBinding(id: string): KeyBinding | null {
const action = shortcutAction(id)
if (!action) return null
return readStoredBinding(id) ?? action.defaultBinding
}
export function resolveAllBindings(): Record<string, KeyBinding> {
const bindings: Record<string, KeyBinding> = {}
for (const action of SHORTCUT_ACTIONS) {
bindings[action.id] = resolveBinding(action.id) ?? action.defaultBinding
}
return bindings
}
/**
* Everything a new combination would collide with: the other actions, plus the
* combinations the shell owns. `label` is what the dialog names in the error.
*/
export function buildConflicts(exceptId: string, label: (id: string) => string): BindingConflict[] {
const conflicts = SHORTCUT_ACTIONS.filter((action) => action.id !== exceptId).flatMap(
(action) => {
const binding = resolveBinding(action.id)
return binding ? [{ id: action.id, label: label(action.id), binding }] : []
},
)
return [...conflicts, ...RESERVED_BINDINGS]
}
+32
View File
@@ -81,6 +81,38 @@ export async function exportErrorLogs(
return await invoke('plugin:utils|export_error_logs', { outputPath, errorMessage })
}
export async function exportLauncherLogs({
range = 'last2Hours',
level = 'all',
includeSystemInfo = true,
includeInstanceLogs = false,
includeCrashAnalysis = false,
fileNamePrefix = 'Starlight Launcher logs',
} = {}) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const outputPath = await save({
defaultPath: `${fileNamePrefix} ${timestamp}.zip`,
filters: [
{
name: 'ZIP archive',
extensions: ['zip'],
},
],
})
if (!outputPath) return null
await invoke('plugin:utils|export_launcher_logs', {
outputPath,
range,
level,
includeSystemInfo,
includeInstanceLogs,
includeCrashAnalysis,
})
return outputPath
}
export async function createInstanceShortcut(instanceName, instanceId, options = {}) {
const outputPath = await save({
defaultPath: `Modrinth - ${instanceName}`,
+204 -2
View File
@@ -11485,5 +11485,207 @@
},
"app.remote-announcements.preview-action": {
"message": "Visit website"
}
}
},
"app.settings.tabs.logs": {
"message": "Logs & diagnostics"
},
"app.settings.logs.export.title": {
"message": "Export logs"
},
"app.settings.logs.export.description": {
"message": "Package launcher logs with an optional environment summary, instance log, and crash analysis."
},
"app.settings.logs.export.button": {
"message": "Export logs…"
},
"app.settings.logs.open-folder": {
"message": "Open logs folder"
},
"app.settings.logs.export.modal.title": {
"message": "Export logs"
},
"app.settings.logs.export.modal.description": {
"message": "Choose how much detail to include. Exported logs have access tokens, Minecraft tokens, and IP addresses replaced with placeholders."
},
"app.settings.logs.export.modal.range": {
"message": "Time range"
},
"app.settings.logs.export.modal.range.30-minutes": {
"message": "Last 30 minutes"
},
"app.settings.logs.export.modal.range.2-hours": {
"message": "Last 2 hours"
},
"app.settings.logs.export.modal.range.all": {
"message": "All sessions"
},
"app.settings.logs.export.modal.level": {
"message": "Log level"
},
"app.settings.logs.export.modal.level.all": {
"message": "All levels"
},
"app.settings.logs.export.modal.level.debug": {
"message": "Debug and above"
},
"app.settings.logs.export.modal.level.info": {
"message": "Info and above"
},
"app.settings.logs.export.modal.extras": {
"message": "Additional information"
},
"app.settings.logs.export.modal.system-info": {
"message": "System and environment summary"
},
"app.settings.logs.export.modal.instance-logs": {
"message": "Most recent instance log"
},
"app.settings.logs.export.modal.crash-analysis": {
"message": "Crash analysis (when a crash is detected)"
},
"app.settings.logs.export.modal.cancel": {
"message": "Cancel"
},
"app.settings.logs.export.modal.confirm": {
"message": "Export"
},
"app.settings.logs.export.notification-title": {
"message": "Logs exported"
},
"app.settings.logs.export.notification-text": {
"message": "The log archive was saved to {path}"
},
"app.skins.armor.title": {"message": "Armour and trims"},
"app.skins.armor.save": {"message": "Save"},
"app.skins.armor.close": {"message": "Close"},
"app.skins.armor.description": {"message": "Try armour and trims on your skin. Nothing is stored until you save it."},
"app.skins.armor.unsaved": {"message": "Unsaved changes"},
"app.skins.armor.reset-to-saved": {"message": "Reset to saved"},
"app.skins.armor.restore-defaults": {"message": "Restore defaults"},
"app.instances.batch-edit-groups.add": {"message": "Add"},
"app.instances.batch-edit-groups.add-to-group-title": {"message": "Add instances to \"{groupName}\""},
"app.instances.batch-edit-groups.added": {"message": "Added"},
"app.instances.batch-edit-groups.cancel": {"message": "Cancel"},
"app.instances.batch-edit-groups.create": {"message": "Create group"},
"app.instances.batch-edit-groups.group-name": {"message": "Group name"},
"app.instances.batch-edit-groups.group-name-placeholder": {"message": "Enter group name"},
"app.instances.batch-edit-groups.no-instances-found": {"message": "No instances found"},
"app.instances.batch-edit-groups.save-changes": {"message": "Save"},
"app.instances.batch-edit-groups.search-instance": {"message": "Search instances"},
"app.instances.group.add-to-group": {"message": "Add to group"},
"app.instances.group.collapse": {"message": "Collapse group"},
"app.instances.group.delete-description": {"message": "Instances in this group will be ungrouped."},
"app.instances.group.delete-group": {"message": "Delete group"},
"app.instances.group.edit-name": {"message": "Edit group name"},
"app.instances.group.empty": {"message": "Drag and drop to add instances."},
"app.instances.group.expand": {"message": "Expand group"},
"app.instances.group.move-down": {"message": "Move group down"},
"app.instances.group.move-up": {"message": "Move group up"},
"app.instances.group.name-empty": {"message": "Group names cannot be empty."},
"app.instances.group.name-too-long": {"message": "Group names cannot be longer than {maxLength} characters."},
"app.instances.group.new-instance": {"message": "New instance"},
"app.instances.group.pinned": {"message": "Pinned"},
"app.instances.group.rename-group": {"message": "Rename group"},
"app.instances.sort-by": {"message": "Sort by"},
"app.instances.sort.direction.asc-alphabetical": {"message": "A–Z"},
"app.instances.sort.direction.asc-date": {"message": "Oldest first"},
"app.instances.sort.direction.asc-recency": {"message": "Least recent first"},
"app.instances.sort.direction.asc-version": {"message": "Oldest version first"},
"app.instances.sort.direction.desc-alphabetical": {"message": "Z–A"},
"app.instances.sort.direction.desc-date": {"message": "Newest first"},
"app.instances.sort.direction.desc-recency": {"message": "Most recent first"},
"app.instances.sort.direction.desc-version": {"message": "Newest version first"},
"app.library.context-menu.pin-instance": {"message": "Pin instance"},
"app.library.context-menu.remove-from-group": {"message": "Remove from group"},
"app.library.context-menu.unpin-instance": {"message": "Unpin instance"},
"app.library.group.new": {"message": "New group"},
"app.library.selection.new-group": {"message": "New group"},
"app.library.selection.remove-from-group": {"message": "Remove from group"},
"app.log-share.settings.title": {"message": "Log sharing & AI analysis"},
"app.log-share.settings.description": {"message": "Share crash diagnostics with LogShare for a structured summary and optional AI analysis. LogShare is preferred; mclo.gs is used as a fallback."},
"app.log-share.settings.share-provider": {"message": "Log sharing service"},
"app.log-share.settings.share-provider-description": {"message": "Where the diagnostic link is uploaded when you share it."},
"app.log-share.settings.ai-source": {"message": "AI analysis source"},
"app.log-share.settings.ai-source-logshare": {"message": "LogShare AI"},
"app.log-share.settings.ai-source-custom": {"message": "Custom AI provider"},
"app.log-share.settings.ai-source-description": {"message": "Both sources send a sanitized and shortened crash context. AI output may be inaccurate."},
"app.log-share.settings.auto-upload": {"message": "Upload to get a structured summary automatically"},
"app.log-share.settings.auto-upload-description": {"message": "Only effective in LogShare AI mode."},
"app.log-share.settings.multi-file": {"message": "Multi-file upload"},
"app.log-share.settings.multi-file-description": {"message": "Upload latest.log, crash reports, hs_err and launcher logs together."},
"app.log-share.settings.no-storage": {"message": "Analyze without storing logs"},
"app.log-share.settings.no-storage-description": {"message": "Submit content directly for analysis and skip the stored upload. Disables the automatic summary."},
"app.log-share.settings.show-progress": {"message": "Show AI analysis progress"},
"app.log-share.settings.show-progress-description": {"message": "Display thinking, tool and limit status while LogShare AI is working."},
"app.log-share.shared-logs.title": {"message": "Shared logs"},
"app.log-share.shared-logs.description": {"message": "Every diagnostic you have shared is listed here. Delete an entry to remove it from your history and request its removal from the sharing service."},
"app.log-share.shared-logs.empty": {"message": "No shared logs yet."},
"app.log-share.shared-logs.delete": {"message": "Delete"},
"app.log-share.shared-logs.deleting": {"message": "Deleting…"},
"app.log-share.shared-logs.deleted": {"message": "Shared log removed."},
"app.log-share.shared-logs.delete-failed": {"message": "Failed to delete the shared log."},
"app.log-share.shared-logs.truncated": {"message": "Truncated"},
"app.minecraft-crash.share-fallback": {"message": "LogShare is unavailable, so the diagnostic was shared via mclo.gs."},
"app.log-share.ai.action": {"message": "Deep AI analysis"},
"app.log-share.summary.title": {"message": "LogShare analysis"},
"app.log-share.summary.loading": {"message": "Loading structured summary..."},
"app.log-share.summary.empty": {"message": "LogShare did not return a structured summary for these logs."},
"app.log-share.summary.no-storage": {"message": "Structured summary is unavailable while no-storage mode is enabled."},
"app.log-share.summary.failed": {"message": "Could not load the LogShare summary: {message}"},
"app.log-share.summary.problems": {"message": "Problems"},
"app.log-share.summary.information": {"message": "Information"},
"app.minecraft-crash.logs.loading": {"message": "Loading crash logs..."},
"app.minecraft-crash.logs.empty": {"message": "No logs from this launch were found."},
"app.minecraft-crash.logs.failed": {"message": "Could not load the crash logs: {message}"},
"app.minecraft-crash.log-file.loading": {"message": "Loading log file..."},
"app.minecraft-crash.log-file.failed": {"message": "Could not load this log file: {message}"},
"app.log-share.ai.tab": {"message": "LogAgent detailed analysis"},
"app.log-share.ai.root-cause": {"message": "Core root cause"},
"app.log-share.ai.confidence": {"message": "Diagnostic confidence"},
"app.log-share.ai.steps": {"message": "Recommended troubleshooting steps"},
"app.log-share.ai.evidence": {"message": "Supporting evidence"},
"app.log-share.ai.thinking": {"message": "Thinking…"},
"app.log-share.ai.queued": {"message": "Queued, about {position} ahead"},
"app.log-share.ai.queued-front": {"message": "Queued, waiting for a free slot"},
"app.log-share.ai.tool": {"message": "Using tool: {name}"},
"app.log-share.ai.unknown-tool": {"message": "tool"},
"app.log-share.ai.tool-result": {"message": "Tool result received"},
"app.log-share.ai.limit": {"message": "Reached tool loop limit"},
"app.log-share.ai.working": {"message": "Analyzing with LogAgent…"},
"app.log-share.ai.failed": {"message": "LogAgent analysis failed: {message}"},
"app.shortcut-settings.change-shortcut": {"message": "Change the shortcut for {action}"},
"app.shortcut-settings.enable": {"message": "Enable quick scrolling"},
"app.shortcut-settings.end-action": {"message": "Scroll to the bottom"},
"app.shortcut-settings.end-action-description": {"message": "Moves the page you are reading to the bottom."},
"app.shortcut-settings.home-action": {"message": "Scroll to the top"},
"app.shortcut-settings.home-action-description": {"message": "Moves the page you are reading to the top."},
"app.shortcut-settings.nav-create": {"message": "Create new instance"},
"app.shortcut-settings.nav-create-description": {"message": "Jump to creating a new instance."},
"app.shortcut-settings.nav-description": {"message": "Jump to a menu item with its shortcut. Each shortcut is off until enabled."},
"app.shortcut-settings.nav-discover": {"message": "Discover content"},
"app.shortcut-settings.nav-discover-description": {"message": "Jump to browsing content."},
"app.shortcut-settings.nav-downloads": {"message": "Downloads"},
"app.shortcut-settings.nav-downloads-description": {"message": "Jump to downloads."},
"app.shortcut-settings.nav-home": {"message": "Home"},
"app.shortcut-settings.nav-home-description": {"message": "Jump to the Home page."},
"app.shortcut-settings.nav-lab": {"message": "Lab"},
"app.shortcut-settings.nav-lab-description": {"message": "Jump to the Lab."},
"app.shortcut-settings.nav-library": {"message": "Library"},
"app.shortcut-settings.nav-library-description": {"message": "Jump to your library."},
"app.shortcut-settings.nav-multiplayer": {"message": "Multiplayer"},
"app.shortcut-settings.nav-multiplayer-description": {"message": "Jump to multiplayer."},
"app.shortcut-settings.nav-settings": {"message": "Settings"},
"app.shortcut-settings.nav-settings-description": {"message": "Jump to the settings."},
"app.shortcut-settings.nav-skins": {"message": "Skin selector"},
"app.shortcut-settings.nav-skins-description": {"message": "Jump to the skin selector."},
"app.shortcut-settings.nav-title": {"message": "Navigation shortcuts"},
"app.shortcut-settings.nav-worlds": {"message": "Worlds"},
"app.shortcut-settings.nav-worlds-description": {"message": "Jump to your worlds."},
"app.shortcut-settings.page-down-action": {"message": "Scroll down one screen"},
"app.shortcut-settings.page-down-action-description": {"message": "Moves the page you are reading down by one screen."},
"app.shortcut-settings.page-up-action": {"message": "Scroll up one screen"},
"app.shortcut-settings.page-up-action-description": {"message": "Moves the page you are reading up by one screen."},
"app.shortcut-settings.scroll-description": {"message": "Move through long pages with the keyboard."},
"app.shortcut-settings.scroll-title": {"message": "Quick scrolling"},
"app.settings.tabs.shortcut-settings": {"message": "Keyboard shortcuts"}
}
+158 -2
View File
@@ -11362,5 +11362,161 @@
"app.settings.defaults.window-title.default-placeholder": { "message": "输入默认窗口标题..." },
"app.action-bar.announcements": { "message": "公告" },
"app.remote-announcements.center-title": { "message": "公告" },
"app.remote-announcements.empty": { "message": "暂无公告" }
}
"app.remote-announcements.empty": { "message": "暂无公告" },
"app.settings.tabs.logs": { "message": "日志与诊断" },
"app.settings.logs.export.title": { "message": "导出日志" },
"app.settings.logs.export.description": { "message": "将启动器日志打包,可附带环境摘要、最近的实例日志与崩溃分析。" },
"app.settings.logs.export.button": { "message": "导出日志…" },
"app.settings.logs.open-folder": { "message": "打开日志文件夹" },
"app.settings.logs.export.modal.title": { "message": "导出日志" },
"app.settings.logs.export.modal.description": { "message": "选择要包含的详细程度。导出的日志会把访问令牌、Minecraft 令牌与 IP 地址替换为占位符。" },
"app.settings.logs.export.modal.range": { "message": "时间范围" },
"app.settings.logs.export.modal.range.30-minutes": { "message": "最近 30 分钟" },
"app.settings.logs.export.modal.range.2-hours": { "message": "最近 2 小时" },
"app.settings.logs.export.modal.range.all": { "message": "全部会话" },
"app.settings.logs.export.modal.level": { "message": "日志等级" },
"app.settings.logs.export.modal.level.all": { "message": "全部等级" },
"app.settings.logs.export.modal.level.debug": { "message": "DEBUG 及以上" },
"app.settings.logs.export.modal.level.info": { "message": "INFO 及以上" },
"app.settings.logs.export.modal.extras": { "message": "附加信息" },
"app.settings.logs.export.modal.system-info": { "message": "系统与环境摘要" },
"app.settings.logs.export.modal.instance-logs": { "message": "最近的实例日志" },
"app.settings.logs.export.modal.crash-analysis": { "message": "崩溃分析(检测到崩溃时)" },
"app.settings.logs.export.modal.cancel": { "message": "取消" },
"app.settings.logs.export.modal.confirm": { "message": "导出" },
"app.settings.logs.export.notification-title": { "message": "日志已导出" },
"app.settings.logs.export.notification-text": { "message": "日志压缩包已保存到 {path}" },
"app.skins.armor.title": {"message": "盔甲与纹饰"},
"app.skins.armor.save": {"message": "保存"},
"app.skins.armor.close": {"message": "关闭"},
"app.skins.armor.description": {"message": "在皮肤上试穿盔甲与纹饰。未保存前不会写入任何内容。"},
"app.skins.armor.unsaved": {"message": "有未保存的更改"},
"app.skins.armor.reset-to-saved": {"message": "重置为已保存"},
"app.skins.armor.restore-defaults": {"message": "恢复默认"},
"app.instances.batch-edit-groups.add": {"message": "添加"},
"app.instances.batch-edit-groups.add-to-group-title": {"message": "添加实例到「{groupName}」"},
"app.instances.batch-edit-groups.added": {"message": "已添加"},
"app.instances.batch-edit-groups.cancel": {"message": "取消"},
"app.instances.batch-edit-groups.create": {"message": "创建分组"},
"app.instances.batch-edit-groups.group-name": {"message": "分组名称"},
"app.instances.batch-edit-groups.group-name-placeholder": {"message": "输入分组名称"},
"app.instances.batch-edit-groups.no-instances-found": {"message": "未找到实例"},
"app.instances.batch-edit-groups.save-changes": {"message": "保存"},
"app.instances.batch-edit-groups.search-instance": {"message": "搜索实例"},
"app.instances.group.add-to-group": {"message": "添加到分组"},
"app.instances.group.collapse": {"message": "折叠分组"},
"app.instances.group.delete-description": {"message": "此分组中的实例将被取消分组。"},
"app.instances.group.delete-group": {"message": "删除分组"},
"app.instances.group.edit-name": {"message": "编辑分组名称"},
"app.instances.group.empty": {"message": "拖放实例到此处添加。"},
"app.instances.group.expand": {"message": "展开分组"},
"app.instances.group.move-down": {"message": "下移分组"},
"app.instances.group.move-up": {"message": "上移分组"},
"app.instances.group.name-empty": {"message": "分组名称不能为空。"},
"app.instances.group.name-too-long": {"message": "分组名称不能超过 {maxLength} 个字符。"},
"app.instances.group.new-instance": {"message": "新建实例"},
"app.instances.group.pinned": {"message": "已置顶"},
"app.instances.group.rename-group": {"message": "重命名分组"},
"app.instances.sort-by": {"message": "排序方式"},
"app.instances.sort.direction.asc-alphabetical": {"message": "A–Z 正序"},
"app.instances.sort.direction.asc-date": {"message": "最早的在前"},
"app.instances.sort.direction.asc-recency": {"message": "最早游玩在前"},
"app.instances.sort.direction.asc-version": {"message": "旧版本在前"},
"app.instances.sort.direction.desc-alphabetical": {"message": "Z–A 倒序"},
"app.instances.sort.direction.desc-date": {"message": "最新的在前"},
"app.instances.sort.direction.desc-recency": {"message": "最近游玩在前"},
"app.instances.sort.direction.desc-version": {"message": "新版本在前"},
"app.library.context-menu.pin-instance": {"message": "置顶实例"},
"app.library.context-menu.remove-from-group": {"message": "移出分组"},
"app.library.context-menu.unpin-instance": {"message": "取消置顶"},
"app.library.group.new": {"message": "新建分组"},
"app.library.selection.new-group": {"message": "新建分组"},
"app.library.selection.remove-from-group": {"message": "移出分组"},
"app.log-share.settings.title": {"message": "日志分享与 AI 分析"},
"app.log-share.settings.description": {"message": "将崩溃诊断分享到 LogShare,获取结构化摘要与可选的 AI 分析。优先使用 LogShare,不可用时回退到 mclo.gs。"},
"app.log-share.settings.share-provider": {"message": "日志分享服务"},
"app.log-share.settings.share-provider-description": {"message": "分享诊断链接时上传到的目标服务。"},
"app.log-share.settings.ai-source": {"message": "AI 分析来源"},
"app.log-share.settings.ai-source-logshare": {"message": "LogShare AI"},
"app.log-share.settings.ai-source-custom": {"message": "自定义 AI 服务商"},
"app.log-share.settings.ai-source-description": {"message": "LogShare AI 在云端分析;自定义则使用下方配置的服务商。"},
"app.log-share.settings.auto-upload": {"message": "自动上传以获取结构化摘要"},
"app.log-share.settings.auto-upload-description": {"message": "仅在 LogShare 模式下生效。"},
"app.log-share.settings.multi-file": {"message": "多文件上传"},
"app.log-share.settings.multi-file-description": {"message": "同时上传 latest.log、崩溃报告、hs_err 以及启动器日志。"},
"app.log-share.settings.no-storage": {"message": "不落盘直接分析"},
"app.log-share.settings.no-storage-description": {"message": "直接提交内容进行分析并跳过存储上传。会关闭自动摘要。"},
"app.log-share.settings.show-progress": {"message": "显示 AI 分析进度"},
"app.log-share.settings.show-progress-description": {"message": "展示 LogAgent 运行期间的思考、工具及上限状态。"},
"app.log-share.shared-logs.title": {"message": "已分享日志"},
"app.log-share.shared-logs.description": {"message": "你分享过的所有诊断都记录在这里。删除条目会将其从记录中移除,并向分享服务请求删除。"},
"app.log-share.shared-logs.empty": {"message": "暂无已分享的日志。"},
"app.log-share.shared-logs.delete": {"message": "删除"},
"app.log-share.shared-logs.deleting": {"message": "删除中…"},
"app.log-share.shared-logs.deleted": {"message": "已删除共享日志。"},
"app.log-share.shared-logs.delete-failed": {"message": "删除已分享日志失败。"},
"app.log-share.shared-logs.truncated": {"message": "已截断"},
"app.minecraft-crash.share-fallback": {"message": "LogShare 不可用,已改用 mclo.gs 分享诊断信息。"},
"app.log-share.ai.action": {"message": "AI 深度分析"},
"app.log-share.summary.title": {"message": "LogShare 分析"},
"app.log-share.summary.loading": {"message": "正在加载结构化摘要…"},
"app.log-share.summary.empty": {"message": "LogShare 未返回这些日志的结构化摘要。"},
"app.log-share.summary.no-storage": {"message": "启用不落盘模式时无法获取结构化摘要。"},
"app.log-share.summary.failed": {"message": "无法加载 LogShare 摘要:{message}"},
"app.log-share.summary.problems": {"message": "问题"},
"app.log-share.summary.information": {"message": "信息"},
"app.minecraft-crash.logs.loading": {"message": "正在加载崩溃日志…"},
"app.minecraft-crash.logs.empty": {"message": "未找到本次启动产生的日志。"},
"app.minecraft-crash.logs.failed": {"message": "无法加载崩溃日志:{message}"},
"app.minecraft-crash.log-file.loading": {"message": "正在加载日志文件…"},
"app.minecraft-crash.log-file.failed": {"message": "无法加载此日志文件:{message}"},
"app.log-share.ai.tab": {"message": "LogAgent 深度分析"},
"app.log-share.ai.root-cause": {"message": "核心根因"},
"app.log-share.ai.confidence": {"message": "诊断置信度"},
"app.log-share.ai.steps": {"message": "推荐排障步骤"},
"app.log-share.ai.evidence": {"message": "支撑证据链"},
"app.log-share.ai.thinking": {"message": "思考中…"},
"app.log-share.ai.queued": {"message": "排队中,前方约 {position} 个任务"},
"app.log-share.ai.queued-front": {"message": "排队中,正在等待空闲槽位"},
"app.log-share.ai.tool": {"message": "正在使用工具:{name}"},
"app.log-share.ai.unknown-tool": {"message": "工具"},
"app.log-share.ai.tool-result": {"message": "已收到工具结果"},
"app.log-share.ai.limit": {"message": "已达到工具调用上限"},
"app.log-share.ai.working": {"message": "正在使用 LogAgent 分析…"},
"app.log-share.ai.failed": {"message": "LogAgent 分析失败:{message}"},
"app.shortcut-settings.change-shortcut": {"message": "更改「{action}」的快捷键"},
"app.shortcut-settings.enable": {"message": "启用快捷滚动"},
"app.shortcut-settings.end-action": {"message": "滚动到页面底部"},
"app.shortcut-settings.end-action-description": {"message": "将当前页面移动到底部。"},
"app.shortcut-settings.home-action": {"message": "滚动到页面顶部"},
"app.shortcut-settings.home-action-description": {"message": "将当前页面移动到顶部。"},
"app.shortcut-settings.nav-create": {"message": "新建实例"},
"app.shortcut-settings.nav-create-description": {"message": "前往新建实例。"},
"app.shortcut-settings.nav-description": {"message": "使用各自的快捷键跳转到对应菜单项。每个快捷键默认关闭,需逐个启用。"},
"app.shortcut-settings.nav-discover": {"message": "发现内容"},
"app.shortcut-settings.nav-discover-description": {"message": "前往浏览内容。"},
"app.shortcut-settings.nav-downloads": {"message": "下载"},
"app.shortcut-settings.nav-downloads-description": {"message": "前往下载。"},
"app.shortcut-settings.nav-home": {"message": "首页"},
"app.shortcut-settings.nav-home-description": {"message": "前往首页。"},
"app.shortcut-settings.nav-lab": {"message": "实验室"},
"app.shortcut-settings.nav-lab-description": {"message": "前往实验室。"},
"app.shortcut-settings.nav-library": {"message": "内容库"},
"app.shortcut-settings.nav-library-description": {"message": "前往内容库。"},
"app.shortcut-settings.nav-multiplayer": {"message": "多人游戏"},
"app.shortcut-settings.nav-multiplayer-description": {"message": "前往多人游戏。"},
"app.shortcut-settings.nav-settings": {"message": "设置"},
"app.shortcut-settings.nav-settings-description": {"message": "前往设置。"},
"app.shortcut-settings.nav-skins": {"message": "皮肤选择器"},
"app.shortcut-settings.nav-skins-description": {"message": "前往皮肤选择器。"},
"app.shortcut-settings.nav-title": {"message": "导航快捷键"},
"app.shortcut-settings.nav-worlds": {"message": "世界"},
"app.shortcut-settings.nav-worlds-description": {"message": "前往你的世界。"},
"app.shortcut-settings.page-down-action": {"message": "向下滚动一屏"},
"app.shortcut-settings.page-down-action-description": {"message": "将当前页面向下移动一屏。"},
"app.shortcut-settings.page-up-action": {"message": "向上滚动一屏"},
"app.shortcut-settings.page-up-action-description": {"message": "将当前页面向上移动一屏。"},
"app.shortcut-settings.scroll-description": {"message": "使用键盘在长页面中快速滚动。"},
"app.shortcut-settings.scroll-title": {"message": "快速滚动"},
"app.settings.tabs.shortcut-settings": {"message": "键盘快捷键"}
}
+51 -1
View File
@@ -6,6 +6,18 @@ import {
resolveFontFamily,
} from '@/helpers/font-family.ts'
/**
* Mirrors `KeyBinding` from `@modrinth/ui`. Declared here so this module stays
* loadable without the UI package.
*/
export interface ShortcutBinding {
device: 'keyboard' | 'mouse'
code: string
mod: boolean
shift: boolean
alt: boolean
}
let systemThemeMq: MediaQueryList | null = null
export const DEFAULT_FEATURE_FLAGS = {
@@ -135,8 +147,30 @@ export type ThemeStore = {
minimalHomeInstanceId: string | null
closeBehavior: CloseBehavior
/** Whether the floating "back to top" button is shown on scrollable pages. */
showScrollTop: boolean
/** Whether quick scrolling shortcuts (Home/End/PageUp/PageDown) are active. */
quickScrollEnabled: boolean
/** Per-nav-item quick jump shortcuts (Ctrl/Cmd + number), off by default. */
shortcutNavHome: boolean
shortcutNavWorlds: boolean
shortcutNavDiscover: boolean
shortcutNavSkins: boolean
shortcutNavMultiplayer: boolean
shortcutNavLibrary: boolean
shortcutNavLab: boolean
shortcutNavDownloads: boolean
shortcutNavCreate: boolean
shortcutNavSettings: boolean
/**
* The combination every shortcut answers to, keyed by action id. Kept here so
* pages re-render when one is recorded; the value itself lives in local
* storage, next to the enable flags.
*/
shortcutBindings: Record<string, ShortcutBinding>
devMode: boolean
featureFlags: FeatureFlags
uiFont: string | null
monoFont: string | null
@@ -162,6 +196,22 @@ export const DEFAULT_THEME_STORE: ThemeStore = {
minimalHomeInstanceId: null,
closeBehavior: 'ask',
showScrollTop: true,
quickScrollEnabled: false,
shortcutNavHome: false,
shortcutNavWorlds: false,
shortcutNavDiscover: false,
shortcutNavSkins: false,
shortcutNavMultiplayer: false,
shortcutNavLibrary: false,
shortcutNavLab: false,
shortcutNavDownloads: false,
shortcutNavCreate: false,
shortcutNavSettings: false,
shortcutBindings: {},
devMode: false,
featureFlags: DEFAULT_FEATURE_FLAGS,
+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.2-beta4"
version = "1.0.2-beta7"
edition.workspace = true
description = "Axolotl Launcher is a cross-platform Minecraft launcher"
homepage = "https://www.ghs.red"
+18
View File
@@ -300,6 +300,17 @@ fn main() {
"logs_explain_crash_with_ai",
"logs_undo_added_mod",
"logs_export_crash_context",
"logs_get_log_share_settings",
"logs_update_log_share_settings",
"logs_logshare_upload_crash",
"logs_logshare_get_insights",
"logs_logshare_analyse_crash_direct",
"logs_logshare_ai_analyze_stored",
"logs_logshare_ai_analyze_direct",
"logs_logshare_delete",
"logs_list_shared_logs",
"logs_record_shared_log",
"logs_delete_shared_log",
])
.default_permission(
DefaultPermissionRule::AllowAllCommands,
@@ -534,6 +545,12 @@ fn main() {
"instance_delete_screenshot_group",
"instance_set_screenshot_group_memberships",
"instance_import_screenshot_groups",
"instance_list_groups",
"instance_create_group",
"instance_rename_group",
"instance_delete_group",
"instance_set_group_order",
"instance_set_group_memberships",
"instance_delete_screenshots",
"instance_export_screenshots",
"instance_move_screenshots",
@@ -694,6 +711,7 @@ fn main() {
"open_path",
"show_launcher_logs_folder",
"export_error_logs",
"export_launcher_logs",
"show_app_db_backups_folder",
"progress_bars_list",
"get_opening_command",
+44
View File
@@ -131,6 +131,12 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
instance_delete_screenshot_group,
instance_set_screenshot_group_memberships,
instance_import_screenshot_groups,
instance_list_groups,
instance_create_group,
instance_rename_group,
instance_delete_group,
instance_set_group_order,
instance_set_group_memberships,
instance_delete_screenshots,
instance_export_screenshots,
instance_move_screenshots,
@@ -1717,6 +1723,44 @@ pub async fn instance_import_screenshot_groups(
Ok(theseus::instance::import_screenshot_groups(groups).await?)
}
#[tauri::command]
pub async fn instance_list_groups()
-> Result<Vec<theseus::instance::InstanceGroup>> {
Ok(theseus::instance::list_groups().await?)
}
#[tauri::command]
pub async fn instance_create_group(
name: String,
) -> Result<theseus::instance::InstanceGroup> {
Ok(theseus::instance::create_group(name).await?)
}
#[tauri::command]
pub async fn instance_rename_group(
id: String,
new_name: String,
) -> Result<theseus::instance::InstanceGroup> {
Ok(theseus::instance::rename_group(id, new_name).await?)
}
#[tauri::command]
pub async fn instance_delete_group(id: String) -> Result<()> {
Ok(theseus::instance::delete_group(id).await?)
}
#[tauri::command]
pub async fn instance_set_group_order(group_ids: Vec<String>) -> Result<()> {
Ok(theseus::instance::set_group_order(group_ids).await?)
}
#[tauri::command]
pub async fn instance_set_group_memberships(
updates: Vec<theseus::instance::InstanceGroupMembershipUpdate>,
) -> Result<()> {
Ok(theseus::instance::set_group_memberships(updates).await?)
}
#[tauri::command]
pub async fn instance_delete_screenshots(
keys: Vec<theseus::instance::ScreenshotKey>,
+91 -1
View File
@@ -4,7 +4,8 @@ use std::path::PathBuf;
use theseus::logs::LogType;
use theseus::logs::{
self, CensoredString, CrashAnalysis, CrashAnalysisAiExplanation,
CrashAnalysisAiSettings, LatestLogCursor, LiveLogSnapshot, Logs,
CrashAnalysisAiSettings, LatestLogCursor, LiveLogSnapshot,
LogShareSettings, LogShareUploadResponse, Logs, SharedLog,
};
/*
@@ -34,6 +35,17 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
logs_explain_crash_with_ai,
logs_undo_added_mod,
logs_export_crash_context,
logs_get_log_share_settings,
logs_update_log_share_settings,
logs_logshare_upload_crash,
logs_logshare_get_insights,
logs_logshare_analyse_crash_direct,
logs_logshare_ai_analyze_stored,
logs_logshare_ai_analyze_direct,
logs_logshare_delete,
logs_list_shared_logs,
logs_record_shared_log,
logs_delete_shared_log,
])
.build()
}
@@ -172,3 +184,81 @@ pub async fn logs_export_crash_context(
writer.close().await.map_err(crate::api::utils::zip_error)?;
Ok(())
}
/// Get the log share settings.
#[tauri::command]
pub async fn logs_get_log_share_settings() -> Result<LogShareSettings> {
Ok(logs::get_log_share_settings().await?)
}
/// Update the log share settings.
#[tauri::command]
pub async fn logs_update_log_share_settings(
settings: LogShareSettings,
) -> Result<()> {
Ok(logs::update_log_share_settings(settings).await?)
}
/// Upload the latest run's crash logs to LogShare.
#[tauri::command]
pub async fn logs_logshare_upload_crash(
instance_id: &str,
) -> Result<LogShareUploadResponse> {
Ok(logs::upload_crash(instance_id).await?)
}
/// Fetch structured insights for a shared log.
#[tauri::command]
pub async fn logs_logshare_get_insights(id: &str) -> Result<serde_json::Value> {
Ok(logs::get_insights(id).await?)
}
/// Analyse the latest run's crash logs directly.
#[tauri::command]
pub async fn logs_logshare_analyse_crash_direct(
instance_id: &str,
) -> Result<serde_json::Value> {
Ok(logs::analyse_crash_direct(instance_id).await?)
}
/// Stream an AI analysis for a stored shared log.
#[tauri::command]
pub async fn logs_logshare_ai_analyze_stored(
instance_id: &str,
id: &str,
) -> Result<String> {
Ok(logs::ai_analyze_stored(instance_id, id).await?)
}
/// Stream an AI analysis for the latest run's crash logs.
#[tauri::command]
pub async fn logs_logshare_ai_analyze_direct(
instance_id: &str,
) -> Result<String> {
Ok(logs::ai_analyze_direct(instance_id).await?)
}
/// Delete a shared log remotely and locally.
#[tauri::command]
pub async fn logs_logshare_delete(id: &str, token: &str) -> Result<()> {
logs::delete_log(id, token).await?;
Ok(())
}
/// List locally recorded shared logs.
#[tauri::command]
pub async fn logs_list_shared_logs() -> Result<Vec<SharedLog>> {
Ok(logs::list_shared_logs().await?)
}
/// Record a shared log locally.
#[tauri::command]
pub async fn logs_record_shared_log(log: SharedLog) -> Result<()> {
Ok(logs::record_shared_log(log).await?)
}
/// Remove a shared log record locally and remotely.
#[tauri::command]
pub async fn logs_delete_shared_log(id: String, token: String) -> Result<()> {
Ok(logs::delete_shared_log(id, token).await?)
}
+307
View File
@@ -25,6 +25,7 @@ pub fn init<R: Runtime>() -> tauri::plugin::TauriPlugin<R> {
open_path,
show_launcher_logs_folder,
export_error_logs,
export_launcher_logs,
show_app_db_backups_folder,
progress_bars_list,
get_opening_command,
@@ -164,6 +165,312 @@ pub async fn export_error_logs(
Ok(())
}
/// Time window included in a launcher log export.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum LogExportRange {
Last30Minutes,
Last2Hours,
All,
}
impl LogExportRange {
fn max_age(self) -> Option<std::time::Duration> {
match self {
Self::Last30Minutes => {
Some(std::time::Duration::from_secs(30 * 60))
}
Self::Last2Hours => {
Some(std::time::Duration::from_secs(2 * 60 * 60))
}
Self::All => None,
}
}
fn label(self) -> &'static str {
match self {
Self::Last30Minutes => "last 30 minutes",
Self::Last2Hours => "last 2 hours",
Self::All => "all sessions",
}
}
}
/// Lowest level included in a launcher log export.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum LogExportLevel {
All,
Debug,
Info,
}
impl LogExportLevel {
fn minimum(self) -> Option<&'static str> {
match self {
Self::All => None,
Self::Debug => Some("debug"),
Self::Info => Some("info"),
}
}
fn label(self) -> &'static str {
match self {
Self::All => "all levels",
Self::Debug => "debug and above",
Self::Info => "info and above",
}
}
}
/// Instance log tail included in an export, in bytes.
const LOG_EXPORT_INSTANCE_LOG_TAIL_BYTES: u64 = 512 * 1024;
/// Export launcher logs (filtered by time range and level) plus optional
/// system information, the most recent instance log, and a crash analysis
/// summary into a ZIP archive.
#[tauri::command]
pub async fn export_launcher_logs(
output_path: PathBuf,
range: LogExportRange,
level: LogExportLevel,
include_system_info: bool,
include_instance_logs: bool,
include_crash_analysis: bool,
) -> Result<()> {
// Censoring needs the app state (credentials, IPs). Without it an export
// would silently ship secrets, so fail rather than degrade.
let state = theseus::State::get().await?;
let archive = tokio::fs::File::create(&output_path).await?;
let mut writer = ZipFileWriter::with_tokio(archive);
let (exported_logs, skipped_logs) =
write_exported_logs(&mut writer, range, level, &state).await?;
let mut manifest = format!(
"Starlight Launcher log export\n\
Exported at: {}\n\
App version: {}\n\
Time range: {}\n\
Level filter: {}\n\
System information: {}\n\
Recent instance log: {}\n\
Crash analysis: {}\n\
Log files: {exported_logs}\n\n\
Access tokens, Minecraft tokens, and IP addresses are replaced with placeholders.\n",
chrono::Local::now().to_rfc3339(),
env!("CARGO_PKG_VERSION"),
range.label(),
level.label(),
if include_system_info {
"included"
} else {
"omitted"
},
if include_instance_logs {
"included"
} else {
"omitted"
},
if include_crash_analysis {
"included"
} else {
"omitted"
},
);
if !skipped_logs.is_empty() {
manifest.push_str("\nSkipped unreadable log files:\n");
for name in &skipped_logs {
manifest.push_str(&format!("- {name}\n"));
}
}
write_zip_entry(&mut writer, "manifest.txt", manifest.as_bytes()).await?;
if include_system_info {
let environment = build_environment_report();
let environment = censor_export_text(environment, &state).await?;
write_zip_entry(
&mut writer,
"system-information.txt",
environment.as_bytes(),
)
.await?;
}
let recent_instance = if include_instance_logs || include_crash_analysis {
newest_instance_log(&state).await
} else {
None
};
if include_instance_logs
&& let Some((instance_id, path)) = recent_instance.as_ref()
{
let tail = read_file_tail(path, LOG_EXPORT_INSTANCE_LOG_TAIL_BYTES)?;
let tail = censor_export_text(tail, &state).await?;
write_zip_entry(
&mut writer,
&format!("minecraft/{instance_id}/latest.log"),
tail.as_bytes(),
)
.await?;
}
if include_crash_analysis
&& let Some((instance_id, _)) = recent_instance.as_ref()
&& let Ok(analysis) = theseus::logs::analyze_crash(instance_id).await
&& (analysis.crashed || !analysis.findings.is_empty())
&& let Ok(report) = serde_json::to_vec_pretty(&analysis)
{
// The analysis carries raw log text and Windows event messages, so it
// goes through the same censoring as the exported logs.
let report = censor_export_text(
String::from_utf8_lossy(&report).into_owned(),
&state,
)
.await?;
write_zip_entry(
&mut writer,
&format!("minecraft/{instance_id}/crash-analysis.json"),
report.as_bytes(),
)
.await?;
}
writer.close().await.map_err(zip_error)?;
Ok(())
}
/// Writes the matching launcher logs and reports how many were written plus
/// the names of any files that could not be read.
async fn write_exported_logs(
writer: &mut ZipFileWriter<tokio::fs::File>,
range: LogExportRange,
level: LogExportLevel,
state: &theseus::State,
) -> Result<(usize, Vec<String>)> {
let Some(directories) = DirectoryInfo::global_handle_if_ready() else {
return Ok((0, Vec::new()));
};
let Some(logs_dir) = directories.launcher_logs_dir() else {
return Ok((0, Vec::new()));
};
if !tokio::fs::try_exists(&logs_dir).await? {
return Ok((0, Vec::new()));
}
let mut entries = tokio::fs::read_dir(&logs_dir).await?;
let mut paths = Vec::new();
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
let is_session_log =
path.file_name().and_then(|name| name.to_str()).is_some_and(
|name| name.starts_with("session_") && name.ends_with(".log"),
);
if is_session_log && entry.file_type().await?.is_file() {
paths.push(path);
}
}
paths.sort();
let mut exported = 0;
let mut skipped = Vec::new();
for path in paths {
let file_name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| "session.log".to_string());
// A single unreadable file must not lose the whole report.
let Ok(contents) = tokio::fs::read(&path).await else {
skipped.push(file_name);
continue;
};
let filtered = theseus::filter_log_contents(
&contents,
range.max_age(),
level.minimum(),
);
let text = String::from_utf8_lossy(&filtered).into_owned();
let censored = censor_export_text(text, state).await?;
write_zip_entry(
writer,
&format!("launcher_logs/{file_name}"),
censored.as_bytes(),
)
.await?;
exported += 1;
}
Ok((exported, skipped))
}
/// Replaces credentials and IP addresses with placeholders. Censoring failures
/// propagate so an export never ships unredacted content.
async fn censor_export_text(
text: String,
state: &theseus::State,
) -> Result<String> {
Ok(theseus::install::censor_shared_text(text, state).await?)
}
fn build_environment_report() -> String {
format!(
"Starlight Launcher environment\n\
App version: {}\n\
Operating system: {}\n\
Architecture: {}\n",
env!("CARGO_PKG_VERSION"),
std::env::consts::OS,
std::env::consts::ARCH,
)
}
/// The instance whose log was written most recently, if any.
async fn newest_instance_log(
state: &theseus::State,
) -> Option<(String, PathBuf)> {
let instances_dir = state.directories.instances_dir();
let mut entries = tokio::fs::read_dir(&instances_dir).await.ok()?;
let mut newest: Option<(std::time::SystemTime, String, PathBuf)> = None;
while let Some(entry) = entries.next_entry().await.ok()? {
if !entry.file_type().await.ok()?.is_dir() {
continue;
}
let log_path = entry.path().join("logs").join("latest.log");
let Ok(metadata) = tokio::fs::metadata(&log_path).await else {
continue;
};
let Ok(modified) = metadata.modified() else {
continue;
};
let is_newer = newest
.as_ref()
.is_none_or(|(newest_modified, ..)| modified > *newest_modified);
if is_newer {
let id = entry.file_name().to_string_lossy().into_owned();
newest = Some((modified, id, log_path));
}
}
newest.map(|(_, id, path)| (id, path))
}
fn read_file_tail(path: &Path, max_bytes: u64) -> Result<String> {
use std::io::{Read, Seek, SeekFrom};
let mut file = std::fs::File::open(path)?;
let length = file.metadata()?.len();
if length > max_bytes {
file.seek(SeekFrom::Start(length - max_bytes))?;
}
let mut contents = Vec::new();
file.read_to_end(&mut contents)?;
Ok(String::from_utf8_lossy(&contents).into_owned())
}
async fn write_zip_file(
writer: &mut ZipFileWriter<tokio::fs::File>,
filename: &str,
+2 -5
View File
@@ -324,12 +324,9 @@ async fn initialize_state(app: tauri::AppHandle) -> api::Result<()> {
/// external game-directory root for the one-click StarLight install flow.
#[tauri::command]
fn get_launcher_root_dir() -> api::Result<String> {
let exe = std::env::current_exe().map_err(|error| {
theseus::Error::from(theseus::ErrorKind::FSError(error.to_string()))
})?;
let dir = exe.parent().ok_or_else(|| {
let dir = theseus::default_game_dir_root().ok_or_else(|| {
theseus::Error::from(theseus::ErrorKind::FSError(
"Launcher executable has no parent directory".to_string(),
"Could not determine a default game directory root".to_string(),
))
})?;
Ok(dir.to_string_lossy().into_owned())
+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.2-beta4"
version = "1.0.2-beta7"
edition.workspace = true
[dependencies]
@@ -0,0 +1,26 @@
CREATE TABLE log_share_settings (
id INTEGER NOT NULL CHECK (id = 0),
share_provider TEXT NOT NULL DEFAULT 'logshare',
ai_source TEXT NOT NULL DEFAULT 'logshare',
auto_upload INTEGER NOT NULL DEFAULT TRUE,
multi_file INTEGER NOT NULL DEFAULT TRUE,
no_storage INTEGER NOT NULL DEFAULT FALSE,
show_progress INTEGER NOT NULL DEFAULT TRUE,
PRIMARY KEY (id)
);
INSERT INTO log_share_settings (id) VALUES (0);
CREATE TABLE shared_logs (
id TEXT NOT NULL PRIMARY KEY,
url TEXT NOT NULL,
raw TEXT NOT NULL,
token TEXT NOT NULL,
provider TEXT NOT NULL DEFAULT 'logshare',
instance_id TEXT NULL,
instance_name TEXT NULL,
truncated INTEGER NOT NULL DEFAULT FALSE,
created_at INTEGER NOT NULL
);
CREATE INDEX shared_logs_created_at_idx ON shared_logs (created_at DESC);
+1 -1
View File
@@ -19,7 +19,7 @@ use uuid::Uuid;
use crate::{ErrorKind, State};
const CATALOG_SOURCE: &str = "LobeHub 906b10e03029648655e0257bda4f785a9e0973f0";
const CATALOG_SOURCE: &str = "LobeHub 6c7a6fb033e443bc27bf34cbd5509ab3db7f22f3";
const KEYRING_PREFIX: &str = "ai-provider";
const OAUTH_CREDENTIAL: &str = "oauth";
const API_KEY_CREDENTIAL: &str = "api-key";
+261
View File
@@ -0,0 +1,261 @@
use crate::event::emit::emit_instance_groups_changed;
use crate::state::instance_groups;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use uuid::Uuid;
const MAX_GROUP_NAME_LENGTH: usize = 256;
pub const FAVORITES_GROUP_ID: &str = instance_groups::FAVORITES_GROUP_ID;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct InstanceGroup {
pub id: String,
pub name: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct InstanceGroupMembershipUpdate {
pub instance_id: String,
pub group_ids: Vec<String>,
}
fn validate_group_name(name: &str) -> crate::Result<&str> {
let name = name.trim();
if name.is_empty() {
return Err(crate::ErrorKind::InputError(
"Group name cannot be empty".to_string(),
)
.into());
}
if name.chars().count() > MAX_GROUP_NAME_LENGTH {
return Err(crate::ErrorKind::InputError(format!(
"Group name cannot exceed {MAX_GROUP_NAME_LENGTH} characters"
))
.into());
}
if name.eq_ignore_ascii_case("none") {
return Err(crate::ErrorKind::InputError(
"Group name cannot be None".to_string(),
)
.into());
}
Ok(name)
}
fn normalize_membership_updates(
mut updates: Vec<InstanceGroupMembershipUpdate>,
) -> crate::Result<Vec<InstanceGroupMembershipUpdate>> {
let mut instance_ids = HashSet::new();
for update in &mut updates {
if !instance_ids.insert(update.instance_id.clone()) {
return Err(crate::ErrorKind::InputError(format!(
"Duplicate instance {} in group membership update",
update.instance_id
))
.into());
}
let mut group_ids = HashSet::new();
update
.group_ids
.retain(|group_id| group_ids.insert(group_id.clone()));
}
Ok(updates)
}
pub async fn list_groups() -> crate::Result<Vec<InstanceGroup>> {
Ok(instance_groups::list()
.into_iter()
.map(|group| InstanceGroup {
id: group.id,
name: group.name,
})
.collect())
}
pub async fn create_group(name: String) -> crate::Result<InstanceGroup> {
let name = validate_group_name(&name)?;
let id = Uuid::new_v4().to_string();
instance_groups::create(&id, name);
Ok(InstanceGroup {
id,
name: name.to_string(),
})
}
pub async fn set_group_order(group_ids: Vec<String>) -> crate::Result<()> {
instance_groups::set_order(&group_ids);
Ok(())
}
pub async fn set_group_memberships(
updates: Vec<InstanceGroupMembershipUpdate>,
) -> crate::Result<()> {
if updates.is_empty() {
return Ok(());
}
let updates = normalize_membership_updates(updates)?;
// Note: the instances themselves are deliberately not validated here.
// JSON-backed instances (`local:` ids) have no row in the `instances` table,
// and requiring one is what used to make grouping them fail outright.
let unique_group_ids = updates
.iter()
.flat_map(|update| update.group_ids.iter())
.collect::<HashSet<_>>();
for group_id in unique_group_ids {
if !instance_groups::group_exists(group_id) {
return Err(crate::ErrorKind::InputError(format!(
"Unknown instance group {group_id}"
))
.into());
}
}
instance_groups::set_memberships(
&updates
.iter()
.map(|update| {
(update.instance_id.clone(), update.group_ids.clone())
})
.collect::<Vec<_>>(),
);
let instance_ids = updates
.into_iter()
.map(|update| update.instance_id)
.collect::<Vec<_>>();
emit_instance_groups_changed(&instance_ids).await?;
Ok(())
}
pub async fn rename_group(
id: String,
new_name: String,
) -> crate::Result<InstanceGroup> {
if id == FAVORITES_GROUP_ID {
return Err(crate::ErrorKind::InputError(
"Favorites cannot be renamed".to_string(),
)
.into());
}
let new_name = validate_group_name(&new_name)?;
let Some(instance_ids) = instance_groups::rename(&id, new_name) else {
return Err(crate::ErrorKind::InputError(format!(
"Unknown instance group {id}"
))
.into());
};
emit_instance_groups_changed(&instance_ids).await?;
Ok(InstanceGroup {
id,
name: new_name.to_string(),
})
}
pub async fn delete_group(id: String) -> crate::Result<()> {
if id == FAVORITES_GROUP_ID {
return Err(crate::ErrorKind::InputError(
"Favorites cannot be deleted".to_string(),
)
.into());
}
let Some(instance_ids) = instance_groups::delete(&id) else {
return Err(crate::ErrorKind::InputError(format!(
"Unknown instance group {id}"
))
.into());
};
emit_instance_groups_changed(&instance_ids).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::{
FAVORITES_GROUP_ID, InstanceGroupMembershipUpdate,
MAX_GROUP_NAME_LENGTH, normalize_membership_updates,
validate_group_name,
};
#[test]
fn group_name_validation_trims_valid_names() {
assert_eq!(validate_group_name(" My group ").unwrap(), "My group");
}
#[test]
fn group_name_validation_rejects_empty_names() {
assert!(validate_group_name(" ").is_err());
}
#[test]
fn group_name_validation_rejects_reserved_name() {
assert!(validate_group_name("NoNe").is_err());
}
#[test]
fn group_name_validation_allows_favorites() {
assert_eq!(validate_group_name("Favorites").unwrap(), "Favorites");
}
#[test]
fn group_name_validation_rejects_long_names() {
assert!(
validate_group_name(&"a".repeat(MAX_GROUP_NAME_LENGTH + 1))
.is_err()
);
}
#[test]
fn favorites_group_id_is_stable() {
assert_eq!(FAVORITES_GROUP_ID, "group:favorites");
}
#[test]
fn membership_updates_reject_duplicate_instances() {
let updates = vec![
InstanceGroupMembershipUpdate {
instance_id: "instance".to_string(),
group_ids: vec!["first".to_string()],
},
InstanceGroupMembershipUpdate {
instance_id: "instance".to_string(),
group_ids: vec!["second".to_string()],
},
];
assert!(normalize_membership_updates(updates).is_err());
}
#[test]
fn membership_updates_deduplicate_groups() {
let updates =
normalize_membership_updates(vec![InstanceGroupMembershipUpdate {
instance_id: "instance".to_string(),
group_ids: vec![
"a".to_string(),
"b".to_string(),
"a".to_string(),
"b".to_string(),
],
}])
.unwrap();
assert_eq!(updates[0].group_ids, &["a", "b"]);
}
}
+6
View File
@@ -5,6 +5,7 @@ mod content;
mod core_components;
mod export_mrpack;
mod get;
mod groups;
mod home;
mod install;
mod lifecycle;
@@ -72,6 +73,11 @@ pub use self::export_mrpack::{
create_mrpack_json, export_mrpack, get_pack_export_candidates,
};
pub use self::get::{get, get_many, list};
pub use self::groups::{
FAVORITES_GROUP_ID, InstanceGroup, InstanceGroupMembershipUpdate,
create_group, delete_group, list_groups, rename_group,
set_group_memberships, set_group_order,
};
pub use self::home::{
get_daily_playtime, get_daily_playtime_details, set_pinned,
};
+270 -240
View File
@@ -1,5 +1,5 @@
{
"source": "LobeHub 906b10e03029648655e0257bda4f785a9e0973f0 model-bank chat models",
"source": "LobeHub 6c7a6fb033e443bc27bf34cbd5509ab3db7f22f3 model-bank chat models",
"providers": {
"ai21": [
{
@@ -203,6 +203,16 @@
}
],
"aihubmix": [
{
"id": "gpt-6-sol",
"name": "GPT-6 Sol",
"enabled": true
},
{
"id": "gpt-6-luna",
"name": "GPT-6 Luna",
"enabled": true
},
{
"id": "gpt-5.5",
"name": "GPT-5.5",
@@ -343,6 +353,11 @@
"name": "ChatGPT-4o",
"enabled": false
},
{
"id": "grok-4.7",
"name": "Grok 4.7",
"enabled": true
},
{
"id": "grok-4-20-non-reasoning",
"name": "Grok 4.20 (Non-Reasoning)",
@@ -368,6 +383,11 @@
"name": "Grok 3 Mini",
"enabled": false
},
{
"id": "claude-opus-5-5",
"name": "Claude Opus 5.5",
"enabled": true
},
{
"id": "claude-opus-4-7",
"name": "Claude Opus 4.7",
@@ -383,11 +403,6 @@
"name": "Claude Opus 4.5",
"enabled": false
},
{
"id": "claude-opus-4-1-20250805",
"name": "Claude Opus 4.1",
"enabled": false
},
{
"id": "claude-sonnet-4-6",
"name": "Claude Sonnet 4.6",
@@ -403,6 +418,21 @@
"name": "Claude Haiku 4.5",
"enabled": true
},
{
"id": "mimo-v2.6-pro",
"name": "MiMo-V2.6 Pro",
"enabled": true
},
{
"id": "mimo-v2.6-pro-ultraspeed",
"name": "MiMo-V2.6 Pro UltraSpeed",
"enabled": true
},
{
"id": "mimo-v2.6-flash",
"name": "MiMo-V2.6 Flash",
"enabled": true
},
{
"id": "DeepSeek-V3.1-Think",
"name": "DeepSeek V3.1 (Think)",
@@ -542,11 +572,6 @@
"name": "Ring-2.6-1T",
"enabled": true
},
{
"id": "Ring-2.5-1T",
"name": "Ring-2.5-1T",
"enabled": false
},
{
"id": "Ling-3.0-flash",
"name": "Ling-3.0-flash",
@@ -561,14 +586,14 @@
"id": "Ling-2.6-flash",
"name": "Ling-2.6-flash",
"enabled": false
},
{
"id": "Ling-2.5-1T",
"name": "Ling-2.5-1T",
"enabled": false
}
],
"anthropic": [
{
"id": "claude-opus-5-5",
"name": "Claude Opus 5.5",
"enabled": true
},
{
"id": "claude-fable-5-1",
"name": "Claude Fable 5.1",
@@ -623,14 +648,24 @@
"id": "claude-haiku-4-5-20251001",
"name": "Claude Haiku 4.5",
"enabled": true
},
{
"id": "claude-opus-4-1-20250805",
"name": "Claude Opus 4.1",
"enabled": false
}
],
"azure": [
{
"id": "gpt-6-astra",
"name": "GPT-6 Astra",
"enabled": true
},
{
"id": "gpt-6-sol",
"name": "GPT-6 Sol",
"enabled": true
},
{
"id": "gpt-6-luna",
"name": "GPT-6 Luna",
"enabled": true
},
{
"id": "gpt-5.4",
"name": "GPT-5.4",
@@ -914,6 +949,11 @@
}
],
"bedrock": [
{
"id": "global.anthropic.claude-opus-5-5",
"name": "Claude Opus 5.5",
"enabled": true
},
{
"id": "global.anthropic.claude-opus-4-7",
"name": "Claude Opus 4.7",
@@ -1030,14 +1070,29 @@
"id": "gpt-oss-120b",
"name": "GPT OSS 120B",
"enabled": false
},
{
"id": "zai-glm-4.7",
"name": "GLM-4.7",
"enabled": false
}
],
"chatgpt": [
{
"id": "gpt-6.1-sol",
"name": "GPT-6.1 Sol",
"enabled": true
},
{
"id": "gpt-6-astra",
"name": "GPT-6 Astra",
"enabled": true
},
{
"id": "gpt-6-sol",
"name": "GPT-6 Sol",
"enabled": true
},
{
"id": "gpt-6-luna",
"name": "GPT-6 Luna",
"enabled": true
},
{
"id": "gpt-5.6-sol",
"name": "GPT-5.6 Sol",
@@ -1056,7 +1111,7 @@
{
"id": "gpt-5.5",
"name": "GPT-5.5",
"enabled": true
"enabled": false
}
],
"cloudflare": [
@@ -1883,10 +1938,15 @@
"name": "Gemini Flash-Lite Latest",
"enabled": false
},
{
"id": "gemini-3.8-flash",
"name": "Gemini 3.8 Flash",
"enabled": true
},
{
"id": "gemini-3.7-flash",
"name": "Gemini 3.7 Flash",
"enabled": true
"enabled": false
},
{
"id": "gemini-3.6-flash",
@@ -1972,26 +2032,6 @@
"id": "gemini-2.5-flash-lite",
"name": "Gemini 2.5 Flash-Lite",
"enabled": false
},
{
"id": "gemini-2.0-flash",
"name": "Gemini 2.0 Flash",
"enabled": false
},
{
"id": "gemini-2.0-flash-001",
"name": "Gemini 2.0 Flash 001",
"enabled": false
},
{
"id": "gemini-2.0-flash-lite",
"name": "Gemini 2.0 Flash-Lite",
"enabled": false
},
{
"id": "gemini-2.0-flash-lite-001",
"name": "Gemini 2.0 Flash-Lite 001",
"enabled": false
}
],
"groq": [
@@ -2005,10 +2045,15 @@
"name": "Compound Mini",
"enabled": false
},
{
"id": "qwen/qwen3.8-27b",
"name": "Qwen3.8 27B",
"enabled": true
},
{
"id": "qwen/qwen3.6-27b",
"name": "Qwen3.6 27B",
"enabled": true
"enabled": false
},
{
"id": "minimaxai/minimax-m2.7",
@@ -2025,16 +2070,6 @@
"name": "GPT OSS 20B",
"enabled": false
},
{
"id": "llama-3.1-8b-instant",
"name": "Llama 3.1 8B Instant",
"enabled": false
},
{
"id": "llama-3.3-70b-versatile",
"name": "Llama 3.3 70B Versatile",
"enabled": false
},
{
"id": "meta-llama/llama-prompt-guard-2-22m",
"name": "Llama Prompt Guard 2 22M",
@@ -3575,13 +3610,13 @@
],
"mistral": [
{
"id": "mistral-medium-3.5",
"name": "Mistral Medium 3.5",
"enabled": true
"id": "zai-glm-5-2",
"name": "Z.ai GLM 5.2",
"enabled": false
},
{
"id": "devstral-2512",
"name": "Devstral 2",
"id": "mistral-medium-3.5",
"name": "Mistral Medium 3.5",
"enabled": true
},
{
@@ -3589,61 +3624,21 @@
"name": "Devstral Small 2",
"enabled": false
},
{
"id": "mistral-medium-2508",
"name": "Mistral Medium 3.1",
"enabled": false
},
{
"id": "magistral-medium-2509",
"name": "Magistral Medium 1.2",
"enabled": false
},
{
"id": "magistral-small-2509",
"name": "Magistral Small 1.2",
"enabled": false
},
{
"id": "open-mistral-nemo",
"name": "Mistral Nemo",
"enabled": false
},
{
"id": "mistral-small-2603",
"name": "Mistral Small 4",
"enabled": false
},
{
"id": "mistral-small-2506",
"name": "Mistral Small 3.2",
"enabled": false
},
{
"id": "mistral-large-2512",
"name": "Mistral Large 3",
"enabled": true
},
{
"id": "mistral-large-2411",
"name": "Mistral Large 2.1",
"enabled": false
},
{
"id": "codestral-latest",
"name": "Codestral 2508",
"enabled": false
},
{
"id": "pixtral-large-latest",
"name": "Pixtral Large",
"enabled": false
},
{
"id": "pixtral-12b-2409",
"name": "Pixtral 12B",
"enabled": false
},
{
"id": "ministral-3b-latest",
"name": "Ministral 3B",
@@ -3653,16 +3648,6 @@
"id": "ministral-8b-latest",
"name": "Ministral 8B",
"enabled": false
},
{
"id": "open-codestral-mamba",
"name": "Codestral Mamba",
"enabled": false
},
{
"id": "labs-leanstral-2603",
"name": "Leanstral",
"enabled": false
}
],
"modelscope": [
@@ -3676,30 +3661,10 @@
"name": "Qwen3 Next 80B A3B Instruct",
"enabled": false
},
{
"id": "deepseek-ai/DeepSeek-V3.2",
"name": "DeepSeek V3.2",
"enabled": true
},
{
"id": "deepseek-ai/DeepSeek-V3.2-Exp",
"name": "DeepSeek V3.2 Exp",
"enabled": false
},
{
"id": "deepseek-ai/DeepSeek-V3.1",
"name": "DeepSeek V3.1",
"enabled": false
},
{
"id": "Qwen/Qwen3-235B-A22B",
"name": "Qwen3 235B A22B",
"enabled": false
},
{
"id": "Qwen/Qwen3-32B",
"name": "Qwen3 32B",
"enabled": false
}
],
"moonshot": [
@@ -3722,41 +3687,6 @@
"id": "kimi-k2.6",
"name": "Kimi K2.6",
"enabled": false
},
{
"id": "kimi-k2.5",
"name": "Kimi K2.5",
"enabled": false
},
{
"id": "moonshot-v1-8k",
"name": "Moonshot V1 8K",
"enabled": false
},
{
"id": "moonshot-v1-32k",
"name": "Moonshot V1 32K",
"enabled": false
},
{
"id": "moonshot-v1-128k",
"name": "Moonshot V1 128K",
"enabled": false
},
{
"id": "moonshot-v1-8k-vision-preview",
"name": "Moonshot V1 8K Vision Preview",
"enabled": false
},
{
"id": "moonshot-v1-32k-vision-preview",
"name": "Moonshot V1 32K Vision Preview",
"enabled": false
},
{
"id": "moonshot-v1-128k-vision-preview",
"name": "Moonshot V1 128K Vision Preview",
"enabled": false
}
],
"nebius": [
@@ -4424,16 +4354,6 @@
"name": "Qwen3.5 397B A17B",
"enabled": false
},
{
"id": "minimax-m2.5",
"name": "MiniMax M2.5",
"enabled": false
},
{
"id": "kimi-k2.5",
"name": "Kimi K2.5",
"enabled": false
},
{
"id": "gpt-oss:20b",
"name": "GPT-OSS 20B",
@@ -4451,6 +4371,26 @@
}
],
"openai": [
{
"id": "gpt-6.1-sol",
"name": "GPT-6.1 Sol",
"enabled": true
},
{
"id": "gpt-6-astra",
"name": "GPT-6 Astra",
"enabled": true
},
{
"id": "gpt-6-sol",
"name": "GPT-6 Sol",
"enabled": true
},
{
"id": "gpt-6-luna",
"name": "GPT-6 Luna",
"enabled": true
},
{
"id": "chat-latest",
"name": "Chat Latest",
@@ -4474,7 +4414,7 @@
{
"id": "gpt-5.5",
"name": "GPT-5.5",
"enabled": true
"enabled": false
},
{
"id": "gpt-5.5-pro",
@@ -4484,7 +4424,7 @@
{
"id": "gpt-5.4",
"name": "GPT-5.4",
"enabled": true
"enabled": false
},
{
"id": "gpt-5.4-pro",
@@ -4494,7 +4434,7 @@
{
"id": "gpt-5.4-mini",
"name": "GPT-5.4 mini",
"enabled": true
"enabled": false
},
{
"id": "gpt-5.4-nano",
@@ -4708,6 +4648,16 @@
"name": "MiniMax M3",
"enabled": false
},
{
"id": "muse-spark-1.2-contributor",
"name": "Muse Spark 1.2 Contributor",
"enabled": false
},
{
"id": "muse-spark-1.3-contributor",
"name": "Muse Spark 1.3 Contributor",
"enabled": true
},
{
"id": "qwen3.6-plus",
"name": "Qwen3.6 Plus",
@@ -4912,6 +4862,41 @@
"name": "Auto (best for prompt)",
"enabled": true
},
{
"id": "anthropic/claude-opus-5.5",
"name": "Claude Opus 5.5",
"enabled": true
},
{
"id": "openai/gpt-6-sol",
"name": "GPT-6 Sol",
"enabled": true
},
{
"id": "openai/gpt-6-luna",
"name": "GPT-6 Luna",
"enabled": true
},
{
"id": "x-ai/grok-4.7",
"name": "Grok 4.7",
"enabled": true
},
{
"id": "xiaomi/mimo-v2.6-pro",
"name": "MiMo-V2.6 Pro",
"enabled": true
},
{
"id": "xiaomi/mimo-v2.6-pro-ultraspeed",
"name": "MiMo-V2.6 Pro UltraSpeed",
"enabled": true
},
{
"id": "xiaomi/mimo-v2.6-flash",
"name": "MiMo-V2.6 Flash",
"enabled": true
},
{
"id": "deepseek/deepseek-chat-v3.1",
"name": "DeepSeek V3.1",
@@ -5260,6 +5245,26 @@
}
],
"qwen": [
{
"id": "deepseek-v4-pro-0813",
"name": "DeepSeek V4 Pro 0813",
"enabled": false
},
{
"id": "deepseek-v4-flash-0731",
"name": "DeepSeek V4 Flash 0731",
"enabled": false
},
{
"id": "qwen3.8-max-0902",
"name": "Qwen3.8 Max 0902",
"enabled": true
},
{
"id": "qwen3.8-max",
"name": "Qwen3.8 Max",
"enabled": true
},
{
"id": "kimi-k2.6",
"name": "Kimi K2.6",
@@ -5490,10 +5495,15 @@
"name": "QwQ Plus",
"enabled": false
},
{
"id": "qwen3.8-flash",
"name": "Qwen3.8 Flash",
"enabled": true
},
{
"id": "qwen3.7-flash",
"name": "Qwen3.7 Flash",
"enabled": true
"enabled": false
},
{
"id": "qwen3.6-flash",
@@ -5802,75 +5812,40 @@
}
],
"sambanova": [
{
"id": "MiniMax-M2.7",
"name": "MiniMax M2.7",
"enabled": false
},
{
"id": "DeepSeek-V3.1",
"name": "DeepSeek V3.1",
"enabled": false
},
{
"id": "Meta-Llama-3.3-70B-Instruct",
"name": "Meta Llama 3.3 70B Instruct",
"enabled": true
},
{
"id": "Meta-Llama-3.2-1B-Instruct",
"name": "Meta Llama 3.2 1B Instruct",
"enabled": false
},
{
"id": "Meta-Llama-3.2-3B-Instruct",
"name": "Meta Llama 3.2 3B Instruct",
"enabled": false
},
{
"id": "Llama-3.2-11B-Vision-Instruct",
"name": "Meta Llama 3.2 11B Vision Instruct",
"id": "gpt-oss-120b",
"name": "GPT OSS 120B",
"enabled": true
},
{
"id": "Llama-3.2-90B-Vision-Instruct",
"name": "Meta Llama 3.2 90B Vision Instruct",
"id": "MiniMax-M3",
"name": "MiniMax M3",
"enabled": true
},
{
"id": "Meta-Llama-3.1-8B-Instruct",
"name": "Meta Llama 3.1 8B Instruct",
"id": "DeepSeek-V3.2",
"name": "DeepSeek V3.2",
"enabled": false
},
{
"id": "Meta-Llama-3.1-70B-Instruct",
"name": "Meta Llama 3.1 70B Instruct",
"id": "gemma-4-31B-it",
"name": "Gemma 4 31B IT",
"enabled": false
},
{
"id": "Meta-Llama-3.1-405B-Instruct",
"name": "Meta Llama 3.1 405B Instruct",
"enabled": false
},
{
"id": "Llama-3.1-Tulu-3-405B",
"name": "Llama 3.1 Tulu 3 405B",
"enabled": false
},
{
"id": "DeepSeek-R1",
"name": "DeepSeek R1",
"enabled": false
},
{
"id": "DeepSeek-R1-Distill-Llama-70B",
"name": "DeepSeek R1 Distill Llama 70B",
"enabled": true
},
{
"id": "QwQ-32B-Preview",
"name": "QwQ 32B Preview",
"enabled": true
},
{
"id": "Qwen2.5-72B-Instruct",
"name": "Qwen2.5 72B Instruct",
"enabled": true
},
{
"id": "Qwen2.5-Coder-32B-Instruct",
"name": "Qwen2.5 Coder 32B Instruct",
"enabled": true
}
],
"search1api": [
@@ -6262,6 +6237,11 @@
}
],
"stepfun": [
{
"id": "step-5-preview",
"name": "Step 5 Preview",
"enabled": true
},
{
"id": "step-3.7-flash",
"name": "Step 3.7 Flash",
@@ -6407,6 +6387,16 @@
}
],
"supergrok": [
{
"id": "grok-4.7",
"name": "Grok 4.7",
"enabled": true
},
{
"id": "grok-4.6",
"name": "Grok 4.6",
"enabled": true
},
{
"id": "grok-4.5",
"name": "Grok 4.5",
@@ -7166,10 +7156,15 @@
}
],
"vertexai": [
{
"id": "gemini-3.8-flash",
"name": "Gemini 3.8 Flash",
"enabled": true
},
{
"id": "gemini-3.7-flash",
"name": "Gemini 3.7 Flash",
"enabled": true
"enabled": false
},
{
"id": "gemini-3.6-flash",
@@ -7345,20 +7340,30 @@
"name": "Doubao Seed 2.1 Turbo",
"enabled": true
},
{
"id": "deepseek-v4-pro-ga",
"name": "DeepSeek V4 Pro 0813",
"enabled": false
},
{
"id": "deepseek-v4-flash-ga",
"name": "DeepSeek V4 Flash 0731",
"enabled": false
},
{
"id": "glm-5-2",
"name": "GLM-5.2",
"enabled": true
"enabled": false
},
{
"id": "deepseek-v4-pro",
"name": "DeepSeek V4 Pro",
"enabled": true
"enabled": false
},
{
"id": "deepseek-v4-flash",
"name": "DeepSeek V4 Flash",
"enabled": true
"enabled": false
},
{
"id": "doubao-seed-2.0-pro",
@@ -7701,6 +7706,16 @@
}
],
"xai": [
{
"id": "grok-4.7",
"name": "Grok 4.7",
"enabled": true
},
{
"id": "grok-4.6",
"name": "Grok 4.6",
"enabled": true
},
{
"id": "grok-4.5",
"name": "Grok 4.5",
@@ -7728,6 +7743,21 @@
}
],
"xiaomimimo": [
{
"id": "mimo-v2.6-pro",
"name": "MiMo-V2.6 Pro",
"enabled": true
},
{
"id": "mimo-v2.6-pro-ultraspeed",
"name": "MiMo-V2.6 Pro UltraSpeed",
"enabled": true
},
{
"id": "mimo-v2.6-flash",
"name": "MiMo-V2.6 Flash",
"enabled": true
},
{
"id": "mimo-v2.5-pro",
"name": "MiMo-V2.5 Pro",
+109 -31
View File
@@ -1,6 +1,6 @@
use std::fmt::Write as _;
use std::io::{BufRead, Read, SeekFrom};
use std::path::Path;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use futures::TryFutureExt;
@@ -27,6 +27,15 @@ pub use crash_analysis::{
update_crash_analysis_ai_settings,
};
mod logshare;
pub use logshare::{
LogShareDeleteResponse, LogShareSettings, LogShareUploadResponse,
SharedLog, ai_analyze_direct, ai_analyze_stored, analyse_crash_direct,
delete_log, delete_shared_log, get_insights, get_log_share_settings,
list_shared_logs, record_shared_log, update_log_share_settings,
upload_crash,
};
#[derive(Serialize, Debug)]
pub struct Logs {
pub log_type: LogType,
@@ -39,6 +48,54 @@ pub struct Logs {
pub enum LogType {
InfoLog,
CrashReport,
JvmCrash,
LauncherLog,
}
fn isolated_minecraft_root(instance_root: &Path) -> Option<PathBuf> {
let versions_dir = instance_root.parent()?;
if versions_dir
.file_name()
.is_some_and(|name| name.eq_ignore_ascii_case("versions"))
{
versions_dir.parent().map(Path::to_path_buf)
} else {
None
}
}
fn log_directories_for_type(
state: &State,
game_dir: &Path,
log_type: LogType,
) -> Vec<PathBuf> {
match log_type {
LogType::InfoLog => vec![state.directories.game_logs_dir(game_dir)],
LogType::CrashReport => {
vec![state.directories.game_crash_reports_dir(game_dir)]
}
LogType::JvmCrash | LogType::LauncherLog => {
let mut directories = vec![game_dir.to_path_buf()];
if let Some(root) = isolated_minecraft_root(game_dir) {
directories.push(root);
}
directories
}
}
}
fn is_log_file_for_type(log_type: LogType, file_name: &str) -> bool {
match log_type {
LogType::JvmCrash => {
let lower = file_name.to_ascii_lowercase();
lower.starts_with("hs_err") && lower.ends_with(".log")
}
LogType::LauncherLog => matches!(
file_name.to_ascii_lowercase().as_str(),
"launcher_log.txt" | "latest_stdout.log"
),
_ => true,
}
}
const LOG_COMPACTION_THRESHOLD: usize = 20;
@@ -448,14 +505,11 @@ pub async fn get_logs_from_type(
.directories
.resolve_game_dir(&instance_path, game_dir_override.as_deref());
let logs_folder = match log_type {
LogType::InfoLog => state.directories.game_logs_dir(&game_dir),
LogType::CrashReport => {
state.directories.game_crash_reports_dir(&game_dir)
let mut seen_files = std::collections::HashSet::new();
for logs_folder in log_directories_for_type(&state, &game_dir, log_type) {
if !logs_folder.exists() {
continue;
}
};
if logs_folder.exists() {
for entry in std::fs::read_dir(&logs_folder)
.map_err(|e| IOError::with_path(e, &logs_folder))?
{
@@ -471,6 +525,12 @@ pub async fn get_logs_from_type(
}
if let Some(file_name) = path.file_name() {
let file_name = file_name.to_string_lossy().to_string();
if !is_log_file_for_type(log_type, &file_name) {
continue;
}
if !seen_files.insert(file_name.clone()) {
continue;
}
logs.push(
Logs::build(
log_type,
@@ -507,6 +567,20 @@ pub async fn get_logs(
&mut logs,
)
.await?;
get_logs_from_type(
instance_id,
LogType::JvmCrash,
clear_contents,
&mut logs,
)
.await?;
get_logs_from_type(
instance_id,
LogType::LauncherLog,
clear_contents,
&mut logs,
)
.await?;
let mut logs = logs.into_iter().collect::<crate::Result<Vec<Logs>>>()?;
logs.sort_by(|a, b| b.age.cmp(&a.age).then(b.filename.cmp(&a.filename)));
@@ -526,13 +600,15 @@ pub async fn get_logs_by_filename(
.directories
.resolve_game_dir(&instance_path, game_dir_override.as_deref());
let path = match log_type {
LogType::InfoLog => state.directories.game_logs_dir(&game_dir),
LogType::CrashReport => {
state.directories.game_crash_reports_dir(&game_dir)
}
}
.join(&filename);
let path = log_directories_for_type(&state, &game_dir, log_type)
.into_iter()
.map(|directory| directory.join(&filename))
.find(|path| path.is_file())
.ok_or_else(|| {
crate::ErrorKind::OtherError(format!(
"Log file not found: {filename}"
))
})?;
let metadata = std::fs::metadata(&path)?;
let age = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH);
@@ -546,14 +622,15 @@ async fn get_output_by_filename_from_path(
log_type: LogType,
file_name: &str,
) -> crate::Result<CensoredString> {
let logs_folder = match log_type {
LogType::InfoLog => state.directories.game_logs_dir(game_dir),
LogType::CrashReport => {
state.directories.game_crash_reports_dir(game_dir)
}
};
let path = logs_folder.join(file_name);
let path = log_directories_for_type(state, game_dir, log_type)
.into_iter()
.map(|directory| directory.join(file_name))
.find(|path| path.is_file())
.ok_or_else(|| {
crate::ErrorKind::OtherError(format!(
"Log file not found: {file_name}"
))
})?;
let credentials = Credentials::get_all(&state.pool)
.await?
@@ -650,14 +727,15 @@ pub async fn delete_logs_by_filename(
.directories
.resolve_game_dir(&instance_path, game_dir_override.as_deref());
let logs_folder = match log_type {
LogType::InfoLog => state.directories.game_logs_dir(&game_dir),
LogType::CrashReport => {
state.directories.game_crash_reports_dir(&game_dir)
}
};
let path = logs_folder.join(filename);
let path = log_directories_for_type(&state, &game_dir, log_type)
.into_iter()
.map(|directory| directory.join(filename))
.find(|path| path.is_file())
.ok_or_else(|| {
crate::ErrorKind::OtherError(format!(
"Log file not found: {filename}"
))
})?;
io::remove_file(&path).await?;
Ok(())
}
+649
View File
@@ -0,0 +1,649 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::CensoredString;
use super::crash_analysis::analyze_crash;
use crate::State;
use crate::emit_logshare_ai_event;
const LOGSHARE_BASE_URL: &str = "https://api.logshare.cn";
const LOGSHARE_AI_READ_TIMEOUT_SECS: u64 = 300;
const LOGSHARE_SOURCE_PREFIX: &str = "starlight";
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LogShareSettings {
pub share_provider: String,
pub ai_source: String,
pub auto_upload: bool,
pub multi_file: bool,
pub no_storage: bool,
pub show_progress: bool,
}
impl Default for LogShareSettings {
fn default() -> Self {
Self {
share_provider: "logshare".to_string(),
ai_source: "logshare".to_string(),
auto_upload: true,
multi_file: true,
no_storage: false,
show_progress: true,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SharedLog {
pub id: String,
pub url: String,
pub raw: String,
pub token: String,
pub provider: String,
pub instance_id: Option<String>,
pub instance_name: Option<String>,
pub truncated: bool,
pub created_at: i64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LogShareUploadResponse {
pub success: bool,
pub id: String,
pub url: String,
pub raw: String,
pub token: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LogShareDeleteResponse {
pub success: bool,
pub deleted: Vec<String>,
pub failed: Vec<String>,
}
#[derive(Serialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
struct UploadFile {
name: String,
content: String,
}
#[derive(Serialize, Debug, Clone)]
struct UploadBody {
content: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
files: Vec<UploadFile>,
source: String,
}
pub async fn get_log_share_settings() -> crate::Result<LogShareSettings> {
let state = State::get().await?;
let row = sqlx::query_as::<_, (String, String, i64, i64, i64, i64)>(
"SELECT share_provider, ai_source, auto_upload, multi_file, no_storage, show_progress FROM log_share_settings WHERE id = 0",
)
.fetch_one(&state.pool)
.await?;
Ok(LogShareSettings {
share_provider: row.0,
ai_source: row.1,
auto_upload: row.2 != 0,
multi_file: row.3 != 0,
no_storage: row.4 != 0,
show_progress: row.5 != 0,
})
}
pub async fn update_log_share_settings(
settings: LogShareSettings,
) -> crate::Result<()> {
let settings = normalize_settings(settings);
let state = State::get().await?;
sqlx::query(
"UPDATE log_share_settings SET share_provider = ?, ai_source = ?, auto_upload = ?, multi_file = ?, no_storage = ?, show_progress = ? WHERE id = 0",
)
.bind(&settings.share_provider)
.bind(&settings.ai_source)
.bind(settings.auto_upload)
.bind(settings.multi_file)
.bind(settings.no_storage)
.bind(settings.show_progress)
.execute(&state.pool)
.await?;
Ok(())
}
fn normalize_settings(mut settings: LogShareSettings) -> LogShareSettings {
if settings.share_provider != "logshare" {
settings.share_provider = "mclogs".to_string();
}
if settings.ai_source != "logshare" {
settings.ai_source = "custom".to_string();
}
settings
}
pub async fn list_shared_logs() -> crate::Result<Vec<SharedLog>> {
let state = State::get().await?;
let rows = sqlx::query_as::<_, (String, String, String, String, String, Option<String>, Option<String>, i64, i64)>(
"SELECT id, url, raw, token, provider, instance_id, instance_name, truncated, created_at FROM shared_logs ORDER BY created_at DESC",
)
.fetch_all(&state.pool)
.await?;
Ok(rows
.into_iter()
.map(|row| SharedLog {
id: row.0,
url: row.1,
raw: row.2,
token: row.3,
provider: row.4,
instance_id: row.5,
instance_name: row.6,
truncated: row.7 != 0,
created_at: row.8,
})
.collect())
}
pub async fn record_shared_log(log: SharedLog) -> crate::Result<()> {
let state = State::get().await?;
let created_at = log.created_at.max(now_seconds());
sqlx::query(
"INSERT INTO shared_logs (id, url, raw, token, provider, instance_id, instance_name, truncated, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET url = excluded.url, raw = excluded.raw, token = excluded.token, provider = excluded.provider, instance_id = excluded.instance_id, instance_name = excluded.instance_name, truncated = excluded.truncated",
)
.bind(&log.id)
.bind(&log.url)
.bind(&log.raw)
.bind(&log.token)
.bind(&log.provider)
.bind(&log.instance_id)
.bind(&log.instance_name)
.bind(log.truncated)
.bind(created_at)
.execute(&state.pool)
.await?;
Ok(())
}
async fn remove_shared_log_record(id: &str) -> crate::Result<()> {
let state = State::get().await?;
sqlx::query("DELETE FROM shared_logs WHERE id = ?")
.bind(id)
.execute(&state.pool)
.await?;
Ok(())
}
pub async fn delete_shared_log(id: String, token: String) -> crate::Result<()> {
let remote_result = delete_log(&id, &token).await;
if let Err(error) = remote_result {
tracing::warn!(
"Remote LogShare deletion failed for {id}; removing the local record anyway: {error}"
);
}
remove_shared_log_record(&id).await
}
fn now_seconds() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
fn source_identifier() -> String {
format!("{LOGSHARE_SOURCE_PREFIX}/{}", env!("CARGO_PKG_VERSION"))
}
struct CollectedCrashLog {
name: String,
content: CensoredString,
}
struct CollectedCrashLogs {
combined_log: CensoredString,
sources: Vec<CollectedCrashLog>,
}
async fn collect_crash_logs(
instance_id: &str,
) -> crate::Result<CollectedCrashLogs> {
let analysis = analyze_crash(instance_id).await?;
Ok(CollectedCrashLogs {
combined_log: analysis.combined_log,
sources: analysis
.sources
.into_iter()
.map(|source| CollectedCrashLog {
name: source.filename,
content: source.content,
})
.collect(),
})
}
async fn prepare_upload(instance_id: &str) -> crate::Result<UploadBody> {
let settings = get_log_share_settings().await?;
let logs = collect_crash_logs(instance_id).await?;
let combined = logs.combined_log.as_str().to_string();
let files = if settings.multi_file {
logs.sources
.iter()
.map(|source| UploadFile {
name: source.name.clone(),
content: source.content.as_str().to_string(),
})
.collect::<Vec<_>>()
} else {
Vec::new()
};
Ok(UploadBody {
content: combined,
files,
source: source_identifier(),
})
}
async fn request_client() -> crate::Result<reqwest::Client> {
let state = State::get().await?;
let proxy = state.proxy_config().await?;
let builder = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(30))
.read_timeout(Duration::from_secs(LOGSHARE_AI_READ_TIMEOUT_SECS))
.user_agent(crate::launcher_user_agent());
proxy.apply(builder)?.build().map_err(Into::into)
}
pub async fn upload_crash(
instance_id: &str,
) -> crate::Result<LogShareUploadResponse> {
let prepared = prepare_upload(instance_id).await?;
let client = request_client().await?;
let body_value = serde_json::to_value(&prepared)?;
let request = client
.post(format!("{LOGSHARE_BASE_URL}/v1/log"))
.header("Accept", "application/json")
.header("Accept-Encoding", "br, gzip");
let response = request.json(&body_value).send().await?;
let status = response.status();
let text = response.text().await?;
if !status.is_success() {
return Err(crate::ErrorKind::OtherError(format!(
"LogShare upload failed with HTTP {status}: {}",
text.chars().take(500).collect::<String>()
))
.into());
}
let value: Value = serde_json::from_str(&text).map_err(|_| {
crate::ErrorKind::OtherError(
"LogShare returned invalid JSON".to_string(),
)
})?;
if value.get("success").and_then(Value::as_bool) != Some(true) {
return Err(crate::ErrorKind::OtherError(format!(
"LogShare upload failed: {}",
value
.get("error")
.and_then(Value::as_str)
.unwrap_or("unknown error")
))
.into());
}
Ok(LogShareUploadResponse {
success: true,
id: value
.get("id")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
url: value
.get("url")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
raw: value
.get("raw")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
token: value
.get("token")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
})
}
pub async fn get_insights(id: &str) -> crate::Result<Value> {
let client = request_client().await?;
let response = client
.get(format!("{LOGSHARE_BASE_URL}/v1/insights/{id}"))
.header("Accept", "application/json")
.header("Accept-Encoding", "br, gzip")
.send()
.await?;
let status = response.status();
let text = response.text().await?;
if !status.is_success() {
return Err(crate::ErrorKind::OtherError(format!(
"LogShare analysis failed with HTTP {status}: {}",
text.chars().take(500).collect::<String>()
))
.into());
}
serde_json::from_str(&text).map_err(|_| {
crate::ErrorKind::OtherError(
"LogShare returned invalid insights JSON".to_string(),
)
.into()
})
}
pub async fn analyse_crash_direct(instance_id: &str) -> crate::Result<Value> {
let prepared = prepare_upload(instance_id).await?;
let client = request_client().await?;
let response = client
.post(format!("{LOGSHARE_BASE_URL}/v1/analyse"))
.header("Accept", "application/json")
.header("Accept-Encoding", "br, gzip")
.json(&prepared)
.send()
.await?;
let status = response.status();
let text = response.text().await?;
if !status.is_success() {
return Err(crate::ErrorKind::OtherError(format!(
"LogShare analysis failed with HTTP {status}: {}",
text.chars().take(500).collect::<String>()
))
.into());
}
serde_json::from_str(&text).map_err(|_| {
crate::ErrorKind::OtherError(
"LogShare returned invalid analysis JSON".to_string(),
)
.into()
})
}
pub async fn delete_log(
id: &str,
token: &str,
) -> crate::Result<LogShareDeleteResponse> {
let client = request_client().await?;
let response = client
.delete(format!("{LOGSHARE_BASE_URL}/v1/log/{id}"))
.bearer_auth(token)
.header("Accept", "application/json")
.header("Accept-Encoding", "br, gzip")
.send()
.await?;
let status = response.status();
let text = response.text().await?;
if !status.is_success() {
return Err(crate::ErrorKind::OtherError(format!(
"LogShare deletion failed with HTTP {status}: {}",
text.chars().take(500).collect::<String>()
))
.into());
}
serde_json::from_str(&text).map_err(|_| {
crate::ErrorKind::OtherError(
"LogShare returned invalid deletion JSON".to_string(),
)
.into()
})
}
pub async fn ai_analyze_stored(
instance_id: &str,
id: &str,
) -> crate::Result<String> {
let url = format!("{LOGSHARE_BASE_URL}/v1/ai/{id}");
stream_ai(instance_id, url, None).await
}
pub async fn ai_analyze_direct(instance_id: &str) -> crate::Result<String> {
let prepared = prepare_upload(instance_id).await?;
let url = format!("{LOGSHARE_BASE_URL}/v1/ai/analyse");
let body = serde_json::to_value(&prepared)?;
stream_ai(instance_id, url, Some(body)).await
}
async fn stream_ai(
instance_id: &str,
url: String,
body: Option<Value>,
) -> crate::Result<String> {
let settings = get_log_share_settings().await?;
let show_progress = settings.show_progress;
let client = request_client().await?;
let mut request = client
.request(
if body.is_some() {
reqwest::Method::POST
} else {
reqwest::Method::GET
},
url.as_str(),
)
.header("Accept", "text/event-stream")
.header("Accept-Encoding", "br, gzip");
if let Some(payload) = body {
request = request.json(&payload);
}
let response = request.send().await?;
let status = response.status();
if !status.is_success() {
if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
return Err(crate::ErrorKind::OtherError(
"LogAgent queue is full, please retry later".to_string(),
)
.into());
}
let text = response.text().await?;
return Err(crate::ErrorKind::OtherError(format!(
"LogAgent analysis failed with HTTP {status}: {}",
text.chars().take(500).collect::<String>()
))
.into());
}
let mut stream = response.bytes_stream();
let mut parser = SseParser::new();
let mut output = String::new();
loop {
let maybe = tokio::time::timeout(
Duration::from_secs(LOGSHARE_AI_READ_TIMEOUT_SECS),
stream.next(),
)
.await
.map_err(|_| {
crate::ErrorKind::OtherError(
"LogAgent analysis timed out".to_string(),
)
})?;
let Some(chunk) = maybe else {
break;
};
let chunk = chunk?;
for event in parser.feed(&chunk) {
if let Some(delta) = event.content {
output.push_str(&delta);
if show_progress {
emit_logshare_ai_event(
instance_id,
"delta",
json!({ "content": delta }),
)
.await?;
}
}
if let Some(status_event) = event.status_event {
if show_progress || status_event.event_type == "queued" {
emit_logshare_ai_event(
instance_id,
&status_event.event_type,
status_event.data,
)
.await?;
}
}
if let Some(message) = event.error {
return Err(crate::ErrorKind::OtherError(format!(
"LogAgent analysis failed: {message}"
))
.into());
}
if event.done {
return Ok(output);
}
}
}
// A stream that ended without `event: done` is acceptable as long as text
// was produced; otherwise it is a protocol error worth surfacing.
if output.is_empty() {
return Err(crate::ErrorKind::OtherError(
"LogAgent analysis ended without output".to_string(),
)
.into());
}
Ok(output)
}
struct ParsedEvent {
content: Option<String>,
status_event: Option<ParsedStatusEvent>,
done: bool,
error: Option<String>,
}
struct ParsedStatusEvent {
event_type: String,
data: Value,
}
struct SseParser {
buffer: Vec<u8>,
}
impl SseParser {
fn new() -> Self {
Self { buffer: Vec::new() }
}
fn feed(&mut self, chunk: &[u8]) -> Vec<ParsedEvent> {
self.buffer.extend_from_slice(chunk);
let mut events = Vec::new();
loop {
let lf_pos = find_bytes(&self.buffer, b"\n\n");
let crlf_pos = find_bytes(&self.buffer, b"\r\n\r\n");
let (pos, separator_len) = match (lf_pos, crlf_pos) {
(Some(lf_pos), Some(crlf_pos)) if crlf_pos < lf_pos => {
(crlf_pos, 4)
}
(Some(lf_pos), _) => (lf_pos, 2),
(None, Some(crlf_pos)) => (crlf_pos, 4),
(None, None) => break,
};
let block =
String::from_utf8_lossy(&self.buffer[..pos]).into_owned();
self.buffer.drain(..pos + separator_len);
if let Some(event) = parse_sse_block(&block) {
events.push(event);
}
}
events
}
}
fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack.windows(needle.len()).position(|w| w == needle)
}
fn parse_sse_block(block: &str) -> Option<ParsedEvent> {
let mut event_name: Option<String> = None;
let mut data_lines = Vec::new();
for line in block.lines() {
if let Some(rest) = line.strip_prefix("event:") {
event_name = Some(rest.trim().to_string());
} else if let Some(rest) = line.strip_prefix("data:") {
data_lines.push(rest.trim_start().to_string());
}
}
if event_name.is_none() && data_lines.is_empty() {
return None;
}
let data_text = data_lines.join("\n");
let event_name = event_name.as_deref().unwrap_or("message");
match event_name {
"done" => Some(ParsedEvent {
content: None,
status_event: None,
done: true,
error: None,
}),
"error" => Some(ParsedEvent {
content: None,
status_event: None,
done: false,
error: Some(
serde_json::from_str::<Value>(&data_text)
.ok()
.and_then(|value| {
value
.get("error")
.and_then(Value::as_str)
.map(str::to_string)
})
.unwrap_or_else(|| data_text.clone()),
),
}),
"status" => {
let Ok(value) = serde_json::from_str::<Value>(&data_text) else {
return None;
};
let event_type = value
.get("type")
.and_then(Value::as_str)
.unwrap_or("status")
.to_string();
Some(ParsedEvent {
content: None,
status_event: Some(ParsedStatusEvent {
event_type,
data: value,
}),
done: false,
error: None,
})
}
_ => {
let Ok(value) = serde_json::from_str::<Value>(&data_text) else {
return None;
};
let content = value
.pointer("/choices/0/delta/content")
.and_then(Value::as_str)
.map(str::to_string);
Some(ParsedEvent {
content,
status_event: None,
done: false,
error: None,
})
}
}
}
+45 -2
View File
@@ -6,8 +6,9 @@ use crate::event::{
};
#[cfg(feature = "tauri")]
use crate::event::{
InstancePayload, JavaDiscoveryPayload, JavaDownloadConfirmationPayload,
LoadingPayload, ProcessPayload, ServerPayload, WarningPayload,
InstanceGroupsChangedPayload, InstancePayload, JavaDiscoveryPayload,
JavaDownloadConfirmationPayload, LoadingPayload, ProcessPayload,
ServerPayload, WarningPayload,
};
use futures::prelude::*;
use serde_json::Value;
@@ -488,6 +489,26 @@ pub async fn emit_friend(payload: FriendPayload) -> crate::Result<()> {
Ok(())
}
#[allow(unused_variables)]
pub async fn emit_instance_groups_changed(
instance_ids: &[String],
) -> crate::Result<()> {
#[cfg(feature = "tauri")]
{
let event_state = crate::EventState::get()?;
event_state
.app
.emit(
"instance_groups_changed",
InstanceGroupsChangedPayload {
instance_ids: instance_ids.to_vec(),
},
)
.map_err(EventError::from)?;
}
Ok(())
}
#[allow(unused_variables)]
pub async fn emit_notification(payload: Value) -> crate::Result<()> {
#[cfg(feature = "tauri")]
@@ -591,3 +612,25 @@ where
})
.await
}
pub async fn emit_logshare_ai_event(
instance_id: &str,
event_type: &str,
data: Value,
) -> crate::Result<()> {
#[cfg(feature = "tauri")]
{
let event_state = crate::EventState::get()?;
event_state
.app
.emit(
"logshare_ai",
crate::event::LogShareAiEventPayload {
instance_id: instance_id.to_string(),
event_type: event_type.to_string(),
data,
},
)
.map_err(EventError::from)?;
}
Ok(())
}
+12
View File
@@ -395,6 +395,10 @@ pub enum ServerPayloadType {
eula_text: String,
},
}
#[derive(Serialize, Clone)]
pub struct InstanceGroupsChangedPayload {
pub instance_ids: Vec<String>,
}
#[derive(Serialize, Clone)]
#[cfg(feature = "tauri")]
@@ -468,6 +472,14 @@ mod log_types {
#[serde(flatten)]
pub event: LogEvent,
}
#[derive(Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub struct LogShareAiEventPayload {
pub instance_id: String,
pub event_type: String,
pub data: serde_json::Value,
}
}
#[derive(Debug, thiserror::Error)]
+1 -1
View File
@@ -670,7 +670,7 @@ fn read_file_tail(path: &Path, max_bytes: u64) -> crate::Result<String> {
Ok(output)
}
async fn censor_support_text(
pub(crate) async fn censor_support_text(
mut text: String,
state: &State,
) -> crate::Result<String> {
+9
View File
@@ -41,3 +41,12 @@ pub use runner::{
retry_job, retry_job_as_new, skip_missing_content_and_resume_job,
update_managed_curseforge_modpack, upgrade_unmanaged_instance,
};
/// Replaces credentials and IP addresses in text the user may share publicly
/// (support reports, exported logs) with placeholders.
pub async fn censor_shared_text(
text: String,
state: &crate::State,
) -> crate::Result<String> {
diagnostics::censor_support_text(text, state).await
}
+3 -2
View File
@@ -26,8 +26,9 @@ pub use api::*;
pub use error::*;
pub use event::{
EventState, LoadingBar, LoadingBarType, emit::emit_loading,
emit::init_loading,
emit::emit_logshare_ai_event, emit::init_loading,
};
pub use logger::filter_log_contents;
pub use logger::start_logger;
pub use state::db::{
backup_current_app_db_for_update, beta_database_exists,
@@ -38,7 +39,7 @@ pub use state::{DirectoryInfo, State};
pub use storage::*;
pub use util::fetch::build_proxied_client;
pub use util::file_lock::{LockingProcess, get_locking_processes};
pub use util::platform::is_process_elevated;
pub use util::platform::{default_game_dir_root, is_process_elevated};
pub use util::proxy::{ProxyConfig, ProxyMode, ProxyTestResult};
pub use util::symlink::SymlinkCapability;
+108
View File
@@ -240,6 +240,114 @@ fn launcher_log_is_expired(
now.duration_since(created).is_ok_and(|age| age > max_age)
}
/// Ordinal for the levels the launcher writes, ordered from most to least
/// verbose. Unknown tokens are ignored so unrecognized lines are never pruned.
fn log_level_ordinal(token: &str) -> Option<u8> {
match token {
"TRACE" => Some(0),
"DEBUG" => Some(1),
"INFO" => Some(2),
"WARN" => Some(3),
"ERROR" => Some(4),
_ => None,
}
}
fn log_level_minimum_ordinal(level: &str) -> Option<u8> {
match level {
"trace" => Some(0),
"debug" => Some(1),
"info" => Some(2),
"warn" => Some(3),
"error" => Some(4),
_ => None,
}
}
/// How a log line relates to the surrounding entries.
enum LogEntryHeader {
/// Timestamp and level parsed: the entry can be filtered.
Classified(chrono::DateTime<chrono::FixedOffset>, u8),
/// Timestamp parsed but the level is unknown: keep it rather than
/// dropping content this logic does not understand.
Unclassified,
}
/// Reads the timestamp and level of an entry line. Continuation lines of a
/// multi-line message carry no prefix and return `None`, so callers keep them
/// grouped with the entry they belong to.
fn parse_log_entry_header(line: &str) -> Option<LogEntryHeader> {
let (timestamp, rest) = line.split_once(char::is_whitespace)?;
let timestamp = chrono::DateTime::parse_from_rfc3339(timestamp).ok()?;
let level = rest.trim_start().split_whitespace().next()?;
Some(match log_level_ordinal(level) {
Some(ordinal) => LogEntryHeader::Classified(timestamp, ordinal),
None => LogEntryHeader::Unclassified,
})
}
/// Keeps or drops whole log entries by a predicate over their timestamp and
/// level ordinal, returning `None` when nothing was dropped.
///
/// Multi-line messages are kept or dropped together with their header, the
/// bytes of kept lines are preserved exactly (no re-encoding), and entries
/// whose level cannot be classified are always kept.
fn filter_log_entries<F>(contents: &[u8], keep: F) -> Option<Vec<u8>>
where
F: Fn(chrono::DateTime<chrono::FixedOffset>, u8) -> bool,
{
let mut kept = Vec::with_capacity(contents.len());
let mut changed = false;
let mut keep_entry = true;
for line in contents.split_inclusive(|byte| *byte == b'\n') {
match parse_log_entry_header(&String::from_utf8_lossy(line)) {
Some(LogEntryHeader::Classified(timestamp, ordinal)) => {
keep_entry = keep(timestamp, ordinal);
}
Some(LogEntryHeader::Unclassified) => keep_entry = true,
// Continuation line: it follows the decision of its entry.
None => {}
}
if keep_entry {
kept.extend_from_slice(line);
} else {
changed = true;
}
}
changed.then_some(kept)
}
/// Filters launcher log bytes for an export: entries older than `max_age` and
/// entries below `min_level` are removed. Pass `None` for either bound to keep
/// everything on that axis. Multi-line messages stay intact.
pub fn filter_log_contents(
contents: &[u8],
max_age: Option<std::time::Duration>,
min_level: Option<&str>,
) -> Vec<u8> {
let now = chrono::Local::now().fixed_offset();
let minimum = min_level.and_then(log_level_minimum_ordinal);
filter_log_entries(contents, |timestamp, ordinal| {
if let Some(minimum) = minimum
&& ordinal < minimum
{
return false;
}
if let Some(max_age) = max_age {
let age = (now - timestamp).to_std().unwrap_or_default();
if age > max_age {
return false;
}
}
true
})
.unwrap_or_else(|| contents.to_vec())
}
struct LogEventWriter {
writer: RotatingLogWriter,
buffer: Vec<u8>,
@@ -0,0 +1,613 @@
//! Instance grouping backed by a standalone JSON file in the app's settings
//! directory, next to `settings.json`.
//!
//! Groups used to live in SQLite (`instance_groups` /
//! `instance_group_memberships`). That layout could not express membership for
//! JSON-backed instances (`local:` ids, i.e. every `.minecraft` and
//! multi-library instance) because they have no row in the `instances` table,
//! and it duplicated membership into the per-instance sidecars. This module is
//! the single source of truth instead; the SQL tables are left untouched but
//! are no longer read or written (they are only read once, at import time).
use crate::state::State;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::PathBuf;
use std::sync::{OnceLock, RwLock};
use tracing::{info, warn};
pub const INSTANCE_GROUPS_FILE_NAME: &str = "instance_groups.json";
/// Current `instance_groups.json` schema version.
pub const INSTANCE_GROUPS_SCHEMA_VERSION: u32 = 1;
pub const FAVORITES_GROUP_ID: &str = "group:favorites";
const FAVORITES_GROUP_NAME: &str = "Pinned";
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GroupDefinition {
pub id: String,
pub name: String,
}
/// On-disk shape. The order of `groups` *is* the display order, so no
/// `display_order` field is needed: the public API only ever communicates
/// ordering through the order of `list()` and `set_order()`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InstanceGroupsFile {
#[serde(default)]
pub schema_version: u32,
#[serde(default)]
pub groups: Vec<GroupDefinition>,
/// instance id -> group ids.
#[serde(default)]
pub memberships: HashMap<String, Vec<String>>,
}
impl Default for InstanceGroupsFile {
fn default() -> Self {
Self {
schema_version: INSTANCE_GROUPS_SCHEMA_VERSION,
groups: vec![GroupDefinition {
id: FAVORITES_GROUP_ID.to_string(),
name: FAVORITES_GROUP_NAME.to_string(),
}],
memberships: HashMap::new(),
}
}
}
impl InstanceGroupsFile {
fn has_group(&self, id: &str) -> bool {
self.groups.iter().any(|group| group.id == id)
}
/// Guarantees the favorites sentinel exists and sits first, drops
/// memberships pointing at groups that no longer exist, and drops instances
/// left with no groups at all.
fn normalize(&mut self) {
self.schema_version = INSTANCE_GROUPS_SCHEMA_VERSION;
match self.groups.iter().position(|g| g.id == FAVORITES_GROUP_ID) {
Some(0) => {}
Some(index) => {
let favorites = self.groups.remove(index);
self.groups.insert(0, favorites);
}
None => self.groups.insert(
0,
GroupDefinition {
id: FAVORITES_GROUP_ID.to_string(),
name: FAVORITES_GROUP_NAME.to_string(),
},
),
}
let known = self
.groups
.iter()
.map(|group| group.id.clone())
.collect::<HashSet<_>>();
for group_ids in self.memberships.values_mut() {
let mut seen = HashSet::new();
group_ids
.retain(|id| known.contains(id) && seen.insert(id.clone()));
}
self.memberships
.retain(|_, group_ids| !group_ids.is_empty());
}
}
static STORE: OnceLock<RwLock<InstanceGroupsFile>> = OnceLock::new();
fn file_path() -> Option<PathBuf> {
let state = State::get_if_initialized()?;
Some(
state
.directories
.settings_dir
.join(INSTANCE_GROUPS_FILE_NAME),
)
}
/// Reads the store from disk, or `None` when it has never been written.
fn read_from_disk() -> Option<InstanceGroupsFile> {
let path = file_path()?;
if !path.exists() {
return None;
}
match fs::read_to_string(&path)
.map_err(|e| e.to_string())
.and_then(|content| {
serde_json::from_str::<InstanceGroupsFile>(&content)
.map_err(|e| e.to_string())
}) {
Ok(mut file) => {
file.normalize();
Some(file)
}
Err(error) => {
// A corrupt file must not wipe the user's groups silently on the
// next write, so bail out to an empty store without touching disk.
warn!("Failed to read {INSTANCE_GROUPS_FILE_NAME}: {error}");
None
}
}
}
fn write_to_disk(file: &InstanceGroupsFile) {
let Some(path) = file_path() else {
return;
};
let write = serde_json::to_string_pretty(file)
.map_err(|e| e.to_string())
.and_then(|content| {
fs::write(&path, content).map_err(|e| e.to_string())
});
if let Err(error) = write {
warn!("Failed to save {INSTANCE_GROUPS_FILE_NAME}: {error}");
}
}
fn store() -> &'static RwLock<InstanceGroupsFile> {
STORE.get_or_init(|| RwLock::new(read_from_disk().unwrap_or_default()))
}
fn with_read<T>(f: impl FnOnce(&InstanceGroupsFile) -> T) -> T {
let guard = store().read().unwrap_or_else(|e| e.into_inner());
f(&guard)
}
/// Mutates the store and persists the whole file. `f` returns the instance ids
/// whose membership changed, so callers can emit the change event.
fn with_write<T>(f: impl FnOnce(&mut InstanceGroupsFile) -> T) -> T {
let mut guard = store().write().unwrap_or_else(|e| e.into_inner());
let result = f(&mut guard);
guard.normalize();
write_to_disk(&guard);
result
}
// ── Reads ───────────────────────────────────────────────────────────────────
pub fn list() -> Vec<GroupDefinition> {
with_read(|file| file.groups.clone())
}
pub fn group_exists(id: &str) -> bool {
with_read(|file| file.has_group(id))
}
/// Group ids for one instance, in the order they were assigned. Synchronous so
/// that `instance_metadata_from_instance` can call it.
pub fn group_ids_for(instance_id: &str) -> Vec<String> {
with_read(|file| {
file.memberships
.get(instance_id)
.cloned()
.unwrap_or_default()
})
}
fn instances_in_group(
file: &InstanceGroupsFile,
group_id: &str,
) -> Vec<String> {
file.memberships
.iter()
.filter(|(_, group_ids)| group_ids.iter().any(|id| id == group_id))
.map(|(instance_id, _)| instance_id.clone())
.collect()
}
// ── Writes ──────────────────────────────────────────────────────────────────
/// Adds a group at the top of the list, matching the previous SQL behavior
/// where new groups got the lowest `display_order`. Favorites stays first.
pub fn create(id: &str, name: &str) {
with_write(|file| {
let definition = GroupDefinition {
id: id.to_string(),
name: name.to_string(),
};
// `normalize` moves favorites back to index 0 afterwards.
file.groups.insert(0, definition);
});
}
/// Renames a group, returning the affected instance ids, or `None` when the
/// group does not exist.
pub fn rename(id: &str, name: &str) -> Option<Vec<String>> {
with_write(|file| {
let group = file.groups.iter_mut().find(|group| group.id == id)?;
group.name = name.to_string();
Some(instances_in_group(file, id))
})
}
/// Deletes a group and strips it from every instance, returning the affected
/// instance ids, or `None` when the group does not exist.
pub fn delete(id: &str) -> Option<Vec<String>> {
with_write(|file| {
let index = file.groups.iter().position(|group| group.id == id)?;
let affected = instances_in_group(file, id);
file.groups.remove(index);
// `normalize` prunes the now-dangling ids out of `memberships`.
Some(affected)
})
}
/// Reorders groups to match `group_ids`. Groups missing from the argument keep
/// their relative order at the end, so a stale frontend list can never drop a
/// group. Favorites is pinned first regardless.
pub fn set_order(group_ids: &[String]) {
with_write(|file| reorder_groups(&mut file.groups, group_ids));
}
/// Reorders `groups` to match `group_ids`. Groups the argument omits keep their
/// relative order after the listed ones, so a stale frontend list can never drop
/// a group. Pure so the ordering rules can be tested without the process-wide
/// store, which tests would otherwise race over.
fn reorder_groups(groups: &mut Vec<GroupDefinition>, group_ids: &[String]) {
let mut remaining = std::mem::take(groups);
let mut ordered = Vec::with_capacity(remaining.len());
for id in group_ids {
if id == FAVORITES_GROUP_ID {
continue;
}
if let Some(index) = remaining.iter().position(|group| &group.id == id)
{
ordered.push(remaining.remove(index));
}
}
ordered.extend(remaining);
*groups = ordered;
}
/// Replaces the group list of each given instance wholesale.
pub fn set_memberships(updates: &[(String, Vec<String>)]) {
with_write(|file| {
for (instance_id, group_ids) in updates {
if group_ids.is_empty() {
file.memberships.remove(instance_id);
} else {
file.memberships
.insert(instance_id.clone(), group_ids.clone());
}
}
});
}
/// Replaces the group list of a single instance.
pub fn set_instance_groups(instance_id: &str, group_ids: &[String]) {
set_memberships(&[(instance_id.to_string(), group_ids.to_vec())]);
}
/// Looks a group up by name, creating it if absent, and returns its id.
/// Used by the legacy launcher import, which only knows group names.
pub fn find_or_create_by_name(name: &str) -> String {
with_write(|file| {
if let Some(group) = file.groups.iter().find(|group| group.name == name)
{
return group.id.clone();
}
let id = uuid::Uuid::new_v4().to_string();
file.groups.push(GroupDefinition {
id: id.clone(),
name: name.to_string(),
});
id
})
}
/// Adds one group to an instance, keeping its existing groups.
pub fn add_instance_to_group(instance_id: &str, group_id: &str) {
with_write(|file| {
let entry =
file.memberships.entry(instance_id.to_string()).or_default();
if !entry.iter().any(|id| id == group_id) {
entry.push(group_id.to_string());
}
});
}
/// Drops an instance's membership entry, e.g. after the instance is deleted.
pub fn forget_instance(instance_id: &str) {
with_write(|file| {
file.memberships.remove(instance_id);
});
}
/// Re-keys an instance's membership, e.g. when a `local:` id changes because the
/// instance directory moved.
pub fn rename_instance(old_id: &str, new_id: &str) {
if old_id == new_id {
return;
}
with_write(|file| {
if let Some(group_ids) = file.memberships.remove(old_id) {
file.memberships.insert(new_id.to_string(), group_ids);
}
});
}
// ── One-time import ─────────────────────────────────────────────────────────
async fn import_sql_groups(
pool: &sqlx::SqlitePool,
) -> crate::Result<InstanceGroupsFile> {
let columns: Vec<String> = sqlx::query_scalar(
"SELECT name FROM pragma_table_info('instance_groups')",
)
.fetch_all(pool)
.await?;
let has_column = |name: &str| columns.iter().any(|column| column == name);
let mut file = InstanceGroupsFile {
schema_version: INSTANCE_GROUPS_SCHEMA_VERSION,
groups: Vec::new(),
memberships: HashMap::new(),
};
if has_column("id") && has_column("name") {
let rows = sqlx::query_as::<_, (String, String)>(
"SELECT id, name FROM instance_groups ORDER BY display_order, name, id",
)
.fetch_all(pool)
.await?;
for (id, name) in rows {
file.groups.push(GroupDefinition { id, name });
}
let has_memberships: bool = sqlx::query_scalar(
"SELECT EXISTS(
SELECT 1 FROM sqlite_master
WHERE type = 'table' AND name = 'instance_group_memberships'
)",
)
.fetch_one(pool)
.await?;
if has_memberships {
let memberships = sqlx::query_as::<_, (String, String)>(
"SELECT instance_id, group_id FROM instance_group_memberships",
)
.fetch_all(pool)
.await?;
for (instance_id, group_id) in memberships {
file.memberships
.entry(instance_id)
.or_default()
.push(group_id);
}
}
} else if has_column("instance_id") && has_column("group_name") {
let rows = sqlx::query_as::<_, (String, String)>(
"SELECT instance_id, group_name
FROM instance_groups
ORDER BY group_name, instance_id",
)
.fetch_all(pool)
.await?;
let mut group_ids = HashMap::<String, String>::new();
for (instance_id, group_name) in rows {
let group_id = group_ids
.entry(group_name.clone())
.or_insert_with(|| uuid::Uuid::new_v4().to_string())
.clone();
file.memberships
.entry(instance_id)
.or_default()
.push(group_id.clone());
if !file.groups.iter().any(|group| group.id == group_id) {
file.groups.push(GroupDefinition {
id: group_id,
name: group_name,
});
}
}
} else if !columns.is_empty() {
warn!(
columns = ?columns,
"Skipping instance group import from an unrecognized SQLite schema"
);
}
file.normalize();
Ok(file)
}
/// Creates `instance_groups.json` from the pre-existing SQLite tables and
/// instance sidecars, the first time the app runs after this change.
///
/// The SQL access here is read-only and happens exactly once; afterwards the
/// tables are never touched again (they are kept as-is so no DB migration is
/// needed).
pub async fn ensure_imported(state: &State) -> crate::Result<()> {
let Some(path) = file_path() else {
return Ok(());
};
if path.exists() {
// Populate the in-memory cache eagerly so the first synchronous read
// does not race with a write.
let _ = list();
return Ok(());
}
let file = import_sql_groups(&state.pool).await?;
let group_count = file.groups.len();
let instance_count = file.memberships.len();
// Seed the cache with the imported data instead of letting `store()` read
// the file we are about to write.
{
let lock = store();
let mut guard = lock.write().unwrap_or_else(|e| e.into_inner());
*guard = file;
write_to_disk(&guard);
}
info!(
"Imported {group_count} instance groups covering {instance_count} instances into {INSTANCE_GROUPS_FILE_NAME}"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use sqlx::sqlite::SqlitePoolOptions;
fn file_with_groups(ids: &[&str]) -> InstanceGroupsFile {
InstanceGroupsFile {
schema_version: INSTANCE_GROUPS_SCHEMA_VERSION,
groups: ids
.iter()
.map(|id| GroupDefinition {
id: id.to_string(),
name: id.to_string(),
})
.collect(),
memberships: HashMap::new(),
}
}
#[test]
fn normalize_inserts_favorites_first() {
let mut file = file_with_groups(&["a", "b"]);
file.normalize();
assert_eq!(file.groups[0].id, FAVORITES_GROUP_ID);
assert_eq!(file.groups.len(), 3);
}
#[test]
fn normalize_moves_favorites_to_front() {
let mut file = file_with_groups(&["a", FAVORITES_GROUP_ID, "b"]);
file.normalize();
assert_eq!(file.groups[0].id, FAVORITES_GROUP_ID);
assert_eq!(file.groups[1].id, "a");
assert_eq!(file.groups[2].id, "b");
}
#[test]
fn normalize_drops_orphan_memberships() {
let mut file = file_with_groups(&["a"]);
file.memberships.insert(
"instance".to_string(),
vec!["a".to_string(), "nonexistent".to_string()],
);
file.normalize();
assert_eq!(file.memberships["instance"], &["a"]);
}
#[test]
fn normalize_drops_memberships_for_nonexistent_instances() {
let mut file = file_with_groups(&["a"]);
file.memberships.insert(
"instance".to_string(),
vec!["nonexistent1".to_string(), "nonexistent2".to_string()],
);
file.normalize();
assert!(!file.memberships.contains_key("instance"));
}
fn group_ids(groups: &[GroupDefinition]) -> Vec<String> {
groups.iter().map(|group| group.id.clone()).collect()
}
#[test]
fn set_order_ignores_unknown_ids() {
let mut groups = file_with_groups(&["a", "b", "c"]).groups;
reorder_groups(&mut groups, &["unknown".to_string(), "c".to_string()]);
// The unknown id matches nothing and simply contributes no group.
assert_eq!(group_ids(&groups), vec!["c", "a", "b"]);
}
#[test]
fn set_order_retains_missing_groups_at_end() {
let mut groups = file_with_groups(&["a", "b", "c"]).groups;
groups.push(GroupDefinition {
id: "extra".to_string(),
name: "extra".to_string(),
});
reorder_groups(&mut groups, &["b".to_string()]);
// `b` moves to the front and every group the argument omitted survives
// after it, so a stale list can never drop a group. Favorites is pinned
// by `normalize`, which the store applies around this call.
assert_eq!(group_ids(&groups), vec!["b", "a", "c", "extra"]);
}
#[test]
fn set_order_keeps_favorites_out_of_the_reorder() {
let mut groups = file_with_groups(&["a", FAVORITES_GROUP_ID]).groups;
reorder_groups(&mut groups, &[FAVORITES_GROUP_ID.to_string()]);
// Favorites is skipped explicitly and survives at its previous position;
// `normalize` moves it to the front afterwards.
assert_eq!(group_ids(&groups), vec!["a", FAVORITES_GROUP_ID]);
}
#[test]
fn normalize_does_not_lose_favorites_membership() {
let mut file = file_with_groups(&[]);
file.memberships.insert(
"my_instance".to_string(),
vec![FAVORITES_GROUP_ID.to_string()],
);
file.normalize();
assert_eq!(file.memberships["my_instance"], &[FAVORITES_GROUP_ID]);
}
#[test]
fn normalize_deduplicates_group_ids() {
let mut file = file_with_groups(&["a", "b"]);
file.memberships.insert(
"instance".to_string(),
vec!["a".to_string(), "a".to_string(), "b".to_string()],
);
file.normalize();
assert_eq!(file.memberships["instance"].len(), 2);
}
#[tokio::test]
async fn imports_legacy_instance_group_schema() {
let pool = SqlitePoolOptions::new()
.connect("sqlite::memory:")
.await
.unwrap();
sqlx::query(
"CREATE TABLE instance_groups (
instance_id TEXT NOT NULL,
group_name TEXT NOT NULL,
PRIMARY KEY (instance_id, group_name)
)",
)
.execute(&pool)
.await
.unwrap();
sqlx::query(
"INSERT INTO instance_groups (instance_id, group_name)
VALUES ('instance-1', 'Survival'), ('instance-2', 'Survival'),
('instance-1', 'Creative')",
)
.execute(&pool)
.await
.unwrap();
let file = import_sql_groups(&pool).await.unwrap();
assert_eq!(file.groups.len(), 3);
assert_eq!(file.groups[0].id, FAVORITES_GROUP_ID);
assert_eq!(file.memberships["instance-1"].len(), 2);
assert_eq!(file.memberships["instance-2"].len(), 1);
assert!(file.groups.iter().any(|group| group.name == "Survival"));
}
}
@@ -1,3 +1,4 @@
use crate::state::instance_groups;
use crate::state::instances::{
ContentSet, Instance, InstanceLaunchOverrides, InstanceLink,
LoaderComponent,
@@ -91,11 +92,12 @@ impl InstanceMetadata {
record: instance_rows::InstanceMetadataRecord,
loader_components: Vec<LoaderComponent>,
) -> Self {
let groups = instance_groups::group_ids_for(&record.instance.id);
Self {
instance: record.instance,
applied_content_set: record.applied_content_set,
link: record.link,
groups: record.groups,
groups,
launch_overrides: record.launch_overrides,
loader_components,
synced_options: Default::default(),
+5
View File
@@ -26,6 +26,7 @@ pub use self::instance_types::*;
pub(crate) mod instances;
pub use self::instances::*;
pub(crate) mod instance_groups;
mod settings;
pub use self::settings::*;
@@ -487,6 +488,10 @@ impl State {
.get_or_try_init(move || Self::initialize_state(app_identifier))
.await?;
if let Err(e) = instance_groups::ensure_imported(state).await {
tracing::error!("Error importing legacy instance groups: {e}");
}
if let Err(e) =
crate::install::recovery::recover_interrupted_jobs(state).await
{
+135 -27
View File
@@ -713,16 +713,37 @@ impl Process {
pending.push_str(&String::from_utf8_lossy(&chunk[..read]));
// Drain every complete frame currently buffered.
while let Some(frame) = take_next_log4j_frame(&mut pending) {
Self::handle_log4j_frame(
instance_id,
instance_name,
process_id,
log_path.as_ref(),
&frame,
)
.await;
// Mods can write plain text to either pipe even when the
// launcher selected XML logging. Forward it as soon as a line
// is complete instead of retaining it until the game exits.
while let Some(output) = take_next_log_output(&mut pending) {
match output {
LogOutput::Xml(frame) => {
Self::handle_log4j_frame(
instance_id,
instance_name,
process_id,
log_path.as_ref(),
&frame,
)
.await;
}
LogOutput::Legacy(text) => {
if let Err(e) =
Self::append_to_log_file(&log_path, &text)
{
tracing::warn!(
"Failed to write to log file: {e}"
);
}
if !text.trim_end().is_empty() {
Self::emit_legacy_log(
instance_id,
text.trim_end(),
);
}
}
}
}
// Guard against a runaway buffer if no frame delimiters ever
@@ -1360,32 +1381,119 @@ impl Process {
Ok(())
}
}
/// Cuts the next complete `<log4j:Event …>…</log4j:Event>` frame out of the
/// live buffer and returns it as an owned string, leaving any trailing partial
/// frame in place.
///
/// Returns `None` when the buffer does not yet contain a full frame. This is a
/// plain string operation on purpose: it never poisons any parser state, so a
/// split or malformed frame on the live pipe cannot stop log forwarding.
fn take_next_log4j_frame(buffer: &mut String) -> Option<String> {
#[derive(Debug, Eq, PartialEq)]
enum LogOutput {
Xml(String),
Legacy(String),
}
/// Drains complete XML frames or plain text in stream order. Partial frames
/// and plain text lines remain buffered until their next chunk arrives.
fn take_next_log_output(buffer: &mut String) -> Option<LogOutput> {
const OPEN: &str = "<log4j:Event";
const CLOSE: &str = "</log4j:Event>";
let start = buffer.find(OPEN)?;
// Discard anything before the frame (raw text, XML prolog, …).
if start > 0 {
buffer.drain(..start);
match buffer.find(OPEN) {
Some(0) => {
let close = buffer.find(CLOSE)?;
let end = close + CLOSE.len();
Some(LogOutput::Xml(buffer.drain(..end).collect()))
}
Some(start) => Some(LogOutput::Legacy(buffer.drain(..start).collect())),
None => {
let end = buffer.find('\n')? + 1;
Some(LogOutput::Legacy(buffer.drain(..end).collect()))
}
}
let close = buffer.find(CLOSE)?;
let end = close + CLOSE.len();
let frame = buffer[..end].to_string();
buffer.drain(..end);
Some(frame)
}
#[cfg(test)]
mod post_upgrade_tests {
use super::*;
#[test]
fn mixed_log_output_keeps_partial_xml_and_multiline_messages() {
let mut pending = "raw\n<log4j:Ev".to_string();
assert_eq!(
take_next_log_output(&mut pending),
Some(LogOutput::Legacy("raw\n".into()))
);
assert_eq!(take_next_log_output(&mut pending), None);
pending.push_str("ent><log4j:Message><![CDATA[first\nsecond");
assert_eq!(take_next_log_output(&mut pending), None);
pending.push_str("]]></log4j:Message></log4j:Event>\nafter\n");
assert_eq!(take_next_log_output(&mut pending), Some(LogOutput::Xml("<log4j:Event><log4j:Message><![CDATA[first\nsecond]]></log4j:Message></log4j:Event>".into())));
assert_eq!(
take_next_log_output(&mut pending),
Some(LogOutput::Legacy("\n".into()))
);
assert_eq!(
take_next_log_output(&mut pending),
Some(LogOutput::Legacy("after\n".into()))
);
assert!(pending.is_empty());
}
#[tokio::test]
async fn xml_logging_forwards_plain_text_before_pipe_closes() {
use tokio::io::AsyncWriteExt;
let instance_id = Uuid::new_v4().to_string();
let directory = tempfile::tempdir().unwrap();
let log_path = directory.path().join("live.log");
let (mut writer, reader) = tokio::io::duplex(1024);
let output = Process::process_output(
&instance_id,
"instance",
"Instance",
"process",
reader,
&log_path,
true,
);
tokio::pin!(output);
writer.write_all(b"mod output\n").await.unwrap();
let forwarded = async {
loop {
if get_log_buffer(&instance_id) == ["mod output"] {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
}
};
tokio::select! {
_ = &mut output => panic!("reader ended while writer is still open"),
result = tokio::time::timeout(std::time::Duration::from_secs(1), forwarded) => {
result.expect("plain text was buffered until EOF");
}
}
assert_eq!(std::fs::read_to_string(&log_path).unwrap(), "mod output\n");
drop(writer);
output.await;
remove_log_buffer(&instance_id);
}
#[tokio::test]
async fn xml_logging_preserves_plain_text_before_xml_frames() {
let instance_id = Uuid::new_v4().to_string();
let directory = tempfile::tempdir().unwrap();
let log_path = directory.path().join("mixed.log");
let input = "mod output\n<log4j:Event level=\"INFO\"><log4j:Message><![CDATA[xml output]]></log4j:Message></log4j:Event>\n";
Process::process_output(
&instance_id,
"instance",
"Instance",
"process",
std::io::Cursor::new(input),
&log_path,
true,
)
.await;
let lines = get_log_buffer(&instance_id);
assert_eq!(lines.first().map(String::as_str), Some("mod output"));
assert!(lines.iter().any(|line| line.contains("xml output")));
remove_log_buffer(&instance_id);
}
#[test]
fn live_log_snapshot_sequences_batches_and_preserves_position_after_clear()
{
+29
View File
@@ -1,5 +1,6 @@
//! Platform-related code
use daedalus::minecraft::{Os, OsRule};
use std::path::PathBuf;
/// (e.g. "Run as administrator" on Windows).
#[cfg(target_os = "windows")]
@@ -143,3 +144,31 @@ pub fn classpath_separator(java_arch: &str) -> &'static str {
Os::Windows | Os::WindowsArm64 => ";",
}
}
/// Root directory used as the default for one-click StarLight instance
/// installs. Portable builds live next to their executable, which is a fine
/// place for game data. System installs (e.g. a Linux `.deb` under `/usr/bin`)
/// do not, so fall back to the user's home directory there.
pub fn default_game_dir_root() -> Option<PathBuf> {
let exe_dir = std::env::current_exe().ok()?.parent()?.to_path_buf();
if cfg!(target_os = "linux") && is_system_install_dir(&exe_dir) {
return dirs::home_dir();
}
Some(exe_dir)
}
#[cfg(target_os = "linux")]
fn is_system_install_dir(path: &std::path::Path) -> bool {
const SYSTEM_PREFIXES: &[&str] = &[
"/usr/", "/opt/", "/snap/", "/bin/", "/sbin/", "/lib/", "/lib64/",
];
let display = path.to_string_lossy();
SYSTEM_PREFIXES
.iter()
.any(|prefix| display.starts_with(prefix))
}
#[cfg(not(target_os = "linux"))]
fn is_system_install_dir(_path: &std::path::Path) -> bool {
false
}
@@ -0,0 +1,23 @@
<template>
<span class="inline-flex flex-wrap items-center gap-1">
<kbd
v-for="(part, index) in parts"
:key="`${index}-${part}`"
aria-hidden="true"
class="rounded-md border border-solid border-surface-4 bg-surface-3 px-2 py-0.5 font-mono text-sm text-[var(--color-text-primary)]"
>
{{ part }}
</kbd>
<span class="sr-only">{{ text }}</span>
</span>
</template>
<script setup lang="ts">
import { useBindingParts, useBindingText } from '../../composables/use-keybinding-labels'
import type { KeyBinding } from '../../utils/keybinding'
const props = defineProps<{ binding: KeyBinding }>()
const parts = useBindingParts(() => props.binding)
const text = useBindingText(() => props.binding)
</script>
@@ -7,6 +7,8 @@ import type { ButtonProps } from './types'
const props = withDefaults(defineProps<ButtonProps>(), {
type: 'base',
size: 'md',
iconOnly: false,
circular: false,
nativeType: 'button',
disabled: false,
loading: false,
@@ -26,8 +28,11 @@ defineExpose({ element })
:color="props.color"
:size="props.size"
:interaction="props.interaction"
:icon-only="props.iconOnly"
:circular="props.circular"
:native-type="props.nativeType"
:disabled="props.disabled || props.loading"
:aria-label="props.iconOnly ? props.label : undefined"
:aria-busy="props.loading || undefined"
>
<slot />
@@ -13,7 +13,10 @@ import type {
const baseClasses = [
// Base
'relative inline-flex min-w-0 shrink-0 items-center justify-center',
'whitespace-nowrap border-0 no-underline',
// The transparent border is load-bearing, not decorative: it participates in
// layout, so an auto-width button is 2px wider than it would be without it.
// The ring participates in layout; dropping it would silently narrow every text button.
'whitespace-nowrap border border-solid border-transparent no-underline',
// Interactions
'touch-manipulation cursor-pointer select-none transition-[background-color,color,box-shadow,filter,opacity,transform] duration-150 ease-out',
'enabled:active:scale-[0.97]',
@@ -26,6 +29,8 @@ const baseClasses = [
].join(' ')
const sizeClasses: Record<ButtonSize, string> = {
'2xs':
'h-6 gap-1 rounded-lg px-1.5 text-sm font-semibold leading-5 [&>svg]:size-4 [&>svg]:min-h-4 [&>svg]:min-w-4 [&>svg]:shrink-0',
xs: 'h-7 gap-1 rounded-lg px-1.5 text-sm font-semibold leading-5 [&>svg]:size-4 [&>svg]:min-h-4 [&>svg]:min-w-4 [&>svg]:shrink-0',
sm: 'h-8 gap-1 rounded-[10px] px-1.5 text-sm font-semibold leading-5 [&>svg]:size-4 [&>svg]:min-h-4 [&>svg]:min-w-4 [&>svg]:shrink-0',
md: 'h-9 gap-1.5 rounded-xl px-2.5 text-base font-semibold leading-5 [&>svg]:size-5 [&>svg]:min-h-5 [&>svg]:min-w-5 [&>svg]:shrink-0',
@@ -34,6 +39,7 @@ const sizeClasses: Record<ButtonSize, string> = {
}
const iconOnlySizeClasses: Record<ButtonSize, string> = {
'2xs': 'min-w-6 w-6 !px-0',
xs: 'min-w-7 w-7 !px-0',
sm: 'min-w-8 w-8 !px-0',
md: 'min-w-9 w-9 !px-0',
@@ -42,14 +48,23 @@ const iconOnlySizeClasses: Record<ButtonSize, string> = {
}
const typeClasses: Record<ButtonType, string> = {
base: 'button-frame--base bg-surface-4 text-contrast [&>svg]:text-primary',
base: 'button-frame--base bg-surface-4 text-[var(--color-text-primary)] [&>svg]:text-[var(--color-text-default)]',
colored:
'button-frame--colored bg-[--button-color] text-[var(--color-accent-contrast)] [&>svg]:text-inherit',
'colored-text':
'button-frame--colored-text bg-surface-4 text-[--button-color] [&>svg]:text-inherit',
outlined:
'button-frame--outlined bg-transparent text-[var(--button-color,var(--color-contrast))] [&>svg]:text-[var(--button-color,var(--color-base))]',
'button-frame--outlined bg-transparent text-[var(--button-color,var(--color-text-primary))] [&>svg]:text-[var(--button-color,var(--color-text-default))]',
quiet: 'button-frame--quiet bg-transparent [&>svg]:text-inherit',
// A 25% tint of the accent colour. All three read the same tint; they differ
// in label colour and whether they carry the raised shadow. Without a colour
// the tint variable is unset and the fill falls back to the raised surface,
// which is what the legacy uncoloured chip rendered as.
chip: 'button-frame--chip bg-[--button-highlight,var(--surface-4)] text-[var(--button-color,var(--color-text-default))] [&>svg]:text-inherit',
'chip-text':
'button-frame--chip-text bg-[--button-highlight,var(--surface-4)] text-[var(--button-color,var(--color-text-default))] [&>svg]:text-inherit',
highlight:
'button-frame--highlight bg-[--button-highlight,var(--surface-4)] text-[var(--color-text-primary)] [&>svg]:text-inherit',
}
const interactionClasses: Record<ButtonInteraction, string> = {
@@ -67,7 +82,17 @@ const colorVariables: Record<ButtonColor, string> = {
green: 'var(--color-green)',
blue: 'var(--color-blue)',
purple: 'var(--color-purple)',
medal_promotion: 'var(--medal-promotion-text-orange, var(--color-orange))',
}
// The 25%-opacity tint behind `chip`/`highlight`. Each accent has its own
// token, so the tint must be looked up rather than derived.
const highlightVariables: Record<ButtonColor, string> = {
brand: 'var(--color-brand-highlight)',
red: 'var(--color-red-highlight)',
orange: 'var(--color-orange-highlight)',
green: 'var(--color-green-highlight)',
blue: 'var(--color-blue-highlight)',
purple: 'var(--color-purple-highlight)',
}
const props = withDefaults(
@@ -101,7 +126,20 @@ const classes = computed(() => [
props.circular ? '!rounded-full' : '',
])
const style = computed((): CSSProperties | undefined => {
// `outlined` and `quiet` deliberately publish nothing without an explicit
// colour, so their own `var(--button-color, <default>)` fallbacks apply —
// that is what reproduces the legacy default ring and text colours.
if ((props.type === 'outlined' || props.type === 'quiet') && !props.color) return undefined
if (props.type === 'chip' || props.type === 'chip-text' || props.type === 'highlight') {
// Without an accent these fall back to the page surface and the default
// label, matching the legacy behaviour for an uncoloured chip.
const accent = props.color
if (!accent) return undefined
return {
'--button-color': colorVariables[accent],
'--button-highlight': highlightVariables[accent],
} as CSSProperties
}
if (
props.type !== 'colored' &&
props.type !== 'colored-text' &&
@@ -163,11 +201,24 @@ defineExpose({ element })
mask-composite: exclude;
}
/* The ring is a real border so it participates in layout. Set here rather
* than as a utility because it has to beat the transparent border colour in
* `baseClasses`. */
.button-frame--outlined {
box-shadow: inset 0 0 0 1px var(--button-color, var(--surface-5));
border-color: var(--button-color, var(--surface-5));
}
.button-frame--quiet {
color: var(--button-color, var(--color-base));
color: var(--button-color, var(--color-text-default));
}
/* `chip` and `highlight` are tinted fills rather than transparent ones, so they
* keep the raised-button shadow. `chip-text` is the same tint without it --
* the legacy `highlight-colored-text`, which never had a shadow. */
.button-frame--chip,
.button-frame--highlight {
box-shadow:
inset 0 0 0 1px var(--surface-5),
0 1px 1px rgba(0, 0, 0, 0.12);
}
</style>
@@ -1,56 +1,74 @@
export type ButtonType = 'base' | 'colored' | 'colored-text' | 'outlined' | 'quiet'
export type ButtonType =
'base' | 'colored' | 'colored-text' | 'outlined' | 'quiet' | 'chip' | 'chip-text' | 'highlight'
export type ButtonSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
export type ButtonSize = '2xs' | 'xs' | 'sm' | 'md' | 'lg' | 'xl'
export type ButtonInteraction = 'surface' | 'filled' | 'none'
// TODO: Standardized color string enum props across @modrinth/ui
export type ButtonColor =
| 'brand'
| 'red'
| 'orange'
| 'green'
| 'blue'
| 'purple'
| 'medal_promotion'
export type ButtonColor = 'brand' | 'red' | 'orange' | 'green' | 'blue' | 'purple'
export type ButtonVisualProps = {
type ButtonVisualBase = {
size?: ButtonSize
interaction?: ButtonInteraction
} & (
}
type ButtonVisualWithoutInteraction =
| {
type?: 'base'
color?: never
interaction?: never
}
| {
type: 'outlined'
type: Exclude<ButtonType, 'base' | 'quiet'>
color?: ButtonColor
interaction?: never
}
| {
type: 'colored'
color?: ButtonColor
}
| {
type: 'colored-text'
color?: ButtonColor
}
| {
type: 'quiet'
color?: ButtonColor
}
)
/**
* Public visual combinations supported by the current button frame.
*
* `interaction` only changes quiet buttons, so exposing it on any other type
* would accept a prop that has no effect. Keeping that restriction here makes
* Button and ButtonLink share one truthful visual contract.
*/
export type ButtonVisualProps = ButtonVisualBase &
(
| ButtonVisualWithoutInteraction
| {
type: 'quiet'
color?: ButtonColor
interaction?: ButtonInteraction
}
)
export type ButtonNativeType = 'button' | 'submit' | 'reset'
export interface ButtonProps {
type?: ButtonType
color?: ButtonColor
size?: ButtonSize
interaction?: ButtonInteraction
nativeType?: ButtonNativeType
disabled?: boolean
loading?: boolean
}
/** Icon-only controls need a name because their slot has no visible label. */
export type ButtonContentProps =
| {
iconOnly: true
label: string
}
| {
iconOnly?: false
label?: never
}
export type ButtonProps = ButtonVisualProps &
ButtonContentProps & {
circular?: boolean
nativeType?: ButtonNativeType
disabled?: boolean
loading?: boolean
}
export type ButtonLinkProps = ButtonVisualProps &
ButtonContentProps & {
as?: string | import('vue').Component
href?: string
disabled?: boolean
circular?: boolean
}
export interface ButtonElementHandle {
element: HTMLElement | null
+1
View File
@@ -118,3 +118,4 @@ export { default as TimeFramePicker } from './TimeFramePicker.vue'
export { default as Timeline } from './Timeline.vue'
export { default as Toggle } from './Toggle.vue'
export { default as UnsavedChangesPopup } from './UnsavedChangesPopup.vue'
export { default as KeybindingChips } from './KeybindingChips.vue'
@@ -0,0 +1,256 @@
<template>
<div
ref="treeRef"
role="tree"
:aria-label="formatMessage(messages.treeLabel)"
class="max-h-[18rem] overflow-y-auto rounded-lg border border-solid border-surface-4 bg-surface-2 p-1"
@keydown="handleKeydown"
>
<div
v-for="(row, index) in visibleRows"
:key="row.id"
:ref="(element) => setRowRef(row.id, element)"
role="treeitem"
:tabindex="index === activeIndex ? 0 : -1"
:aria-level="row.level + 1"
:aria-expanded="row.expandable ? row.expanded : undefined"
:aria-selected="row.kind === 'item' ? row.selected : undefined"
:aria-disabled="row.disabled ? true : undefined"
class="flex cursor-pointer items-center gap-2 rounded-md py-2 pr-2 text-sm transition-colors duration-150"
:class="[
row.disabled ? 'cursor-not-allowed opacity-50' : 'hover:bg-surface-3',
row.selected
? 'bg-brand-highlight text-[var(--color-text-primary)]'
: 'text-[var(--color-text-default)]',
row.kind === 'item' ? '' : 'font-semibold text-[var(--color-text-primary)]',
]"
:style="{ paddingLeft: `${row.level * 1.25 + 0.5}rem` }"
@click="activateRow(row)"
@focus="activeIndex = index"
>
<ChevronRightIcon
v-if="row.expandable"
class="h-4 w-4 shrink-0 text-[var(--color-text-tertiary)] transition-transform duration-150"
:class="{ 'rotate-90': row.expanded }"
aria-hidden="true"
/>
<span v-else class="w-4 shrink-0" aria-hidden="true" />
<span class="min-w-0 flex-1 truncate">{{ row.label }}</span>
<span v-if="row.disabledReason" class="shrink-0 text-xs text-[var(--color-text-tertiary)]">
{{ row.disabledReason }}
</span>
</div>
</div>
</template>
<script setup lang="ts">
import { ChevronRightIcon } from '@modrinth/assets'
import { computed, nextTick, ref } from 'vue'
import { defineMessages, useVIntl } from '../../composables/i18n'
import { type KeyBinding, type KeyBindingDevice, keyCodeLabel } from '../../utils/keybinding'
import { KEYBINDING_CATALOG, type KeybindingCatalogItem } from '../../utils/keybinding-catalog'
const props = withDefaults(
defineProps<{
/** The combination being assembled, used to mark the chosen input. */
binding: KeyBinding | null
/** Reasons an input may not be used, keyed by code. */
disabledCodes?: Map<string, string>
}>(),
{ disabledCodes: () => new Map() },
)
const emit = defineEmits<{
select: [{ device: KeyBindingDevice; code: string }]
escape: []
}>()
const { formatMessage } = useVIntl()
const messages = defineMessages({
treeLabel: {
id: 'ui.keybinding-modal.tree-label',
defaultMessage: 'Inputs a shortcut can use',
},
})
interface TreeRow {
id: string
kind: 'device' | 'group' | 'item'
level: number
label: string
expandable: boolean
expanded: boolean
selected: boolean
disabled: boolean
disabledReason?: string
item?: KeybindingCatalogItem
}
const expanded = ref(new Set<string>(['keyboard']))
const activeIndex = ref(0)
const rowRefs = new Map<string, HTMLElement>()
function groupRowId(deviceId: string, groupId: string) {
return `${deviceId}:${groupId}`
}
function itemRowId(deviceId: string, groupId: string, code: string) {
return `${deviceId}:${groupId}:${code}`
}
function itemLabel(item: KeybindingCatalogItem) {
return item.label ? formatMessage(item.label) : keyCodeLabel(item.code)
}
function itemState(item: KeybindingCatalogItem) {
const reason = props.disabledCodes.get(item.code)
return { disabled: Boolean(reason), disabledReason: reason }
}
const visibleRows = computed<TreeRow[]>(() => {
const rows: TreeRow[] = []
for (const device of KEYBINDING_CATALOG) {
const deviceExpanded = expanded.value.has(device.id)
rows.push({
id: device.id,
kind: 'device',
level: 0,
label: formatMessage(device.label),
expandable: true,
expanded: deviceExpanded,
selected: false,
disabled: false,
})
if (!deviceExpanded) continue
for (const group of device.groups) {
const rowId = groupRowId(device.id, group.id)
const groupExpanded = expanded.value.has(rowId)
rows.push({
id: rowId,
kind: 'group',
level: 1,
label: formatMessage(group.label),
expandable: true,
expanded: groupExpanded,
selected: false,
disabled: false,
})
if (!groupExpanded) continue
for (const item of group.items) {
const state = itemState(item)
rows.push({
id: itemRowId(device.id, group.id, item.code),
kind: 'item',
level: 2,
label: itemLabel(item),
expandable: false,
expanded: false,
selected: props.binding?.device === item.device && props.binding?.code === item.code,
item,
...state,
})
}
}
}
return rows
})
function setRowRef(id: string, element: unknown) {
if (element instanceof HTMLElement) rowRefs.set(id, element)
else rowRefs.delete(id)
}
function focusRow(index: number) {
const row = visibleRows.value[index]
if (!row) return
activeIndex.value = index
void nextTick(() => rowRefs.get(row.id)?.focus())
}
function toggle(row: TreeRow) {
if (!row.expandable) return
const next = new Set(expanded.value)
if (next.has(row.id)) next.delete(row.id)
else next.add(row.id)
expanded.value = next
// Collapsing can leave the active row past the end, which would stop the
// keyboard from moving anywhere.
const lastIndex = visibleRows.value.length - 1
if (activeIndex.value > lastIndex) focusRow(lastIndex)
}
function parentIndexOf(row: TreeRow) {
for (let index = visibleRows.value.indexOf(row) - 1; index >= 0; index -= 1) {
if (visibleRows.value[index].level < row.level) return index
}
return -1
}
function activateRow(row: TreeRow) {
if (row.kind === 'item') {
if (row.disabled || !row.item) return
emit('select', { device: row.item.device, code: row.item.code })
return
}
toggle(row)
}
function handleKeydown(event: KeyboardEvent) {
const row = visibleRows.value[activeIndex.value]
if (!row) return
switch (event.key) {
case 'ArrowDown':
event.preventDefault()
focusRow(Math.min(activeIndex.value + 1, visibleRows.value.length - 1))
break
case 'ArrowUp':
event.preventDefault()
focusRow(Math.max(activeIndex.value - 1, 0))
break
case 'ArrowRight':
event.preventDefault()
if (row.expandable && !row.expanded) toggle(row)
else if (row.expandable) focusRow(activeIndex.value + 1)
break
case 'ArrowLeft': {
event.preventDefault()
if (row.expandable && row.expanded) {
toggle(row)
break
}
const parent = parentIndexOf(row)
if (parent !== -1) focusRow(parent)
break
}
case 'Home':
event.preventDefault()
focusRow(0)
break
case 'End':
event.preventDefault()
focusRow(visibleRows.value.length - 1)
break
case 'Enter':
case ' ':
event.preventDefault()
activateRow(row)
break
case 'Escape':
// Handled here so escape leaves the picker instead of the whole dialog.
event.preventDefault()
event.stopPropagation()
emit('escape')
break
default:
break
}
}
</script>
@@ -0,0 +1,574 @@
<template>
<NewModal
ref="modal"
:header="headerText"
max-width="540px"
:on-hide="handleModalHide"
:close-on-click-outside="false"
>
<div class="flex min-w-0 flex-col gap-4">
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex min-w-0 flex-col gap-1">
<span class="text-sm text-[var(--color-text-tertiary)]">{{
formatMessage(messages.current)
}}</span>
<KeybindingChips v-if="props.binding" :binding="props.binding" />
<span v-else class="text-sm text-[var(--color-text-tertiary)]">{{
formatMessage(messages.unset)
}}</span>
</div>
<Button v-if="canRestoreDefault" type="outlined" size="2xs" @click="restoreDefault"
>{{ formatMessage(messages.restoreDefault) }}
</Button>
</div>
<button
v-if="phase !== 'tree'"
type="button"
class="flex min-h-[7rem] cursor-pointer flex-col items-center justify-center gap-3 rounded-xl border-2 border-dashed p-4 transition-colors duration-200"
:class="
phase === 'listening'
? 'border-brand bg-brand-highlight'
: 'border-surface-4 bg-surface-2 hover:border-brand'
"
:disabled="phase !== 'idle'"
@click="beginListening"
>
<template v-if="phase === 'listening'">
<span class="text-base font-semibold text-[var(--color-text-primary)]">
{{ formatMessage(messages.listeningTitle) }}
</span>
<span v-if="liveParts.length" class="flex flex-wrap items-center justify-center gap-1">
<kbd
v-for="(part, index) in liveParts"
:key="`${index}-${part}`"
class="rounded-md border border-solid border-surface-4 bg-surface-3 px-2 py-0.5 font-mono text-sm text-[var(--color-text-primary)]"
>
{{ part }}
</kbd>
</span>
<span v-else class="text-sm text-[var(--color-text-tertiary)]">
{{ formatMessage(messages.listeningHint) }}
</span>
<span class="block h-1 w-full max-w-[16rem] overflow-hidden rounded-full bg-surface-4">
<span
:key="captureRun"
class="keybinding-capture-bar block h-full rounded-full bg-brand"
:style="{ animationDuration: `${props.listenDurationMs}ms` }"
/>
</span>
</template>
<template v-else-if="phase === 'verifying'">
<span class="text-base font-semibold text-[var(--color-text-primary)]">
{{ formatMessage(verified ? messages.verifiedTitle : messages.verifyingTitle) }}
</span>
<KeybindingChips v-if="candidate" :binding="candidate" />
<span v-if="!verified" class="text-sm text-[var(--color-text-tertiary)]">
{{ formatMessage(messages.verifyingHint) }}
</span>
</template>
<template v-else>
<span class="text-base font-semibold text-[var(--color-text-primary)]">
{{ formatMessage(messages.captureTitle) }}
</span>
<span class="text-sm text-[var(--color-text-tertiary)]">{{
formatMessage(messages.captureHint)
}}</span>
</template>
</button>
<template v-else>
<div
class="flex flex-col gap-2 rounded-xl border border-solid border-surface-4 bg-surface-2 p-3"
>
<span class="text-sm font-semibold text-[var(--color-text-primary)]">
{{ formatMessage(messages.modifiers) }}
</span>
<div class="flex flex-wrap gap-2">
<Button
v-for="modifier in modifierOptions"
:key="modifier.field"
size="2xs"
:type="modifierState[modifier.field] ? 'highlight' : 'outlined'"
:aria-pressed="modifierState[modifier.field]"
@click="modifierState[modifier.field] = !modifierState[modifier.field]"
>
{{ modifier.label }}
</Button>
</div>
</div>
<KeybindingChoiceTree
:binding="treeBinding"
:disabled-codes="treeDisabledCodes"
@select="selectTreeInput"
@escape="phase = 'idle'"
/>
</template>
<div class="flex flex-col gap-1" aria-live="polite">
<p v-if="issueText" class="m-0 text-sm text-red">{{ issueText }}</p>
<p v-else-if="mismatchText" class="m-0 text-sm text-orange">{{ mismatchText }}</p>
<p v-else-if="verified" class="m-0 text-sm text-green">
{{ formatMessage(messages.verifiedHint) }}
</p>
<p v-else-if="nothingCapturedText" class="m-0 text-sm text-[var(--color-text-tertiary)]">
{{ nothingCapturedText }}
</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<Button v-if="phase === 'tree'" type="outlined" @click="leaveTree"
>{{ formatMessage(messages.useCapture) }}
</Button>
<Button v-else type="outlined" @click="enterTree"
>{{ formatMessage(messages.useSpecial) }}
</Button>
<span v-if="phase === 'tree'" class="text-xs text-[var(--color-text-tertiary)]">
{{ formatMessage(messages.specialHint) }}
</span>
</div>
</div>
<template #actions>
<div class="flex justify-end gap-2">
<Button type="outlined" @click="cancel">{{ formatMessage(messages.cancel) }}</Button>
<Button type="colored" color="brand" :disabled="!canSave" @click="save"
>{{ formatMessage(messages.save) }}
</Button>
</div>
</template>
</NewModal>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
import { defineMessages, useVIntl } from '../../composables/i18n'
import { useKeybindingLabels } from '../../composables/use-keybinding-labels'
import {
type BindingConflict,
bindingFromKeyboardEvent,
bindingsEqual,
isModifierCode,
type KeyBinding,
keyCodeLabel,
validateBinding,
} from '../../utils/keybinding'
import { KEYBINDING_CATALOG } from '../../utils/keybinding-catalog'
import Button from '../base/buttons/Button.vue'
import KeybindingChips from '../base/KeybindingChips.vue'
import KeybindingChoiceTree from './KeybindingChoiceTree.vue'
import NewModal from './NewModal.vue'
const props = withDefaults(
defineProps<{
/** The action being configured, shown in the title. */
actionLabel?: string
/** The combination the action answers to right now. */
binding?: KeyBinding | null
/** The combination the action ships with, offered as a way back. */
defaultBinding?: KeyBinding | null
/** Combinations that belong to something else. */
conflicts?: BindingConflict[]
/** How long a recording may run before it settles on its own. */
listenDurationMs?: number
/** How long after the last key is released a recording settles. */
settleMs?: number
}>(),
{
actionLabel: undefined,
binding: null,
defaultBinding: null,
conflicts: () => [],
listenDurationMs: 5000,
settleMs: 700,
},
)
const emit = defineEmits<{
save: [binding: KeyBinding]
cancel: []
}>()
const { formatMessage } = useVIntl()
const labels = useKeybindingLabels()
const messages = defineMessages({
title: { id: 'ui.keybinding-modal.title', defaultMessage: 'Set a shortcut' },
titleFor: {
id: 'ui.keybinding-modal.title-for',
defaultMessage: 'Shortcut for {action}',
},
current: { id: 'ui.keybinding-modal.current', defaultMessage: 'Current shortcut' },
unset: { id: 'ui.keybinding-modal.unset', defaultMessage: 'Not set' },
restoreDefault: {
id: 'ui.keybinding-modal.restore-default',
defaultMessage: 'Restore default',
},
captureTitle: {
id: 'ui.keybinding-modal.capture-title',
defaultMessage: 'Click here to record',
},
captureHint: {
id: 'ui.keybinding-modal.capture-hint',
defaultMessage: 'Then press the keys you want this shortcut to use.',
},
listeningTitle: {
id: 'ui.keybinding-modal.listening-title',
defaultMessage: 'Listening\u2026',
},
listeningHint: {
id: 'ui.keybinding-modal.listening-hint',
defaultMessage: 'Press the keys you want to use.',
},
verifyingTitle: {
id: 'ui.keybinding-modal.verifying-title',
defaultMessage: 'Press it again to confirm',
},
verifyingHint: {
id: 'ui.keybinding-modal.verifying-hint',
defaultMessage: 'This checks the combination was recorded correctly.',
},
verifiedTitle: {
id: 'ui.keybinding-modal.verified-title',
defaultMessage: 'Confirmed',
},
verifiedHint: {
id: 'ui.keybinding-modal.verified-hint',
defaultMessage: 'Confirmed. Save to use this shortcut.',
},
issueConflict: {
id: 'ui.keybinding-modal.issue-conflict',
defaultMessage: 'Already used by {label}.',
},
issueReserved: {
id: 'ui.keybinding-modal.issue-reserved',
defaultMessage: '{label} is reserved by the launcher.',
},
issueNeedsModifier: {
id: 'ui.keybinding-modal.issue-needs-modifier',
defaultMessage: 'Hold Ctrl/Cmd, Alt or Shift as well, or pick a function or navigation key.',
},
mismatch: {
id: 'ui.keybinding-modal.mismatch',
defaultMessage: 'That was a different combination, so recording started again.',
},
nothingCaptured: {
id: 'ui.keybinding-modal.nothing-captured',
defaultMessage: 'No key was recorded.',
},
useSpecial: {
id: 'ui.keybinding-modal.use-special',
defaultMessage: 'Pick an input another way',
},
useCapture: {
id: 'ui.keybinding-modal.use-capture',
defaultMessage: 'Record a combination instead',
},
specialHint: {
id: 'ui.keybinding-modal.special-hint',
defaultMessage: 'Mouse buttons, the wheel and combinations with them can only be picked here.',
},
modifiers: { id: 'ui.keybinding-modal.modifiers', defaultMessage: 'Modifiers' },
save: { id: 'ui.keybinding-modal.save', defaultMessage: 'Save' },
cancel: { id: 'ui.keybinding-modal.cancel', defaultMessage: 'Cancel' },
})
type Phase = 'idle' | 'listening' | 'verifying' | 'tree'
const modal = ref<InstanceType<typeof NewModal>>()
const phase = ref<Phase>('idle')
const candidate = ref<KeyBinding | null>(null)
const livePressed = ref<KeyBinding | null>(null)
const captured = ref<KeyBinding | null>(null)
const mismatch = ref<KeyBinding | null>(null)
const nothingCaptured = ref(false)
const verified = ref(false)
const captureRun = ref(0)
const treeInput = ref<{ device: KeyBinding['device']; code: string } | null>(null)
const modifierState = reactive({ mod: false, shift: false, alt: false })
let listenTimer: number | undefined
let settleTimer: number | undefined
const headerText = computed(() =>
props.actionLabel
? formatMessage(messages.titleFor, { action: props.actionLabel })
: formatMessage(messages.title),
)
const modifierOptions = computed(() => [
{ field: 'mod' as const, label: labels.value.mod },
{ field: 'alt' as const, label: labels.value.alt },
{ field: 'shift' as const, label: labels.value.shift },
])
const liveParts = computed(() => {
const pressed = livePressed.value
if (!pressed) return []
const parts: string[] = []
if (pressed.mod) parts.push(labels.value.mod)
if (pressed.alt) parts.push(labels.value.alt)
if (pressed.shift) parts.push(labels.value.shift)
if (!isModifierCode(pressed.code)) parts.push(keyCodeLabel(pressed.code))
return parts
})
const treeBinding = computed<KeyBinding | null>(() =>
treeInput.value ? { ...treeInput.value, ...modifierState } : null,
)
const proposed = computed(() => (phase.value === 'tree' ? treeBinding.value : candidate.value))
const canRestoreDefault = computed(
() =>
Boolean(props.defaultBinding) &&
(!props.binding || !bindingsEqual(props.binding, props.defaultBinding as KeyBinding)),
)
const issue = computed(() =>
proposed.value ? validateBinding(proposed.value, props.conflicts) : null,
)
const issueText = computed(() => {
const value = issue.value
if (!value) return null
if (value.kind === 'needs-modifier') return formatMessage(messages.issueNeedsModifier)
return formatMessage(value.reserved ? messages.issueReserved : messages.issueConflict, {
label: value.label,
})
})
const mismatchText = computed(() => (mismatch.value ? formatMessage(messages.mismatch) : null))
const nothingCapturedText = computed(() =>
nothingCaptured.value ? formatMessage(messages.nothingCaptured) : null,
)
const isVerified = computed(() => phase.value === 'tree' || verified.value)
const canSave = computed(() => Boolean(proposed.value) && !issue.value && isVerified.value)
/** Inputs the picker must refuse, keyed by code, with the reason to show. */
const treeDisabledCodes = computed(() => {
const disabled = new Map<string, string>()
for (const device of KEYBINDING_CATALOG) {
for (const group of device.groups) {
for (const item of group.items) {
const found = validateBinding(
{ device: item.device, code: item.code, ...modifierState },
props.conflicts,
)
if (found?.kind === 'conflict') {
disabled.set(
item.code,
formatMessage(found.reserved ? messages.issueReserved : messages.issueConflict, {
label: found.label,
}),
)
}
}
}
}
return disabled
})
function clearTimers() {
window.clearTimeout(listenTimer)
window.clearTimeout(settleTimer)
listenTimer = undefined
settleTimer = undefined
}
function beginListening() {
clearTimers()
candidate.value = null
livePressed.value = null
captured.value = null
nothingCaptured.value = false
verified.value = false
captureRun.value += 1
phase.value = 'listening'
listenTimer = window.setTimeout(finishListening, props.listenDurationMs)
}
function finishListening() {
clearTimers()
if (!captured.value) {
nothingCaptured.value = true
phase.value = 'idle'
return
}
candidate.value = captured.value
mismatch.value = null
verified.value = false
phase.value = 'verifying'
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
// Leaving the recording is a step back, not closing the dialog.
event.preventDefault()
// Immediate: the dialog's own escape handler sits on the same node.
event.stopImmediatePropagation()
clearTimers()
phase.value = 'idle'
return
}
if (phase.value === 'listening') {
event.preventDefault()
event.stopImmediatePropagation()
livePressed.value = {
device: 'keyboard',
code: event.code,
mod: event.ctrlKey || event.metaKey,
shift: event.shiftKey,
alt: event.altKey,
}
const combination = bindingFromKeyboardEvent(event)
if (combination) {
captured.value = combination
window.clearTimeout(settleTimer)
settleTimer = undefined
}
return
}
if (phase.value === 'verifying') {
event.preventDefault()
event.stopImmediatePropagation()
const attempt = bindingFromKeyboardEvent(event)
if (!attempt || !candidate.value) return
if (bindingsEqual(attempt, candidate.value)) {
verified.value = true
mismatch.value = null
return
}
mismatch.value = attempt
beginListening()
}
}
function handleKeyup(event: KeyboardEvent) {
if (phase.value !== 'listening') return
event.stopPropagation()
const stillHeld = event.ctrlKey || event.metaKey || event.shiftKey || event.altKey
if (stillHeld || !captured.value) return
// Nothing is held any more, so the combination is as complete as it gets.
window.clearTimeout(settleTimer)
settleTimer = window.setTimeout(finishListening, props.settleMs)
}
function attachListeners() {
window.addEventListener('keydown', handleKeydown, true)
window.addEventListener('keyup', handleKeyup, true)
}
function detachListeners() {
window.removeEventListener('keydown', handleKeydown, true)
window.removeEventListener('keyup', handleKeyup, true)
}
watch(phase, (value) => {
if (value === 'listening' || value === 'verifying') attachListeners()
else detachListeners()
})
onBeforeUnmount(() => {
clearTimers()
detachListeners()
})
function enterTree() {
const source = candidate.value ?? props.binding
modifierState.mod = source?.mod ?? false
modifierState.alt = source?.alt ?? false
modifierState.shift = source?.shift ?? false
treeInput.value = source ? { device: source.device, code: source.code } : null
phase.value = 'tree'
}
function leaveTree() {
treeInput.value = null
phase.value = 'idle'
}
function selectTreeInput(input: { device: KeyBinding['device']; code: string }) {
treeInput.value = input
}
function restoreDefault() {
if (!props.defaultBinding) return
candidate.value = props.defaultBinding
mismatch.value = null
nothingCaptured.value = false
verified.value = true
phase.value = 'verifying'
}
function reset() {
clearTimers()
phase.value = 'idle'
candidate.value = null
livePressed.value = null
captured.value = null
mismatch.value = null
nothingCaptured.value = false
verified.value = false
treeInput.value = null
modifierState.mod = false
modifierState.alt = false
modifierState.shift = false
}
function handleModalHide() {
reset()
}
function show() {
reset()
modal.value?.show()
}
function hide() {
modal.value?.hide()
}
function save() {
const value = proposed.value
if (!value || !canSave.value) return
emit('save', value)
modal.value?.hide()
}
function cancel() {
emit('cancel')
modal.value?.hide()
}
defineExpose({ show, hide })
</script>
<style scoped>
@keyframes keybinding-capture-drain {
from {
width: 100%;
}
to {
width: 0%;
}
}
.keybinding-capture-bar {
animation-name: keybinding-capture-drain;
animation-timing-function: linear;
animation-fill-mode: forwards;
}
@media (prefers-reduced-motion: reduce) {
.keybinding-capture-bar {
animation: none;
width: 100%;
}
}
</style>
@@ -8,3 +8,4 @@ export { default as ShareModal } from './ShareModal.vue'
export type { Tab as TabbedModalTab } from './TabbedModal.vue'
export { default as TabbedModal } from './TabbedModal.vue'
export { default as UploadProgressModal } from './UploadProgressModal.vue'
export { default as KeybindingModal } from './KeybindingModal.vue'
+1
View File
@@ -30,3 +30,4 @@ export * from './use-loading-state-core'
export * from './use-ready-state'
export * from './use-server-image'
export * from './virtual-scroll'
export * from './use-keybinding-labels'
@@ -0,0 +1,54 @@
import { computed } from 'vue'
import {
bindingParts,
bindingText,
type KeyBinding,
type KeybindingLabels,
} from '../utils/keybinding'
import { MOUSE_CODE_MESSAGES } from '../utils/keybinding-catalog'
import { defineMessages, useVIntl } from './i18n'
const messages = defineMessages({
mod: { id: 'ui.keybinding-modal.mod', defaultMessage: 'Ctrl/Cmd' },
shift: { id: 'ui.keybinding-modal.shift', defaultMessage: 'Shift' },
alt: { id: 'ui.keybinding-modal.alt', defaultMessage: 'Alt' },
})
/**
* The names a combination is built from, in the reader's language. Shared so a
* shortcut reads the same wherever it is shown.
*/
export function useKeybindingLabels() {
const { formatMessage } = useVIntl()
return computed<KeybindingLabels>(() => ({
mod: formatMessage(messages.mod),
shift: formatMessage(messages.shift),
alt: formatMessage(messages.alt),
mouseButton: Object.fromEntries(
Object.entries(MOUSE_CODE_MESSAGES).map(([code, message]) => [code, formatMessage(message)]),
),
wheelUp: formatMessage(MOUSE_CODE_MESSAGES.WheelUp),
wheelDown: formatMessage(MOUSE_CODE_MESSAGES.WheelDown),
}))
}
/** Splits a combination into the pieces a key cap is drawn for. */
export function useBindingParts(binding: () => KeyBinding | null) {
const labels = useKeybindingLabels()
return computed(() => {
const value = binding()
return value ? bindingParts(value, labels.value) : []
})
}
export function useBindingText(binding: () => KeyBinding | null) {
const labels = useKeybindingLabels()
return computed(() => {
const value = binding()
return value ? bindingText(value, labels.value) : ''
})
}
@@ -1,5 +1,6 @@
export { default as JLineCommandInput } from './components/JLineCommandInput.vue'
export { default as LogViewport } from './components/LogViewport.vue'
export * from './jline'
export { default as ConsolePageLayout } from './layout.vue'
export * from './providers'
export * from './types'
export * from './types'
+45 -1
View File
@@ -4861,5 +4861,49 @@
},
"skin.preview.armor.unequipped": {
"defaultMessage": "Unequipped"
}
},
"ui.keybinding-modal.alt": {"defaultMessage": "Alt"},
"ui.keybinding-modal.cancel": {"defaultMessage": "Cancel"},
"ui.keybinding-modal.capture-hint": {"defaultMessage": "Then press the keys you want this shortcut to use."},
"ui.keybinding-modal.capture-title": {"defaultMessage": "Click here to record"},
"ui.keybinding-modal.current": {"defaultMessage": "Current shortcut"},
"ui.keybinding-modal.device-keyboard": {"defaultMessage": "Keyboard"},
"ui.keybinding-modal.device-mouse": {"defaultMessage": "Mouse"},
"ui.keybinding-modal.group-digits": {"defaultMessage": "Digits"},
"ui.keybinding-modal.group-function": {"defaultMessage": "Function keys"},
"ui.keybinding-modal.group-letters": {"defaultMessage": "Letters"},
"ui.keybinding-modal.group-mouse-buttons": {"defaultMessage": "Buttons"},
"ui.keybinding-modal.group-navigation": {"defaultMessage": "Navigation keys"},
"ui.keybinding-modal.group-punctuation": {"defaultMessage": "Punctuation"},
"ui.keybinding-modal.group-wheel": {"defaultMessage": "Wheel"},
"ui.keybinding-modal.issue-conflict": {"defaultMessage": "Already used by {label}."},
"ui.keybinding-modal.issue-needs-modifier": {"defaultMessage": "Hold Ctrl/Cmd, Alt or Shift as well, or pick a function or navigation key."},
"ui.keybinding-modal.issue-reserved": {"defaultMessage": "{label} is reserved by the launcher."},
"ui.keybinding-modal.listening-hint": {"defaultMessage": "Press the keys you want to use."},
"ui.keybinding-modal.listening-title": {"defaultMessage": "Listening…"},
"ui.keybinding-modal.mismatch": {"defaultMessage": "That was a different combination, so recording started again."},
"ui.keybinding-modal.mod": {"defaultMessage": "Ctrl/Cmd"},
"ui.keybinding-modal.modifiers": {"defaultMessage": "Modifiers"},
"ui.keybinding-modal.mouse-back": {"defaultMessage": "Back button"},
"ui.keybinding-modal.mouse-forward": {"defaultMessage": "Forward button"},
"ui.keybinding-modal.mouse-left": {"defaultMessage": "Left click"},
"ui.keybinding-modal.mouse-middle": {"defaultMessage": "Middle click"},
"ui.keybinding-modal.mouse-right": {"defaultMessage": "Right click"},
"ui.keybinding-modal.nothing-captured": {"defaultMessage": "No key was recorded."},
"ui.keybinding-modal.restore-default": {"defaultMessage": "Restore default"},
"ui.keybinding-modal.save": {"defaultMessage": "Save"},
"ui.keybinding-modal.shift": {"defaultMessage": "Shift"},
"ui.keybinding-modal.special-hint": {"defaultMessage": "Mouse buttons, the wheel and combinations with them can only be picked here."},
"ui.keybinding-modal.title": {"defaultMessage": "Set a shortcut"},
"ui.keybinding-modal.title-for": {"defaultMessage": "Shortcut for {action}"},
"ui.keybinding-modal.tree-label": {"defaultMessage": "Inputs a shortcut can use"},
"ui.keybinding-modal.unset": {"defaultMessage": "Not set"},
"ui.keybinding-modal.use-capture": {"defaultMessage": "Record a combination instead"},
"ui.keybinding-modal.use-special": {"defaultMessage": "Pick an input another way"},
"ui.keybinding-modal.verified-hint": {"defaultMessage": "Confirmed. Save to use this shortcut."},
"ui.keybinding-modal.verified-title": {"defaultMessage": "Confirmed"},
"ui.keybinding-modal.verifying-hint": {"defaultMessage": "This checks the combination was recorded correctly."},
"ui.keybinding-modal.verifying-title": {"defaultMessage": "Press it again to confirm"},
"ui.keybinding-modal.wheel-down": {"defaultMessage": "Wheel down"},
"ui.keybinding-modal.wheel-up": {"defaultMessage": "Wheel up"}
}
+45 -1
View File
@@ -4882,5 +4882,49 @@
},
"skin.preview.armor.unequipped": {
"message": "未装备"
}
},
"ui.keybinding-modal.alt": {"defaultMessage": "Alt"},
"ui.keybinding-modal.cancel": {"defaultMessage": "取消"},
"ui.keybinding-modal.capture-hint": {"defaultMessage": "然后按下你想让这个快捷键使用的按键。"},
"ui.keybinding-modal.capture-title": {"defaultMessage": "点击此处开始录制"},
"ui.keybinding-modal.current": {"defaultMessage": "当前快捷键"},
"ui.keybinding-modal.device-keyboard": {"defaultMessage": "键盘"},
"ui.keybinding-modal.device-mouse": {"defaultMessage": "鼠标"},
"ui.keybinding-modal.group-digits": {"defaultMessage": "数字键"},
"ui.keybinding-modal.group-function": {"defaultMessage": "功能键"},
"ui.keybinding-modal.group-letters": {"defaultMessage": "字母键"},
"ui.keybinding-modal.group-mouse-buttons": {"defaultMessage": "鼠标键"},
"ui.keybinding-modal.group-navigation": {"defaultMessage": "导航键"},
"ui.keybinding-modal.group-punctuation": {"defaultMessage": "符号键"},
"ui.keybinding-modal.group-wheel": {"defaultMessage": "滚轮"},
"ui.keybinding-modal.issue-conflict": {"defaultMessage": "已被「{label}」占用。"},
"ui.keybinding-modal.issue-needs-modifier": {"defaultMessage": "请同时按住 Ctrl/Cmd、Alt 或 Shift,或改选功能键、导航键。"},
"ui.keybinding-modal.issue-reserved": {"defaultMessage": "「{label}」由启动器保留。"},
"ui.keybinding-modal.listening-hint": {"defaultMessage": "请按下你想使用的按键。"},
"ui.keybinding-modal.listening-title": {"defaultMessage": "正在监听…"},
"ui.keybinding-modal.mismatch": {"defaultMessage": "组合不一致,已重新开始录制。"},
"ui.keybinding-modal.mod": {"defaultMessage": "Ctrl/Cmd"},
"ui.keybinding-modal.modifiers": {"defaultMessage": "修饰键"},
"ui.keybinding-modal.mouse-back": {"defaultMessage": "后退键"},
"ui.keybinding-modal.mouse-forward": {"defaultMessage": "前进键"},
"ui.keybinding-modal.mouse-left": {"defaultMessage": "鼠标左键"},
"ui.keybinding-modal.mouse-middle": {"defaultMessage": "鼠标中键"},
"ui.keybinding-modal.mouse-right": {"defaultMessage": "鼠标右键"},
"ui.keybinding-modal.nothing-captured": {"defaultMessage": "没有录制到按键。"},
"ui.keybinding-modal.restore-default": {"defaultMessage": "恢复默认"},
"ui.keybinding-modal.save": {"defaultMessage": "保存"},
"ui.keybinding-modal.shift": {"defaultMessage": "Shift"},
"ui.keybinding-modal.special-hint": {"defaultMessage": "鼠标键、滚轮以及与它们组合的按键只能在这里选择。"},
"ui.keybinding-modal.title": {"defaultMessage": "设置快捷键"},
"ui.keybinding-modal.title-for": {"defaultMessage": "设置「{action}」的快捷键"},
"ui.keybinding-modal.tree-label": {"defaultMessage": "快捷键可用的输入"},
"ui.keybinding-modal.unset": {"defaultMessage": "未设置"},
"ui.keybinding-modal.use-capture": {"defaultMessage": "改用按键录制"},
"ui.keybinding-modal.use-special": {"defaultMessage": "改用特殊方式选择"},
"ui.keybinding-modal.verified-hint": {"defaultMessage": "已确认,保存后生效。"},
"ui.keybinding-modal.verified-title": {"defaultMessage": "已确认"},
"ui.keybinding-modal.verifying-hint": {"defaultMessage": "用于确认组合是否被正确录制。"},
"ui.keybinding-modal.verifying-title": {"defaultMessage": "请再按一次以确认"},
"ui.keybinding-modal.wheel-down": {"defaultMessage": "滚轮向下"},
"ui.keybinding-modal.wheel-up": {"defaultMessage": "滚轮向上"}
}
+2
View File
@@ -16,3 +16,5 @@ export * from './truncate'
export * from './version-compatibility'
export * from './vue-children'
export * from './webgl/skin-rendering'
export * from './keybinding'
export * from './keybinding-catalog'
+149
View File
@@ -0,0 +1,149 @@
import { defineMessages } from '../composables/i18n'
import type { KeyBindingDevice } from './keybinding'
/** Structurally identical to the i18n `MessageDescriptor`, without the dependency. */
export interface CatalogMessage {
id: string
defaultMessage: string
}
export interface KeybindingCatalogItem {
device: KeyBindingDevice
code: string
/** Set for inputs whose name has to be translated; key caps read the same everywhere. */
label?: CatalogMessage
}
export interface KeybindingCatalogGroup {
id: string
label: CatalogMessage
items: KeybindingCatalogItem[]
}
export interface KeybindingCatalogDevice {
id: KeyBindingDevice
label: CatalogMessage
groups: KeybindingCatalogGroup[]
}
const messages = defineMessages({
mouseLeft: { id: 'ui.keybinding-modal.mouse-left', defaultMessage: 'Left click' },
mouseMiddle: { id: 'ui.keybinding-modal.mouse-middle', defaultMessage: 'Middle click' },
mouseRight: { id: 'ui.keybinding-modal.mouse-right', defaultMessage: 'Right click' },
mouseBack: { id: 'ui.keybinding-modal.mouse-back', defaultMessage: 'Back button' },
mouseForward: { id: 'ui.keybinding-modal.mouse-forward', defaultMessage: 'Forward button' },
wheelUp: { id: 'ui.keybinding-modal.wheel-up', defaultMessage: 'Wheel up' },
wheelDown: { id: 'ui.keybinding-modal.wheel-down', defaultMessage: 'Wheel down' },
deviceKeyboard: { id: 'ui.keybinding-modal.device-keyboard', defaultMessage: 'Keyboard' },
deviceMouse: { id: 'ui.keybinding-modal.device-mouse', defaultMessage: 'Mouse' },
groupLetters: { id: 'ui.keybinding-modal.group-letters', defaultMessage: 'Letters' },
groupDigits: { id: 'ui.keybinding-modal.group-digits', defaultMessage: 'Digits' },
groupFunction: { id: 'ui.keybinding-modal.group-function', defaultMessage: 'Function keys' },
groupNavigation: {
id: 'ui.keybinding-modal.group-navigation',
defaultMessage: 'Navigation keys',
},
groupPunctuation: {
id: 'ui.keybinding-modal.group-punctuation',
defaultMessage: 'Punctuation',
},
groupMouseButtons: {
id: 'ui.keybinding-modal.group-mouse-buttons',
defaultMessage: 'Buttons',
},
groupWheel: { id: 'ui.keybinding-modal.group-wheel', defaultMessage: 'Wheel' },
})
/**
* Names for the pointer inputs. Shared by the picker tree and by the chips that
* render a saved combination, so both read the same way.
*/
export const MOUSE_CODE_MESSAGES: Record<string, CatalogMessage> = {
Mouse0: messages.mouseLeft,
Mouse1: messages.mouseMiddle,
Mouse2: messages.mouseRight,
Mouse3: messages.mouseBack,
Mouse4: messages.mouseForward,
WheelUp: messages.wheelUp,
WheelDown: messages.wheelDown,
}
const LETTER_CODES: KeybindingCatalogItem[] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
.split('')
.map((letter) => ({ device: 'keyboard', code: `Key${letter}` }))
const DIGIT_CODES: KeybindingCatalogItem[] = '0123456789'
.split('')
.map((digit) => ({ device: 'keyboard', code: `Digit${digit}` }))
const FUNCTION_CODES: KeybindingCatalogItem[] = Array.from({ length: 12 }, (_, index) => ({
device: 'keyboard',
code: `F${index + 1}`,
}))
const NAVIGATION_CODES: KeybindingCatalogItem[] = [
'Home',
'End',
'PageUp',
'PageDown',
'Insert',
'Delete',
'ArrowUp',
'ArrowDown',
'ArrowLeft',
'ArrowRight',
].map((code) => ({ device: 'keyboard', code }))
const PUNCTUATION_CODES: KeybindingCatalogItem[] = [
'Comma',
'Period',
'Slash',
'Semicolon',
'Quote',
'BracketLeft',
'BracketRight',
'Backslash',
'Minus',
'Equal',
'Backquote',
'Space',
].map((code) => ({ device: 'keyboard', code }))
const MOUSE_ITEMS: KeybindingCatalogItem[] = Object.entries(MOUSE_CODE_MESSAGES).map(
([code, label]) => ({ device: 'mouse', code, label }),
)
/**
* Everything a shortcut can be attached to, grouped for the picker. Inputs that
* cannot be reproduced by pressing them - mouse buttons, the wheel, and any
* combination of those with the keyboard - are only reachable from here.
*/
export const KEYBINDING_CATALOG: KeybindingCatalogDevice[] = [
{
id: 'keyboard',
label: messages.deviceKeyboard,
groups: [
{ id: 'letters', label: messages.groupLetters, items: LETTER_CODES },
{ id: 'digits', label: messages.groupDigits, items: DIGIT_CODES },
{ id: 'function', label: messages.groupFunction, items: FUNCTION_CODES },
{ id: 'navigation', label: messages.groupNavigation, items: NAVIGATION_CODES },
{ id: 'punctuation', label: messages.groupPunctuation, items: PUNCTUATION_CODES },
],
},
{
id: 'mouse',
label: messages.deviceMouse,
groups: [
{
id: 'buttons',
label: messages.groupMouseButtons,
items: MOUSE_ITEMS.filter((item) => item.code.startsWith('Mouse')),
},
{
id: 'wheel',
label: messages.groupWheel,
items: MOUSE_ITEMS.filter((item) => item.code.startsWith('Wheel')),
},
],
},
]
+229
View File
@@ -0,0 +1,229 @@
/**
* The device a binding was recorded from. Keyboard bindings are matched against
* `KeyboardEvent`, mouse bindings against `MouseEvent` and `WheelEvent`.
*/
export type KeyBindingDevice = 'keyboard' | 'mouse'
/**
* A single shortcut. `mod` is the primary modifier held down: the launcher has
* always treated Ctrl and Cmd as one and the same, so a binding recorded on one
* platform keeps working on the other.
*/
export interface KeyBinding {
device: KeyBindingDevice
/** A `KeyboardEvent.code`, or one of the mouse codes below. */
code: string
mod: boolean
shift: boolean
alt: boolean
}
/** `MouseEvent.button`, in the order browsers report it. */
export const MOUSE_BUTTON_CODES = ['Mouse0', 'Mouse1', 'Mouse2', 'Mouse3', 'Mouse4'] as const
export const WHEEL_CODES = ['WheelUp', 'WheelDown'] as const
const MODIFIER_CODES = new Set([
'ControlLeft',
'ControlRight',
'ShiftLeft',
'ShiftRight',
'AltLeft',
'AltRight',
'MetaLeft',
'MetaRight',
'CapsLock',
])
/**
* Codes that may be bound on their own. Anything else has to carry a modifier,
* so a shortcut cannot swallow ordinary typing or list navigation.
*/
const MODIFIER_FREE_CODES = new Set<string>([
'Home',
'End',
'PageUp',
'PageDown',
...Array.from({ length: 24 }, (_, index) => `F${index + 1}`),
...MOUSE_BUTTON_CODES.filter((code) => code !== 'Mouse0'),
...WHEEL_CODES,
])
/**
* Codes that always need a modifier, whatever else is allowed. A bare left
* click is how the whole interface is operated, so it can never be a shortcut.
*/
const MODIFIER_REQUIRED_CODES = new Set<string>(['Mouse0'])
/** A combination someone else already answers to. */
export interface BindingConflict {
id: string
label: string
binding: KeyBinding
/** The shell or the operating system owns it rather than another action. */
reserved?: boolean
}
export type BindingIssue =
{ kind: 'conflict'; label: string; reserved: boolean } | { kind: 'needs-modifier' }
export interface KeybindingLabels {
mod: string
shift: string
alt: string
/** Keyed by mouse code, e.g. `Mouse0`. */
mouseButton: Record<string, string>
wheelUp: string
wheelDown: string
}
export function isModifierCode(code: string): boolean {
return MODIFIER_CODES.has(code)
}
export function isMouseCode(code: string): boolean {
return code.startsWith('Mouse') || (WHEEL_CODES as readonly string[]).includes(code)
}
/**
* Canonical form used to compare bindings, so two ways of recording the same
* combination still collide.
*/
export function bindingKey(binding: KeyBinding): string {
const modifiers = [binding.mod && 'mod', binding.alt && 'alt', binding.shift && 'shift']
.filter(Boolean)
.join('+')
return `${binding.device}|${binding.code}|${modifiers}`
}
export function bindingsEqual(a: KeyBinding, b: KeyBinding): boolean {
return bindingKey(a) === bindingKey(b)
}
function eventModifiers(event: MouseEvent | KeyboardEvent | WheelEvent) {
return {
mod: event.ctrlKey || event.metaKey,
shift: event.shiftKey,
alt: event.altKey,
}
}
/**
* The combination an event represents, or null while only modifiers are held -
* a lone Ctrl is not a shortcut.
*/
export function bindingFromKeyboardEvent(event: KeyboardEvent): KeyBinding | null {
if (event.repeat || isModifierCode(event.code)) return null
return { device: 'keyboard', code: event.code, ...eventModifiers(event) }
}
export function bindingFromMouseEvent(event: MouseEvent): KeyBinding | null {
const code = `Mouse${event.button}`
if (!(MOUSE_BUTTON_CODES as readonly string[]).includes(code)) return null
return { device: 'mouse', code, ...eventModifiers(event) }
}
export function bindingFromWheelEvent(event: WheelEvent): KeyBinding | null {
if (event.deltaY === 0) return null
const code = event.deltaY < 0 ? 'WheelUp' : 'WheelDown'
return { device: 'mouse', code, ...eventModifiers(event) }
}
function modifiersMatch(binding: KeyBinding, event: MouseEvent | KeyboardEvent | WheelEvent) {
const { mod, shift, alt } = eventModifiers(event)
return binding.mod === mod && binding.shift === shift && binding.alt === alt
}
export function bindingMatchesKeyboardEvent(binding: KeyBinding, event: KeyboardEvent): boolean {
return (
binding.device === 'keyboard' && binding.code === event.code && modifiersMatch(binding, event)
)
}
export function bindingMatchesMouseEvent(binding: KeyBinding, event: MouseEvent): boolean {
return (
binding.device === 'mouse' &&
binding.code === `Mouse${event.button}` &&
modifiersMatch(binding, event)
)
}
export function bindingMatchesWheelEvent(binding: KeyBinding, event: WheelEvent): boolean {
if (binding.device !== 'mouse' || event.deltaY === 0) return false
const code = event.deltaY < 0 ? 'WheelUp' : 'WheelDown'
return binding.code === code && modifiersMatch(binding, event)
}
/**
* Whether a combination may be saved, ignoring who it belongs to. Returns the
* problem to show instead of the binding when it may not.
*/
export function validateBinding(
binding: KeyBinding,
conflicts: BindingConflict[],
): BindingIssue | null {
const unmodified = !binding.mod && !binding.shift && !binding.alt
if (unmodified && MODIFIER_REQUIRED_CODES.has(binding.code)) {
return { kind: 'needs-modifier' }
}
if (unmodified && !MODIFIER_FREE_CODES.has(binding.code)) {
return { kind: 'needs-modifier' }
}
const conflict = conflicts.find((entry) => bindingsEqual(entry.binding, binding))
if (conflict) {
return { kind: 'conflict', label: conflict.label, reserved: conflict.reserved ?? false }
}
return null
}
const CODE_LABELS: Record<string, string> = {
ArrowUp: '\u2191',
ArrowDown: '\u2193',
ArrowLeft: '\u2190',
ArrowRight: '\u2192',
PageUp: 'Page Up',
PageDown: 'Page Down',
Escape: 'Esc',
Space: 'Space',
Insert: 'Insert',
Delete: 'Delete',
Comma: ',',
Period: '.',
Slash: '/',
Semicolon: ';',
Quote: "'",
BracketLeft: '[',
BracketRight: ']',
Backslash: '\\',
Minus: '-',
Equal: '=',
Backquote: '`',
}
/** How a single code reads on a key cap. */
export function keyCodeLabel(code: string): string {
if (code.startsWith('Key')) return code.slice(3)
if (code.startsWith('Digit')) return code.slice(5)
if (code.startsWith('Numpad')) return `Num ${code.slice(6)}`
return CODE_LABELS[code] ?? code
}
/** The combination split into the pieces a key cap is drawn for. */
export function bindingParts(binding: KeyBinding, labels: KeybindingLabels): string[] {
const parts: string[] = []
if (binding.mod) parts.push(labels.mod)
if (binding.alt) parts.push(labels.alt)
if (binding.shift) parts.push(labels.shift)
if (binding.code === 'WheelUp') parts.push(labels.wheelUp)
else if (binding.code === 'WheelDown') parts.push(labels.wheelDown)
else if (binding.device === 'mouse') parts.push(labels.mouseButton[binding.code] ?? binding.code)
else parts.push(keyCodeLabel(binding.code))
return parts
}
export function bindingText(binding: KeyBinding, labels: KeybindingLabels): string {
return bindingParts(binding, labels).join(' + ')
}
+22 -2
View File
@@ -28,6 +28,13 @@ export function truncateLogToMaxBytes(content: string, maxBytes: number): string
return textDecoder.decode(bytes.subarray(start))
}
/**
* Log sharing providers supported by the launcher. LogShare is the default
* and is implemented in the desktop app through native Tauri commands; mclo.gs
* is the network fallback used when LogShare is unreachable or unselected.
*/
export type LogShareProvider = 'logshare' | 'mclogs'
/**
* Result of sharing log content. `truncated` is set when the content exceeded
* `LOG_SHARE_MAX_BYTES` and only its tail was uploaded.
@@ -39,12 +46,25 @@ export type LogShareResult = {
/**
* Share log content through mclo.gs. Content larger than `LOG_SHARE_MAX_BYTES`
* is trimmed to its last
* `LOG_SHARE_MAX_BYTES` before uploading.
* is trimmed to its last `LOG_SHARE_MAX_BYTES` before uploading.
*/
export async function shareLogs(
client: AbstractModrinthClient,
content: string,
): Promise<LogShareResult> {
return shareLogsWithProvider(client, content, 'mclogs')
}
/**
* Share log content through the given provider. The `logshare` provider is
* only available inside the desktop app (native commands); this shared helper
* routes the `mclogs` fallback so both launcher surfaces can share generic
* log buffers.
*/
export async function shareLogsWithProvider(
client: AbstractModrinthClient,
content: string,
_provider: LogShareProvider = 'mclogs',
): Promise<LogShareResult> {
const uploadContent = truncateLogToMaxBytes(content, LOG_SHARE_MAX_BYTES)
const truncated = uploadContent !== content
+1
View File
@@ -30,6 +30,7 @@ const allowedUntranslatedMessages = new Set([
'Cleanroom',
'LiteLoader',
'LogShare.CN',
'LogShare AI',
'NeoForge',
'OptiFine',
'Quilt',