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。

57.9 KB
Raw Blame
/**
 * refreshRemoteSessionsRetry.test.ts —— 控制端首拉对「被控端刚上线 DB 未就绪」的瞬态重试。
 *
 * 真机实测根因:被控端宣布在线早于自身 localDb 迁移完成 → 控制端首拉 `local-db:sessions:list`
 * 撞「DbClient not ready」→ 旧实现静默放弃 → 控制端永远看不到被控端会话。本测试锁:
 *   - isTransientRemoteError 正确分类瞬态 / 永久错误;
 *   - 瞬态错误退避重试,直到成功 → setDeviceSessions(被控端会话出现在控制端);
 *   - 永久错误(被控开关关 / channel 不允许)立即放弃,不空转;
 *   - 重试耗尽后放弃,不抛。
 */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import type { Session } from '@/lib/ccAgent.types';
import { DEVICE_LINK_RECONCILIATION_PROBE_MARKER } from '@cindy/maker-shared/device-link-contract';

vi.mock('@/lib/logger', () => ({
  createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));

import {
  refreshRemoteDeviceSessions,
  isTransientRemoteError,
} from '@/features/device-link/refreshRemoteSessions';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { unresponsiveDevicesStore } from '@/features/device-link/unresponsiveDevicesStore';
import {
  applyRemoteSessionActivity,
  clearRemoteSessionActivity,
  getRemoteSessionActivity,
} from '@/features/device-link/remoteSessionActivityStore';

const invoke = vi.fn();
const historyInvoke = vi.fn();
let n = 0;
const did = () => `retry-dev-${n++}`;
const noSleep = async () => {};

beforeEach(() => {
  invoke.mockReset();
  historyInvoke.mockReset().mockResolvedValue({ ok: true, sessions: [], hasMore: false });
  // Existing cases exercise compatibility with hosts predating batch reconciliation.
  vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: (...args: unknown[]) => {
    if (args[1] === 'local-db:history:query') return historyInvoke(...args);
    if (args[1] === 'local-db:sessions:get-many') return Promise.reject(new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] old host'));
    return invoke(...args);
  } } } });
});

afterEach(() => {
  unresponsiveDevicesStore.clearAll();
  remoteProjectsStore.clear();
  clearRemoteSessionActivity();
  vi.unstubAllGlobals();
});

it('keeps cached content and leaves recovery probing to main while a device is unresponsive', async () => {
  const device = did();
  const cached = session('cached');
  remoteProjectsStore.setDeviceSessions(device, 'Host', [cached]);
  const cachedSnapshot = remoteProjectsStore.getDeviceSessions(device);
  unresponsiveDevicesStore.apply(device, true);
  expect(await refreshRemoteDeviceSessions(device)).toBe('gave-up');
  expect(invoke).not.toHaveBeenCalled();
  expect(remoteProjectsStore.getDeviceSessions(device)).toEqual(cachedSnapshot);
  unresponsiveDevicesStore.apply(device, false);
  invoke.mockResolvedValue([session('fresh')]);
  expect(await refreshRemoteDeviceSessions(device)).toBe('ok');
  expect(invoke).toHaveBeenCalledOnce();
});

it('marks periodic and archived reads as background while keeping initial reads foreground', async () => {
  invoke.mockResolvedValue([]);
  const initial = did();
  const periodic = did();
  await refreshRemoteDeviceSessions(initial);
  await refreshRemoteDeviceSessions(periodic, undefined, { coalescingMode: 'weak' });
  expect(invoke.mock.calls.find(([peer]) => peer === initial)?.[3]).toEqual({ background: false });
  expect(invoke.mock.calls.find(([peer]) => peer === periodic)?.[3]).toEqual({ background: true });
});

it('stops an existing retry chain as soon as main opens the circuit', async () => {
  const device = did();
  invoke.mockRejectedValue(new Error('[DEVICE_LINK_TIMEOUT] timeout'));
  const sleep = vi.fn(async () => { unresponsiveDevicesStore.apply(device, true); });
  expect(await refreshRemoteDeviceSessions(device, undefined, { sleep })).toBe('gave-up');
  expect(sleep).toHaveBeenCalledOnce();
  expect(invoke).toHaveBeenCalledOnce();
});

function session(id: string, partial: Partial<Session> = {}): Session {
  return {
    id,
    userId: 'user-1',
    title: id,
    workingDir: null,
    workspaceKind: 'dialogue',
    model: 'model-1',
    effort: 'medium',
    permissionMode: 'default',
    sdkSessionId: null,
    totalTokenUsage: 0,
    totalCostUsd: 0,
    contextTokens: 0,
    contextWindow: 0,
    fastMode: false,
    clearedAt: null,
    pinnedAt: null,
    userSendAt: null,
    status: 'active',
    agentKind: 'cc',
    extraDirs: [],
    createdAt: '2026-08-02T00:00:00.000Z',
    updatedAt: '2026-08-02T00:00:00.000Z',
    ...partial,
  };
}

function legacyMinimalSession(id: string) {
  return {
    id,
    title: id,
    workingDir: null,
    model: 'model-1',
    status: 'active',
    agentKind: 'cc',
    createdAt: '2026-08-02T00:00:00.000Z',
    updatedAt: '2026-08-02T00:00:00.000Z',
  };
}

