按审查结论重构:先补测试网,再搬代码

顺序是刻意的。前端一行测试都没有,直接挪代码挪坏了 bun test 不会红,所以先把纯逻辑
抽到能被测试的位置并补上用例,最后才动组件。测试从 37 条增加到 77 条。

抽出来的四块:
- shared/outbound-chain.ts  「这个端口现在走哪条线」的链路解析,带防环,9 条测试
- web/delay-test.ts          延迟测试失败时说什么,6 个分支原本一条测试都没有
- web/runtime.ts             运行时状态的模块级单例,照 prefs.ts 已有的模式
- web/components/InboundList.vue  入站列表

出站的文本原本散成四份(读一份、显示一份、写回一份、表单又抄一份),加一种出站模式
要同时改四处,漏一个就是显示与写回不一致。合并成 OUTBOUND_PRESETS 一张表。

给认证和透传白名单补了 20 条测试。两者都是安全边界、都是纯函数、都不需要内核在线,
之前却只靠需要活内核的冒烟脚本间接覆盖。其中「形似但不是健康检查的路径」几条确认了
正则没写松。

另外:配置快照不再把整份文件原文下发(前端从不读,白白让响应体积翻倍);
yaml-cosmetics 的测试改走生产路径,之前它自己拼了一遍三步流程,落盘链路漏掉其中一步
测试照样会绿。
This commit is contained in:
im0o
2026-08-10 18:21:23 +08:00
parent 6b208847a2
commit c5ac59ecf9
19 changed files with 781 additions and 355 deletions
+10 -86
View File
@@ -1,46 +1,39 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { ApiError, api, getToken, setToken } from './api'
import type { ConfigSnapshot, ProxyInfo } from './api'
import { ApiError, api, clearToken, getToken, setToken } from './api'
import type { ConfigSnapshot } from './api'
import { NAV } from './nav'
import { density, toggleDensity } from './prefs'
import { kernel, reloadRuntime } from './runtime'
import RouterPage from './views/RouterPage.vue'
import TokenGate from './views/TokenGate.vue'
import IconFold from '~icons/ri/sidebar-fold-line'
import IconUnfold from '~icons/ri/sidebar-unfold-line'
const snapshot = ref<ConfigSnapshot | null>(null)
const kernel = ref<{ online: boolean; version?: string }>({ online: false })
const providerLines = ref<string[]>([])
/** 订阅线路 → 它所属的订阅名。测延迟时要用它选对接口 */
const lineProvider = ref<Record<string, string>>({})
const runtime = ref<Record<string, ProxyInfo>>({})
const needsToken = ref(!getToken())
const loadError = ref('')
const booted = ref(false)
const refreshing = ref(false)
const active = ref('router')
const active = ref('dashboard')
/**
* 重新读一遍状态。
*
* 关键在于**不能把页面拆掉重建**:之前每次刷新都会先切到「读取中」,
* 于是路由页被卸载、选中的那一路入站丢失,改完一个设置还要重新找回原来的位置。
* 所以只有首次加载显示占位,之后都是原地更新。
* 关键在于**不能把页面拆掉重建**:之前每次刷新都会先切到「读取中」,于是路由页被卸载、
* 选中的那一路入站丢失,改完一个设置还要重新找回原来的位置。所以只有首次加载显示占位,
* 之后都是原地更新。
*/
async function load() {
refreshing.value = true
loadError.value = ''
try {
const [config, status] = await Promise.all([api.readConfig(), api.kernel()])
snapshot.value = config
kernel.value = status
snapshot.value = await api.readConfig()
needsToken.value = false
// 订阅里有哪些线路只有运行中的内核知道,配置文件里只有一个订阅地址。
// 拿不到不算错误——界面照常能编辑,只是订阅线路那一档不可选。
runtime.value = status.online ? await readRuntime() : {}
await reloadRuntime()
} catch (error) {
if (error instanceof ApiError && error.unauthorized) {
clearToken()
needsToken.value = true
} else {
loadError.value = error instanceof Error ? error.message : String(error)
@@ -51,69 +44,6 @@ async function load() {
}
}
/**
* 出站的运行时状态:协议类型、策略组当前选中了谁、最近一次延迟。
*
* 要读两处。/proxies 只包含内核全局名字表里的东西——内置出站、自有线路、策略组;
* 订阅线路不在那张表上,它们的类型和延迟只能从 /providers/proxies 拿。
* 两边合成一张表,界面上就不用关心某个名字是从哪来的了。
*
* 顺带记下每条订阅线路属于哪个订阅:测它的延迟必须从所属订阅进去。
*/
async function readRuntime(): Promise<Record<string, ProxyInfo>> {
const merged: Record<string, ProxyInfo> = {}
const lines: string[] = []
const owner: Record<string, string> = {}
try {
Object.assign(merged, (await api.proxies()).proxies)
} catch {
// 拿不到就当没有,界面照常显示,只是没有延迟数字
}
try {
const { providers } = await api.providers()
for (const [name, provider] of Object.entries(providers)) {
// 内核会给每个用了 proxies 的策略组造一个内部 provider,那些不是订阅
if (provider.vehicleType === 'Compatible') continue
for (const line of provider.proxies) {
merged[line.name] = line
lines.push(line.name)
owner[line.name] = name
}
}
} catch {
// 同上
}
providerLines.value = lines
lineProvider.value = owner
return merged
}
/**
* 切换策略组时先在本地改掉,不等内核回话。
*
* 这一步不写配置文件,失败率极低;而等一个往返再更新会让点击感觉发木。
* 真失败了随后的刷新会把状态纠正回来。
*/
function optimisticSelect(group: string, member: string) {
const info = runtime.value[group]
if (info) info.now = member
}
/**
* 只重读运行时状态,不碰配置文件。
*
* 切换策略组、测一条线路的延迟,改变的只是内核的运行状态。走完整的 load() 会让服务端
* 重读整份配置、重新解析、再跑一遍引用校验,外加两个多余的往返——最便宜的动作触发了
* 最贵的操作。
*/
async function reloadRuntime() {
if (!kernel.value.online) return
runtime.value = await readRuntime()
}
function submitToken(value: string) {
setToken(value)
void load()
@@ -192,13 +122,7 @@ const current = computed(() => NAV.find((n) => n.key === active.value))
v-if="active === 'router'"
:data="snapshot.data"
:revision="snapshot.revision"
:kernel-online="kernel.online"
:provider-lines="providerLines"
:line-provider="lineProvider"
:runtime="runtime"
@saved="load"
@optimistic-select="optimisticSelect"
@runtime-changed="reloadRuntime"
/>
<div v-else class="note">
-9
View File
@@ -69,7 +69,6 @@ async function request<T>(method: string, path: string, body?: unknown): Promise
export interface ConfigSnapshot {
data: ConfigObject
yaml: string
revision: string
diagnostics: ConfigDiagnostic[]
}
@@ -81,14 +80,6 @@ export interface ApplySuccess {
reloadMessage: string
}
export interface ApplyFailure {
ok: false
stage: 'stale' | 'self-check' | 'kernel-check' | 'write' | 'reload'
message: string
hint: string
restored: boolean
}
export interface ProxyInfo {
/** 出站的名字。/proxies 用键名标识,provider 里的线路则带在对象上 */
name: string
+110
View File
@@ -0,0 +1,110 @@
<script setup lang="ts">
/**
* 入站列表。每行一路入站:端口、类型、名字、它落在哪个出站上。
*
* 只管显示和选中,不碰任何数据。
*/
import { inboundTypeLabel, isUnsetOutbound, outboundLabel } from '@shared/inbounds.ts'
import type { Inbound } from '@shared/inbounds.ts'
defineProps<{ inbounds: Inbound[] }>()
const selected = defineModel<string | null>('selected', { required: true })
</script>
<template>
<ol class="rows">
<li v-for="inbound in inbounds" :key="inbound.id">
<button
type="button"
:class="['line', selected === inbound.id && 'is-on']"
@click="selected = inbound.id"
>
<span class="port mono">{{ inbound.port }}</span>
<span class="type mono">{{ inboundTypeLabel(inbound.type) }}</span>
<span class="name">
{{ inbound.name }}
<span v-if="inbound.isDefault" class="tag">默认</span>
</span>
<span :class="['out mono', isUnsetOutbound(inbound.outbound) && 'is-muted']">
{{ outboundLabel(inbound.outbound) }}
</span>
</button>
</li>
</ol>
</template>
<style scoped>
.rows {
list-style: none;
margin: 0;
padding: 0;
border: 1px solid var(--c-border);
border-radius: var(--r-md);
background: var(--c-surface);
overflow: hidden;
}
.rows li + li {
border-top: 1px solid var(--c-border);
}
.line {
width: 100%;
display: grid;
grid-template-columns: 4.5rem 5rem 1fr minmax(5rem, auto);
align-items: center;
gap: var(--s-3);
padding: var(--s-3) var(--s-4);
border: none;
background: none;
cursor: pointer;
text-align: left;
}
.line:hover {
background: var(--c-surface-sunken);
}
.line.is-on {
background: var(--c-accent-soft);
}
.port {
font-size: var(--t-lg);
font-variant-numeric: tabular-nums;
}
.type {
font-size: var(--t-xs);
color: var(--c-text-faint);
}
.name {
display: flex;
align-items: center;
gap: var(--s-2);
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag {
flex: none;
padding: 0 var(--s-2);
border: 1px solid var(--c-border-strong);
border-radius: 999px;
font-size: var(--t-xs);
color: var(--c-text-soft);
line-height: 1.6;
}
.out {
font-size: var(--t-sm);
text-align: right;
}
.out.is-muted {
color: var(--c-text-faint);
}
</style>
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from 'bun:test'
import { ApiError } from './api'
import { describeTestFailure } from './delay-test'
const LINE = '[vless]Gomami.SIN Secret'
describe('延迟测试失败时告诉用户什么', () => {
it('超时说明是几秒内没完成', () => {
// 只说「超时」,用户不知道是等了 1 秒还是 60 秒,也就不知道该不该重试
expect(describeTestFailure(LINE, new ApiError(504, {}), 5000)).toBe(
`${LINE} 延迟测试超时,5 秒内没有取到测试地址`,
)
})
it('找不到这个名字时指出该从订阅进去测', () => {
// 订阅线路不在内核的全局出站表里,这是本项目最容易踩的一条约束
expect(describeTestFailure(LINE, new ApiError(404, { message: 'Resource not found' }))).toContain(
'不在内核的出站表里',
)
})
it('连接失败且内核没给具体原因时,给出能指导排查的话', () => {
const generic = new ApiError(503, { message: 'An error occurred in the delay test' })
expect(describeTestFailure(LINE, generic)).toBe(
`${LINE} 无法建立连接,线路可能已失效,或本机到该服务器的网络不通`,
)
})
it('内核给了具体原因就原样带上', () => {
const specific = new ApiError(503, { message: 'dial tcp: i/o timeout' })
expect(describeTestFailure(LINE, specific)).toBe(`${LINE} 无法建立连接:dial tcp: i/o timeout`)
})
it('没见过的状态码带上状态码和内核原话', () => {
expect(describeTestFailure(LINE, new ApiError(500, { message: 'boom' }))).toBe(
`${LINE} 延迟测试失败(HTTP 500):boom`,
)
})
it('状态码没见过且内核没说话时不留一个空冒号', () => {
expect(describeTestFailure(LINE, new ApiError(500, {}))).toBe(
`${LINE} 延迟测试失败(HTTP 500)`,
)
})
it('不是接口错误时也要说出是什么', () => {
// 网络断了、代码抛了异常,都会走到这里,不能显示成 [object Object]
expect(describeTestFailure(LINE, new TypeError('Failed to fetch'))).toBe(
`${LINE} 延迟测试失败:TypeError: Failed to fetch`,
)
})
})
+74
View File
@@ -0,0 +1,74 @@
/**
* 线路延迟测试。
*
* 单独成一个模块,是因为「测失败了该跟用户说什么」有六个分支,而它原本写在组件里,
* 一条测试都加不了。这些话是用户唯一能看到的诊断信息,值得测。
*/
import { ref } from 'vue'
import { ApiError, api } from './api'
/** 超时,毫秒。文案里会用到它,所以不能让接口和文案各写一个数。 */
export const TEST_TIMEOUT_MS = 5000
/**
* 把内核的延迟测试结果翻译成一句说明原因的话。
*
* 内核对这件事的回答是精确的(内核源码 hub/route/proxies.go:122-145):
* 504 在给定超时内没有完成
* 503 连接建立失败,或者测得的延迟为 0
* 404 这个名字不在内核的全局出站表里
* 笼统说一句「测不通」会把它们混在一起,而这三种要查的地方完全不一样。
*/
export function describeTestFailure(
name: string,
error: unknown,
timeoutMs = TEST_TIMEOUT_MS,
): string {
if (!(error instanceof ApiError)) return `${name} 延迟测试失败:${String(error)}`
if (error.status === 504) {
return `${name} 延迟测试超时,${String(timeoutMs / 1000)} 秒内没有取到测试地址`
}
if (error.status === 404) {
return `${name} 不在内核的出站表里,无法测试。订阅线路需要从所属订阅进去测。`
}
const detail = String(error.payload.message ?? '')
// 内核对连接失败给的是一句没有信息量的通用英文,替换成能指导排查的话
const generic = detail === '' || detail === 'An error occurred in the delay test'
if (error.status === 503) {
return generic
? `${name} 无法建立连接,线路可能已失效,或本机到该服务器的网络不通`
: `${name} 无法建立连接:${detail}`
}
return `${name} 延迟测试失败(HTTP ${String(error.status)})${generic ? '' : `:${detail}`}`
}
/**
* 管理「哪几条线路正在测」。
*
* 测延迟是纯读操作,不影响配置也不影响别的线路,所以它只标记自己那一条忙碌,
* 不禁用界面上的任何其它东西。
*/
export function useDelayTest(onFinished: () => void, onFailure: (message: string) => void) {
const testing = ref<string[]>([])
async function test(name: string, provider?: string) {
if (testing.value.includes(name)) return
testing.value = [...testing.value, name]
try {
await api.testLine(name, provider, TEST_TIMEOUT_MS)
onFinished()
} catch (error) {
// 测不通是关于线路的结论,不是 Patchbay 出了故障
onFailure(describeTestFailure(name, error))
} finally {
testing.value = testing.value.filter((n) => n !== name)
}
}
return { testing, test }
}
+5 -7
View File
@@ -15,15 +15,13 @@ export interface NavItem {
key: string
label: string
icon: Component
/** 还没做的页面标 true,导航上显示但点进去是占位 */
pending?: boolean
}
export const NAV: NavItem[] = [
{ key: 'dashboard', label: '仪表盘', icon: IconDashboard, pending: true },
{ key: 'dashboard', label: '仪表盘', icon: IconDashboard },
{ key: 'router', label: '路由', icon: IconRoute },
{ key: 'config', label: '配置', icon: IconConfig, pending: true },
{ key: 'requests', label: '请求', icon: IconRequests, pending: true },
{ key: 'connections', label: '连接', icon: IconConnections, pending: true },
{ key: 'settings', label: '设置', icon: IconSettings, pending: true },
{ key: 'config', label: '配置', icon: IconConfig },
{ key: 'requests', label: '请求', icon: IconRequests },
{ key: 'connections', label: '连接', icon: IconConnections },
{ key: 'settings', label: '设置', icon: IconSettings },
]
+82
View File
@@ -0,0 +1,82 @@
/**
* 内核的运行时状态:有哪些出站、每个是什么协议、策略组当前选中谁、最近一次延迟。
*
* 这些数据配置文件里没有,只有运行中的内核知道;而且界面上有三层组件要用它。
* 原本它住在根组件里靠 props 一层层往下传,中间有两层完全不碰它、纯粹为了转发而
* 声明了参数。做成模块级单例之后那两层就不用再知道它的存在了。
*
* 用的是 web/prefs.ts 已有的模式(模块级 ref),不是新抽象。
*/
import { ref } from 'vue'
import { api } from './api'
import type { ProxyInfo } from './api'
/** 出站名字 → 运行时信息。内核没连接时是空的。 */
export const runtime = ref<Record<string, ProxyInfo>>({})
/** 订阅带来的线路,按订阅返回的顺序。 */
export const providerLines = ref<string[]>([])
/** 订阅线路 → 它所属的订阅名。测它的延迟必须从所属订阅进去。 */
export const lineProvider = ref<Record<string, string>>({})
export const kernel = ref<{ online: boolean; version?: string }>({ online: false })
/**
* 重新读一遍运行时状态。
*
* 要读两处:`/proxies` 只包含内核全局名字表里的东西(内置出站、自有线路、策略组),
* 订阅线路不在那张表上,它们的协议和延迟只能从 `/providers/proxies` 拿。合成一张表
* 之后,界面就不用关心某个名字是从哪来的了。
*
* 任何一处取不到都不算错误——界面照常显示,只是少了延迟数字。内核没起来的时候正是
* 最需要这个界面的时候。
*/
export async function reloadRuntime(): Promise<void> {
kernel.value = await api.kernel().catch(() => ({ online: false }))
if (!kernel.value.online) {
runtime.value = {}
providerLines.value = []
lineProvider.value = {}
return
}
const merged: Record<string, ProxyInfo> = {}
try {
Object.assign(merged, (await api.proxies()).proxies)
} catch {
// 拿不到就当没有
}
const lines: string[] = []
const owner: Record<string, string> = {}
try {
const { providers } = await api.providers()
for (const [name, provider] of Object.entries(providers)) {
// 内核会给每个用了 proxies 的策略组造一个内部 provider,那些不是订阅
if (provider.vehicleType === 'Compatible') continue
for (const line of provider.proxies) {
merged[line.name] = line
lines.push(line.name)
owner[line.name] = name
}
}
} catch {
// 同上
}
runtime.value = merged
providerLines.value = lines
lineProvider.value = owner
}
/**
* 切换策略组选中谁时先在本地改掉,不等内核回话。
*
* 这一步不写配置文件、失败率极低,而等一个往返再更新会让点击感觉发木。
* 真失败了随后的刷新会把状态纠正回来。
*/
export function optimisticSelect(group: string, member: string): void {
const node = runtime.value[group]
if (node) node.now = member
}
+7 -32
View File
@@ -8,8 +8,9 @@
*/
import { computed } from 'vue'
import type { Inbound, OutboundMode } from '@shared/inbounds.ts'
import { lastSwitchableGroup, resolveChain } from '@shared/outbound-chain.ts'
import { latestDelay } from '../api'
import type { ProxyInfo } from '../api'
import { kernel, providerLines, runtime } from '../runtime'
import OutboundCard from '../components/OutboundCard.vue'
import IconOffline from '~icons/ri/cloud-off-line'
import IconEdit from '~icons/ri/edit-line'
@@ -19,11 +20,8 @@ const props = defineProps<{
inbound: Inbound
groups: string[]
ownProxies: string[]
providerLines: string[]
runtime: Record<string, ProxyInfo>
/** 流量最终交给哪个出站。走规则的入站要查到规则表末尾的 MATCH */
destination: string | null
kernelOnline: boolean
/** 正在提交的那个出站的名字。只有它显示忙碌,其余照常能点 */
pendingOutbound: string | null
/** 正在测延迟的线路 */
@@ -42,39 +40,16 @@ const emit = defineEmits<{
const locked = computed(() => props.inbound.isDefault)
function describe(name: string): string {
const info = props.runtime[name]
const info = runtime.value[name]
if (!info) return ''
return info.now ? `${info.type}(${info.now})` : info.type
}
const delayOf = (name: string) => latestDelay(props.runtime[name])
const delayOf = (name: string) => latestDelay(runtime.value[name])
const isTesting = (name: string) => props.testing.includes(name)
/**
* 从落脚的出站一路跟着「当前选中」往下走,直到走到一条真正的线路。
*
* 策略组可以选中另一个策略组,所以「这个端口现在走哪条线」往往要跳好几层。
* 只显示第一层等于没回答问题。
*/
const chain = computed(() => {
const hops: string[] = []
let cursor = props.destination
while (cursor && !hops.includes(cursor)) {
hops.push(cursor)
cursor = props.runtime[cursor]?.now ?? null
}
return hops
})
/** 链条上最后一个还是策略组的环节——用户能在这里换选中。 */
const switchable = computed(() => {
for (let i = chain.value.length - 1; i >= 0; i -= 1) {
const name = chain.value[i]!
const info = props.runtime[name]
if (info?.all?.length) return { group: name, members: info.all, now: info.now ?? '' }
}
return null
})
const chain = computed(() => resolveChain(runtime.value, props.destination))
const switchable = computed(() => lastSwitchableGroup(runtime.value, chain.value))
function isCurrentOutbound(mode: OutboundMode): boolean {
const now = props.inbound.outbound
@@ -205,7 +180,7 @@ const NO_PROXY_FIELD = '该入站没有 proxy 字段'
</template>
<h4 :class="locked && 'is-dim'">订阅线路</h4>
<p v-if="!kernelOnline" class="hint">
<p v-if="!kernel.online" class="hint">
<IconOffline />
内核未连接,无法获取订阅线路
</p>
+32 -192
View File
@@ -1,37 +1,35 @@
<script setup lang="ts">
/**
* 路由页:一张「端口 → 出站」的表,加上选中那一路的详情。
*
* 这里只做编排——把配置数据、运行时状态和三个子组件接起来,并守住一条:
* 所有改配置文件的动作都从 commit() 走,失败时按停在哪一步说不同的话。
* 运行时动作(切换选中、测延迟)不经过它,因为它们不写文件也不需要校验。
*/
import { computed, onMounted, ref, watch } from 'vue'
import {
collectInbounds,
collectOutboundNames,
outboundLabel,
outboundToProxyField,
resolveDestination,
} from '@shared/inbounds.ts'
import type { Inbound, OutboundMode } from '@shared/inbounds.ts'
import type { ConfigObject } from '../../vendor/config-editor/index.ts'
import { ApiError, api } from '../api'
import type { ListenerFields, ProxyInfo } from '../api'
import type { ListenerFields } from '../api'
import { lineProvider, optimisticSelect, providerLines, reloadRuntime } from '../runtime'
import { useDelayTest } from '../delay-test'
import { density } from '../prefs'
import InboundList from '../components/InboundList.vue'
import InboundDetail from './InboundDetail.vue'
import InboundForm from './InboundForm.vue'
import IconAdd from '~icons/ri/add-line'
const props = defineProps<{
data: ConfigObject
revision: string
kernelOnline: boolean
providerLines: string[]
/** 订阅线路 → 所属订阅 */
lineProvider: Record<string, string>
runtime: Record<string, ProxyInfo>
}>()
const props = defineProps<{ data: ConfigObject; revision: string }>()
const emit = defineEmits<{
/** 配置文件变了,需要重读整份配置 */
saved: []
/** 只有内核的运行时状态变了,不用重读配置 */
runtimeChanged: []
optimisticSelect: [group: string, member: string]
}>()
/** 配置文件变了,需要重读整份配置。运行时的变化不走这里。 */
const emit = defineEmits<{ saved: [] }>()
const inbounds = computed(() => collectInbounds(props.data))
const outbounds = computed(() => collectOutboundNames(props.data))
@@ -48,8 +46,13 @@ const formOpen = ref(false)
const formEditing = ref<Inbound | null>(null)
/** 正在提交的那个出站的名字。只有它显示忙碌,其余卡片照常能点 */
const pendingOutbound = ref<string | null>(null)
/** 正在测延迟的线路 */
const testing = ref<string[]>([])
const { testing, test } = useDelayTest(
() => void reloadRuntime(),
(message) => {
notice.value = message
},
)
onMounted(async () => {
try {
@@ -71,28 +74,9 @@ watch(
const selected = computed(() => inbounds.value.find((i) => i.id === selectedId.value) ?? null)
const takenNames = computed(() => inbounds.value.map((i) => i.name))
const TYPE_LABEL: Record<string, string> = {
mixed: 'HTTP + SOCKS5',
http: 'HTTP',
socks: 'SOCKS5',
redir: 'REDIR',
tproxy: 'TPROXY',
}
function typeLabel(inbound: Inbound): string {
return TYPE_LABEL[inbound.type] ?? inbound.type.toUpperCase()
}
function outboundLabel(mode: OutboundMode): { text: string; muted: boolean } {
if (mode.kind === 'rules') return { text: 'RULE', muted: true }
if (mode.kind === 'direct') return { text: 'DIRECT', muted: false }
if (mode.kind === 'global') return { text: 'GLOBAL', muted: false }
return { text: mode.name, muted: false }
}
const clone = () => JSON.parse(JSON.stringify(props.data)) as ConfigObject
/** 所有改动都走这一条路:落盘失败时按停在哪一步说不同的话。 */
/** 所有改配置文件的动作都从这里走。 */
async function commit(next: ConfigObject, success: string) {
saving.value = true
failure.value = null
@@ -115,7 +99,7 @@ async function commit(next: ConfigObject, success: string) {
async function pickOutbound(mode: OutboundMode) {
const target = selected.value
if (!target || target.listenerIndex === null || pendingOutbound.value) return
pendingOutbound.value = outboundLabel(mode).text
pendingOutbound.value = outboundLabel(mode)
const next = clone()
const entry = (next.listeners as ConfigObject[])[target.listenerIndex]!
@@ -125,7 +109,7 @@ async function pickOutbound(mode: OutboundMode) {
else entry.proxy = proxy
try {
await commit(next, `${target.name} 的出站已设为 ${outboundLabel(mode).text}`)
await commit(next, `${target.name} 的出站已设为 ${outboundLabel(mode)}`)
} finally {
pendingOutbound.value = null
}
@@ -136,7 +120,6 @@ function openAdd() {
formOpen.value = true
}
function openEdit() {
if (!selected.value || selected.value.isDefault) return
formEditing.value = selected.value
@@ -159,17 +142,16 @@ async function submitForm(entry: ConfigObject) {
if (editingIndex === null) selectedId.value = `listener:${String(listeners.length - 1)}`
}
/** 切换策略组当前选中谁。运行时动作,不写配置文件,所以不走那条落盘链路。 */
/** 切换策略组当前选中谁。运行时动作,不写配置文件,所以不走 commit()。 */
async function selectMember(group: string, member: string) {
if (saving.value) return
// 先本地改掉,别让点击等一个往返。失败了随后的刷新会纠正回来。
emit('optimisticSelect', group, member)
optimisticSelect(group, member)
failure.value = null
done.value = ''
notice.value = ''
try {
await api.selectProxy(group, member)
emit('runtimeChanged')
await reloadRuntime()
} catch (error) {
failure.value = {
message: error instanceof ApiError ? error.message : String(error),
@@ -178,52 +160,6 @@ async function selectMember(group: string, member: string) {
}
}
/** 延迟测试用的超时,毫秒。也用在失败提示里,让「超时」这个词有具体含义。 */
const TEST_TIMEOUT_MS = 5000
/**
* 把内核的延迟测试结果翻译成一句说明原因的话。
*
* 内核的语义是精确的(hub/route/proxies.go:122-145):
* 504 在给定超时内没有完成
* 503 连接建立失败,或者测得的延迟为 0
* 笼统说一句「测不通」会把这两种情况混在一起,而它们要查的地方不一样。
*/
function describeTestFailure(name: string, error: unknown): string {
if (!(error instanceof ApiError)) return `${name} 延迟测试失败:${String(error)}`
const seconds = String(TEST_TIMEOUT_MS / 1000)
if (error.status === 504) return `${name} 延迟测试超时,${seconds} 秒内没有取到测试地址`
const detail = String(error.payload.message ?? '')
const generic = detail === '' || detail === 'An error occurred in the delay test'
if (error.status === 404) {
return `${name} 不在内核的出站表里,无法测试。订阅线路需要从所属订阅进去测。`
}
if (error.status === 503) {
return generic
? `${name} 无法建立连接,线路可能已失效,或本机到该服务器的网络不通`
: `${name} 无法建立连接:${detail}`
}
return `${name} 延迟测试失败(HTTP ${String(error.status)})${generic ? '' : `:${detail}`}`
}
/** 测一条线路的延迟。纯读操作,不影响任何配置,所以不禁用任何东西。 */
async function testLine(name: string) {
if (testing.value.includes(name)) return
testing.value = [...testing.value, name]
try {
await api.testLine(name, props.lineProvider[name], TEST_TIMEOUT_MS)
emit('runtimeChanged')
} catch (error) {
// 测不通是关于线路的结论,不是 Patchbay 出了故障。既不该用错误框,
// 也不该用成功的绿色——它需要第三种中性的样子。
notice.value = describeTestFailure(name, error)
} finally {
testing.value = testing.value.filter((n) => n !== name)
}
}
async function removeSelected() {
const target = selected.value
if (!target || target.listenerIndex === null || saving.value) return
@@ -272,42 +208,21 @@ async function removeSelected() {
<p v-else-if="notice" class="notice">{{ notice }}</p>
<div class="split">
<ol class="rows">
<li v-for="inbound in inbounds" :key="inbound.id">
<button
type="button"
:class="['line', selectedId === inbound.id && 'is-on']"
@click="selectedId = inbound.id"
>
<span class="port mono">{{ inbound.port }}</span>
<span class="type">{{ typeLabel(inbound) }}</span>
<span class="name">
{{ inbound.name }}
<span v-if="inbound.isDefault" class="tag">默认</span>
</span>
<span :class="['out', outboundLabel(inbound.outbound).muted && 'is-muted']">
{{ outboundLabel(inbound.outbound).text }}
</span>
</button>
</li>
</ol>
<InboundList v-model:selected="selectedId" :inbounds="inbounds" />
<InboundDetail
v-if="selected"
:inbound="selected"
:groups="outbounds.groups"
:own-proxies="outbounds.ownProxies"
:provider-lines="providerLines"
:destination="resolveDestination(data, selected)"
:runtime="runtime"
:kernel-online="kernelOnline"
:pending-outbound="pendingOutbound"
:testing="testing"
@pick="pickOutbound"
@edit="openEdit"
@remove="removeSelected"
@select="selectMember"
@test="testLine"
:testing="testing"
:pending-outbound="pendingOutbound"
@test="(name: string) => test(name, lineProvider[name])"
/>
</div>
@@ -414,81 +329,6 @@ async function removeSelected() {
}
}
.rows {
list-style: none;
margin: 0;
padding: 0;
border: 1px solid var(--c-border);
border-radius: var(--r-md);
background: var(--c-surface);
overflow: hidden;
}
.rows li + li {
border-top: 1px solid var(--c-border);
}
.line {
width: 100%;
display: grid;
grid-template-columns: 4.5rem 6.5rem 1fr minmax(5rem, auto);
align-items: center;
gap: var(--s-3);
padding: var(--s-3) var(--s-4);
border: none;
background: none;
cursor: pointer;
text-align: left;
}
.line:hover {
background: var(--c-surface-sunken);
}
.line.is-on {
background: var(--c-accent-soft);
}
.port {
font-size: var(--t-lg);
font-variant-numeric: tabular-nums;
}
.type {
font-size: var(--t-xs);
color: var(--c-text-faint);
}
.name {
display: flex;
align-items: center;
gap: var(--s-2);
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag {
flex: none;
padding: 0 var(--s-2);
border: 1px solid var(--c-border-strong);
border-radius: 999px;
font-size: var(--t-xs);
color: var(--c-text-soft);
line-height: 1.6;
}
.out {
font-family: var(--f-mono);
font-size: var(--t-sm);
text-align: right;
}
.out.is-muted {
color: var(--c-text-faint);
}
.empty {
color: var(--c-text-faint);
font-size: var(--t-sm);