Files
clash-verge-rev/src/services/events.ts
T
wonfen 22947632c0 refactor: Rewrite and improve sysproxy logic (#7744)
* fix(cmd): preserve anyhow context in coded errors

Use alternate error formatting so coded failures retain the full anyhow context chain without changing their wire format.

* fix(macos): skip redundant proxy disable writes

When both proxy modes are off, read macOS state first and skip networksetup if the OS is already clean. Update the guard target only after a successful write.

* feat(proxy): classify system proxy failures

Attach stable, actionable proxy failure codes to anyhow chains while preserving the original diagnostic causes.

* feat(cmd): return structured command failures

Replace encoded error strings with serializable code and detail fields, and update frontend notice consumers to handle the structured shape.

* fix(scripts): use the js-yaml namespace import

Import js-yaml through its ESM namespace so the i18n cleanup script can access load and dump.

* feat(proxy): localize classified proxy failures

Map privilege and direct-fallback codes to localized explanations, and let mapped causes outrank generic operation keys in notices.

* fix(ui): bound notice text and render failure details

Limit resolved notice text without truncating clipboard content, and normalize structured failures embedded in translation parameters.

* feat(proxy): persist unseen proxy failures

Store unresolved classified failures by code, notify the frontend when the table changes, and show each failure sequence once when a visible window can receive it.

* feat(proxy): report tray and hotkey toggle failures

Record classified failures from tray and hotkey proxy toggles so they appear when a visible window is available.

* fix(ui): restore the proxy switch after failed toggles

Refresh frontend proxy state after a failed toggle so the switch reflects the rolled-back configuration.

* feat(proxy): stop the guard after repeated failures

Report guard outcomes, stop after the failure threshold, and persist the classified failure for the frontend.

* fix(macos): preserve proxy during service handoff

Stop a sidecar being handed to the service without clearing proxy state that the new owner must inherit.

* feat(macos): classify misplaced sidecar state

Distinguish a refused sidecar proxy write from a machine that still needs the privileged service installed.

* feat(ui): recover misplaced sidecar notices

Offer a restart action for macOS proxy failures caused by a ready service while the core still runs as a sidecar.

* feat(ui): install the service from proxy notices

Let privilege notices install the macOS service, restart the core, and report the runtime mode that was actually reached.

* feat(cmd): attach requested proxy operations

Carry the requested proxy direction with structured command failures when the originating command knows it.

* feat(sysproxy): drain guards before OS access

Wait for the local proxy guard to stop before OS reads, service handoff, or final writes, and refuse transitions when it does not drain.

* feat(sysproxy): recover partial proxy writes

Use write progress to choose whether to restore the old guard or compensate with a disabled proxy state, while preserving actionable errors.

* feat(sysproxy): skip already-applied proxy writes

Compare macOS proxy snapshots with global, PAC, and disabled targets so matching state avoids redundant privileged writes.

* feat(proxy): report background proxy failures

Persist and surface classified proxy failures from lifecycle paths that have no direct caller awaiting the result.

* feat(ui): move proxy recovery into a dialog

Guide users through installing or switching to the service after a refused proxy write, and suppress duplicate toast reports.

* fix(ui): close proxy dialog after service recovery

Dismiss the recovery dialog once the core reaches service mode, even when the original proxy request remains pending.

* feat(ui): retry proxy request after service recovery

Replay the requested proxy direction after the core reaches service mode, while leaving incidental restores unchanged.

* fix(proxy): refresh state after successful apply

Publish the proxy refresh from the shared apply path after releasing the lifecycle lock, and remove the tray-specific duplicate.

* feat(ui): show proxy recovery progress

Display installation, restart, and proxy-apply stages while keeping the primary action spinner visible during recovery.

* feat(ui): route unavailable TUN through service recovery

Let the TUN switch request service recovery and restore its requested state after the core restarts in service mode.

* fix(ui): avoid duplicate TUN recovery errors

Roll back deferred TUN toggles without reporting an error, and publish configuration refreshes from the transaction commit path.

* chore: update changelog & pinlock

* fix(core): resolve platform-specific clippy warnings

* fix(core): detect Windows wildcard TCP conflicts

Windows permits a specific exclusive bind beside an existing non-exclusive wildcard listener. Consult the system TCP listener table so the probe reports that overlap as a conflict.
2026-08-14 23:52:37 +08:00

101 lines
3.4 KiB
TypeScript

import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import type { RunState } from './cmds'
/**
* Every event pushed to the frontend, and what it carries.
*
* The names were string literals on both sides of the IPC seam, so renaming one was a silent
* no-op rather than a compile error. Declaring them here does not make the Rust side check
* itself, but it does mean the frontend has exactly one place to look and one payload type
* per name instead of a `listen<T>` guess at each call site.
*/
interface VergeEvents {
/** The core's own configuration changed. */
'verge://refresh-clash-config': string
/** The app's configuration changed. */
'verge://refresh-verge-config': string
/** The set of profiles changed. */
'verge://refresh-profiles': string
/** The active profile's proxies changed. */
'verge://refresh-proxy-config': null
/** A backend message for the user: `[status, message]`. */
'verge://notice-message': [string, string]
/** A profile's auto-update timer was rescheduled. */
'verge://timer-updated': string
/** How the core is running changed; carries the whole snapshot. */
'verge://run-state-changed': RunState
/** Pending failures changed; reread the table. */
'verge://pending-failures-changed': null
/** Which profile is active changed. */
'profile-changed': string
'profile-update-started': { uid?: string }
'profile-update-completed': { uid?: string }
/** Frontend to frontend: the home card asks the test page to run every test. */
'verge://test-all': null
}
type VergeEventName = keyof VergeEvents
type VergeEventHandlers = {
[Name in VergeEventName]?: (payload: VergeEvents[Name]) => void
}
/**
* Subscribe to backend events, returning the teardown.
*
* Registration is asynchronous, so a subscription can resolve after the caller has already
* torn down; that is tracked here rather than at each call site, where it was implemented
* four different ways and omitted in one of them.
*
* `onSubscribed` runs once every listener is live. Anything whose state arrives only by event
* needs it: between the first read and the listener being registered there is a gap, and a
* transition landing in it is not queued anywhere — it is simply missed, and the next event is
* whenever the backend happens to move again. Re-reading at that point closes the gap without
* going back to polling for it.
*/
export const subscribeVergeEvents = (
handlers: VergeEventHandlers,
onSubscribed?: () => void,
): (() => void) => {
let disposed = false
const unlisteners: UnlistenFn[] = []
const registrations = Object.entries(handlers).map(([name, handler]) => {
if (!handler) return Promise.resolve()
return listen(name, ({ payload }) => {
;(handler as (payload: unknown) => void)(payload)
})
.then((unlisten) => {
// Resolved after teardown: unsubscribe immediately rather than leak.
if (disposed) {
unlisten()
return
}
unlisteners.push(unlisten)
})
.catch((error) => {
console.error(`[events] failed to subscribe to ${name}:`, error)
})
})
if (onSubscribed) {
void Promise.all(registrations).then(() => {
if (disposed) return
onSubscribed()
})
}
return () => {
disposed = true
for (const unlisten of unlisteners.splice(0)) {
try {
unlisten()
} catch (error) {
console.error('[events] teardown failed:', error)
}
}
}
}