Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): add dormant Discord ingress scheduler foundation (#2099)

nanaco1d7aaa2fb445
diff --git a/apps/desktop/src/main/im/scheduler/__tests__/deviceSnapshot.test.ts b/apps/desktop/src/main/im/scheduler/__tests__/deviceSnapshot.test.ts
new file mode 100644
index 0000000000..6137b1161b
--- /dev/null
+++ b/apps/desktop/src/main/im/scheduler/__tests__/deviceSnapshot.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildSchedulerDesktopDeviceSnapshot } from '../deviceSnapshot';
+
+describe('scheduler desktop snapshot projection', () => {
+ it('requires an online self Desktop and sorts online Desktop peers', () => {
+ expect(
+ buildSchedulerDesktopDeviceSnapshot(
+ [
+ { deviceId: 'z', platform: 'darwin', online: true, isSelf: true },
+ { deviceId: 'b', platform: 'linux', online: true, isSelf: false },
+ { deviceId: 'a', platform: 'win32', online: true, isSelf: false },
+ { deviceId: 'phone', platform: 'ios', online: true, isSelf: false },
+ { deviceId: 'offline', platform: 'darwin', online: false, isSelf: false },
+ ],
+ 42,
+ ),
+ ).toEqual({
+ selfDeviceId: 'z',
+ peers: [
+ { deviceId: 'a', platform: 'win32' },
+ { deviceId: 'b', platform: 'linux' },
+ ],
+ observedAt: 42,
+ });
+ });
+
+ it('returns null when the full response cannot prove this Desktop is online', () => {
+ expect(
+ buildSchedulerDesktopDeviceSnapshot([
+ { deviceId: 'peer', platform: 'darwin', online: true, isSelf: false },
+ ]),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/im/scheduler/__tests__/manager.test.ts b/apps/desktop/src/main/im/scheduler/__tests__/manager.test.ts
new file mode 100644
index 0000000000..fc5fa2c854
--- /dev/null
+++ b/apps/desktop/src/main/im/scheduler/__tests__/manager.test.ts
@@ -0,0 +1,2142 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { ImSchedulerManager } from '../manager';
+import type { SchedulerTransport, SchedulerTransportEvent } from '../transport';
+
+const identity = '12345678901234567';
+const nextIdentity = '12345678901234568';
+const peerBindingGeneration = 'peer-binding-0001';
+const oldLocalBindingGeneration = 'local-binding-old1';
+const nextLocalBindingGeneration = 'local-binding-next';
+const currentLocalBindingGeneration = 'local-binding-current';
+
+function sequenceFactory(...values: string[]): () => string {
+ let index = 0;
+ return () => values[Math.min(index++, values.length - 1)]!;
+}
+
+function dirtyGap(runtimeIdentity: string, generation: string, bindingGeneration: string) {
+ return {
+ identity: runtimeIdentity,
+ bindingGeneration,
+ generation,
+ state: 'dirty' as const,
+ };
+}
+
+function normalizeSchedulerPush(
+ event: SchedulerTransportEvent,
+ pushes: Array<{ peerDeviceId: string; payload: unknown }>,
+): SchedulerTransportEvent {
+ if (event.type !== 'push' || !event.payload || typeof event.payload !== 'object') return event;
+ const payload = event.payload as Record<string, unknown>;
+ const latestLocalBindingGeneration = [...pushes]
+ .reverse()
+ .map((push) => push.payload)
+ .find(
+ (candidate) =>
+ candidate !== null &&
+ typeof candidate === 'object' &&
+ (candidate as { kind?: unknown }).kind === 'probe',
+ ) as { channels?: Array<{ bindingGeneration?: string }> } | undefined;
+ const recipientBindingGeneration =
+ latestLocalBindingGeneration?.channels?.[0]?.bindingGeneration ?? 'local-binding-0001';
+ const bindRuntime = (runtime: unknown): unknown =>
+ runtime && typeof runtime === 'object'
+ ? { bindingGeneration: recipientBindingGeneration, ...runtime }
+ : runtime;
+ const channels = Array.isArray(payload.channels)
+ ? payload.channels.map((channel) =>
+ channel && typeof channel === 'object'
+ ? { bindingGeneration: peerBindingGeneration, ...channel }
+ : channel,
+ )
+ : payload.channels;
+ return {
+ ...event,
+ payload: {
+ ...payload,
+ channels,
+ ...(payload.runtime === undefined ? {} : { runtime: bindRuntime(payload.runtime) }),
+ ...(Array.isArray(payload.runtimeGaps)
+ ? { runtimeGaps: payload.runtimeGaps.map(bindRuntime) }
+ : {}),
+ },
+ };
+}
+
+function createTransport(
+ overrides: Partial<{
+ status: 'online' | 'offline';
+ owner: boolean;
+ requestSnapshot: SchedulerTransport['requestSnapshot'];
+ }> = {},
+) {
+ let listener: ((event: SchedulerTransportEvent) => void) | null = null;
+ const pushes: Array<{ peerDeviceId: string; payload: unknown }> = [];
+ const snapshotRequests: Array<{ accountGeneration: string; requestId: string }> = [];
+ const transport: SchedulerTransport = {
+ selfDeviceId: 'z',
+ platform: 'darwin',
+ getStatus: () => overrides.status ?? 'online',
+ isOwner: () => overrides.owner ?? true,
+ subscribe: (next) => {
+ listener = next;
+ return () => {
+ listener = null;
+ };
+ },
+ sendPush: (peerDeviceId, payload) => pushes.push({ peerDeviceId, payload }),
+ requestSnapshot:
+ overrides.requestSnapshot ??
+ ((accountGeneration, requestId) => {
+ snapshotRequests.push({ accountGeneration, requestId });
+ }),
+ };
+ return {
+ transport,
+ pushes,
+ snapshotRequests,
+ emit(event: SchedulerTransportEvent) {
+ listener?.(normalizeSchedulerPush(event, pushes));
+ },
+ };
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('dormant scheduler manager', () => {
+ it('fails closed until the authoritative peer view is confirmed', () => {
+ const harness = createTransport();
+ const decisions: string[] = [];
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ onDecision: (decision) => decisions.push(`${decision.state}:${decision.reason}`),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity },
+ reason: 'incomplete-peer-view',
+ });
+
+ const probe = harness.pushes.find((push) => push.peerDeviceId === 'a')?.payload as {
+ nonce?: string;
+ };
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 2,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity },
+ reason: 'peer-won',
+ });
+ expect(decisions).toContain('standby:incomplete-peer-view');
+ });
+
+ it('elects the local Desktop only after relay and ownership gates pass', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'active',
+ channel: { channel: 'discord', identity },
+ reason: 'elected',
+ });
+
+ harness.transport.getStatus = () => 'offline';
+ harness.emit({ type: 'relay-status', status: 'offline' });
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity },
+ reason: 'relay-offline',
+ });
+ });
+
+ it('rejects an untagged snapshot from before a relay disconnect', async () => {
+ vi.useFakeTimers();
+ let status: 'online' | 'offline' = 'online';
+ const harness = createTransport();
+ harness.transport.getStatus = () => status;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `nonce-${String(++count).padStart(14, '0')}`;
+ })(),
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+
+ status = 'offline';
+ harness.emit({ type: 'relay-status', status: 'offline' });
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 2 },
+ });
+ status = 'online';
+ harness.emit({ type: 'relay-status', status: 'online' });
+ expect(manager.getDecision().reason).toBe('missing-snapshot');
+
+ await vi.advanceTimersByTimeAsync(100);
+ const request = harness.snapshotRequests.at(-1);
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request?.accountGeneration,
+ requestId: request?.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+ manager.stop();
+ });
+
+ it('refreshes the authoritative snapshot after relay recovery', () => {
+ let status: 'online' | 'offline' = 'online';
+ const harness = createTransport();
+ harness.transport.getStatus = () => status;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `nonce-${String(++count).padStart(14, '0')}`;
+ })(),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+
+ status = 'offline';
+ harness.emit({ type: 'relay-status', status: 'offline' });
+ status = 'online';
+ harness.emit({ type: 'relay-status', status: 'online' });
+ const request = harness.snapshotRequests.at(-1);
+ expect(request).toBeTruthy();
+
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request?.accountGeneration,
+ requestId: request?.requestId,
+ snapshot: {
+ selfDeviceId: 'z',
+ peers: [{ deviceId: 'a', platform: 'win32' }],
+ observedAt: 2,
+ },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+ manager.stop();
+ });
+
+ it('refreshes the peer snapshot while the local Discord binding is absent', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => null,
+ nonceFactory: () => 'round-000000000000',
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: null,
+ reason: 'missing-binding',
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(harness.snapshotRequests).toHaveLength(1);
+ manager.stop();
+ });
+
+ it('keeps bounded recovery alive when requestSnapshot throws synchronously', async () => {
+ vi.useFakeTimers();
+ let attempts = 0;
+ const harness = createTransport({
+ requestSnapshot: () => {
+ attempts += 1;
+ throw new Error('snapshot request failed');
+ },
+ });
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(attempts).toBe(1);
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity },
+ reason: 'missing-snapshot',
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(attempts).toBeGreaterThan(1);
+ manager.stop();
+ });
+
+ it('consumes a rejected requestSnapshot promise and keeps retrying', async () => {
+ vi.useFakeTimers();
+ let attempts = 0;
+ const harness = createTransport({
+ requestSnapshot: () => {
+ attempts += 1;
+ return Promise.reject(new Error('snapshot request rejected'));
+ },
+ });
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+
+ await vi.advanceTimersByTimeAsync(100);
+ await Promise.resolve();
+ expect(attempts).toBe(1);
+ expect(manager.getDecision().reason).toBe('missing-snapshot');
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(attempts).toBeGreaterThan(1);
+ manager.stop();
+ });
+
+ it('does not let an older request rejection clear a newer account request', async () => {
+ vi.useFakeTimers();
+ const requests: Array<{
+ accountGeneration: string;
+ requestId: string;
+ resolve: () => void;
+ reject: (error: Error) => void;
+ }> = [];
+ const harness = createTransport({
+ requestSnapshot: (accountGeneration, requestId) =>
+ new Promise<void>((resolve, reject) => {
+ requests.push({ accountGeneration, requestId, resolve, reject });
+ }),
+ });
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `nonce-${String(++count).padStart(14, '0')}`;
+ })(),
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ await vi.advanceTimersByTimeAsync(100);
+ expect(requests).toHaveLength(1);
+
+ manager.resetAccountDiscovery();
+ expect(requests).toHaveLength(2);
+ requests[0].reject(new Error('stale snapshot request rejected'));
+ await Promise.resolve();
+
+ requests[1].resolve();
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: requests[1].accountGeneration,
+ requestId: requests[1].requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 2 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+ manager.stop();
+ });
+
+ it('does not clear a synchronously delivered snapshot after requestSnapshot returns', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport({
+ requestSnapshot: (accountGeneration, requestId) => {
+ // The callback is invoked only after createTransport has returned.
+ transportHarness.emit({
+ type: 'snapshot',
+ accountGeneration,
+ requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 },
+ });
+ },
+ });
+ const transportHarness = harness;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(manager.getDecision()).toEqual({
+ state: 'active',
+ channel: { channel: 'discord', identity },
+ reason: 'elected',
+ });
+ manager.stop();
+ });
+
+ it('restarts the discovery round when ownership returns', () => {
+ const owner = { value: false };
+ const harness = createTransport();
+ harness.transport.isOwner = () => owner.value;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `round-${String(++count).padStart(14, '0')}`;
+ })(),
+ });
+ manager.start();
+ harness.emit({ type: 'snapshot', snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 } });
+ expect(manager.getDecision().reason).toBe('not-owner');
+ owner.value = true;
+ harness.emit({ type: 'ownership', owner: true });
+ expect(manager.getDecision().reason).toBe('missing-snapshot');
+ const request = harness.snapshotRequests.at(-1);
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request?.accountGeneration,
+ requestId: request?.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 2 },
+ });
+ expect(manager.getDecision().reason).toBe('elected');
+ });
+
+ it('does not re-adopt a runtime gap from a probe delayed across a binding reset', () => {
+ let localIdentity = identity;
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity: localIdentity }),
+ nonceFactory: () => 'round-000000000000',
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ manager.getRuntimeGaps().adopt(dirtyGap(identity, 'a'.repeat(32), oldLocalBindingGeneration));
+
+ localIdentity = nextIdentity;
+ manager.resetBindingDiscovery();
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 2,
+ nonce: 'round-peer-00000',
+ channels: [{ channel: 'discord', identity }],
+ runtimeGaps: [{ identity, generation: 'a'.repeat(32), state: 'dirty' }],
+ },
+ });
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+ });
+
+ it('allows a same-identity token refresh to adopt a new runtime gap', () => {
+ let round = 0;
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ bindingGenerationFactory: sequenceFactory(
+ oldLocalBindingGeneration,
+ currentLocalBindingGeneration,
+ ),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const oldGap = dirtyGap(identity, 'a'.repeat(32), oldLocalBindingGeneration);
+ manager.getRuntimeGaps().adopt(oldGap);
+
+ manager.resetBindingDiscovery();
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+ const probe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ const refreshedGap = dirtyGap(identity, 'b'.repeat(32), currentLocalBindingGeneration);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 2,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [oldGap],
+ },
+ });
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 3,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [refreshedGap],
+ },
+ });
+
+ expect(manager.getRuntimeGaps().values()).toEqual([refreshedGap]);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 4,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [oldGap],
+ },
+ });
+ expect(manager.getRuntimeGaps().values()).toEqual([refreshedGap]);
+ manager.stop();
+ });
+
+ it('does not re-adopt a dirty generation after its exact clean frame arrived first', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ bindingGenerationFactory: () => currentLocalBindingGeneration,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const probe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string } | undefined;
+ const generation = 'c'.repeat(32);
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 2,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtime: { identity, generation, state: 'clean' },
+ },
+ });
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 3,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [{ identity, generation, state: 'dirty' }],
+ },
+ });
+
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+ manager.stop();
+ });
+
+ it('keeps the binding barrier after more stale gaps than the wire limit', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ bindingGenerationFactory: sequenceFactory(
+ oldLocalBindingGeneration,
+ currentLocalBindingGeneration,
+ ),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ manager.resetBindingDiscovery();
+ const probe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+
+ for (let index = 0; index < 9; index += 1) {
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: index + 2,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [
+ dirtyGap(identity, index.toString(16).repeat(32), oldLocalBindingGeneration),
+ ],
+ },
+ });
+ }
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+
+ const currentGap = dirtyGap(identity, 'f'.repeat(32), currentLocalBindingGeneration);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 20,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [currentGap],
+ },
+ });
+ expect(manager.getRuntimeGaps().values()).toEqual([currentGap]);
+ manager.stop();
+ });
+
+ it('continues bounded discovery after a synchronous final snapshot with unresolved peers', async () => {
+ vi.useFakeTimers();
+ let requestCount = 0;
+ const harness = createTransport({
+ requestSnapshot: (accountGeneration, requestId) => {
+ requestCount += 1;
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration,
+ requestId,
+ snapshot: {
+ selfDeviceId: 'z',
+ peers: [{ deviceId: 'a', platform: 'win32' }],
+ observedAt: requestCount + 1,
+ },
+ });
+ },
+ });
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `round-${String(++count).padStart(14, '0')}`;
+ })(),
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(requestCount).toBe(1);
+ await vi.advanceTimersByTimeAsync(100);
+ expect(requestCount).toBe(2);
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+ manager.stop();
+ });
+
+ it('rejects an unseen old generation observed only in a prior peer advertisement', () => {
+ let localIdentity = identity;
+ let round = 0;
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity: localIdentity }),
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ bindingGenerationFactory: sequenceFactory(
+ oldLocalBindingGeneration,
+ nextLocalBindingGeneration,
+ currentLocalBindingGeneration,
+ ),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ const oldGap = dirtyGap(identity, 'a'.repeat(32), oldLocalBindingGeneration);
+ localIdentity = nextIdentity;
+ manager.resetBindingDiscovery();
+ let probe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 2,
+ channels: [{ channel: 'discord', identity: nextIdentity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [oldGap],
+ },
+ });
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+
+ localIdentity = identity;
+ manager.resetBindingDiscovery();
+ probe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ const refreshedGap = dirtyGap(identity, 'b'.repeat(32), currentLocalBindingGeneration);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 3,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [oldGap],
+ },
+ });
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 4,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [refreshedGap],
+ },
+ });
+ expect(manager.getRuntimeGaps().values()).toEqual([refreshedGap]);
+ manager.stop();
+ });
+
+ it('allows a same-identity rebind while rejecting the previous binding generation', () => {
+ let localIdentity: string | null = identity;
+ let round = 0;
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () =>
+ localIdentity ? { channel: 'discord', identity: localIdentity } : null,
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ bindingGenerationFactory: sequenceFactory(
+ oldLocalBindingGeneration,
+ nextLocalBindingGeneration,
+ currentLocalBindingGeneration,
+ ),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const oldGap = dirtyGap(identity, 'a'.repeat(32), oldLocalBindingGeneration);
+ manager.getRuntimeGaps().adopt(oldGap);
+
+ localIdentity = null;
+ manager.resetBindingDiscovery();
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+
+ localIdentity = identity;
+ manager.resetBindingDiscovery();
+ const probe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ const refreshedGap = dirtyGap(identity, 'b'.repeat(32), currentLocalBindingGeneration);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 2,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [oldGap],
+ },
+ });
+
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 3,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [refreshedGap],
+ },
+ });
+
+ expect(manager.getRuntimeGaps().values()).toEqual([refreshedGap]);
+ manager.stop();
+ });
+
+ it('allows a same-identity account reset to adopt a new runtime gap', () => {
+ let round = 0;
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ bindingGenerationFactory: sequenceFactory(
+ oldLocalBindingGeneration,
+ currentLocalBindingGeneration,
+ ),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 },
+ });
+ manager.getRuntimeGaps().adopt({
+ identity,
+ bindingGeneration: oldLocalBindingGeneration,
+ generation: 'a'.repeat(32),
+ state: 'dirty',
+ });
+
+ manager.resetAccountDiscovery();
+ const request = harness.snapshotRequests.at(-1);
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request?.accountGeneration,
+ requestId: request?.requestId,
+ snapshot: {
+ selfDeviceId: 'z',
+ peers: [{ deviceId: 'a', platform: 'win32' }],
+ observedAt: 2,
+ },
+ });
+ const probe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ const refreshedGap = dirtyGap(identity, 'b'.repeat(32), currentLocalBindingGeneration);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 3,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: probe?.nonce,
+ runtimeGaps: [refreshedGap],
+ },
+ });
+
+ expect(manager.getRuntimeGaps().values()).toEqual([refreshedGap]);
+ manager.stop();
+ });
+
+ it('keeps rejecting untagged snapshots after a tagged recovery response', () => {
+ const owner = { value: false };
+ const harness = createTransport();
+ harness.transport.isOwner = () => owner.value;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `round-${String(++count).padStart(14, '0')}`;
+ })(),
+ });
+ manager.start();
+ harness.emit({ type: 'snapshot', snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 } });
+
+ owner.value = true;
+ harness.emit({ type: 'ownership', owner: true });
+ const request = harness.snapshotRequests.at(-1);
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request?.accountGeneration,
+ requestId: request?.requestId,
+ snapshot: {
+ selfDeviceId: 'z',
+ peers: [{ deviceId: 'a', platform: 'win32' }],
+ observedAt: 2,
+ },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 100 },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+ });
+
+ it('locks the tagged snapshot gate after the first tagged startup response', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ discoveryRetryDelayMs: 100,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+ const request = harness.snapshotRequests.at(-1)!;
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request.accountGeneration,
+ requestId: request.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 2 },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 100 },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+ manager.stop();
+ });
+
+ it('drops an older snapshot instead of reviving a stale election view', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 10 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 9 },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'active',
+ channel: { channel: 'discord', identity },
+ reason: 'elected',
+ });
+ });
+
+ it('fails closed when the authoritative snapshot disappears', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 10 },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'active',
+ channel: { channel: 'discord', identity },
+ reason: 'elected',
+ });
+
+ harness.emit({ type: 'snapshot', snapshot: null });
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity },
+ reason: 'missing-snapshot',
+ });
+ });
+
+ it('retries when an authoritative snapshot names a different self device', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'other', peers: [], observedAt: 1 },
+ });
+ expect(manager.getDecision().reason).toBe('missing-snapshot');
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(harness.snapshotRequests).toHaveLength(1);
+ manager.stop();
+ });
+
+ it('retries a lost discovery probe and starts a fresh round after the bound', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ discoveryRetryDelayMs: 100,
+ snapshotResponseTimeoutMs: 100,
+ maxDiscoveryRetries: 2,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ await vi.advanceTimersByTimeAsync(250);
+ const probes = harness.pushes
+ .filter((push) => push.peerDeviceId === 'a')
+ .map((push) => push.payload)
+ .filter(
+ (payload): payload is { kind: 'probe'; nonce: string } =>
+ typeof payload === 'object' &&
+ payload !== null &&
+ (payload as { kind?: unknown }).kind === 'probe',
+ );
+ expect(probes).toHaveLength(3);
+ expect(new Set(probes.map((probe) => probe.nonce))).toEqual(new Set(['round-000000000000']));
+ expect(harness.snapshotRequests).toHaveLength(2);
+
+ await vi.advanceTimersByTimeAsync(50);
+ const secondRoundCount = harness.pushes.filter((push) => push.peerDeviceId === 'a').length;
+ expect(secondRoundCount).toBeGreaterThan(probes.length);
+ await vi.advanceTimersByTimeAsync(100);
+ expect(harness.pushes.filter((push) => push.peerDeviceId === 'a').length).toBeGreaterThan(
+ secondRoundCount,
+ );
+ manager.stop();
+ });
+
+ it('clamps a zero discovery retry limit to one recovery attempt', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 0,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(harness.snapshotRequests).toHaveLength(1);
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+ manager.stop();
+ });
+
+ it('restarts discovery instead of applying a late peer probe', () => {
+ const harness = createTransport();
+ let round = 0;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const probe = harness.pushes.find((push) => push.peerDeviceId === 'a')?.payload as {
+ nonce?: string;
+ };
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 2,
+ channels: [],
+ inReplyTo: probe?.nonce,
+ },
+ });
+ expect(manager.getDecision().state).toBe('active');
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 3,
+ nonce: 'round-peer-00000',
+ channels: [{ channel: 'discord', identity }],
+ },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ const refreshedProbe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ expect(refreshedProbe.nonce).not.toBe(probe?.nonce);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 4,
+ channels: [],
+ inReplyTo: refreshedProbe.nonce,
+ },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'active',
+ channel: { channel: 'discord', identity },
+ reason: 'elected',
+ });
+ });
+
+ it('propagates a binding change in the next peer probe and scopes runtime gaps', () => {
+ let localIdentity = identity;
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity: localIdentity }),
+ nonceFactory: (() => {
+ let round = 0;
+ return () => `round-${String(++round).padStart(14, '0')}`;
+ })(),
+ bindingGenerationFactory: sequenceFactory(
+ oldLocalBindingGeneration,
+ currentLocalBindingGeneration,
+ ),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ manager.getRuntimeGaps().adopt(dirtyGap(identity, 'a'.repeat(32), oldLocalBindingGeneration));
+
+ localIdentity = nextIdentity;
+ manager.resetBindingDiscovery();
+ const latestProbe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { channels?: Array<{ identity: string }>; nonce?: string } | undefined;
+ expect(latestProbe?.channels).toEqual([
+ {
+ channel: 'discord',
+ identity: nextIdentity,
+ bindingGeneration: currentLocalBindingGeneration,
+ },
+ ]);
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 2,
+ channels: [{ channel: 'discord', identity: nextIdentity }],
+ inReplyTo: latestProbe?.nonce,
+ runtimeGaps: [
+ dirtyGap(identity, 'a'.repeat(32), oldLocalBindingGeneration),
+ dirtyGap(nextIdentity, 'b'.repeat(32), currentLocalBindingGeneration),
+ ],
+ },
+ });
+ expect(manager.getRuntimeGaps().values()).toEqual([
+ dirtyGap(nextIdentity, 'b'.repeat(32), currentLocalBindingGeneration),
+ ]);
+
+ manager
+ .getRuntimeGaps()
+ .adopt(dirtyGap(nextIdentity, 'b'.repeat(32), currentLocalBindingGeneration));
+ manager.resetAccountDiscovery();
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+ });
+
+ it('retains the previous binding identity until its reset clears old gaps', () => {
+ let localIdentity = identity;
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity: localIdentity }),
+ nonceFactory: () => 'round-000000000000',
+ });
+ manager.start();
+ manager.getRuntimeGaps().adopt(dirtyGap(identity, 'a'.repeat(32), oldLocalBindingGeneration));
+
+ localIdentity = nextIdentity;
+ harness.emit({ type: 'ownership', owner: true });
+ manager.resetBindingDiscovery();
+ expect(manager.getRuntimeGaps().values()).toEqual([]);
+ });
+
+ it('lets a peer learn the new binding before it elects an ingress', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity: nextIdentity }),
+ nonceFactory: () => 'round-000000000000',
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const probe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string } | undefined;
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 2,
+ nonce: 'round-peer-00000',
+ channels: [{ channel: 'discord', identity: nextIdentity }],
+ },
+ });
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 3,
+ channels: [{ channel: 'discord', identity: nextIdentity }],
+ inReplyTo: probe?.nonce,
+ },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity: nextIdentity },
+ reason: 'peer-won',
+ });
+ });
+
+ it('ignores snapshot responses from before an account reset', () => {
+ let round = 0;
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => `nonce-${String(++round).padStart(14, '0')}`,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+
+ manager.resetAccountDiscovery();
+ const request = harness.snapshotRequests.at(-1);
+ expect(request).toBeTruthy();
+ expect(manager.getDecision().reason).toBe('missing-snapshot');
+
+ harness.emit({
+ type: 'snapshot',
+ requestId: 'nonce-old-account',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 2 },
+ });
+ expect(manager.getDecision().reason).toBe('missing-snapshot');
+
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request?.accountGeneration,
+ requestId: request?.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 3 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+ });
+
+ it('ignores presence changes for non-Desktop devices', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 1 },
+ });
+ harness.emit({ type: 'peer-presence', deviceId: 'phone', platform: 'ios', online: false });
+ expect(manager.getDecision()).toEqual({
+ state: 'active',
+ channel: { channel: 'discord', identity },
+ reason: 'elected',
+ });
+ });
+
+ it('does not reply to probes from devices outside the current authoritative snapshot', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const before = harness.pushes.length;
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'unknown',
+ payload: {
+ kind: 'probe',
+ sentAt: 2,
+ nonce: 'round-unknown000',
+ channels: [{ channel: 'discord', identity }],
+ },
+ });
+ expect(harness.pushes).toHaveLength(before);
+ });
+
+ it('ignores a late snapshot after a discovery retry starts a new round', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `nonce-${String(++count).padStart(14, '0')}`;
+ })(),
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+ const request = harness.snapshotRequests[0];
+ expect(request).toBeTruthy();
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request.accountGeneration,
+ requestId: 'nonce-old-response',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 2 },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request.accountGeneration,
+ requestId: request.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 2 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+ manager.stop();
+ });
+
+ it('accepts a current snapshot after the observed clock moves backwards', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `nonce-${String(++count).padStart(14, '0')}`;
+ })(),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 10 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+
+ harness.emit({ type: 'peer-presence', deviceId: 'a', platform: 'win32', online: true });
+ const request = harness.snapshotRequests.at(-1);
+ expect(manager.getDecision().reason).toBe('missing-snapshot');
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request?.accountGeneration,
+ requestId: request?.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 5 },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'active',
+ channel: { channel: 'discord', identity },
+ reason: 'elected',
+ });
+ });
+
+ it('starts a new discovery round when the final snapshot response times out', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `nonce-${String(++count).padStart(14, '0')}`;
+ })(),
+ discoveryRetryDelayMs: 100,
+ snapshotResponseTimeoutMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+ const pushesAtFinalRequest = harness.pushes.length;
+ await vi.advanceTimersByTimeAsync(100);
+ expect(harness.snapshotRequests).toHaveLength(1);
+ expect(harness.pushes.length).toBeGreaterThan(pushesAtFinalRequest);
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+ manager.stop();
+ });
+
+ it('retries after a final refresh returns an empty authoritative snapshot', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `nonce-${String(++count).padStart(14, '0')}`;
+ })(),
+ discoveryRetryDelayMs: 100,
+ snapshotResponseTimeoutMs: 500,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ await vi.advanceTimersByTimeAsync(100);
+ const request = harness.snapshotRequests.at(-1);
+ expect(request).toBeTruthy();
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request?.accountGeneration,
+ requestId: request?.requestId,
+ snapshot: null,
+ });
+ expect(manager.getDecision().reason).toBe('missing-snapshot');
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(harness.snapshotRequests.length).toBeGreaterThan(1);
+ manager.stop();
+ });
+
+ it('accepts a slow final snapshot response before its independent timeout', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `nonce-${String(++count).padStart(14, '0')}`;
+ })(),
+ discoveryRetryDelayMs: 100,
+ snapshotResponseTimeoutMs: 300,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ await vi.advanceTimersByTimeAsync(250);
+ const request = harness.snapshotRequests.at(-1);
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: request?.accountGeneration,
+ requestId: request?.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 2 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+ manager.stop();
+ });
+
+ it('continues discovery when one peer probe send throws', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ const sendPush = harness.transport.sendPush;
+ harness.transport.sendPush = (peerDeviceId, payload) => {
+ if (peerDeviceId === 'a') throw new Error('peer queue closed');
+ sendPush(peerDeviceId, payload);
+ };
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => 'round-000000000000',
+ discoveryRetryDelayMs: 100,
+ snapshotResponseTimeoutMs: 300,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: {
+ selfDeviceId: 'z',
+ peers: [
+ { deviceId: 'a', platform: 'win32' },
+ { deviceId: 'b', platform: 'darwin' },
+ ],
+ observedAt: 1,
+ },
+ });
+ expect(
+ harness.pushes.filter(
+ (push) =>
+ push.peerDeviceId === 'b' && (push.payload as { kind?: unknown }).kind === 'probe',
+ ),
+ ).toHaveLength(1);
+
+ await vi.advanceTimersByTimeAsync(100);
+ expect(harness.snapshotRequests).toHaveLength(1);
+ expect(
+ harness.pushes.filter(
+ (push) =>
+ push.peerDeviceId === 'b' && (push.payload as { kind?: unknown }).kind === 'probe',
+ ),
+ ).toHaveLength(2);
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+ manager.stop();
+ });
+
+ it('retries an unbinding declaration until the peer view is confirmed', async () => {
+ vi.useFakeTimers();
+ let localIdentity: string | null = identity;
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () =>
+ localIdentity ? { channel: 'discord', identity: localIdentity } : null,
+ nonceFactory: () => 'round-000000000000',
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 1,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+
+ localIdentity = null;
+ manager.resetBindingDiscovery();
+ const probesAfterReset = harness.pushes.filter(
+ (push) => push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ );
+ expect((probesAfterReset.at(-1)?.payload as { channels?: unknown }).channels).toEqual([]);
+
+ await vi.advanceTimersByTimeAsync(100);
+ const probesAfterRetry = harness.pushes.filter(
+ (push) => push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ );
+ expect(probesAfterRetry.length).toBeGreaterThan(probesAfterReset.length);
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: null,
+ reason: 'missing-binding',
+ });
+ manager.stop();
+ });
+
+ it('restarts discovery for a peer binding change despite remote clock rollback', () => {
+ const harness = createTransport();
+ let round = 0;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const probe = harness.pushes.find((push) => push.peerDeviceId === 'a')?.payload as {
+ nonce?: string;
+ };
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 100,
+ channels: [],
+ inReplyTo: probe?.nonce,
+ },
+ });
+ expect(manager.getDecision().state).toBe('active');
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 10,
+ nonce: 'round-peer-00000',
+ channels: [{ channel: 'discord', identity }],
+ },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ const refreshedProbe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 11,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: refreshedProbe.nonce,
+ },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity },
+ reason: 'peer-won',
+ });
+ });
+
+ it('rejects an older binding advertisement after a newer binding probe', () => {
+ const harness = createTransport();
+ let round = 0;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity: nextIdentity }),
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const probe = harness.pushes.find((push) => push.peerDeviceId === 'a')?.payload as {
+ nonce?: string;
+ };
+ const oldChannel = {
+ channel: 'discord' as const,
+ identity: nextIdentity,
+ bindingGeneration: peerBindingGeneration,
+ };
+ const newChannel = {
+ channel: 'discord' as const,
+ identity: nextIdentity,
+ bindingGeneration: nextLocalBindingGeneration,
+ };
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 3,
+ nonce: 'round-peer-00000',
+ channels: [newChannel],
+ },
+ });
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 4,
+ channels: [oldChannel],
+ inReplyTo: probe?.nonce,
+ },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ const refreshedProbe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ expect(refreshedProbe.nonce).not.toBe(probe?.nonce);
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 5,
+ channels: [newChannel],
+ inReplyTo: refreshedProbe.nonce,
+ },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity: nextIdentity },
+ reason: 'peer-won',
+ });
+ });
+
+ it('rejects a conflicting delayed advertisement after confirming the same retry nonce', async () => {
+ vi.useFakeTimers();
+ const harness = createTransport();
+ let round = 0;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ discoveryRetryDelayMs: 100,
+ maxDiscoveryRetries: 2,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const initialProbe = harness.pushes.find(
+ (push) => push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce: string };
+
+ await vi.advanceTimersByTimeAsync(100);
+ const retryProbe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce: string };
+ expect(retryProbe.nonce).toBe(initialProbe.nonce);
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 3,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: initialProbe.nonce,
+ },
+ });
+ expect(manager.getDecision().reason).toBe('peer-won');
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 2,
+ channels: [],
+ inReplyTo: initialProbe.nonce,
+ },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ const refreshedProbe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce: string };
+ expect(refreshedProbe.nonce).not.toBe(initialProbe.nonce);
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 4,
+ channels: [{ channel: 'discord', identity }],
+ inReplyTo: refreshedProbe.nonce,
+ },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity },
+ reason: 'peer-won',
+ });
+ manager.stop();
+ });
+
+ it('rotates discovery when contradictory peer probes arrive out of order', () => {
+ const harness = createTransport();
+ let round = 0;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity: nextIdentity }),
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const initialProbe = harness.pushes.find(
+ (push) => push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ const oldChannel = {
+ channel: 'discord' as const,
+ identity: nextIdentity,
+ bindingGeneration: peerBindingGeneration,
+ };
+ const newChannel = {
+ channel: 'discord' as const,
+ identity: nextIdentity,
+ bindingGeneration: nextLocalBindingGeneration,
+ };
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 3,
+ nonce: 'round-peer-new-000',
+ channels: [newChannel],
+ },
+ });
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 4,
+ nonce: 'round-peer-old-000',
+ channels: [oldChannel],
+ },
+ });
+
+ const refreshedProbe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ expect(refreshedProbe.nonce).not.toBe(initialProbe?.nonce);
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ // This advertisement belongs to the pre-conflict round and must not
+ // satisfy the fresh round, even though its channels match the stale probe.
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 5,
+ channels: [oldChannel],
+ inReplyTo: initialProbe?.nonce,
+ },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 6,
+ channels: [newChannel],
+ inReplyTo: refreshedProbe.nonce,
+ },
+ });
+ expect(manager.getDecision()).toEqual({
+ state: 'standby',
+ channel: { channel: 'discord', identity: nextIdentity },
+ reason: 'peer-won',
+ });
+ });
+
+ it('forgets ignored probe nonces when a peer goes offline and reconnects', () => {
+ const harness = createTransport();
+ let round = 0;
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity: nextIdentity }),
+ nonceFactory: () => `round-${String(++round).padStart(14, '0')}`,
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 1 },
+ });
+ const oldChannel = {
+ channel: 'discord' as const,
+ identity: nextIdentity,
+ bindingGeneration: peerBindingGeneration,
+ };
+ const newChannel = {
+ channel: 'discord' as const,
+ identity: nextIdentity,
+ bindingGeneration: nextLocalBindingGeneration,
+ };
+ const reusedNonce = 'round-peer-reused';
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 2,
+ nonce: 'round-peer-new-000',
+ channels: [newChannel],
+ },
+ });
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 3,
+ nonce: reusedNonce,
+ channels: [oldChannel],
+ },
+ });
+
+ harness.emit({ type: 'peer-presence', deviceId: 'a', platform: 'win32', online: false });
+ const snapshotRequest = harness.snapshotRequests.at(-1)!;
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: snapshotRequest.accountGeneration,
+ requestId: snapshotRequest.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [{ deviceId: 'a', platform: 'win32' }], observedAt: 4 },
+ });
+ const reconnectProbe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'probe',
+ sentAt: 5,
+ nonce: reusedNonce,
+ channels: [newChannel],
+ },
+ });
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 6,
+ channels: [oldChannel],
+ inReplyTo: reconnectProbe.nonce,
+ },
+ });
+ expect(manager.getDecision().reason).toBe('incomplete-peer-view');
+
+ const refreshedProbe = [...harness.pushes]
+ .reverse()
+ .find(
+ (push) =>
+ push.peerDeviceId === 'a' && (push.payload as { kind?: unknown }).kind === 'probe',
+ )?.payload as { nonce?: string };
+ expect(refreshedProbe.nonce).not.toBe(reconnectProbe.nonce);
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: 'a',
+ payload: {
+ kind: 'advertisement',
+ sentAt: 7,
+ channels: [newChannel],
+ inReplyTo: refreshedProbe.nonce,
+ },
+ });
+ expect(manager.getDecision().reason).toBe('peer-won');
+ });
+
+ it('prunes ignored probe nonces to the current authoritative peer set', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity: nextIdentity }),
+ nonceFactory: () => 'round-000000000000',
+ });
+ manager.start();
+ const oldChannel = {
+ channel: 'discord' as const,
+ identity: nextIdentity,
+ bindingGeneration: peerBindingGeneration,
+ };
+ const newChannel = {
+ channel: 'discord' as const,
+ identity: nextIdentity,
+ bindingGeneration: nextLocalBindingGeneration,
+ };
+
+ for (let index = 0; index < 16; index += 1) {
+ const deviceId = `peer-${String(index).padStart(2, '0')}`;
+ harness.emit({
+ type: 'snapshot',
+ snapshot: {
+ selfDeviceId: 'z',
+ peers: [{ deviceId, platform: 'win32' }],
+ observedAt: index + 1,
+ },
+ });
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: deviceId,
+ payload: {
+ kind: 'probe',
+ sentAt: index * 2 + 1,
+ nonce: `peer-new-${String(index).padStart(8, '0')}`,
+ channels: [newChannel],
+ },
+ });
+ harness.emit({
+ type: 'push',
+ sourceDeviceId: deviceId,
+ payload: {
+ kind: 'probe',
+ sentAt: index * 2 + 2,
+ nonce: `peer-old-${String(index).padStart(8, '0')}`,
+ channels: [oldChannel],
+ },
+ });
+ }
+
+ const managerState = manager as unknown as {
+ ignoredPeerProbeNonces: Map<string, Set<string>>;
+ };
+ expect([...managerState.ignoredPeerProbeNonces.keys()]).toEqual(['peer-15']);
+
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 17 },
+ });
+ expect(managerState.ignoredPeerProbeNonces.size).toBe(0);
+ });
+
+ it('keeps overlapping snapshot responses isolated by request id', () => {
+ const harness = createTransport();
+ const manager = new ImSchedulerManager({
+ transport: harness.transport,
+ getLocalChannel: () => ({ channel: 'discord', identity }),
+ nonceFactory: (() => {
+ let count = 0;
+ return () => `nonce-${String(++count).padStart(14, '0')}`;
+ })(),
+ });
+ manager.start();
+ harness.emit({
+ type: 'snapshot',
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 10 },
+ });
+ harness.emit({ type: 'peer-presence', deviceId: 'a', platform: 'win32', online: true });
+ const first = harness.snapshotRequests.at(-1);
+ harness.emit({ type: 'peer-presence', deviceId: 'b', platform: 'win32', online: true });
+ const second = harness.snapshotRequests.at(-1);
+ expect(first?.requestId).not.toBe(second?.requestId);
+
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: first?.accountGeneration,
+ requestId: first?.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 11 },
+ });
+ expect(manager.getDecision().reason).toBe('missing-snapshot');
+
+ harness.emit({
+ type: 'snapshot',
+ accountGeneration: second?.accountGeneration,
+ requestId: second?.requestId,
+ snapshot: { selfDeviceId: 'z', peers: [], observedAt: 5 },
+ });
+ expect(manager.getDecision().state).toBe('active');
+ });
+});
diff --git a/apps/desktop/src/main/im/scheduler/__tests__/runtimeGaps.test.ts b/apps/desktop/src/main/im/scheduler/__tests__/runtimeGaps.test.ts
new file mode 100644
index 0000000000..b8455b9fb2
--- /dev/null
+++ b/apps/desktop/src/main/im/scheduler/__tests__/runtimeGaps.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, it } from 'vitest';
+
+import { RuntimeGapSet } from '../runtimeGaps';
+
+const gap = (identity: string, generation: string, bindingGeneration = 'binding-123456789') => ({
+ identity,
+ bindingGeneration,
+ generation,
+ state: 'dirty' as const,
+});
+
+describe('bounded runtime gaps', () => {
+ it('keeps every unresolved generation for one binding', () => {
+ const gaps = new RuntimeGapSet();
+ expect(gaps.adopt(gap('12345678901234567', 'f'.repeat(32)))).toBe(true);
+ expect(gaps.adopt(gap('12345678901234567', '1'.repeat(32)))).toBe(true);
+ expect(gaps.values()).toEqual([
+ gap('12345678901234567', '1'.repeat(32)),
+ gap('12345678901234567', 'f'.repeat(32)),
+ ]);
+
+ const reversed = new RuntimeGapSet();
+ reversed.adopt(gap('12345678901234567', '1'.repeat(32)));
+ reversed.adopt(gap('12345678901234567', 'f'.repeat(32)));
+ expect(reversed.values()).toEqual(gaps.values());
+ });
+
+ it('resolves only the exact identity, binding, and runtime generation', () => {
+ const gaps = new RuntimeGapSet();
+ const first = gap('12345678901234567', '1'.repeat(32));
+ const second = gap('12345678901234567', '2'.repeat(32));
+ const nextBinding = gap('12345678901234567', '1'.repeat(32), 'binding-987654321');
+ gaps.adopt(first);
+ gaps.adopt(second);
+ gaps.adopt(nextBinding);
+
+ expect(gaps.resolve(first)).toBe(true);
+ expect(gaps.resolve(first)).toBe(false);
+ expect(gaps.values()).toEqual([second, nextBinding]);
+ });
+
+ it('does not resurrect a dirty generation whose clean frame arrived first', () => {
+ const gaps = new RuntimeGapSet();
+ const resolvedBeforeDirty = gap('12345678901234567', '3'.repeat(32));
+
+ expect(gaps.resolve(resolvedBeforeDirty)).toBe(true);
+ expect(gaps.adopt(resolvedBeforeDirty)).toBe(false);
+ expect(gaps.values()).toEqual([]);
+ });
+
+ it('keeps a full resolved window fail-closed when a new tombstone crosses the trim boundary', () => {
+ const gaps = new RuntimeGapSet();
+ const resolvedWindow = Array.from({ length: 32 }, (_, index) =>
+ gap('12345678901234567', index.toString(16).padStart(32, '0')),
+ );
+ const newest = gap('12345678901234567', 'f'.repeat(32));
+
+ for (const runtime of resolvedWindow) expect(gaps.resolve(runtime)).toBe(true);
+ expect(gaps.resolve(newest)).toBe(true);
+
+ // The overflowing binding is represented by one bounded lifecycle
+ // barrier, so neither the newly inserted tombstone nor an older evicted
+ // generation can return through a delayed dirty advertisement.
+ expect(gaps.adopt(newest)).toBe(false);
+ expect(gaps.adopt(resolvedWindow[0])).toBe(false);
+ expect(gaps.values()).toEqual([]);
+
+ const laterClean = gap('12345678901234567', 'e'.repeat(32));
+ expect(gaps.resolve(laterClean)).toBe(false);
+ expect(gaps.adopt(laterClean)).toBe(false);
+
+ // Rebinding clears the fail-closed barrier and allows the new lifecycle to
+ // collect legitimate gaps again.
+ expect(gaps.clearIdentity('12345678901234567')).toBe(true);
+ expect(gaps.adopt(newest)).toBe(true);
+ });
+
+ it('retains at most the protocol limit with deterministic tuple ordering', () => {
+ const gaps = new RuntimeGapSet();
+ for (let index = 0; index < 9; index += 1) {
+ gaps.adopt(gap('12345678901234567', index.toString(16).repeat(32)));
+ }
+ expect(gaps.values()).toHaveLength(8);
+ expect(gaps.values().map((runtime) => runtime.generation)).toEqual([
+ '0'.repeat(32),
+ '1'.repeat(32),
+ '2'.repeat(32),
+ '3'.repeat(32),
+ '4'.repeat(32),
+ '5'.repeat(32),
+ '6'.repeat(32),
+ '7'.repeat(32),
+ ]);
+ });
+
+ it('can retire one binding without clearing unrelated account gaps', () => {
+ const gaps = new RuntimeGapSet();
+ gaps.adopt(gap('12345678901234567', '1'.repeat(32)));
+ gaps.adopt(gap('12345678901234568', '2'.repeat(32)));
+ expect(gaps.clearIdentity('12345678901234567')).toBe(true);
+ expect(gaps.values()).toEqual([gap('12345678901234568', '2'.repeat(32))]);
+ });
+});
diff --git a/apps/desktop/src/main/im/scheduler/__tests__/state.test.ts b/apps/desktop/src/main/im/scheduler/__tests__/state.test.ts
new file mode 100644
index 0000000000..45d3700a78
--- /dev/null
+++ b/apps/desktop/src/main/im/scheduler/__tests__/state.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+
+import { compareSchedulerStrings, selectIngressDevice } from '../state';
+
+describe('Discord scheduler election state', () => {
+ it('orders scheduler values without consulting the process locale', () => {
+ expect(compareSchedulerStrings('Z', 'a')).toBe(-1);
+ expect(compareSchedulerStrings('a', 'Z')).toBe(1);
+ expect(compareSchedulerStrings('same', 'same')).toBe(0);
+ });
+
+ it('selects the same deterministic Desktop regardless of input order', () => {
+ const devices = [
+ {
+ deviceId: 'z',
+ online: true,
+ platform: 'darwin',
+ channels: [{ channel: 'discord' as const, identity: '12345678901234567' }],
+ lastSeenAt: 2,
+ },
+ {
+ deviceId: 'a',
+ online: true,
+ platform: 'win32',
+ channels: [{ channel: 'discord' as const, identity: '12345678901234567' }],
+ lastSeenAt: 1,
+ },
+ ];
+ expect(selectIngressDevice('discord', '12345678901234567', devices)).toBe('a');
+ expect(selectIngressDevice('discord', '12345678901234567', [...devices].reverse())).toBe('a');
+ });
+
+ it('ignores offline, mobile, and differently configured devices', () => {
+ expect(
+ selectIngressDevice('discord', '12345678901234567', [
+ {
+ deviceId: 'offline',
+ online: false,
+ platform: 'darwin',
+ channels: [{ channel: 'discord' as const, identity: '12345678901234567' }],
+ lastSeenAt: 1,
+ },
+ {
+ deviceId: 'phone',
+ online: true,
+ platform: 'ios',
+ channels: [{ channel: 'discord' as const, identity: '12345678901234567' }],
+ lastSeenAt: 1,
+ },
+ {
+ deviceId: 'other',
+ online: true,
+ platform: 'linux',
+ channels: [{ channel: 'discord' as const, identity: '76543210987654321' }],
+ lastSeenAt: 1,
+ },
+ ]),
+ ).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/im/scheduler/deviceSnapshot.ts b/apps/desktop/src/main/im/scheduler/deviceSnapshot.ts
new file mode 100644
index 0000000000..4738364335
--- /dev/null
+++ b/apps/desktop/src/main/im/scheduler/deviceSnapshot.ts
@@ -0,0 +1,37 @@
+import type { DeviceView } from '@cindy/device-link';
+
+import { compareSchedulerStrings, isDesktopSchedulerPlatform } from './state';
+
+export interface SchedulerDesktopDeviceSnapshot {
+ /** Presence of this row is the completion barrier for an authoritative view. */
+ selfDeviceId: string;
+ peers: Array<{ deviceId: string; platform: string }>;
+ observedAt: number;
+}
+
+/**
+ * Project the server's full Device Link view into the scheduler's small,
+ * desktop-only snapshot. No network request belongs here; PR-B supplies the
+ * existing Device Link REST adapter.
+ */
+export function buildSchedulerDesktopDeviceSnapshot(
+ devices: readonly Pick<DeviceView, 'deviceId' | 'platform' | 'online' | 'isSelf'>[],
+ observedAt = Date.now(),
+): SchedulerDesktopDeviceSnapshot | null {
+ const self = devices.find(
+ (device) => device.isSelf && device.online && isDesktopSchedulerPlatform(device.platform),
+ );
+ if (!self) return null;
+
+ return {
+ selfDeviceId: self.deviceId,
+ peers: devices
+ .flatMap((device) => {
+ if (device.isSelf || !device.online || !isDesktopSchedulerPlatform(device.platform))
+ return [];
+ return [{ deviceId: device.deviceId, platform: device.platform }];
+ })
+ .sort((left, right) => compareSchedulerStrings(left.deviceId, right.deviceId)),
+ observedAt,
+ };
+}
diff --git a/apps/desktop/src/main/im/scheduler/manager.ts b/apps/desktop/src/main/im/scheduler/manager.ts
new file mode 100644
index 0000000000..a4c6b0452b
--- /dev/null
+++ b/apps/desktop/src/main/im/scheduler/manager.ts
@@ -0,0 +1,696 @@
+/** Dormant, provider-free coordinator. Discord Gateway wiring belongs to PR-B. */
+
+import { randomUUID } from 'node:crypto';
+
+import {
+ isImSchedulerFrame,
+ type ImSchedulerFrame,
+ type SchedulerAdvertisementFrame,
+ type SchedulerChannelBinding,
+ type SchedulerRuntimeFrame,
+} from '@cindy/device-link';
+import { RuntimeGapSet } from './runtimeGaps';
+import {
+ isDesktopSchedulerPlatform,
+ selectIngressDevice,
+ type SchedulerChannelIdentity,
+ type SchedulerDevice,
+} from './state';
+import type { SchedulerDesktopDeviceSnapshot } from './deviceSnapshot';
+import type { SchedulerTransport, SchedulerTransportEvent } from './transport';
+
+const DEFAULT_DISCOVERY_RETRY_DELAY_MS = 1_000;
+const DEFAULT_DISCOVERY_RETRY_LIMIT = 3;
+const DEFAULT_SNAPSHOT_RESPONSE_TIMEOUT_MS = 5_000;
+
+export type SchedulerDecision =
+ | { state: 'active'; channel: SchedulerChannelIdentity; reason: 'elected' }
+ | { state: 'standby'; channel: SchedulerChannelIdentity | null; reason: SchedulerStandbyReason };
+
+export type SchedulerStandbyReason =
+ | 'stopped'
+ | 'relay-offline'
+ | 'not-owner'
+ | 'missing-binding'
+ | 'missing-snapshot'
+ | 'incomplete-peer-view'
+ | 'peer-won';
+
+interface PeerAdvertisement {
+ sentAt: number;
+ frame: SchedulerAdvertisementFrame;
+}
+
+function sameSchedulerChannels(
+ left: readonly SchedulerChannelBinding[],
+ right: readonly SchedulerChannelBinding[],
+): boolean {
+ return (
+ left.length === right.length &&
+ left.every(
+ (channel, index) =>
+ channel.channel === right[index]?.channel &&
+ channel.identity === right[index]?.identity &&
+ channel.bindingGeneration === right[index]?.bindingGeneration,
+ )
+ );
+}
+
+export interface ImSchedulerManagerOptions {
+ transport: SchedulerTransport;
+ getLocalChannel: () => SchedulerChannelIdentity | null;
+ onDecision?: (decision: SchedulerDecision) => void;
+ nonceFactory?: () => string;
+ bindingGenerationFactory?: () => string;
+ discoveryRetryDelayMs?: number;
+ snapshotResponseTimeoutMs?: number;
+ maxDiscoveryRetries?: number;
+}
+
+/**
+ * The manager owns only election state. It never starts, stops, or inspects a
+ * provider client, so creating this object cannot change existing IM behavior.
+ */
+export class ImSchedulerManager {
+ private readonly transport: SchedulerTransport;
+ private readonly getLocalChannel: () => SchedulerChannelIdentity | null;
+ private readonly onDecision?: (decision: SchedulerDecision) => void;
+ private readonly nonceFactory: () => string;
+ private readonly bindingGenerationFactory: () => string;
+ private readonly discoveryRetryDelayMs: number;
+ private readonly snapshotResponseTimeoutMs: number;
+ private readonly maxDiscoveryRetries: number;
+ private readonly peers = new Map<string, PeerAdvertisement>();
+ private readonly confirmedPeers = new Set<string>();
+ private readonly pendingPeerProbeChannels = new Map<string, readonly SchedulerChannelBinding[]>();
+ private readonly ignoredPeerProbeNonces = new Map<string, Set<string>>();
+ private readonly runtimeGaps = new RuntimeGapSet();
+ private unsubscribe: (() => void) | null = null;
+ private snapshot: SchedulerDesktopDeviceSnapshot | null = null;
+ private lastSnapshotObservedAt: number | null = null;
+ private snapshotAccountGeneration = '';
+ private snapshotRequestId: string | null = null;
+ private awaitingSnapshot = false;
+ private requiresTaggedSnapshot = false;
+ private snapshotRefreshPending = false;
+ private lastLocalIdentity: string | null = null;
+ private localBindingGeneration = '';
+ private discoveryNonce = '';
+ private discoveryRetryAttempt = 0;
+ private discoveryRetryTimer: ReturnType<typeof setTimeout> | null = null;
+ private started = false;
+ private decision: SchedulerDecision = { state: 'standby', channel: null, reason: 'stopped' };
+
+ constructor(options: ImSchedulerManagerOptions) {
+ this.transport = options.transport;
+ this.getLocalChannel = options.getLocalChannel;
+ this.onDecision = options.onDecision;
+ this.nonceFactory = options.nonceFactory ?? (() => randomUUID().replaceAll('-', ''));
+ this.bindingGenerationFactory =
+ options.bindingGenerationFactory ?? (() => randomUUID().replaceAll('-', ''));
+ this.discoveryRetryDelayMs = Math.max(
+ 1,
+ Math.floor(options.discoveryRetryDelayMs ?? DEFAULT_DISCOVERY_RETRY_DELAY_MS),
+ );
+ this.snapshotResponseTimeoutMs = Math.max(
+ 1,
+ Math.floor(options.snapshotResponseTimeoutMs ?? DEFAULT_SNAPSHOT_RESPONSE_TIMEOUT_MS),
+ );
+ this.maxDiscoveryRetries = Math.max(
+ 1,
+ Math.floor(options.maxDiscoveryRetries ?? DEFAULT_DISCOVERY_RETRY_LIMIT),
+ );
+ }
+
+ start(): void {
+ if (this.started) return;
+ this.started = true;
+ this.resetSnapshotRequestState();
+ this.requiresTaggedSnapshot = false;
+ this.snapshotAccountGeneration = this.nonceFactory();
+ this.localBindingGeneration = this.bindingGenerationFactory();
+ this.lastLocalIdentity = this.getLocalChannel()?.identity ?? null;
+ this.unsubscribe = this.transport.subscribe((event) => this.handleEvent(event));
+ this.beginDiscoveryRound();
+ this.reconcile();
+ }
+
+ stop(): void {
+ if (!this.started) return;
+ this.started = false;
+ this.cancelDiscoveryRetry();
+ this.unsubscribe?.();
+ this.unsubscribe = null;
+ this.runtimeGaps.clear();
+ this.clearPeerDiscoveryState();
+ this.snapshot = null;
+ this.lastSnapshotObservedAt = null;
+ this.resetSnapshotRequestState();
+ this.requiresTaggedSnapshot = false;
+ this.snapshotAccountGeneration = '';
+ this.lastLocalIdentity = null;
+ this.localBindingGeneration = '';
+ this.publishDecision({ state: 'standby', channel: null, reason: 'stopped' });
+ }
+
+ /** Start a new round after a binding change while retaining the account view. */
+ resetBindingDiscovery(): void {
+ this.resetDiscovery('binding');
+ }
+
+ /** Start a new account-scoped round and discard the previous account state. */
+ resetAccountDiscovery(): void {
+ this.resetDiscovery('account');
+ }
+
+ resetDiscovery(scope: 'binding' | 'account' = 'binding'): void {
+ if (!this.started) return;
+ this.cancelDiscoveryRetry();
+ if (scope === 'account') {
+ this.snapshot = null;
+ this.lastSnapshotObservedAt = null;
+ this.snapshotAccountGeneration = this.nonceFactory();
+ this.resetSnapshotRequestState();
+ this.requiresTaggedSnapshot = true;
+ const currentIdentity = this.getLocalChannel()?.identity ?? null;
+ this.lastLocalIdentity = currentIdentity;
+ this.localBindingGeneration = this.bindingGenerationFactory();
+ this.runtimeGaps.clear();
+ this.clearPeerDiscoveryState();
+ } else {
+ const currentIdentity = this.getLocalChannel()?.identity ?? null;
+ if (this.lastLocalIdentity) this.runtimeGaps.clearIdentity(this.lastLocalIdentity);
+ if (currentIdentity) this.runtimeGaps.clearIdentity(currentIdentity);
+ this.localBindingGeneration = this.bindingGenerationFactory();
+ this.lastLocalIdentity = currentIdentity;
+ }
+ this.beginDiscoveryRound();
+ if (scope === 'account') this.requestSnapshot(false);
+ this.reconcile();
+ }
+
+ getDecision(): SchedulerDecision {
+ return this.decision;
+ }
+
+ getRuntimeGaps(): RuntimeGapSet {
+ return this.runtimeGaps;
+ }
+
+ private handleEvent(event: SchedulerTransportEvent): void {
+ if (!this.started) return;
+ switch (event.type) {
+ case 'relay-status':
+ if (event.status === 'offline') {
+ this.cancelDiscoveryRetry();
+ this.snapshot = null;
+ this.lastSnapshotObservedAt = null;
+ this.resetSnapshotRequestState();
+ this.requiresTaggedSnapshot = true;
+ this.clearPeerDiscoveryState();
+ } else {
+ this.invalidateAuthoritativeSnapshot();
+ this.beginDiscoveryRound();
+ this.requestSnapshot(false);
+ }
+ this.reconcile();
+ return;
+ case 'ownership':
+ if (event.owner) {
+ // Ownership may have been absent long enough for the Device Link
+ // membership view to change. Never elect from a snapshot collected
+ // before that gap; require a tagged refresh for the current request
+ // generation before discovery can complete again.
+ this.invalidateAuthoritativeSnapshot();
+ this.beginDiscoveryRound();
+ this.requestSnapshot(false);
+ } else {
+ this.cancelDiscoveryRetry();
+ }
+ this.reconcile();
+ return;
+ case 'snapshot': {
+ if (
+ this.requiresTaggedSnapshot &&
+ (event.accountGeneration === undefined || event.requestId === undefined)
+ ) {
+ return;
+ }
+ if (
+ event.accountGeneration !== undefined &&
+ event.accountGeneration !== this.snapshotAccountGeneration
+ ) {
+ return;
+ }
+ const pendingRequestId = this.snapshotRequestId;
+ if (event.requestId !== undefined && event.requestId !== pendingRequestId) return;
+ if (this.awaitingSnapshot && event.requestId === undefined) return;
+ const isCurrentRequest =
+ event.requestId !== undefined && event.requestId === pendingRequestId;
+ if (isCurrentRequest && event.accountGeneration === this.snapshotAccountGeneration) {
+ this.requiresTaggedSnapshot = true;
+ }
+ const preserveRetryAttempt = this.snapshotRefreshPending;
+ this.resetSnapshotRequestState();
+ if (event.snapshot === null) {
+ // A null authoritative snapshot means the transport can no longer
+ // prove that this Desktop is present. Retaining the previous view
+ // would allow a stale self row to keep the ingress active.
+ this.snapshot = null;
+ this.lastSnapshotObservedAt = null;
+ this.requiresTaggedSnapshot = true;
+ this.clearPeerDiscoveryState();
+ this.beginDiscoveryRound();
+ this.reconcile();
+ return;
+ }
+ if (
+ !isCurrentRequest &&
+ this.lastSnapshotObservedAt !== null &&
+ event.snapshot.observedAt < this.lastSnapshotObservedAt
+ ) {
+ // A clock rollback or delayed response must not revive an older
+ // account view after a newer snapshot has already been accepted.
+ this.reconcile();
+ return;
+ }
+ this.prunePeerDiscoveryState(event.snapshot.peers.map((peer) => peer.deviceId));
+ this.snapshot = event.snapshot;
+ this.lastSnapshotObservedAt = event.snapshot.observedAt;
+ // Once a lifecycle freshness boundary has been crossed, keep the
+ // tagged-response gate latched for the rest of this manager lifetime.
+ // An older untagged request may still complete after this response.
+ this.beginDiscoveryRound({ resetRetryAttempt: !preserveRetryAttempt });
+ this.reconcile();
+ return;
+ }
+ case 'peer-presence':
+ if (!isDesktopSchedulerPlatform(event.platform)) return;
+ // Incremental presence is a signal to fetch a new full snapshot, not
+ // an authoritative replacement for the existing membership view.
+ this.cancelDiscoveryRetry();
+ this.snapshot = null;
+ this.lastSnapshotObservedAt = null;
+ this.resetSnapshotRequestState();
+ this.requiresTaggedSnapshot = true;
+ if (!event.online) {
+ this.clearPeerDiscoveryState(event.deviceId);
+ } else {
+ this.beginDiscoveryRound();
+ }
+ this.requestSnapshot(false);
+ this.reconcile();
+ return;
+ case 'push':
+ this.handlePush(event.sourceDeviceId, event.payload);
+ }
+ }
+
+ private handlePush(sourceDeviceId: string, payload: unknown): void {
+ if (!isImSchedulerFrame(payload) || !this.isAuthoritativePeer(sourceDeviceId)) return;
+ if (payload.kind === 'probe') {
+ this.observePeerProbe(sourceDeviceId, payload);
+ this.sendAdvertisement(sourceDeviceId, payload.nonce);
+ this.reconcile();
+ return;
+ }
+ if (payload.inReplyTo !== this.discoveryNonce) return;
+ const pendingProbeChannels = this.pendingPeerProbeChannels.get(sourceDeviceId);
+ if (pendingProbeChannels && !sameSchedulerChannels(pendingProbeChannels, payload.channels)) {
+ // A probe and an advertisement can cross in flight. Do not let the
+ // advertisement complete the old round; start a fresh nonce so the
+ // peer must confirm its current binding again.
+ this.beginDiscoveryRound();
+ this.reconcile();
+ return;
+ }
+ if (this.confirmedPeers.has(sourceDeviceId)) {
+ const confirmedChannels = this.peers.get(sourceDeviceId)?.frame.channels ?? [];
+ if (!sameSchedulerChannels(confirmedChannels, payload.channels)) {
+ // Retries reuse a nonce, so differently bound advertisements for that
+ // nonce have no trustworthy ordering. Keep neither and require the
+ // peer to confirm its current binding in a fresh round.
+ this.beginDiscoveryRound();
+ this.reconcile();
+ return;
+ }
+ }
+ this.confirmedPeers.add(sourceDeviceId);
+ this.peers.set(sourceDeviceId, { sentAt: payload.sentAt, frame: payload });
+ this.pendingPeerProbeChannels.delete(sourceDeviceId);
+ for (const runtime of [payload.runtime, ...(payload.runtimeGaps ?? [])]) {
+ if (!runtime || !this.isRuntimeForLocalBinding(runtime)) continue;
+ if (runtime.state === 'dirty') this.runtimeGaps.adopt(runtime);
+ if (runtime.state === 'clean') this.runtimeGaps.resolve(runtime);
+ }
+ if (this.isDiscoveryComplete()) this.cancelDiscoveryRetry();
+ this.reconcile();
+ }
+
+ private isAuthoritativePeer(deviceId: string): boolean {
+ return this.snapshot?.peers.some((peer) => peer.deviceId === deviceId) === true;
+ }
+
+ private adoptRuntimeGap(runtime: SchedulerRuntimeFrame): void {
+ // Runtime frames are scoped to this Desktop's current binding lifecycle,
+ // not merely to the Discord application id. This is the durable barrier:
+ // an old peer frame cannot return after a reset, even if no tombstone for
+ // that opaque runtime generation was ever retained locally.
+ if (!this.isRuntimeForLocalBinding(runtime)) return;
+ this.runtimeGaps.adopt(runtime);
+ }
+
+ private isRuntimeForLocalBinding(runtime: SchedulerRuntimeFrame): boolean {
+ const localBinding = this.getLocalBinding();
+ return Boolean(
+ localBinding &&
+ runtime.identity === localBinding.identity &&
+ runtime.bindingGeneration === localBinding.bindingGeneration,
+ );
+ }
+
+ private observePeerProbe(
+ sourceDeviceId: string,
+ payload: Extract<ImSchedulerFrame, { kind: 'probe' }>,
+ ): void {
+ if (this.isIgnoredPeerProbeNonce(sourceDeviceId, payload.nonce)) return;
+
+ // A confirmed advertisement is authoritative for the current discovery
+ // round. A later probe with a different binding is only an invalidation
+ // signal: start a new nonce and wait for a fresh advertisement instead of
+ // using the probe itself as an election view. This also handles a real
+ // binding change without trusting remote wall-clock ordering.
+ if (this.confirmedPeers.has(sourceDeviceId)) {
+ const confirmed = this.peers.get(sourceDeviceId)?.frame.channels ?? [];
+ if (sameSchedulerChannels(confirmed, payload.channels)) return;
+ this.ignorePeerProbeNonce(sourceDeviceId, payload.nonce);
+ this.beginDiscoveryRound();
+ return;
+ }
+ const pending = this.pendingPeerProbeChannels.get(sourceDeviceId);
+ if (pending && !sameSchedulerChannels(pending, payload.channels)) {
+ // Probes from the same peer can cross in flight. Treat a contradictory
+ // probe as stale/ambiguous, rotate our nonce, and let the next round's
+ // advertisement establish the peer view. Do not overwrite the pending
+ // binding with whichever probe happened to arrive last.
+ this.ignorePeerProbeNonce(sourceDeviceId, payload.nonce);
+ this.beginDiscoveryRound();
+ return;
+ }
+ this.pendingPeerProbeChannels.set(sourceDeviceId, [...payload.channels]);
+ this.peers.set(sourceDeviceId, {
+ sentAt: payload.sentAt,
+ frame: {
+ kind: 'advertisement',
+ sentAt: payload.sentAt,
+ channels: payload.channels,
+ ...(payload.runtime ? { runtime: payload.runtime } : {}),
+ ...(payload.runtimeGaps ? { runtimeGaps: payload.runtimeGaps } : {}),
+ },
+ });
+ // A probe can be delayed across a binding reset and carries no response
+ // tag for the receiver's current discovery round. Its channel view is
+ // useful for election convergence, but runtime gaps are only authoritative
+ // when returned in an advertisement replying to our current nonce.
+ }
+
+ private ignorePeerProbeNonce(sourceDeviceId: string, nonce: string): void {
+ const nonces = this.ignoredPeerProbeNonces.get(sourceDeviceId) ?? new Set<string>();
+ nonces.add(nonce);
+ // Keep this defensive cache bounded per visible peer. It only suppresses
+ // duplicate stale probes; the next local discovery round still performs
+ // a fresh authoritative advertisement exchange.
+ while (nonces.size > 8) nonces.delete(nonces.values().next().value!);
+ this.ignoredPeerProbeNonces.set(sourceDeviceId, nonces);
+ }
+
+ private isIgnoredPeerProbeNonce(sourceDeviceId: string, nonce: string): boolean {
+ return this.ignoredPeerProbeNonces.get(sourceDeviceId)?.has(nonce) === true;
+ }
+
+ private beginDiscoveryRound(options: { resetRetryAttempt?: boolean } = {}): void {
+ this.cancelDiscoveryRetry(false);
+ if (options.resetRetryAttempt !== false) this.discoveryRetryAttempt = 0;
+ this.discoveryNonce = this.nonceFactory();
+ this.peers.clear();
+ this.confirmedPeers.clear();
+ this.pendingPeerProbeChannels.clear();
+ this.publishProbeToVisiblePeers();
+ this.scheduleDiscoveryRetry();
+ }
+
+ private publishProbeToVisiblePeers(): void {
+ const channel = this.getLocalBinding();
+ for (const peer of this.snapshot?.peers ?? []) {
+ this.sendPushSafely(peer.deviceId, {
+ kind: 'probe',
+ sentAt: Date.now(),
+ nonce: this.discoveryNonce,
+ channels: channel ? [channel] : [],
+ });
+ }
+ }
+
+ private isDiscoveryComplete(): boolean {
+ return (
+ this.snapshot !== null &&
+ this.snapshot.selfDeviceId === this.transport.selfDeviceId &&
+ this.snapshot.peers.every((peer) => this.confirmedPeers.has(peer.deviceId))
+ );
+ }
+
+ private scheduleDiscoveryRetry(): void {
+ if (
+ this.discoveryRetryTimer ||
+ !this.started ||
+ this.transport.getStatus() !== 'online' ||
+ !this.transport.isOwner() ||
+ this.isDiscoveryComplete() ||
+ this.discoveryRetryAttempt >= this.maxDiscoveryRetries
+ )
+ return;
+
+ const nonce = this.discoveryNonce;
+ this.discoveryRetryTimer = setTimeout(() => {
+ this.discoveryRetryTimer = null;
+ if (!this.started || nonce !== this.discoveryNonce || this.isDiscoveryComplete()) return;
+ this.discoveryRetryAttempt += 1;
+ const roundNonce = this.discoveryNonce;
+ const requestId = this.requestSnapshot(true);
+ if (!this.started) return;
+ if (roundNonce !== this.discoveryNonce) {
+ if (!this.isDiscoveryComplete() && this.discoveryRetryAttempt >= this.maxDiscoveryRetries) {
+ this.discoveryRetryAttempt = 0;
+ this.scheduleDiscoveryRetry();
+ }
+ this.reconcile();
+ return;
+ }
+ this.publishProbeToVisiblePeers();
+ if (this.discoveryRetryAttempt >= this.maxDiscoveryRetries) {
+ // Wait for the final refresh response before opening another round.
+ // A bounded timeout below keeps a lost response from blocking recovery.
+ this.snapshotRefreshPending = false;
+ if (this.awaitingSnapshot && this.snapshotRequestId === requestId) {
+ this.scheduleFinalSnapshotTimeout(roundNonce, requestId);
+ } else {
+ this.resetSnapshotRequestState();
+ this.beginDiscoveryRound();
+ }
+ } else {
+ this.scheduleDiscoveryRetry();
+ }
+ this.reconcile();
+ }, this.discoveryRetryDelayMs);
+ this.discoveryRetryTimer.unref?.();
+ }
+
+ private cancelDiscoveryRetry(resetRetryAttempt = true): void {
+ if (this.discoveryRetryTimer) clearTimeout(this.discoveryRetryTimer);
+ this.discoveryRetryTimer = null;
+ if (resetRetryAttempt) this.discoveryRetryAttempt = 0;
+ }
+
+ private requestSnapshot(preserveRetryAttempt: boolean): string {
+ const accountGeneration = this.snapshotAccountGeneration;
+ const requestId = this.nonceFactory();
+ this.snapshotRequestId = requestId;
+ this.awaitingSnapshot = true;
+ this.snapshotRefreshPending = preserveRetryAttempt;
+ try {
+ const result = this.transport.requestSnapshot(accountGeneration, requestId);
+ void Promise.resolve(result).catch(() => {
+ this.handleSnapshotRequestFailure(accountGeneration, requestId);
+ });
+ } catch {
+ this.handleSnapshotRequestFailure(accountGeneration, requestId);
+ }
+ return requestId;
+ }
+
+ private handleSnapshotRequestFailure(accountGeneration: string, requestId: string): void {
+ if (
+ !this.started ||
+ accountGeneration !== this.snapshotAccountGeneration ||
+ requestId !== this.snapshotRequestId ||
+ !this.awaitingSnapshot
+ ) {
+ return;
+ }
+ const retryExhausted = this.discoveryRetryAttempt >= this.maxDiscoveryRetries;
+ this.resetSnapshotRequestState();
+ this.requiresTaggedSnapshot = true;
+ if (retryExhausted) this.beginDiscoveryRound();
+ this.reconcile();
+ }
+
+ private scheduleFinalSnapshotTimeout(roundNonce: string, requestId: string): void {
+ if (this.discoveryRetryTimer) clearTimeout(this.discoveryRetryTimer);
+ this.discoveryRetryTimer = setTimeout(() => {
+ this.discoveryRetryTimer = null;
+ if (
+ !this.started ||
+ roundNonce !== this.discoveryNonce ||
+ requestId !== this.snapshotRequestId ||
+ !this.awaitingSnapshot
+ ) {
+ return;
+ }
+ this.resetSnapshotRequestState();
+ this.beginDiscoveryRound();
+ this.reconcile();
+ }, this.snapshotResponseTimeoutMs);
+ this.discoveryRetryTimer.unref?.();
+ }
+
+ private resetSnapshotRequestState(): void {
+ this.snapshotRequestId = null;
+ this.awaitingSnapshot = false;
+ this.snapshotRefreshPending = false;
+ }
+
+ private clearPeerDiscoveryState(deviceId?: string): void {
+ if (deviceId !== undefined) {
+ this.peers.delete(deviceId);
+ this.confirmedPeers.delete(deviceId);
+ this.pendingPeerProbeChannels.delete(deviceId);
+ this.ignoredPeerProbeNonces.delete(deviceId);
+ return;
+ }
+ this.peers.clear();
+ this.confirmedPeers.clear();
+ this.pendingPeerProbeChannels.clear();
+ this.ignoredPeerProbeNonces.clear();
+ }
+
+ private prunePeerDiscoveryState(visiblePeerIds: readonly string[]): void {
+ const visiblePeers = new Set(visiblePeerIds);
+ for (const deviceId of this.pendingPeerProbeChannels.keys()) {
+ if (!visiblePeers.has(deviceId)) this.pendingPeerProbeChannels.delete(deviceId);
+ }
+ for (const deviceId of this.ignoredPeerProbeNonces.keys()) {
+ if (!visiblePeers.has(deviceId)) this.ignoredPeerProbeNonces.delete(deviceId);
+ }
+ }
+
+ private invalidateAuthoritativeSnapshot(): void {
+ this.cancelDiscoveryRetry();
+ this.snapshot = null;
+ this.lastSnapshotObservedAt = null;
+ this.resetSnapshotRequestState();
+ this.requiresTaggedSnapshot = true;
+ this.clearPeerDiscoveryState();
+ }
+
+ private sendAdvertisement(peerDeviceId: string, inReplyTo?: string): void {
+ const channel = this.getLocalBinding();
+ this.sendPushSafely(peerDeviceId, {
+ kind: 'advertisement',
+ sentAt: Date.now(),
+ channels: channel ? [channel] : [],
+ ...(inReplyTo ? { inReplyTo } : {}),
+ });
+ }
+
+ private sendPushSafely(peerDeviceId: string, payload: ImSchedulerFrame): void {
+ try {
+ this.transport.sendPush(peerDeviceId, payload);
+ } catch {
+ // A single peer's queue/relay failure must not abort the rest of the
+ // discovery round. The bounded retry timer remains the recovery path.
+ }
+ }
+
+ private getLocalBinding(): SchedulerChannelBinding | null {
+ const channel = this.getLocalChannel();
+ return channel && this.localBindingGeneration
+ ? { ...channel, bindingGeneration: this.localBindingGeneration }
+ : null;
+ }
+
+ private reconcile(): void {
+ const channel = this.getLocalChannel();
+ if (!this.started) return;
+ if (this.transport.getStatus() !== 'online') {
+ this.cancelDiscoveryRetry();
+ this.publishDecision({ state: 'standby', channel, reason: 'relay-offline' });
+ return;
+ }
+ if (!this.transport.isOwner()) {
+ this.cancelDiscoveryRetry();
+ this.publishDecision({ state: 'standby', channel, reason: 'not-owner' });
+ return;
+ }
+ if (!channel) {
+ this.scheduleDiscoveryRetry();
+ this.publishDecision({ state: 'standby', channel: null, reason: 'missing-binding' });
+ return;
+ }
+ if (!this.snapshot || this.snapshot.selfDeviceId !== this.transport.selfDeviceId) {
+ this.scheduleDiscoveryRetry();
+ this.publishDecision({ state: 'standby', channel, reason: 'missing-snapshot' });
+ return;
+ }
+ if (this.snapshot.peers.some((peer) => !this.confirmedPeers.has(peer.deviceId))) {
+ this.scheduleDiscoveryRetry();
+ this.publishDecision({ state: 'standby', channel, reason: 'incomplete-peer-view' });
+ return;
+ }
+
+ this.cancelDiscoveryRetry();
+
+ const devices: SchedulerDevice[] = [
+ {
+ deviceId: this.transport.selfDeviceId,
+ online: true,
+ platform: this.transport.platform,
+ channels: [channel],
+ lastSeenAt: this.snapshot.observedAt,
+ },
+ ...this.snapshot.peers.map((peer) => ({
+ deviceId: peer.deviceId,
+ online: true,
+ platform: peer.platform,
+ channels: this.peers.get(peer.deviceId)?.frame.channels ?? [],
+ lastSeenAt: this.peers.get(peer.deviceId)?.sentAt ?? 0,
+ })),
+ ];
+ const winner = selectIngressDevice('discord', channel.identity, devices);
+ this.publishDecision(
+ winner === this.transport.selfDeviceId
+ ? { state: 'active', channel, reason: 'elected' }
+ : { state: 'standby', channel, reason: 'peer-won' },
+ );
+ }
+
+ private publishDecision(decision: SchedulerDecision): void {
+ if (
+ this.decision.state === decision.state &&
+ this.decision.reason === decision.reason &&
+ this.decision.channel?.identity === decision.channel?.identity
+ )
+ return;
+ this.decision = decision;
+ this.onDecision?.(decision);
+ }
+}
diff --git a/apps/desktop/src/main/im/scheduler/runtimeGaps.ts b/apps/desktop/src/main/im/scheduler/runtimeGaps.ts
new file mode 100644
index 0000000000..11420d8fe5
--- /dev/null
+++ b/apps/desktop/src/main/im/scheduler/runtimeGaps.ts
@@ -0,0 +1,153 @@
+import { MAX_RUNTIME_GAPS, type SchedulerRuntimeFrame } from '@cindy/device-link';
+import { compareSchedulerStrings } from './state';
+
+const MAX_RESOLVED_RUNTIME_GENERATIONS = MAX_RUNTIME_GAPS * 4;
+const MAX_SATURATED_RUNTIME_BINDINGS = MAX_RUNTIME_GAPS * 4;
+
+/**
+ * Bounded, deterministic runtime-gap state. This is deliberately a data
+ * structure only; Discord offline notices and Gateway lifecycle stay in PR-B.
+ */
+export class RuntimeGapSet {
+ private readonly gaps = new Map<string, SchedulerRuntimeFrame>();
+ private readonly resolved = new Map<
+ string,
+ Pick<SchedulerRuntimeFrame, 'identity' | 'bindingGeneration' | 'generation'>
+ >();
+ private readonly saturatedBindings = new Map<
+ string,
+ Pick<SchedulerRuntimeFrame, 'identity' | 'bindingGeneration'>
+ >();
+
+ private static key(
+ runtime: Pick<SchedulerRuntimeFrame, 'identity' | 'bindingGeneration' | 'generation'>,
+ ): string {
+ return `${runtime.identity}\u0000${runtime.bindingGeneration}\u0000${runtime.generation}`;
+ }
+
+ private static bindingKey(
+ runtime: Pick<SchedulerRuntimeFrame, 'identity' | 'bindingGeneration'>,
+ ): string {
+ return `${runtime.identity}\u0000${runtime.bindingGeneration}`;
+ }
+
+ adopt(runtime: SchedulerRuntimeFrame): boolean {
+ if (runtime.state !== 'dirty') return false;
+ const key = RuntimeGapSet.key(runtime);
+ if (
+ this.saturatedBindings.has(RuntimeGapSet.bindingKey(runtime)) ||
+ this.resolved.has(key) ||
+ this.gaps.has(key)
+ )
+ return false;
+ this.gaps.set(key, { ...runtime, state: 'dirty' });
+ this.trim();
+ return this.gaps.has(key);
+ }
+
+ resolve(
+ runtime: Pick<SchedulerRuntimeFrame, 'identity' | 'bindingGeneration' | 'generation'>,
+ ): boolean {
+ const key = RuntimeGapSet.key(runtime);
+ const bindingKey = RuntimeGapSet.bindingKey(runtime);
+ const changed =
+ this.gaps.has(key) ||
+ (!this.resolved.has(key) && !this.saturatedBindings.has(bindingKey));
+ this.gaps.delete(key);
+ if (this.saturatedBindings.has(bindingKey)) return changed;
+ this.resolved.set(key, {
+ identity: runtime.identity,
+ bindingGeneration: runtime.bindingGeneration,
+ generation: runtime.generation,
+ });
+ this.trimResolved(runtime);
+ return changed;
+ }
+
+ get(identity: string): SchedulerRuntimeFrame | undefined {
+ const runtime = this.values().find((candidate) => candidate.identity === identity);
+ return runtime ? { ...runtime } : undefined;
+ }
+
+ values(): SchedulerRuntimeFrame[] {
+ return [...this.gaps.values()]
+ .sort(
+ (left, right) =>
+ compareSchedulerStrings(left.identity, right.identity) ||
+ compareSchedulerStrings(left.bindingGeneration, right.bindingGeneration) ||
+ compareSchedulerStrings(left.generation, right.generation),
+ )
+ .map((runtime) => ({ ...runtime }));
+ }
+
+ get size(): number {
+ return this.gaps.size;
+ }
+
+ clear(): void {
+ this.gaps.clear();
+ this.resolved.clear();
+ this.saturatedBindings.clear();
+ }
+
+ clearIdentity(identity: string): boolean {
+ let changed = false;
+ for (const [key, runtime] of this.gaps) {
+ if (runtime.identity !== identity) continue;
+ this.gaps.delete(key);
+ changed = true;
+ }
+ for (const [key, runtime] of this.resolved) {
+ if (runtime.identity !== identity) continue;
+ this.resolved.delete(key);
+ changed = true;
+ }
+ for (const [key, binding] of this.saturatedBindings) {
+ if (binding.identity !== identity) continue;
+ this.saturatedBindings.delete(key);
+ changed = true;
+ }
+ return changed;
+ }
+
+ private trim(): void {
+ const retained = this.values().slice(0, MAX_RUNTIME_GAPS);
+ this.gaps.clear();
+ for (const runtime of retained) this.gaps.set(RuntimeGapSet.key(runtime), runtime);
+ }
+
+ private trimResolved(
+ newest: Pick<SchedulerRuntimeFrame, 'identity' | 'bindingGeneration'>,
+ ): void {
+ if (this.resolved.size <= MAX_RESOLVED_RUNTIME_GENERATIONS) return;
+
+ // Runtime generations are opaque random values, so evicting one exact
+ // tombstone would make a delayed dirty frame indistinguishable from new
+ // work. Collapse the overflowing current binding into one fail-closed
+ // barrier instead. A binding reset clears that barrier and starts a fresh
+ // lifecycle, while both collections remain bounded.
+ this.saturateBinding(newest);
+ while (this.resolved.size > MAX_RESOLVED_RUNTIME_GENERATIONS) {
+ const oldest = this.resolved.values().next().value;
+ if (!oldest) break;
+ this.saturateBinding(oldest);
+ }
+ }
+
+ private saturateBinding(
+ binding: Pick<SchedulerRuntimeFrame, 'identity' | 'bindingGeneration'>,
+ ): void {
+ const bindingKey = RuntimeGapSet.bindingKey(binding);
+ this.saturatedBindings.set(bindingKey, {
+ identity: binding.identity,
+ bindingGeneration: binding.bindingGeneration,
+ });
+ for (const [key, runtime] of this.resolved) {
+ if (RuntimeGapSet.bindingKey(runtime) === bindingKey) this.resolved.delete(key);
+ }
+
+ if (this.saturatedBindings.size <= MAX_SATURATED_RUNTIME_BINDINGS) return;
+ const oldestBinding = this.saturatedBindings.keys().next().value;
+ if (oldestBinding) this.saturatedBindings.delete(oldestBinding);
+ }
+}
diff --git a/apps/desktop/src/main/im/scheduler/state.ts b/apps/desktop/src/main/im/scheduler/state.ts
new file mode 100644
index 0000000000..8b0c73b7d9
--- /dev/null
+++ b/apps/desktop/src/main/im/scheduler/state.ts
@@ -0,0 +1,53 @@
+/** Pure state and deterministic election rules for the dormant Discord ingress scheduler. */
+
+import type { SchedulerChannelIdentity } from '@cindy/device-link';
+
+export type { SchedulerChannelIdentity } from '@cindy/device-link';
+
+export type SchedulerPlatform = 'darwin' | 'linux' | 'win32';
+
+export interface SchedulerDevice {
+ deviceId: string;
+ online: boolean;
+ platform: string;
+ channels: readonly SchedulerChannelIdentity[];
+ lastSeenAt: number;
+}
+
+const DESKTOP_PLATFORMS = new Set<SchedulerPlatform>(['darwin', 'linux', 'win32']);
+
+/** Locale-independent ordering for values that participate in election state. */
+export function compareSchedulerStrings(left: string, right: string): number {
+ if (left === right) return 0;
+ return left < right ? -1 : 1;
+}
+
+export function isDesktopSchedulerPlatform(
+ platform: string | null | undefined,
+): platform is SchedulerPlatform {
+ return typeof platform === 'string' && DESKTOP_PLATFORMS.has(platform as SchedulerPlatform);
+}
+
+/**
+ * Pick exactly one ingress owner. Device ids are the only tie-breaker: time,
+ * process ordering, and random values must not affect the result.
+ */
+export function selectIngressDevice(
+ channel: 'discord',
+ identity: string,
+ devices: readonly SchedulerDevice[],
+): string | null {
+ return (
+ devices
+ .filter(
+ (device) =>
+ device.online &&
+ isDesktopSchedulerPlatform(device.platform) &&
+ device.channels.some(
+ (configured) => configured.channel === channel && configured.identity === identity,
+ ),
+ )
+ .map((device) => device.deviceId)
+ .sort(compareSchedulerStrings)[0] ?? null
+ );
+}
diff --git a/apps/desktop/src/main/im/scheduler/transport.ts b/apps/desktop/src/main/im/scheduler/transport.ts
new file mode 100644
index 0000000000..c1f1999a9a
--- /dev/null
+++ b/apps/desktop/src/main/im/scheduler/transport.ts
@@ -0,0 +1,32 @@
+import type { SchedulerDesktopDeviceSnapshot } from './deviceSnapshot';
+import type { ImSchedulerFrame } from '@cindy/device-link';
+
+export type SchedulerRelayStatus = 'online' | 'offline';
+
+export type SchedulerTransportEvent =
+ | { type: 'relay-status'; status: SchedulerRelayStatus }
+ | { type: 'ownership'; owner: boolean }
+ /** null invalidates the previously accepted authoritative view. */
+ | {
+ type: 'snapshot';
+ snapshot: SchedulerDesktopDeviceSnapshot | null;
+ accountGeneration?: string;
+ requestId?: string;
+ }
+ | { type: 'peer-presence'; deviceId: string; platform: string; online: boolean }
+ | { type: 'push'; sourceDeviceId: string; payload: unknown };
+
+/**
+ * Device Link adapter boundary. PR-A only defines this contract; PR-B is the
+ * first PR allowed to connect it to the existing host/client implementation.
+ */
+export interface SchedulerTransport {
+ readonly selfDeviceId: string;
+ readonly platform: string;
+ getStatus(): SchedulerRelayStatus;
+ isOwner(): boolean;
+ subscribe(listener: (event: SchedulerTransportEvent) => void): () => void;
+ sendPush(peerDeviceId: string, payload: ImSchedulerFrame): void;
+ /** REST/presence refresh hook used by bounded discovery retries. */
+ requestSnapshot: (accountGeneration: string, requestId: string) => void | Promise<void>;
+}
diff --git a/docs/im-discord-scheduler-pr-split.md b/docs/im-discord-scheduler-pr-split.md
new file mode 100644
index 0000000000..4711a47f78
--- /dev/null
+++ b/docs/im-discord-scheduler-pr-split.md
@@ -0,0 +1,140 @@
+# Discord 单 ingress PR 拆分计划
+
+> 状态:执行计划(2026-08-07)
+>
+> 原始 PR:[#1861](https://github.com/makecindy/cindy/pull/1861)
+>
+> 原始需求:[#187](https://github.com/makecindy/cindy/issues/187)
+
+## 为什么拆分
+
+PR #1861 已经累积了大量 review 轮次和增量修复,导致调度基础、Discord Gateway 接入、
+交接排空和离线补偿无法在一个 diff 中被整体复核。本计划把已有结论按依赖顺序拆成小 PR,
+不重新设计产品行为,也不把跨 Cindy 账号的唯一绑定带入客户端。
+
+拆分的硬边界:
+
+- 只处理同一 Cindy 账号、多台 Desktop 的 Discord 个人 Bot 单 ingress。
+- 不修改 Telegram、飞书、钉钉、企业微信、个人微信等其他 IM 的调度行为。
+- 不修改服务端,不实现跨 Cindy 账号 registry/CAS;#187 的跨账号唯一绑定另行处理。
+- 不修改用户本地已有的 `cindy-protocol` submodule 工作区改动。
+- 从最新 `origin/main` 新建分支;不携带原 PR 的 37 个历史提交。
+- PR-A 合入前不创建或推进 PR-B;PR-C 只有在补偿消费侧能够干净解耦时才创建。
+
+## PR-A:调度基础层(先合)
+
+建议标题:`feat(desktop): add dormant Discord ingress scheduler foundation`
+
+目标:新增可测试的调度基础设施,但不启动任何 IM、不创建 Discord Gateway、不改变现有运行
+行为。调度器依赖本地 `SchedulerTransport` 抽象,Discord 适配留给 PR-B。
+
+### 文件边界
+
+保留或新增:
+
+- `apps/desktop/src/main/im/scheduler/transport.ts`
+- `packages/device-link/src/discordSchedulerProtocol.ts`
+- `packages/device-link/src/__tests__/discordSchedulerProtocol.test.ts`
+- `apps/desktop/src/main/im/scheduler/state.ts`
+- `apps/desktop/src/main/im/scheduler/deviceSnapshot.ts`
+- `apps/desktop/src/main/im/scheduler/runtimeGaps.ts`
+- `apps/desktop/src/main/im/scheduler/manager.ts`
+- `apps/desktop/src/main/im/scheduler/__tests__/state.test.ts`
+- `apps/desktop/src/main/im/scheduler/__tests__/deviceSnapshot.test.ts`
+- `apps/desktop/src/main/im/scheduler/__tests__/runtimeGaps.test.ts`
+- `apps/desktop/src/main/im/scheduler/__tests__/manager.test.ts`
+
+Device Link 的具体 host/client 接线全部延后到 PR-B。PR-A 只在
+`packages/device-link/src/discordSchedulerProtocol.ts` 定义这条 Discord-only 隧道 payload
+的共享形状,并在 `scheduler/transport.ts` 定义适配接口和事件形状;不修改 relay envelope、
+`cindy-protocol` 或现有 Device Link host/client 行为。这样 PR-A 可以在不启动任何 IM 的前提下
+独立审查和测试。
+
+### PR-A 必须覆盖的状态不变量
+
+- relay 不在线、ownership 不成立、self Desktop 不在权威快照中时 fail-closed。
+- peer presence 必须有当前 discovery round 的确认,不能把空视图当作完整视图。
+- discovery probe 使用 nonce 绑定的有界 retry/refresh;完成、停止、重置或快照世代变化时取消旧轮。
+- 单轮 retry 耗尽后启动新的 discovery round,避免永久停在 incomplete-peer-view;刷新响应保留当前轮计数。
+- snapshot refresh 使用 request id 绑定账号/请求世代,账号切换后拒绝旧响应;null snapshot 撤销旧权威视图。
+- 选主必须是确定性的,同一 `(channel, non-secret identity)` 同一时刻最多一个赢家。
+- 所有选主、快照和 gap 裁剪排序使用 locale-independent comparator;设备成员变化、时钟回拨、账号切换会使旧 discovery/runtime 视图失效。
+- 只有当前权威 Desktop 快照中的 peer 能参与 probe/advertisement;binding 变化会在下一轮 probe 中传播当前非敏感 identity,并立即重算本地选举。
+- runtime gap 以 `(identity, binding generation, runtime generation)` 精确去重,同一
+ binding 的多个未解决 generation 可同时保留,并按该元组确定性裁剪到协议上限;
+ clean 只解析精确元组,并保留四个协议窗口的确定性 resolved tombstone,防止该重放窗口内
+ 先到的 clean 被迟到 dirty 复活;binding generation 继续作为重绑生命周期屏障,不携带
+ token 或 secret。
+- PR-A 的 manager 不被任何现有 IM 启动路径调用。
+
+### PR-A 不包含
+
+- `packages/lizi-im/src/discord/**`
+- `apps/desktop/src/main/im/index.ts`
+- `apps/desktop/src/main/bootstrap-electron.ts`
+- `apps/desktop/src/main/im/shared/**`
+- `packages/lizi-im/src/channelIM.ts`、全局 `IMStatus` 扩展
+- preload、renderer、设置页和 i18n
+- 其他 IM provider 文件
+- 通用 Device Link 重构;仅新增上述 Discord scheduler payload 共享契约
+- Discord Gateway 生命周期、handoff drain 和 offline notice 消费
+
+## PR-B:Discord Gateway 接入
+
+建议标题:`fix(discord): 避免同一 Cindy 账号的多台 Desktop 同时连接 Bot`
+
+依赖:PR-A 已合入 main。
+
+目标:把 Discord Gateway 接到 PR-A 的 transport adapter,闭合 active/standby、ingress 开关、
+reconnecting Client 复用、首次激活失败让位、ownership/relay 失效时立即关 ingress,以及必要的
+handoff drain。只修改 Discord provider 和必要的 Desktop 接线。
+
+### 候选文件
+
+- `packages/lizi-im/src/discord/gateway.ts`
+- `packages/lizi-im/src/discord/index.ts`
+- `packages/lizi-im/src/discord/outbound.ts`
+- `packages/lizi-im/src/discord/__tests__/**`
+- `apps/desktop/src/main/im/index.ts`
+- `apps/desktop/src/main/im/scheduler/manager.ts`(仅接入 PR-A 的 transport,不把其他 IM 纳入调度)
+- `apps/desktop/src/main/im/discordQuitOrdering.ts`
+- `apps/desktop/src/main/im/__tests__/discordQuitOrdering.test.ts`
+- `apps/desktop/src/main/bootstrap-electron.ts`(仅保留 Discord 关闭顺序所需改动)
+- `apps/desktop/src/preload/preload.ts`
+- `apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx`
+- Discord 设置页相关四语言 i18n 与 renderer 类型镜像
+
+PR-B 不得借机修改公共 IM runner、其他 provider 或服务端。
+
+## PR-C:离线补偿消费侧(可选)
+
+只有在 PR-B 的 active/standby/handoff 可以不依赖它独立成立时才创建。
+
+建议标题:`fix(discord): preserve offline compensation across ingress handoff`
+
+候选文件:
+
+- `apps/desktop/src/main/im/scheduler/runtimeCompensation.ts`
+- `apps/desktop/src/main/im/scheduler/__tests__/runtimeCompensation.test.ts`
+- manager 中的 clean/dirty runtime 消费、pending clean handoff、predecessor 责任转移
+- Discord lifecycle offline marker 与对应测试
+
+PR-C 不包含新的选举协议、不扩大到其他 IM、不做服务端 CAS、不做快照退避或 UI 重构。
+如果消费侧无法从 PR-B 清晰解耦,则并入 PR-B 的一个明确小 commit,不再继续增加新的补偿
+语义。
+
+## 执行顺序与交付
+
+1. 从最新 `origin/main` 建立 PR-A 分支,先提交本计划文档和基础层代码。
+2. PR-A 只在自身范围内运行定向测试、`pnpm test:unit`、受影响 package typecheck、DCO。
+3. PR-A review/approve/merge 后,基于合入后的 main 建立 PR-B。
+4. PR-B review/approve/merge 后,再判断是否需要 PR-C。
+5. 原 PR #1861 在拆分期间保持 OPEN,不继续追加实现。新 PR 创建后再在原 PR 留言附链接;
+ PR-A/B 合入后再关闭原 PR,保留历史可追溯性。
+
+## 拆分验收
+
+- 每个新 PR 都只有少量语义化 commit,所有 commit 使用 DCO sign-off。
+- PR-A 不触发 IM 行为变化;PR-B 不修改其他 IM;PR-C 不改变选举结论。
+- 每个 PR 的正文准确列出“怎么验证的”、风险、回滚方式和不包含范围。
+- 任何超出上述边界的 review 建议另开 Issue,不回流当前 PR。
diff --git a/packages/device-link/src/__tests__/discordSchedulerProtocol.test.ts b/packages/device-link/src/__tests__/discordSchedulerProtocol.test.ts
new file mode 100644
index 0000000000..2579852c80
--- /dev/null
+++ b/packages/device-link/src/__tests__/discordSchedulerProtocol.test.ts
@@ -0,0 +1,153 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { isImSchedulerFrame } from "../discordSchedulerProtocol.js";
+
+const identity = "12345678901234567";
+const bindingGeneration = "binding-123456789";
+
+describe("Discord scheduler protocol", () => {
+ it("accepts non-secret advertisements, probes, and bounded dirty gaps", () => {
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [{ channel: "discord", identity, bindingGeneration }],
+ inReplyTo: "1234567890abcdef",
+ }),
+ ).toBe(true);
+ expect(
+ isImSchedulerFrame({
+ kind: "probe",
+ sentAt: 1,
+ nonce: "1234567890abcdef",
+ channels: [],
+ runtimeGaps: [
+ {
+ identity,
+ bindingGeneration,
+ generation: "a".repeat(32),
+ state: "dirty",
+ },
+ ],
+ }),
+ ).toBe(true);
+ });
+
+ it("accepts multiple unresolved generations for the same binding", () => {
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [{ channel: "discord", identity, bindingGeneration }],
+ runtimeGaps: [
+ {
+ identity,
+ bindingGeneration,
+ generation: "a".repeat(32),
+ state: "dirty",
+ },
+ {
+ identity,
+ bindingGeneration,
+ generation: "b".repeat(32),
+ state: "dirty",
+ },
+ ],
+ }),
+ ).toBe(true);
+ });
+
+ it("rejects an exact duplicate unresolved generation", () => {
+ const runtime = {
+ identity,
+ bindingGeneration,
+ generation: "a".repeat(32),
+ state: "dirty",
+ };
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [{ channel: "discord", identity, bindingGeneration }],
+ runtimeGaps: [runtime, runtime],
+ }),
+ ).toBe(false);
+ });
+
+ it("rejects credentials, other channels, malformed ids, and invalid runtime state", () => {
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [],
+ token: "secret",
+ }),
+ ).toBe(false);
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [{ channel: "telegram", identity, bindingGeneration }],
+ }),
+ ).toBe(false);
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [
+ {
+ channel: "discord",
+ identity: `${identity}.secret`,
+ bindingGeneration,
+ },
+ ],
+ }),
+ ).toBe(false);
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [],
+ runtime: {
+ identity,
+ bindingGeneration,
+ generation: "a".repeat(32),
+ state: "clean",
+ predecessor: "b".repeat(32),
+ },
+ }),
+ ).toBe(false);
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [{ channel: "discord", identity }],
+ }),
+ ).toBe(false);
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [],
+ runtimeGaps: [{ identity, generation: "a".repeat(32), state: "dirty" }],
+ }),
+ ).toBe(false);
+ });
+
+ it("prevalidates untrusted fields before calculating payload size", () => {
+ const stringify = vi.spyOn(JSON, "stringify");
+ try {
+ expect(
+ isImSchedulerFrame({
+ kind: "advertisement",
+ sentAt: 1,
+ channels: [],
+ unexpected: "x".repeat(100_000),
+ }),
+ ).toBe(false);
+ expect(stringify).not.toHaveBeenCalled();
+ } finally {
+ stringify.mockRestore();
+ }
+ });
+});
diff --git a/packages/device-link/src/discordSchedulerProtocol.ts b/packages/device-link/src/discordSchedulerProtocol.ts
new file mode 100644
index 0000000000..06c7309403
--- /dev/null
+++ b/packages/device-link/src/discordSchedulerProtocol.ts
@@ -0,0 +1,228 @@
+/**
+ * Dormant Discord scheduler payload shared by Device Link clients.
+ *
+ * The relay treats this push payload as opaque, but its topic, bounds, and
+ * validation belong beside the other Device Link tunnel contracts so every
+ * client uses the same wire shape.
+ */
+
+/** Device Link push topic reserved for the Discord-only scheduler adapter. */
+export const IM_SCHEDULER_PUSH_CHANNEL = "cindy:discord-scheduler:v1";
+export const MAX_RUNTIME_GAPS = 8;
+
+export interface SchedulerChannelIdentity {
+ channel: "discord";
+ /** Discord application id only; credentials never belong in this type. */
+ identity: string;
+}
+
+export interface SchedulerChannelBinding extends SchedulerChannelIdentity {
+ /** Opaque lifecycle fence rotated whenever this Desktop's binding changes. */
+ bindingGeneration: string;
+}
+
+export interface SchedulerRuntimeFrame {
+ identity: string;
+ /**
+ * Recipient binding lifecycle for which this runtime state is valid. A peer
+ * must not relabel an older gap when the recipient advertises a new binding.
+ */
+ bindingGeneration: string;
+ generation: string;
+ state: "active" | "dirty" | "clean";
+ predecessor?: string;
+}
+
+export interface SchedulerAdvertisementFrame {
+ kind: "advertisement";
+ sentAt: number;
+ channels: readonly SchedulerChannelBinding[];
+ runtime?: SchedulerRuntimeFrame;
+ runtimeGaps?: readonly SchedulerRuntimeFrame[];
+ /** Matches the discovery probe that caused this advertisement. */
+ inReplyTo?: string;
+}
+
+export interface SchedulerProbeFrame {
+ kind: "probe";
+ sentAt: number;
+ nonce: string;
+ channels: readonly SchedulerChannelBinding[];
+ runtime?: SchedulerRuntimeFrame;
+ runtimeGaps?: readonly SchedulerRuntimeFrame[];
+}
+
+export type ImSchedulerFrame =
+ SchedulerAdvertisementFrame | SchedulerProbeFrame;
+
+const DISCORD_ID_PATTERN = /^[1-9][0-9]{16,19}$/;
+const RUNTIME_GENERATION_PATTERN = /^[a-f0-9]{32}$/;
+const NONCE_PATTERN = /^[A-Za-z0-9_-]{16,64}$/;
+
+function isWithinSchedulerFrameSize(value: unknown): boolean {
+ let size = 0;
+ try {
+ size = JSON.stringify(value).length;
+ } catch {
+ return false;
+ }
+ return size <= 8_192;
+}
+
+export function isSchedulerChannelIdentity(
+ value: unknown,
+): value is SchedulerChannelIdentity {
+ if (!value || typeof value !== "object") return false;
+ const identity = value as Record<string, unknown>;
+ return (
+ Object.keys(identity).length === 2 &&
+ identity.channel === "discord" &&
+ typeof identity.identity === "string" &&
+ DISCORD_ID_PATTERN.test(identity.identity)
+ );
+}
+
+export function isSchedulerChannelBinding(
+ value: unknown,
+): value is SchedulerChannelBinding {
+ if (!value || typeof value !== "object") return false;
+ const binding = value as Record<string, unknown>;
+ return (
+ Object.keys(binding).length === 3 &&
+ binding.channel === "discord" &&
+ typeof binding.identity === "string" &&
+ DISCORD_ID_PATTERN.test(binding.identity) &&
+ typeof binding.bindingGeneration === "string" &&
+ NONCE_PATTERN.test(binding.bindingGeneration)
+ );
+}
+
+export function isSchedulerRuntimeFrame(
+ value: unknown,
+): value is SchedulerRuntimeFrame {
+ if (!value || typeof value !== "object") return false;
+ const runtime = value as Record<string, unknown>;
+ if (
+ Object.keys(runtime).some(
+ (key) =>
+ ![
+ "identity",
+ "bindingGeneration",
+ "generation",
+ "state",
+ "predecessor",
+ ].includes(key),
+ )
+ ) {
+ return false;
+ }
+ if (
+ typeof runtime.identity !== "string" ||
+ !DISCORD_ID_PATTERN.test(runtime.identity)
+ )
+ return false;
+ if (
+ typeof runtime.bindingGeneration !== "string" ||
+ !NONCE_PATTERN.test(runtime.bindingGeneration)
+ ) {
+ return false;
+ }
+ if (
+ typeof runtime.generation !== "string" ||
+ !RUNTIME_GENERATION_PATTERN.test(runtime.generation)
+ ) {
+ return false;
+ }
+ if (
+ runtime.state !== "active" &&
+ runtime.state !== "dirty" &&
+ runtime.state !== "clean"
+ )
+ return false;
+ if (
+ runtime.predecessor !== undefined &&
+ (runtime.state !== "active" ||
+ typeof runtime.predecessor !== "string" ||
+ !RUNTIME_GENERATION_PATTERN.test(runtime.predecessor) ||
+ runtime.predecessor === runtime.generation)
+ )
+ return false;
+ return true;
+}
+
+function isRuntimeGapList(
+ value: unknown,
+): value is readonly SchedulerRuntimeFrame[] | undefined {
+ if (value === undefined) return true;
+ if (!Array.isArray(value) || value.length > MAX_RUNTIME_GAPS) return false;
+ const generations = new Set<string>();
+ return value.every((runtime) => {
+ if (!isSchedulerRuntimeFrame(runtime) || runtime.state !== "dirty")
+ return false;
+ const key = `${runtime.identity}\u0000${runtime.bindingGeneration}\u0000${runtime.generation}`;
+ if (generations.has(key)) return false;
+ generations.add(key);
+ return true;
+ });
+}
+
+export function isImSchedulerFrame(value: unknown): value is ImSchedulerFrame {
+ if (!value || typeof value !== "object") return false;
+ const frame = value as Record<string, unknown>;
+ if (typeof frame.sentAt !== "number" || !Number.isFinite(frame.sentAt))
+ return false;
+
+ if (frame.kind === "probe") {
+ if (
+ Object.keys(frame).some(
+ (key) =>
+ ![
+ "kind",
+ "sentAt",
+ "nonce",
+ "channels",
+ "runtime",
+ "runtimeGaps",
+ ].includes(key),
+ )
+ ) {
+ return false;
+ }
+ const valid =
+ typeof frame.nonce === "string" &&
+ NONCE_PATTERN.test(frame.nonce) &&
+ Array.isArray(frame.channels) &&
+ frame.channels.length <= 1 &&
+ frame.channels.every(isSchedulerChannelBinding) &&
+ (frame.runtime === undefined || isSchedulerRuntimeFrame(frame.runtime)) &&
+ isRuntimeGapList(frame.runtimeGaps);
+ return valid && isWithinSchedulerFrameSize(value);
+ }
+
+ if (frame.kind !== "advertisement") return false;
+ if (
+ Object.keys(frame).some(
+ (key) =>
+ ![
+ "kind",
+ "sentAt",
+ "channels",
+ "runtime",
+ "runtimeGaps",
+ "inReplyTo",
+ ].includes(key),
+ )
+ ) {
+ return false;
+ }
+ const valid =
+ Array.isArray(frame.channels) &&
+ frame.channels.length <= 1 &&
+ frame.channels.every(isSchedulerChannelBinding) &&
+ (frame.runtime === undefined || isSchedulerRuntimeFrame(frame.runtime)) &&
+ isRuntimeGapList(frame.runtimeGaps) &&
+ (frame.inReplyTo === undefined ||
+ (typeof frame.inReplyTo === "string" &&
+ NONCE_PATTERN.test(frame.inReplyTo)));
+ return valid && isWithinSchedulerFrameSize(value);
+}
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 293a3bface..38da6a9791 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -14,6 +14,7 @@ export * from './transport.js';
export * from './topics.js';
export * from './attachmentOssRef.js';
export * from './contactsSyncProtocol.js';
+export * from './discordSchedulerProtocol.js';
export * from './remoteResources.js';
export * from './remoteDesktop.js';
export * from './remoteDesktopViewerSession.js';