function deferred<T>() {
  let resolve!: (value: T | PromiseLike<T>) => void;
  let reject!: (reason?: unknown) => void;
  const promise = new Promise<T>((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}

describe('refresh lifecycle cancellation', () => {
  it.each(['removeDevice', 'markDeviceDisconnected', 'markAllDisconnected', 'clear'] as const)(
    '%s cancels queued strong refreshes, while another peer remains usable', async (action) => {
      const device = did();
      const pending = deferred<Session[]>();
      invoke.mockImplementation((peer: string) => peer === device ? pending.promise : Promise.resolve([session('healthy')]));
      const first = refreshRemoteDeviceSessions(device);
      const queued = refreshRemoteDeviceSessions(device);
      if (action === 'removeDevice' || action === 'markDeviceDisconnected') remoteProjectsStore[action](device);
      else remoteProjectsStore[action]();
      await expect(refreshRemoteDeviceSessions(did())).resolves.toBe('ok');
      pending.resolve([session('cancelled')]);
      expect(await Promise.all([first, queued])).toEqual(['superseded', 'superseded']);
      expect(invoke.mock.calls.filter(([peer]) => peer === device)).toHaveLength(1);
      expect(remoteProjectsStore.getDeviceSessions(device)).toEqual([]);
    },
  );

  it('re-enabling waits for the old physical request, then reads a fresh snapshot', async () => {
    const device = did();
    const pending = deferred<Session[]>();
    invoke.mockReturnValueOnce(pending.promise).mockResolvedValue([session('fresh')]);
    const old = refreshRemoteDeviceSessions(device);
    const queued = refreshRemoteDeviceSessions(device);
    remoteProjectsStore.removeDevice(device);
    const renewed = refreshRemoteDeviceSessions(device);
    expect(invoke).toHaveBeenCalledTimes(1);
    pending.resolve([session('stale')]);
    expect(await Promise.all([old, queued, renewed])).toEqual(['superseded', 'superseded', 'ok']);
    expect(invoke).toHaveBeenCalledTimes(2);
    expect(remoteProjectsStore.getDeviceSessions(device).map(row => row.id)).toEqual(['fresh']);
  });

  it('weak-network reads retain a fresh follow-up for new events', async () => {
    const device = did();
    const pending = deferred<Session[]>();
    invoke.mockReturnValueOnce(pending.promise).mockResolvedValue([session('created-during-read')]);
    const old = refreshRemoteDeviceSessions(device);
    const tick = refreshRemoteDeviceSessions(device, undefined, { coalescingMode: 'weak' });
    const changed = refreshRemoteDeviceSessions(device);
    expect(invoke).toHaveBeenCalledTimes(1);
    pending.resolve([session('old')]);
    await Promise.all([old, tick, changed]);
    expect(invoke).toHaveBeenCalledTimes(2);
    expect(remoteProjectsStore.getDeviceSessions(device).map(row => row.id)).toEqual(['created-during-read']);
  });
});

describe('isTransientRemoteError', () => {
  it('瞬态标记 → true', () => {
    expect(isTransientRemoteError('Error: DbClient not ready')).toBe(true);
    expect(isTransientRemoteError('[NOT_CONNECTED] not connected to relay')).toBe(true);
    expect(isTransientRemoteError('DEVICE_OFFLINE target device offline')).toBe(true);
    // invoke 超时:renderer 实际看到的是 main IPC 层映射后的 [DEVICE_LINK_TIMEOUT],
    // 而非原始 INVOKE_TIMEOUT —— 必须按映射后的码匹配才能触发瞬态重试。
    expect(isTransientRemoteError('[DEVICE_LINK_TIMEOUT] no result within 30000ms')).toBe(true);
  });
  it('永久标记 → false(即便含其它字样也不重试)', () => {
    expect(isTransientRemoteError('[REMOTE_DISABLED] remote control disabled')).toBe(false);
    expect(isTransientRemoteError("[CHANNEL_NOT_ALLOWED] channel 'x' not allowed")).toBe(false);
  });
  it('未知错误 → false(不空转)', () => {
    expect(isTransientRemoteError('some unexpected error')).toBe(false);
  });
});

describe('refreshRemoteDeviceSessions retry', () => {
  it.each(['merge', 'replace'] as const)(
    '%s archived refresh reconciles companions deleted while disconnected',
    async (snapshotMode) => {
      const d = did();
      const bots = ['deleted', 'missing', 'kept', 'restored', 'timeout'].map((id) =>
        session(id, { source: 'bot', status: 'archived', model: 'gpt-6-astra' }),
      );
      remoteProjectsStore.mergeDeviceSessions(d, 'MacBook', bots, 'archived');
      remoteProjectsStore.markDeviceDisconnected(d);
      invoke.mockImplementation(async (_device, channel, args) => {
        if (channel === 'local-db:sessions:list') return [];
        if (args[0] === 'missing') throw new Error('[NOT_FOUND] removed');
        if (args[0] === 'timeout') throw new Error('[DEVICE_LINK_TIMEOUT] unavailable');
        const bot = bots.find((row) => row.id === args[0])!;
        return {
          ...bot,
          status: bot.id === 'deleted' ? 'deleted' : bot.id === 'restored' ? 'active' : 'archived',
        };
      });

      await refreshRemoteDeviceSessions(d, 'MacBook', { status: 'archived', snapshotMode });

      expect(remoteProjectsStore.getDeviceSessions(d, 'archived').map((row) => row.id)).toEqual([
        'kept',
        'timeout',
      ]);
      expect(remoteProjectsStore.getDeviceSessions(d, 'active').map((row) => row.id)).toEqual([
        'restored',
      ]);
      expect(
        remoteProjectsStore.getDeviceSessions(d).every((row) => row.model === 'gpt-6-astra'),
      ).toBe(true);
      expect(invoke).toHaveBeenCalledTimes(6);
    },
  );

  it('keeps independent bounded probe rotation for active and archived companions', async () => {
    const d = did();
    const bots = ['active', 'archived'].flatMap((status) =>
      Array.from({ length: 9 }, (_, i) =>
        session(`${status}-${i}`, {
          source: 'bot',
          status: status as Session['status'],
        }),
      ),
    );
    for (const status of ['active', 'archived'] as const) {
      remoteProjectsStore.mergeDeviceSessions(
        d,
        'MacBook',
        bots.filter((row) => row.status === status),
        status,
      );
    }
    const probed: string[] = [];
    invoke.mockImplementation(async (_device, channel, args) => {
      if (channel === 'local-db:sessions:list') return [];
      probed.push(args[0]);
      return bots.find((row) => row.id === args[0]);
    });
    for (const status of ['active', 'archived', 'active', 'archived'] as const) {
      const before = probed.length;
      await refreshRemoteDeviceSessions(d, 'MacBook', { status });
      expect(probed.length - before).toBe(8);
    }
    expect(new Set(probed).size).toBe(18);
    expect(remoteProjectsStore.getDeviceSessions(d)).toHaveLength(18);
  });

  it('does not invalidate an archived detail probe when the active bucket refreshes', async () => {
    const d = did();
    const bot = session('archived-concurrent', { source: 'bot', status: 'archived' });
    remoteProjectsStore.mergeDeviceSessions(d, 'MacBook', [bot], 'archived');
    const detail = deferred<Session>();
    invoke.mockImplementation(async (_device, channel) =>
      channel === 'local-db:sessions:list' ? [] : detail.promise,
    );
    const refresh = refreshRemoteDeviceSessions(d, 'MacBook', { status: 'archived' });
    await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(2));
    await refreshRemoteDeviceSessions(d, 'MacBook');
    await refreshRemoteDeviceSessions(d, 'MacBook');
    detail.resolve({ ...bot, status: 'deleted' });
    await expect(refresh).resolves.toBe('ok');
    expect(remoteProjectsStore.getDeviceSessions(d)).toEqual([]);
  });

  it('fences archived detail responses against disconnect and newer pushes', async () => {
    const d = did();
    const bot = session('archived-late', {
      source: 'bot',
      status: 'archived',
      model: 'gpt-6-astra',
    });
    remoteProjectsStore.mergeDeviceSessions(d, 'MacBook', [bot], 'archived');
    for (const change of ['push', 'disconnect'] as const) {
      const detail = deferred<Session>();
      invoke
        .mockReset()
        .mockImplementation(async (_device, channel) =>
          channel === 'local-db:sessions:list' ? [] : detail.promise,
        );
      const refresh = refreshRemoteDeviceSessions(d, 'MacBook', { status: 'archived' });
      await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(2));
      if (change === 'push') remoteProjectsStore.applyPatch(d, bot.id, { model: 'new-model' });
      else remoteProjectsStore.markDeviceDisconnected(d);
      detail.resolve({ ...bot, status: 'deleted' });
      await expect(refresh).resolves.toBe(change === 'push' ? 'ok' : 'superseded');
      expect(remoteProjectsStore.getDeviceSessions(d)[0]?.model).toBe('new-model');
    }
  });

  it.each(['merge', 'replace'] as const)(
    '%s refresh preserves a remote companion omitted by the ordinary task list',
    async (snapshotMode) => {
      const d = did();
      const bot = session('remote-lizi', {
        source: 'bot',
        model: 'gpt-6-astra',
        agentKind: 'codex',
        providerId: 'openai',
      });
      remoteProjectsStore.pinSessionOrigin(d, bot.id);
      remoteProjectsStore.mergeDeviceSessions(d, 'MacBook', [bot, session('old-task')]);
      invoke.mockImplementation(async (_device, channel, args) => {
        if (channel === 'local-db:sessions:list') return [session('ordinary-task')];
        if (channel === 'local-db:sessions:get' && args[0] === bot.id) return bot;
        throw new Error(`Unexpected channel: ${channel}`);
      });

      for (let turn = 0; turn < 3; turn++) {
        await expect(refreshRemoteDeviceSessions(d, 'MacBook', { snapshotMode })).resolves.toBe(
          'ok',
        );
        const mirrored = remoteProjectsStore.getDeviceSessions(d).find((row) => row.id === bot.id);
        expect(mirrored).toMatchObject({
          model: 'gpt-6-astra',
          agentKind: 'codex',
          providerId: 'openai',
          source: 'bot',
          deviceLinkDeviceId: d,
        });
        expect(remoteProjectsStore.getSessionDeviceId(bot.id)).toBe(d);
      }
      expect(remoteProjectsStore.getDeviceSessions(d).some((row) => row.id === 'old-task')).toBe(
        false,
      );
    },
  );

  it('preserves a busy companion and applies the host runtime model across an empty list refresh', async () => {
    const d = did();
    const bot = session('busy-companion', {
      source: 'bot',
      model: 'gpt-6-astra',
      agentKind: 'codex',
    });
    remoteProjectsStore.mergeDeviceSessions(d, 'MacBook', [bot]);
    applyRemoteSessionActivity(d, {
      sessionId: bot.id,
      phase: 'running',
      compactDetail: 'generating',
    });
    const runtimeEffective = {
      agentKind: 'codex' as const,
      model: 'gpt-6-astra',
      providerId: 'openai',
      effort: 'high' as const,
      fastMode: false,
    };
    invoke.mockImplementation(async (_device, channel) =>
      channel === 'local-db:sessions:list' ? [] : { ...bot, runtimeEffective },
    );

    await refreshRemoteDeviceSessions(d);

    expect(getRemoteSessionActivity(bot.id, d)?.phase).toBe('running');
    expect(remoteProjectsStore.getDeviceSessions(d)[0]).toMatchObject({ runtimeEffective });
    remoteProjectsStore.applyPatch(d, bot.id, { effort: 'high', listPreview: 'reply received' });
    expect(remoteProjectsStore.getDeviceSessions(d)[0]).toMatchObject({
      model: 'gpt-6-astra',
      effort: 'high',
      listPreview: 'reply received',
    });
  });

  it('keeps the companion snapshot when its detail request times out, without retrying other peers', async () => {
    const d = did();
    const other = did();
    const bot = session('offline-companion', { source: 'bot', model: 'gpt-6-astra' });
    remoteProjectsStore.mergeDeviceSessions(d, 'MacBook', [bot]);
    remoteProjectsStore.setDeviceSessions(other, 'Other Mac', [session('unaffected')]);
    applyRemoteSessionActivity(d, {
      sessionId: bot.id,
      phase: 'running',
      compactDetail: 'generating',
    });
    invoke.mockImplementation(async (device, channel) => {
      expect(device).toBe(d);
      if (channel === 'local-db:sessions:list') return [];
      throw new Error('[DEVICE_LINK_TIMEOUT] detail timed out');
    });

    await expect(refreshRemoteDeviceSessions(d)).resolves.toBe('ok');

    expect(invoke).toHaveBeenCalledTimes(2);
    expect(remoteProjectsStore.getDeviceSessions(d)[0]?.model).toBe('gpt-6-astra');
    expect(getRemoteSessionActivity(bot.id, d)?.phase).toBe('running');
    expect(remoteProjectsStore.getDeviceSessions(other)[0]?.deviceLinkConnectionStatus).toBe(
      'connected',
    );
  });

  it.each(['deleted', 'archived', 'missing'] as const)(
    'reconciles a companion that became %s while disconnected',
    async (terminal) => {
      const d = did();
      const bot = session('retired-companion', { source: 'bot' });
      remoteProjectsStore.mergeDeviceSessions(d, 'MacBook', [bot]);
      remoteProjectsStore.markDeviceDisconnected(d);
      applyRemoteSessionActivity(d, {
        sessionId: bot.id,
        phase: 'running',
        compactDetail: 'generating',
      });
      invoke.mockImplementation(async (_device, channel) => {
        if (channel === 'local-db:sessions:list') return [];
        if (terminal === 'missing') throw new Error('[NOT_FOUND] session missing');
        return { ...bot, status: terminal };
      });

      await refreshRemoteDeviceSessions(d, 'MacBook', { snapshotMode: 'replace' });

      expect(getRemoteSessionActivity(bot.id, d)).toBeUndefined();
      expect(remoteProjectsStore.getDeviceSessions(d, 'active')).toHaveLength(0);
      expect(remoteProjectsStore.getDeviceSessions(d)).toHaveLength(
        terminal === 'archived' ? 1 : 0,
      );
    },
  );

  it('does not revive or modify a companion from a late detail response after disconnect', async () => {
    const d = did();
    const bot = session('late-companion', { source: 'bot', model: 'gpt-6-astra' });
    const detail = deferred<Session>();
    remoteProjectsStore.mergeDeviceSessions(d, 'MacBook', [bot]);
    invoke.mockImplementation(async (_device, channel) =>
      channel === 'local-db:sessions:list' ? [] : detail.promise,
    );
    const refresh = refreshRemoteDeviceSessions(d);
    await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(2));
    remoteProjectsStore.markDeviceDisconnected(d);
    detail.resolve({ ...bot, model: 'stale-model' });
    await expect(refresh).resolves.toBe('superseded');
    expect(remoteProjectsStore.getDeviceSessions(d)[0]).toMatchObject({
      model: 'gpt-6-astra',
      deviceLinkConnectionStatus: 'disconnected',
    });
  });

  it('does not overwrite a live model switch with an older companion detail response', async () => {
    const d = did();
    const bot = session('switching-companion', { source: 'bot', model: 'old-model' });
    const detail = deferred<Session>();
    remoteProjectsStore.mergeDeviceSessions(d, 'MacBook', [bot]);
    invoke.mockImplementation(async (_device, channel) =>
      channel === 'local-db:sessions:list' ? [] : detail.promise,
    );
    const refresh = refreshRemoteDeviceSessions(d);
    await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(2));
    remoteProjectsStore.applyPatch(d, bot.id, { model: 'gpt-6-astra', agentKind: 'codex' });
    detail.resolve(bot);
    await refresh;
    expect(remoteProjectsStore.getDeviceSessions(d)[0]).toMatchObject({
      model: 'gpt-6-astra',
      agentKind: 'codex',
    });
  });

  it('被控端 DB 未就绪:重试两次后成功 → 会话出现在控制端', async () => {
    const d = did();
    invoke
      .mockRejectedValueOnce(new Error('DbClient not ready'))
      .mockRejectedValueOnce(new Error('DbClient not ready'))
      .mockResolvedValueOnce([session('s1'), session('s2')]);

    await refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });

    expect(invoke).toHaveBeenCalledTimes(3);
    const ids = remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id);
    expect(ids).toContain('s1');
    expect(ids).toContain('s2');
  });

  it('永久错误(REMOTE_DISABLED)→ 不重试,立即放弃(返回 gave-up)', async () => {
    const d = did();
    invoke.mockRejectedValue(new Error('[REMOTE_DISABLED] remote control disabled'));
    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
      'gave-up',
    );
    expect(invoke).toHaveBeenCalledTimes(1);
    expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);
  });

  it('非数组响应不得冒充成功或权威空列表', async () => {
    const d = did();
    invoke.mockResolvedValueOnce(null);

    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
      'gave-up',
    );
    expect(invoke).toHaveBeenCalledTimes(1);
    expect(remoteProjectsStore.hasDevice(d)).toBe(false);
  });

  it('空数组是权威空任务列表并正常发布', async () => {
    const d = did();
    invoke.mockResolvedValueOnce([]);

    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe('ok');

    expect(remoteProjectsStore.hasDevice(d)).toBe(true);
    expect(remoteProjectsStore.getDeviceSessions(d)).toEqual([]);
  });

  it('接受旧端最低任务列表形状,不强制要求新版附加字段', async () => {
    const d = did();
    invoke.mockResolvedValueOnce([legacyMinimalSession('legacy')]);

    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe('ok');

    expect(remoteProjectsStore.getDeviceSessions(d)).toEqual([
      expect.objectContaining({ id: 'legacy', title: 'legacy', status: 'active' }),
    ]);
  });

  it('数组混入非法会话时整份失败,保留旧 shard 且不部分应用', async () => {
    const d = did();
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('existing')]);
    invoke.mockResolvedValueOnce([session('fresh'), null]);

    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
      'gave-up',
    );
    expect(invoke).toHaveBeenCalledTimes(1);
    expect(remoteProjectsStore.getDeviceSessions(d).map((item) => item.id)).toEqual(['existing']);
  });

  it('active 列表混入非 active 会话时按协议损坏处理', async () => {
    const d = did();
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('existing')]);
    invoke.mockResolvedValueOnce([session('archived', { status: 'archived' })]);

    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
      'gave-up',
    );
    expect(remoteProjectsStore.getDeviceSessions(d).map((item) => item.id)).toEqual(['existing']);
  });

  it('损坏的满窗口响应不会触发 sessions:get 补查或改写旧 shard', async () => {
    const d = did();
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('outside-window')]);
    const malformed = [
      ...Array.from({ length: 199 }, (_, index) => session(`recent-${index}`)),
      null,
    ];
    invoke.mockResolvedValueOnce(malformed);

    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
      'gave-up',
    );

    expect(invoke).toHaveBeenCalledTimes(1);
    expect(remoteProjectsStore.getDeviceSessions(d).map((item) => item.id)).toEqual([
      'outside-window',
    ]);
  });

  it('访问被撤销(DEVICE_LINK_ACCESS_REVOKED)→ 不重试,返回 revoked(调用方据此 handleRevoked)', async () => {
    const d = did();
    invoke.mockRejectedValue(new Error('[DEVICE_LINK_ACCESS_REVOKED] revoked'));
    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
      'revoked',
    );
    expect(invoke).toHaveBeenCalledTimes(1); // 终态,不重试
    expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);
  });

  it('超时类失败只额外重试 1 次:每次都吃满隧道超时,不许按完整预算连打 6 个', async () => {
    const d = did();
    invoke.mockRejectedValue(new Error('[DEVICE_LINK_TIMEOUT] no invoke-result within 12000ms'));
    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
      'gave-up',
    );
    expect(invoke).toHaveBeenCalledTimes(2);
  });

  it('超时账本独立:一次超时不吞掉快速失败瞬态错误的完整预算', async () => {
    const d = did();
    invoke
      .mockRejectedValueOnce(new Error('[DEVICE_LINK_TIMEOUT] no invoke-result within 12000ms'))
      .mockRejectedValueOnce(new Error('DbClient not ready'))
      .mockRejectedValueOnce(new Error('DbClient not ready'))
      .mockResolvedValueOnce([session('s1')]);
    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe('ok');
    expect(invoke).toHaveBeenCalledTimes(4);
  });

  it('熔断快速失败(DEVICE_LINK_DEVICE_UNRESPONSIVE)→ 不重试,立即放弃', async () => {
    const d = did();
    invoke.mockRejectedValue(
      new Error('[DEVICE_LINK_DEVICE_UNRESPONSIVE] target device is unresponsive (circuit open)'),
    );
    await expect(refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep })).resolves.toBe(
      'gave-up',
    );
    expect(invoke).toHaveBeenCalledTimes(1);
  });

  it('重试耗尽 → 放弃,不抛(返回 gave-up,尝试次数 = maxAttempts)', async () => {
    const d = did();
    invoke.mockRejectedValue(new Error('DbClient not ready'));
    await expect(
      refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep, maxAttempts: 4 }),
    ).resolves.toBe('gave-up');
    expect(invoke).toHaveBeenCalledTimes(4);
    expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);
  });

  it('首次即成功 → 不重试', async () => {
    const d = did();
    invoke.mockResolvedValueOnce([session('only')]);
    await refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });
    expect(invoke).toHaveBeenCalledTimes(1);
    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toContain('only');
  });

  it('断连使在途快照失效 → 返回 superseded,不冒充终态请求失败', async () => {
    const d = did();
    const snapshot = deferred<Session[]>();
    invoke.mockReturnValueOnce(snapshot.promise);

    const refresh = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });
    remoteProjectsStore.markAllDisconnected();
    snapshot.resolve([session('stale')]);

    await expect(refresh).resolves.toBe('superseded');
    expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);
  });

  it('does not restore deleted tags from a first snapshot overtaken by a catalog push', async () => {
    const d = did();
    const snapshot = deferred<Session[]>();
    invoke.mockReturnValueOnce(snapshot.promise);
    const refresh = refreshRemoteDeviceSessions(d, 'Mac', { sleep: noSleep });
    remoteProjectsStore.applyTagCatalog(d, []);
    snapshot.resolve([session('task', { tags: [{
      id: 'old', name: 'Deleted', color: 'red', favoriteOrder: 0, revision: 1,
    }] })]);
    await expect(refresh).resolves.toBe('superseded');
    expect(remoteProjectsStore.getDeviceSessions(d)).toHaveLength(0);
    invoke.mockResolvedValueOnce([session('task', { tags: [] })]);
    await expect(refreshRemoteDeviceSessions(d, 'Mac', { sleep: noSleep })).resolves.toBe('ok');
    expect(remoteProjectsStore.getDeviceSessions(d)).toMatchObject([{ id: 'task', tags: [] }]);
  });

  it('首拉 active 列表时要求被控端补齐置顶,避免旧置顶被 200 条窗口截掉', async () => {
    const d = did();
    invoke.mockResolvedValueOnce([
      session('recent-1'),
      session('recent-2'),
      session('old-pinned-1'),
      session('old-pinned-2'),
    ]);

    await refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });

    expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [
      200,
      'active',
      { includePinned: true, fresh: true },
    ], { background: false });
    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual([
      'recent-1',
      'recent-2',
      'old-pinned-1',
      'old-pinned-2',
    ]);
  });

  it('按需读取 archived 桶并保留既有 active 桶', async () => {
    const d = did();
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('active-1')], 'active');
    invoke.mockResolvedValueOnce([session('archived-1', { status: 'archived' })]);

    await expect(
      refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep, status: 'archived' }),
    ).resolves.toBe('ok');

    expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [
      1000,
      'archived',
      { includePinned: true, fresh: true },
    ], { background: true });
    expect(remoteProjectsStore.getDeviceSessions(d, 'active').map((s) => s.id)).toEqual([
      'active-1',
    ]);
    expect(remoteProjectsStore.getDeviceSessions(d, 'archived').map((s) => s.id)).toEqual([
      'archived-1',
    ]);
  });

  it('archived 列表混入 active 会话时按协议损坏处理且不覆盖 active 桶', async () => {
    const d = did();
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('active-1')], 'active');
    invoke.mockResolvedValueOnce([session('wrong-active')]);

    await expect(
      refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep, status: 'archived' }),
    ).resolves.toBe('gave-up');

    expect(remoteProjectsStore.getDeviceSessions(d, 'active').map((s) => s.id)).toEqual([
      'active-1',
    ]);
    expect(remoteProjectsStore.hasLoadedSessionStatus(d, 'archived')).toBe(false);
  });

  it('同设备 active 与 archived 请求使用独立单飞和 epoch', async () => {
    const d = did();
    const activeSnapshot = deferred<Session[]>();
    const archivedSnapshot = deferred<Session[]>();
    invoke.mockImplementation(async (_deviceId, _channel, args) => {
      return args[1] === 'archived' ? archivedSnapshot.promise : activeSnapshot.promise;
    });

    const activeRefresh = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });
    const archivedRefresh = refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      status: 'archived',
    });
    archivedSnapshot.resolve([session('archived-1', { status: 'archived' })]);
    activeSnapshot.resolve([session('active-1')]);

    await expect(Promise.all([activeRefresh, archivedRefresh])).resolves.toEqual(['ok', 'ok']);
    expect(invoke).toHaveBeenCalledTimes(2);
    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual([
      'active-1',
      'archived-1',
    ]);
  });

  it('archived 使用 1000 条产品窗口,保留第 201 条之后的有效任务并清理陈旧缓存', async () => {
    const d = did();
    const archived = Array.from({ length: 250 }, (_, index) =>
      session(`archived-recent-${index}`, { status: 'archived' }),
    );
    remoteProjectsStore.setDeviceSessions(
      d,
      'Mac B',
      [session('stale-outside-window', { status: 'archived' })],
      'archived',
    );
    invoke.mockResolvedValueOnce(archived);

    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
      status: 'archived',
    });

    const archivedIds = remoteProjectsStore.getDeviceSessions(d, 'archived').map((item) => item.id);
    expect(archivedIds).toHaveLength(250);
    expect(archivedIds).toContain('archived-recent-200');
    expect(archivedIds).toContain('archived-recent-249');
    expect(archivedIds).not.toContain('stale-outside-window');
    expect(invoke).toHaveBeenCalledTimes(1);
    expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [
      1000,
      'archived',
      { includePinned: true, fresh: true },
    ], { background: true });
  });

  it('周期有界快照更新命中行但保留 200 条窗口外的有效会话', async () => {
    const d = did();
    const recent = Array.from({ length: 200 }, (_, index) =>
      session(`recent-${index}`, index === 0 ? { title: 'new' } : {}),
    );
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [
      session('recent-0', { title: 'old' }),
      session('outside-window'),
    ]);
    invoke
      .mockResolvedValueOnce(recent)
      .mockResolvedValueOnce(session('outside-window', { status: 'active' }));

    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
    });

    const merged = remoteProjectsStore.getMergedRemoteSessions();
    expect(merged).toHaveLength(201);
    expect(merged.map((s) => s.id)).toContain('outside-window');
    expect(merged[0].title).toBe('new');
    expect(invoke).toHaveBeenNthCalledWith(2, d, 'local-db:sessions:get', [
      'outside-window',
      DEVICE_LINK_RECONCILIATION_PROBE_MARKER,
    ]);
  });

  it('默认事件重拉也按有界快照 merge,保留 200 条窗口外的有效会话', async () => {
    const d = did();
    const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('outside-window')]);
    invoke
      .mockResolvedValueOnce(recent)
      .mockResolvedValueOnce(session('outside-window', { status: 'active' }));

    await refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });

    expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(201);
    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toContain(
      'outside-window',
    );
  });

  it('周期快照未满 200 条时视为完整 active 集合并清理缺席行', async () => {
    const d = did();
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [
      session('fresh'),
      session('stale-archived'),
    ]);
    applyRemoteSessionActivity(d, {
      sessionId: 'stale-archived',
      phase: 'running',
      compactDetail: 'still running',
    });
    invoke.mockResolvedValueOnce([session('fresh')]);

    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
    });

    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);
    expect(getRemoteSessionActivity('stale-archived', d)).toBeUndefined();
    expect(invoke).toHaveBeenCalledTimes(1);
  });

  it('周期满窗口用既有 sessions:get 有界补查并把已归档的窗口外行迁入归档桶', async () => {
    const d = did();
    const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('stale-archived')]);
    applyRemoteSessionActivity(d, {
      sessionId: 'stale-archived',
      phase: 'running',
      compactDetail: 'still running',
    });
    invoke
      .mockResolvedValueOnce(recent)
      .mockResolvedValueOnce(session('stale-archived', { status: 'archived' }));

    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
    });

    expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(201);
    expect(remoteProjectsStore.getDeviceSessions(d, 'active').map((s) => s.id)).not.toContain(
      'stale-archived',
    );
    expect(remoteProjectsStore.getDeviceSessions(d, 'archived')).toEqual([
      expect.objectContaining({ id: 'stale-archived', status: 'archived' }),
    ]);
    expect(getRemoteSessionActivity('stale-archived', d)).toBeUndefined();
  });

  it('周期满窗口补查 active 行时回填窗口外会话的权威元数据', async () => {
    const d = did();
    const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [
      session('outside-window', { title: 'old', pinnedAt: '2026-01-01T00:00:00.000Z' }),
    ]);
    invoke
      .mockResolvedValueOnce(recent)
      .mockResolvedValueOnce(
        session('outside-window', { status: 'active', title: 'new', pinnedAt: null }),
      );

    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
    });

    expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside-window')).toEqual(
      expect.objectContaining({ title: 'new', pinnedAt: null }),
    );
  });

  it('周期满窗口每轮最多补查 8 个缺席缓存 id', async () => {
    const d = did();
    const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));
    const outside = Array.from({ length: 12 }, (_, index) => session(`outside-${index}`));
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', outside);
    invoke.mockImplementation(async (_deviceId, channel, args) => {
      if (channel === 'local-db:sessions:list') return recent;
      return session(String(args[0]), { status: 'active' });
    });

    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
    });

    const probes = invoke.mock.calls.filter(([, channel]) => channel === 'local-db:sessions:get');
    expect(probes).toHaveLength(8);
    expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(212);
  });

  it('周期满窗口的相邻补查批次按 8 条推进,不重复检查上一批', async () => {
    const d = did();
    const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));
    const outside = Array.from({ length: 20 }, (_, index) => session(`outside-${index}`));
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', outside);
    invoke.mockImplementation(async (_deviceId, channel, args) => {
      if (channel === 'local-db:sessions:list') return recent;
      return session(String(args[0]), { status: 'active' });
    });

    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
    });
    const firstProbeIds = invoke.mock.calls
      .filter(([, channel]) => channel === 'local-db:sessions:get')
      .map(([, , args]) => String(args[0]));

    invoke.mockClear();
    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
    });
    const secondProbeIds = invoke.mock.calls
      .filter(([, channel]) => channel === 'local-db:sessions:get')
      .map(([, , args]) => String(args[0]));

    expect(firstProbeIds).toHaveLength(8);
    expect(secondProbeIds).toHaveLength(8);
    expect(firstProbeIds).toEqual(outside.slice(0, 8).map((item) => item.id));
    expect(secondProbeIds).toEqual(outside.slice(8, 16).map((item) => item.id));
  });

  it('前一批移除终态行后,下一批仍从原队列的紧邻候选继续', async () => {
    const d = did();
    const recent = Array.from({ length: 200 }, (_, index) => session(`recent-${index}`));
    const outside = Array.from({ length: 20 }, (_, index) => session(`outside-${index}`));
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', outside);
    invoke.mockImplementation(async (_deviceId, channel, args) => {
      if (channel === 'local-db:sessions:list') return recent;
      const sessionId = String(args[0]);
      return session(sessionId, {
        status: sessionId === 'outside-0' || sessionId === 'outside-1' ? 'archived' : 'active',
      });
    });

    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
    });
    invoke.mockClear();

    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
    });
    const secondProbeIds = invoke.mock.calls
      .filter(([, channel]) => channel === 'local-db:sessions:get')
      .map(([, , args]) => String(args[0]));

    expect(secondProbeIds).toEqual(outside.slice(8, 16).map((item) => item.id));
  });

  it('同设备并发重拉合并为单飞执行,期间新触发只补跑一次', async () => {
    const d = did();
    invoke.mockResolvedValueOnce([session('old')]).mockResolvedValueOnce([session('fresh')]);

    const first = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });
    const second = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });
    await expect(Promise.all([first, second])).resolves.toEqual(['ok', 'ok']);

    expect(invoke).toHaveBeenCalledTimes(2);
    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);
  });

  it('慢周期 merge 在途时忽略后续周期 tick,不 bump epoch 自取消', async () => {
    const d = did();
    const snapshot = deferred<Session[]>();
    invoke.mockReturnValueOnce(snapshot.promise);

    const first = refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
      coalescingMode: 'weak',
    });
    const second = refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
      coalescingMode: 'weak',
    });

    snapshot.resolve([session('slow-but-valid')]);
    await expect(Promise.all([first, second])).resolves.toEqual(['ok', 'ok']);
    expect(invoke).toHaveBeenCalledTimes(1);
    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual([
      'slow-but-valid',
    ]);
  });

  it('事件重拉传 fresh,周期 tick 不传', async () => {
    const d = did();
    invoke.mockResolvedValue([]);

    await refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });
    expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [
      200,
      'active',
      { includePinned: true, fresh: true },
    ], { background: false });

    invoke.mockClear();
    invoke.mockResolvedValue([]);
    await refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      coalescingMode: 'weak',
    });
    expect(invoke).toHaveBeenCalledWith(d, 'local-db:sessions:list', [
      200,
      'active',
      { includePinned: true },
    ], { background: true });
  });

  it('同设备补跑排队时立即作废当前 snapshot,避免旧结果短暂覆盖 push 状态', async () => {
    const d = did();
    const firstSnapshot = deferred<Session[]>();
    const secondSnapshot = deferred<Session[]>();
    const secondStarted = deferred<void>();
    invoke.mockReturnValueOnce(firstSnapshot.promise).mockImplementationOnce(() => {
      secondStarted.resolve();
      return secondSnapshot.promise;
    });

    const first = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });
    const second = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });

    firstSnapshot.resolve([session('old')]);
    await secondStarted.promise;
    expect(remoteProjectsStore.getMergedRemoteSessions()).toHaveLength(0);

    secondSnapshot.resolve([session('fresh')]);
    await expect(Promise.all([first, second])).resolves.toEqual(['ok', 'ok']);
    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);
  });

  it('事件型 refresh 排在弱周期 merge 后时保持强语义补跑', async () => {
    const d = did();
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('outside-window')]);
    const periodicSnapshot = deferred<Session[]>();
    const replacementSnapshot = deferred<Session[]>();
    const replacementStarted = deferred<void>();
    invoke.mockReturnValueOnce(periodicSnapshot.promise).mockImplementationOnce(() => {
      replacementStarted.resolve();
      return replacementSnapshot.promise;
    });

    const periodic = refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
      coalescingMode: 'weak',
    });
    const bootstrap = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });

    periodicSnapshot.resolve([session('stale')]);
    await replacementStarted.promise;
    replacementSnapshot.resolve([session('fresh')]);

    await expect(Promise.all([periodic, bootstrap])).resolves.toEqual(['ok', 'ok']);
    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);
    expect(invoke.mock.calls[1]?.[2]).toEqual([
      200,
      'active',
      { includePinned: true, fresh: true },
    ]);
    expect(invoke.mock.calls[1]?.[3]).toEqual({ background: false });
  });

  it('事件型 refresh 在途时弱周期 tick 直接复用,不补跑也不取消当前请求', async () => {
    const d = did();
    remoteProjectsStore.setDeviceSessions(d, 'Mac B', [session('outside-window')]);
    const bootstrapSnapshot = deferred<Session[]>();
    invoke.mockReturnValueOnce(bootstrapSnapshot.promise);

    const bootstrap = refreshRemoteDeviceSessions(d, 'Mac B', { sleep: noSleep });
    const periodic = refreshRemoteDeviceSessions(d, 'Mac B', {
      sleep: noSleep,
      snapshotMode: 'merge',
      coalescingMode: 'weak',
    });

    bootstrapSnapshot.resolve([session('fresh')]);

    await expect(Promise.all([bootstrap, periodic])).resolves.toEqual(['ok', 'ok']);
    expect(invoke).toHaveBeenCalledTimes(1);
    expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['fresh']);
  });
});

