refactor: use native async discovery and simplify shared state

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:57:18 +08:00
1 parent 5032cbb8c0
commit 4e2b6b1200
87 files changed
+2063 -2002

No files matched your search

+123
View File
@@ -0,0 +1,123 @@
import { describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
import { createAppResources } from '../src/lib/app-resources';
import type { QQInfo } from '../src/types';
function setup() {
const api = createApiClient({ tokenStore: { load: () => null, save: () => undefined } });
vi.spyOn(api, 'qqList').mockResolvedValue([]);
vi.spyOn(api.processes, 'list').mockResolvedValue([]);
vi.spyOn(api, 'connections').mockResolvedValue([]);
return { api, store: createAppResources(api) };
}
const accounts: QQInfo[] = [{ uin: '12345', nickname: '当前账号' }];
describe('app resources', () => {
it('publishes data and load status together, distinguishing an empty result from an initial load', async () => {
const { store } = setup();
const initial = store.getSnapshot();
expect(initial.qqList).toEqual({ data: [], ready: false, error: null });
const listener = vi.fn(() => {
expect(store.getSnapshot().qqList).toEqual({ data: [], ready: true, error: null });
});
const unsubscribe = store.subscribe(listener);
await store.refreshQqList();
expect(listener).toHaveBeenCalledOnce();
expect(initial.qqList.ready).toBe(false);
unsubscribe();
await store.refreshQqList();
expect(listener).toHaveBeenCalledOnce();
});
it('keeps the latest request when an older request completes later', async () => {
const { api, store } = setup();
const old = Promise.withResolvers<QQInfo[]>();
vi.mocked(api.qqList).mockReturnValueOnce(old.promise).mockResolvedValueOnce(accounts);
const first = store.refreshQqList();
await store.refreshQqList();
old.resolve([]);
await first;
expect(store.getSnapshot().qqList.data).toEqual(accounts);
});
it.each(['success', 'failure'])(
'keeps a pushed snapshot after a stale REST %s',
async (outcome) => {
const { api, store } = setup();
const request = Promise.withResolvers<QQInfo[]>();
vi.mocked(api.qqList).mockReturnValueOnce(request.promise);
const pending = store.refreshQqList();
store.onEvent({ resource: 'qq-list', data: accounts });
const snapshot = store.getSnapshot();
if (outcome === 'success') {
request.resolve([]);
} else {
request.reject(new Error('过期请求失败'));
}
await pending;
expect(store.getSnapshot()).toBe(snapshot);
expect(snapshot.qqList).toEqual({ data: accounts, ready: true, error: null });
},
);
it('does not invalidate a different resource when receiving a push', async () => {
const { api, store } = setup();
vi.mocked(api.qqList).mockResolvedValueOnce(accounts);
const pending = store.refreshQqList();
store.onEvent({ resource: 'connections', data: [] });
await pending;
expect(store.getSnapshot().qqList.data).toEqual(accounts);
expect(store.getSnapshot().connections.ready).toBe(true);
});
it('retains the last data on failure and clears the error on recovery', async () => {
const { api, store } = setup();
store.onEvent({ resource: 'qq-list', data: accounts });
vi.mocked(api.qqList).mockRejectedValueOnce(new Error('连接中断'));
await store.refreshQqList();
expect(store.getSnapshot().qqList).toEqual({
data: accounts,
ready: true,
error: '连接中断',
});
await store.refreshQqList();
expect(store.getSnapshot().qqList).toEqual({ data: [], ready: true, error: null });
});
it('invalidates pending work on cleanup and allows a new subscription cycle', async () => {
const { api, store } = setup();
const request = Promise.withResolvers<QQInfo[]>();
vi.mocked(api.qqList).mockReturnValueOnce(request.promise);
const pending = store.refreshQqList();
const initial = store.getSnapshot();
store.invalidate();
request.resolve(accounts);
await pending;
expect(store.getSnapshot()).toBe(initial);
await store.refreshQqList();
expect(store.getSnapshot().qqList.ready).toBe(true);
});
it('reconciles all stream resources when frames are dropped', async () => {
const { api, store } = setup();
store.onEvent({ kind: 'ready' });
expect(api.qqList).not.toHaveBeenCalled();
store.onEvent({ kind: 'dropped', count: 3 });
await vi.waitFor(() => expect(store.getSnapshot().connections.ready).toBe(true));
expect(api.qqList).toHaveBeenCalledOnce();
expect(api.processes.list).toHaveBeenCalledOnce();
expect(api.connections).toHaveBeenCalledOnce();
});
it('reports background update failures but rejects an explicit forced check', async () => {
const { api, store } = setup();
vi.spyOn(api.update, 'check').mockRejectedValue(new Error('检查失败'));
await expect(store.refreshUpdate()).resolves.toBeNull();
expect(store.getSnapshot().updateInfo.error).toBe('检查失败');
await expect(store.refreshUpdate(true)).rejects.toThrow('检查失败');
expect(api.update.check).toHaveBeenLastCalledWith(true);
});
});
+119
View File
@@ -0,0 +1,119 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createContactList } from '../src/lib/debug-contacts';
import type { DebugInvokeResult } from '../src/types';
function deferred() {
let resolve!: (result: DebugInvokeResult) => void;
const promise = new Promise<DebugInvokeResult>((done) => {
resolve = done;
});
return { promise, resolve };
}
const success = (nickname: string): DebugInvokeResult => ({
status: 'ok',
data: [{ user_id: 123, nickname }],
});
beforeEach(() => {
vi.stubGlobal('localStorage', { getItem: () => null, setItem: vi.fn() });
});
afterEach(() => vi.unstubAllGlobals());
describe('debug contact lists', () => {
it('keeps account state separate and ignores a response after leaving its list', async () => {
const previous = deferred();
const invoke = vi
.fn()
.mockReturnValueOnce(previous.promise)
.mockResolvedValue(success('current'));
const oldList = createContactList(invoke, 'friends', 'old-account');
const pending = oldList.refresh();
oldList.invalidate();
const current = createContactList(invoke, 'friends', 'new-account');
await current.refresh();
previous.resolve(success('stale'));
await pending;
expect(current.getSnapshot().items[0].label).toBe('current');
expect(oldList.getSnapshot().items).toEqual([]);
expect(createContactList(invoke, 'friends', 'old-account').getSnapshot().items).toEqual([]);
});
it('supersedes an in-flight refresh when using a fresh cached list', async () => {
const pending = deferred();
const invoke = vi
.fn()
.mockResolvedValueOnce(success('cached'))
.mockReturnValueOnce(pending.promise);
const list = createContactList(invoke, 'friends', 'cache-account');
await list.refresh();
const refresh = list.refresh();
await list.refresh(false);
expect(list.getSnapshot().loading).toBe(false);
pending.resolve(success('superseded'));
await refresh;
expect(list.getSnapshot().items[0].label).toBe('cached');
});
it('ignores an earlier refresh that completes after its replacement', async () => {
const first = deferred();
const invoke = vi
.fn()
.mockReturnValueOnce(first.promise)
.mockResolvedValueOnce(success('latest'));
const list = createContactList(invoke, 'friends', 'race-account');
const pending = list.refresh();
await list.refresh();
first.resolve(success('old'));
await pending;
expect(list.getSnapshot().items[0].label).toBe('latest');
});
it('keeps group-member caches scoped to the account and group', async () => {
const invoke = vi.fn().mockResolvedValue(success('member'));
const first = createContactList(invoke, 'members', 'member-account', '111');
await first.refresh();
expect(invoke).toHaveBeenCalledWith('member-account', 'get_group_member_list', {
group_id: '111',
});
expect(
createContactList(invoke, 'members', 'member-account', '111').getSnapshot().items,
).toHaveLength(1);
expect(
createContactList(invoke, 'members', 'member-account', '222').getSnapshot().items,
).toEqual([]);
expect(
createContactList(invoke, 'members', 'other-account', '111').getSnapshot().items,
).toEqual([]);
});
it('reports malformed successful responses instead of caching an empty list', async () => {
const invoke = vi
.fn()
.mockResolvedValueOnce(success('retained'))
.mockResolvedValueOnce({ status: 'ok', data: {} });
const list = createContactList(invoke, 'friends', 'invalid-account');
await list.refresh();
await list.refresh();
expect(list.getSnapshot()).toMatchObject({ loading: false, error: '联系人列表格式无效' });
expect(list.getSnapshot().items[0].label).toBe('retained');
await list.refresh(false);
expect(list.getSnapshot().error).toBeNull();
expect(invoke).toHaveBeenCalledTimes(2);
});
it('does not request contacts without an account or group selection', async () => {
const invoke = vi.fn();
const lists = [
createContactList(invoke, 'friends', ''),
createContactList(invoke, 'members', 'account'),
];
for (const list of lists) {
await list.refresh();
expect(list.getSnapshot()).toEqual({ items: [], loading: false, error: null });
}
expect(invoke).not.toHaveBeenCalled();
});
});
+67
View File
@@ -0,0 +1,67 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { startPolling } from '../src/lib/polling';
let page: EventTarget & { hidden: boolean };
beforeEach(() => {
vi.useFakeTimers();
page = Object.assign(new EventTarget(), { hidden: false });
vi.stubGlobal('document', page);
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
describe('resource polling', () => {
it('starts immediately and skips ticks while a request is pending', async () => {
const pending = Promise.withResolvers<void>();
const refresh = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue(undefined);
const stop = startPolling(refresh, 1000);
expect(refresh).toHaveBeenCalledOnce();
await vi.advanceTimersByTimeAsync(3000);
expect(refresh).toHaveBeenCalledOnce();
pending.resolve();
await vi.advanceTimersByTimeAsync(1000);
expect(refresh).toHaveBeenCalledTimes(2);
stop();
});
it('pauses in the background and refreshes when the page becomes visible', async () => {
page.hidden = true;
const refresh = vi.fn().mockResolvedValue(undefined);
const stop = startPolling(refresh, 1000);
await vi.advanceTimersByTimeAsync(2000);
expect(refresh).not.toHaveBeenCalled();
page.hidden = false;
page.dispatchEvent(new Event('visibilitychange'));
expect(refresh).toHaveBeenCalledOnce();
stop();
await vi.advanceTimersByTimeAsync(2000);
page.dispatchEvent(new Event('visibilitychange'));
expect(refresh).toHaveBeenCalledOnce();
});
it('keeps initial and visibility refreshes when periodic polling is disabled', async () => {
const refresh = vi.fn().mockResolvedValue(undefined);
const stop = startPolling(refresh, 0);
await vi.advanceTimersByTimeAsync(60_000);
expect(refresh).toHaveBeenCalledOnce();
page.dispatchEvent(new Event('visibilitychange'));
expect(refresh).toHaveBeenCalledTimes(2);
stop();
});
it('keeps the update-check cadence independent of page visibility', async () => {
page.hidden = true;
const refresh = vi.fn().mockResolvedValue(undefined);
const stop = startPolling(refresh, 6000, false);
await vi.advanceTimersByTimeAsync(6000);
expect(refresh).toHaveBeenCalledTimes(2);
page.hidden = false;
page.dispatchEvent(new Event('visibilitychange'));
expect(refresh).toHaveBeenCalledTimes(2);
stop();
});
});