describe('queued refresh cancellation', () => {
  // Renderer-local coverage: one controller, two target devices. This is not
  // the shared-host topology. Transport isolation with two controllers sharing
  // one host (including a silent/non-ACKing controller) is covered separately
  // in packages/device-link/src/__tests__/client.test.ts.
  it.each(['disconnect', 'disconnect-all', 'remove', 'clear'] as const)(
    'does not revive a queued refresh after %s; another target in the same controller still works',
    async (action) => {
      const device = did();
      const otherTarget = did();
      remoteProjectsStore.setDeviceSessions(device, 'Remote', [session('cached')]);
      const pending = deferred<Session[]>();
      invoke.mockReturnValueOnce(pending.promise).mockResolvedValue([]);
      const first = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });
      const queued = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });
      if (action === 'disconnect') remoteProjectsStore.markDeviceDisconnected(device);
      if (action === 'disconnect-all') remoteProjectsStore.markAllDisconnected();
      if (action === 'remove') remoteProjectsStore.removeDevice(device);
      if (action === 'clear') remoteProjectsStore.clear();
      await expect(refreshRemoteDeviceSessions(otherTarget)).resolves.toBe('ok');
      pending.resolve([session('stale')]);
      await expect(Promise.all([first, queued])).resolves.toEqual(['superseded', 'superseded']);
      expect(invoke.mock.calls.filter(([peer]) => peer === device)).toHaveLength(1);
      expect(remoteProjectsStore.getDeviceIds()).not.toContain(device);
      expect(remoteProjectsStore.getDeviceIds()).toContain(otherTarget);
    },
  );

  it('accepts a new refresh after reconnect while the stale read is still in flight', async () => {
    const device = did();
    const pending = deferred<Session[]>();
    invoke.mockReturnValueOnce(pending.promise).mockResolvedValue([session('fresh')]);
    const first = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });
    const queued = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });
    remoteProjectsStore.markDeviceDisconnected(device);
    const reconnected = refreshRemoteDeviceSessions(device, 'Remote', { sleep: noSleep });
    expect(invoke).toHaveBeenCalledTimes(1);
    pending.resolve([session('stale')]);
    // The cancelled lifecycle must not report success from the new caller's read.
    // Reconnect waits for the stale physical request, then owns a fresh refresh.
    await expect(Promise.all([first, queued, reconnected])).resolves.toEqual(['superseded', 'superseded', 'ok']);
    expect(invoke).toHaveBeenCalledTimes(2);
    expect(remoteProjectsStore.getDeviceSessions(device).map((s) => s.id)).toEqual(['fresh']);
  });
});

describe('remote schedule mirror', () => {
  const snapshot = (readAt?: number) => ({ runs: [{
    sessionId: 'schedule-session', runId: 'run', scheduleId: 'auto', scheduleName: 'auto',
    scheduleStatus: 'active', status: 'failed', firedAt: 1, readAt,
  }], inflightRunIds: [], inflightPolicies: [] });
  it('bootstraps remote unread and refreshes only metadata on read', async () => {
    const device = did();
    invoke.mockResolvedValueOnce([session('schedule-session')]).mockResolvedValueOnce(snapshot());
    await refreshRemoteDeviceSessions(device, 'Remote', { scope: 'both' });
    expect(remoteProjectsStore.getSessionScheduleInfo('schedule-session')).toMatchObject({ hasUnreadFailedRun: true });
    invoke.mockClear().mockResolvedValue(snapshot(10));
    await refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule' });
    expect(invoke).toHaveBeenCalledTimes(2);
    expect(invoke).toHaveBeenCalledWith(device, 'maker:schedule:list-sidebar-index-runs', []);
    expect(remoteProjectsStore.getSessionScheduleInfo('schedule-session')).toMatchObject({ hasUnreadFailedRun: false });
  });
  it('discards a late response after disconnect and keeps the existing mirror on failure', async () => {
    const device = did();
    invoke.mockResolvedValueOnce([session('schedule-session')]).mockResolvedValueOnce(snapshot());
    await refreshRemoteDeviceSessions(device, 'Remote', { scope: 'both' });
    invoke.mockRejectedValueOnce(new Error('channel not allowed'));
    await refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule', maxAttempts: 1 });
    expect(remoteProjectsStore.getSessionScheduleInfo('schedule-session')?.hasUnreadFailedRun).toBe(true);
    const pending = deferred<unknown>();
    invoke.mockReturnValueOnce(pending.promise);
    const refresh = refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule' });
    remoteProjectsStore.clear();
    pending.resolve(snapshot(10));
    expect(await refresh).toBe('superseded');
    expect(remoteProjectsStore.getSessionScheduleInfo('schedule-session')).toBeUndefined();
  });
});

it('does not publish unchanged schedule snapshots or swallow revocation', async () => {
  const device = did();
  remoteProjectsStore.setDeviceSessions(device, 'Remote', [session('s')]);
  const data = { runs: [{ sessionId: 's', runId: 'r', scheduleId: 'a', scheduleName: 'a', scheduleStatus: 'active', status: 'success' }] };
  invoke.mockResolvedValue(data);
  await refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule' });
  const info = remoteProjectsStore.getSessionScheduleInfo('s');
  const listener = vi.fn();
  const off = remoteProjectsStore.subscribe(listener);
  await refreshRemoteDeviceSessions(device, undefined, { scope: 'schedule' });
  expect(remoteProjectsStore.getSessionScheduleInfo('s')).toBe(info);
  expect(listener).not.toHaveBeenCalled();
  off();
  invoke.mockResolvedValueOnce([session('s')]).mockRejectedValueOnce(new Error('DEVICE_LINK_ACCESS_REVOKED'));
  expect(await refreshRemoteDeviceSessions(device, undefined, { scope: 'both' })).toBe('revoked');
});

describe('batch reconciliation', () => {
  it('uses one batch for eight missing rows and retains metadata and removal semantics', async () => {
    const d = did();
    const recent = Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));
    const outside = Array.from({ length: 8 }, (_, i) => session(`outside-${i}`));
    remoteProjectsStore.setDeviceSessions(d, 'Mac', outside);
    const batchInvoke = vi.fn(async (_device: string, channel: string) => {
      if (channel === 'local-db:history:query') return { ok: true, sessions: [] };
      if (channel === 'local-db:sessions:list') return recent;
      if (channel === 'local-db:sessions:get-many') return outside.slice(1).map((s) => ({ ...s, title: 'updated', model: 'new-model', pinnedAt: '2026-09-12T00:00:00.000Z' }));
      throw new Error('unexpected individual read');
    });
    vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: batchInvoke } } });
    await refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });
    expect(batchInvoke).toHaveBeenCalledTimes(3);
    expect(batchInvoke).toHaveBeenLastCalledWith(d, 'local-db:sessions:get-many', [outside.map((s) => s.id)]);
    const result = remoteProjectsStore.getDeviceSessions(d);
    expect(result.find((s) => s.id === 'outside-0')).toBeUndefined();
    expect(result.find((s) => s.id === 'outside-1')).toMatchObject({ title: 'updated', model: 'new-model', pinnedAt: '2026-09-12T00:00:00.000Z' });
  });

  it.each(['timeout', 'malformed', 'revoked'])('does not multiply a %s batch failure into GET retries or erase cached rows', async (failure) => {
    const d = did();
    const outside = session('outside');
    remoteProjectsStore.setDeviceSessions(d, 'Mac', [outside]);
    const batchInvoke = vi.fn(async (_device: string, channel: string) => {
      if (channel === 'local-db:history:query') return { ok: true, sessions: [] };
      if (channel === 'local-db:sessions:list') return Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));
      if (failure === 'malformed') return [{ id: 'not-requested', status: 'active' }];
      throw new Error(failure === 'timeout' ? '[DEVICE_LINK_TIMEOUT] slow' : '[DEVICE_LINK_ACCESS_REVOKED] revoked');
    });
    vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: batchInvoke } } });
    await refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });
    expect(batchInvoke).toHaveBeenCalledTimes(3);
    expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside')).toMatchObject({ title: 'outside' });
  });

  it('keeps newer pushes when a batch response arrives late', async () => {
    const d = did();
    remoteProjectsStore.setDeviceSessions(d, 'Mac', [session('outside')]);
    const response = deferred<Session[]>();
    const started = deferred<void>();
    const batchInvoke = vi.fn(async (_device: string, channel: string) => {
      if (channel === 'local-db:history:query') return { ok: true, sessions: [] };
      if (channel === 'local-db:sessions:list') return Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));
      started.resolve();
      return response.promise;
    });
    vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: batchInvoke } } });
    const pending = refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });
    await started.promise;
    remoteProjectsStore.applyPatch(d, 'outside', { title: 'newer push' });
    response.resolve([session('outside', { title: 'old response' })]);
    await pending;
    expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside')?.title).toBe('newer push');
  });
});

it('falls back to bounded GETs for oversized batches', async () => {
  const d = did();
  remoteProjectsStore.setDeviceSessions(d, 'Mac', [session('outside')]);
  const calls = vi.fn(async (_device: string, channel: string) => {
    if (channel === 'local-db:history:query') return { ok: true, sessions: [] };
    if (channel === 'local-db:sessions:list') return Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));
    if (channel === 'local-db:sessions:get-many') throw new Error('[PRECONDITION_FAILED] REMOTE_SESSION_BATCH_TOO_LARGE');
    return session('outside', { title: 'updated' });
  });
  vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: calls } } });
  await refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });
  expect(calls).toHaveBeenCalledTimes(4);
  expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside')?.title).toBe('updated');
});

// Released hosts list no bot lanes, but provide owner-scoped history links; unit, real refresh/store path.
it('lists routine and channel tasks from legacy history with ownership, excluding canonical and group chats', async () => {
  const device = did();
  historyInvoke.mockResolvedValueOnce({ ok: true, sessions: [
    { id: 'main', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'canonical' } },
    { id: 'im', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'channel', channel: 'feishu' } },
  ], hasMore: true, nextCursor: 'next' }).mockResolvedValueOnce({ ok: true, sessions: [
    { id: 'routine', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'routine' } },
    { id: 'group', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'group' } },
  ], hasMore: false });
  invoke.mockImplementation(async (_device, channel, args) => channel === 'local-db:sessions:list'
    ? [session('ordinary')] : session(args[0], { source: 'bot' }));
  expect(await refreshRemoteDeviceSessions(device)).toBe('ok');
  const rows = remoteProjectsStore.getDeviceSessions(device);
  expect(rows.map(row => row.id).sort()).toEqual(['im', 'ordinary', 'routine']);
  expect(rows.find(row => row.id === 'im')).toMatchObject({ deviceLinkDeviceId: device, companion: { id: 'cindy', role: 'channel', channel: 'feishu' } });
  expect(historyInvoke).toHaveBeenCalledTimes(2);
});

it('does not resurrect teammate task discovery after its device snapshot is invalidated', async () => {
  const device = did();
  let finish!: (value: unknown) => void;
  invoke.mockResolvedValue([]);
  historyInvoke.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
  const refresh = refreshRemoteDeviceSessions(device);
  await Promise.resolve(); await Promise.resolve();
  remoteProjectsStore.removeDevice(device);
  finish({ ok: true, sessions: [{ id: 'im', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'channel' } }], hasMore: false });
  expect(await refresh).toBe('superseded');
  expect(remoteProjectsStore.getDeviceSessions(device)).toEqual([]);
});

// Unit / review4390134794: a blocked optional history read must not hide the
// already successful ordinary snapshot; existing tests only observe completion.
it('publishes ordinary tasks before legacy teammate discovery finishes', async () => {
  const device = did();
  const pending = deferred<{ ok: boolean; sessions: Session[]; hasMore: boolean }>();
  invoke.mockResolvedValue([session('ready')]);
  historyInvoke.mockReturnValue(pending.promise);
  const refresh = refreshRemoteDeviceSessions(device);
  await Promise.resolve(); await Promise.resolve();
  const earlyIds = remoteProjectsStore.getDeviceSessions(device).map(row => row.id);
  pending.resolve({ ok: true, sessions: [], hasMore: false });
  await expect(refresh).resolves.toBe('ok');
  expect(earlyIds).toContain('ready');
});