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。

fix(desktop): 修复远程伙伴刷新后模型回退与会话信息丢失 (#4204)

FicoWang34a4060e5a5a
diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
index e124d47bdd..f2479d8834 100644
--- a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
+++ b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts
@@ -9,6 +9,7 @@ import {
normalizeSelectedMachineId,
parseMachineSelection,
selectVisibleSessions,
+ type MachineSelection,
serializeMachineSelection,
toggleMachineSelection,
} from '@/features/device-link/selectedMachineStore';
@@ -51,9 +52,47 @@ function mkSession(id: string, deviceLinkDeviceId?: string): Session {
}
describe('selectVisibleSessions', () => {
+ afterEach(() => remoteProjectsStore.clear());
const local = [mkSession('l1'), mkSession('l2')];
const remote = [mkSession('r1', 'dev-a'), mkSession('r2', 'dev-a'), mkSession('r3', 'dev-b')];
+ it.each<{ selection: MachineSelection; expected: string[] }>([
+ { selection: MACHINE_ALL, expected: ['l1', 'l2', 'r1', 'r2', 'r3'] },
+ { selection: [MACHINE_LOCAL], expected: ['l1', 'l2'] },
+ { selection: ['dev-a'], expected: ['r1', 'r2'] },
+ { selection: [MACHINE_LOCAL, 'dev-a'], expected: ['l1', 'l2', 'r1', 'r2'] },
+ ])(
+ 'excludes companion tasks from ordinary sidebar selection $selection',
+ ({ selection, expected }) => {
+ const bots = ['active', 'archived'].map((status) => ({
+ ...mkSession(`bot-${status}`, 'dev-a'),
+ source: 'bot' as const,
+ status: status as Session['status'],
+ model: 'gpt-6-astra',
+ }));
+ remoteProjectsStore.mergeDeviceSessions('dev-a', 'MacBook', [
+ ...remote.slice(0, 2),
+ bots[0]!,
+ ]);
+ remoteProjectsStore.mergeDeviceSessions('dev-a', 'MacBook', [bots[1]!], 'archived');
+ remoteProjectsStore.mergeDeviceSessions('dev-b', 'Other Mac', remote.slice(2));
+ const mirrored = remoteProjectsStore.getMergedRemoteSessions();
+ const locals = [...local, { ...mkSession('local-bot'), source: 'bot' as const }];
+ expect(selectVisibleSessions(locals, mirrored, selection).map((row) => row.id)).toEqual(
+ expected,
+ );
+ expect(
+ remoteProjectsStore.getDeviceSessions('dev-a').filter((row) => row.source === 'bot'),
+ ).toEqual(
+ expect.arrayContaining(
+ bots.map((bot) =>
+ expect.objectContaining({ id: bot.id, status: bot.status, model: 'gpt-6-astra' }),
+ ),
+ ),
+ );
+ },
+ );
+
it('所有(默认)→ 本机 + 全部远程合并(顺序:本地在前)', () => {
expect(selectVisibleSessions(local, remote, MACHINE_ALL).map((s) => s.id)).toEqual([
'l1',
diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
index d557b44241..97f8ffd8e2 100644
--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts
@@ -114,6 +114,284 @@ describe('isTransientRemoteError', () => {
});
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)?.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)?.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)).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
diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
index a4f9755fef..eb5f548bf4 100644
--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts
@@ -237,22 +237,22 @@ function refreshTaskKey(deviceId: string, status: RemoteSessionStatus): string {
}
/**
- * 满窗口缺席行的轮询队列(per-device)。不能用 snapshot epoch 推导数组下标:前一轮
+ * 满窗口缺席行的轮询队列(per-device + status)。不能用 snapshot epoch 推导数组下标:前一轮
* 确认终态并移除候选后,数组会收缩,重算下标会跳过紧邻项。队列在每轮开始时与当前
* missing ids 对账,保留旧轮询顺序、移除已不缺席项,并把新缺席项追加到队尾。
*/
const missingStatusProbeQueues = new Map<string, string[]>();
function reconcileMissingStatusProbeQueue(
- deviceId: string,
+ queueKey: string,
missingSessionIds: readonly string[],
): string[] {
if (missingSessionIds.length === 0) {
- missingStatusProbeQueues.delete(deviceId);
+ missingStatusProbeQueues.delete(queueKey);
return [];
}
const missingIds = new Set(missingSessionIds);
- const previous = missingStatusProbeQueues.get(deviceId) ?? [];
+ const previous = missingStatusProbeQueues.get(queueKey) ?? [];
const queuedIds = new Set<string>();
const queue: string[] = [];
for (const sessionId of previous) {
@@ -265,7 +265,7 @@ function reconcileMissingStatusProbeQueue(
queuedIds.add(sessionId);
queue.push(sessionId);
}
- missingStatusProbeQueues.set(deviceId, queue);
+ missingStatusProbeQueues.set(queueKey, queue);
return queue;
}
@@ -332,11 +332,16 @@ async function probeMissingSessionStatuses(
deviceId: string,
epoch: number,
missingSessionIds: readonly string[],
+ status: RemoteSessionStatus,
): Promise<void> {
- const queue = reconcileMissingStatusProbeQueue(deviceId, missingSessionIds);
+ const queueKey = refreshTaskKey(deviceId, status);
+ const queue = reconcileMissingStatusProbeQueue(queueKey, missingSessionIds);
if (queue.length === 0) return;
const count = Math.min(MISSING_STATUS_PROBE_LIMIT, queue.length);
const candidates = queue.slice(0, count);
+ const snapshots = new Map(
+ remoteProjectsStore.getDeviceSessions(deviceId).map((session) => [session.id, session]),
+ );
const results = await Promise.all(
candidates.map(async (sessionId) => {
try {
@@ -352,9 +357,15 @@ async function probeMissingSessionStatuses(
}),
);
// 更强的 refresh / remove / disconnect 已使本轮失效时,不应用迟到的补查结果。
- if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, 'active')) return;
+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return;
const terminalIds = new Set<string>();
for (const result of results) {
+ // A live push accepted while this GET was in flight is newer than its
+ // snapshot. Do not roll its model/status back; the next tick can reconcile.
+ const current = remoteProjectsStore
+ .getDeviceSessions(deviceId)
+ .find((session) => session.id === result.sessionId);
+ if (current !== snapshots.get(result.sessionId)) continue;
if (result.errorCode === 'NOT_FOUND') {
terminalIds.add(result.sessionId);
remoteProjectsStore.applyPatch(deviceId, result.sessionId, { status: 'deleted' });
@@ -364,7 +375,7 @@ async function probeMissingSessionStatuses(
if (!result.value || typeof result.value !== 'object') continue;
const session = result.value as Partial<Session>;
if (session.id !== result.sessionId) continue;
- if (session.status === 'archived' || session.status === 'deleted') {
+ if (session.status === 'deleted' || (status === 'active' && session.status === 'archived')) {
terminalIds.add(result.sessionId);
remoteProjectsStore.applyPatch(deviceId, result.sessionId, {
status: session.status,
@@ -373,8 +384,9 @@ async function probeMissingSessionStatuses(
removeRemoteSessionActivityEntry(result.sessionId);
continue;
}
- // sessions:get 返回窗口外 active 行时同样是权威快照,回填 title / pinnedAt / model 等
+ // sessions:get 返回缺席行时同样是权威快照,回填 title / pinnedAt / model 等
// 元数据;否则丢失 patched push 后会永久保留旧字段。
+ if (session.status !== status) terminalIds.add(result.sessionId);
remoteProjectsStore.applyPatch(deviceId, result.sessionId, { ...session });
}
const nextQueue = [
@@ -382,9 +394,9 @@ async function probeMissingSessionStatuses(
...candidates.filter((sessionId) => !terminalIds.has(sessionId)),
];
if (nextQueue.length === 0) {
- missingStatusProbeQueues.delete(deviceId);
+ missingStatusProbeQueues.delete(queueKey);
} else {
- missingStatusProbeQueues.set(deviceId, nextQueue);
+ missingStatusProbeQueues.set(queueKey, nextQueue);
}
}
@@ -423,30 +435,37 @@ async function runRefreshRemoteDeviceSessions(
if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status))
return 'superseded';
const sessions = parseRemoteSessionList(value, status);
+ // Companions are fetched by resource:get + sessions:get, not by the
+ // ordinary task list. Keep their live state and reconcile them by id,
+ // even when the ordinary list is empty or is a full replacement.
+ const incomingIds = new Set(sessions.map((session) => session.id));
+ const missingSessions = remoteProjectsStore
+ .getDeviceSessions(deviceId, status)
+ .filter((session) => !incomingIds.has(session.id));
+ const missingCompanionIds = missingSessions
+ .filter((session) => session.source === 'bot')
+ .map((session) => session.id);
if ((opts.snapshotMode ?? 'merge') === 'merge') {
- const incomingIds = new Set(sessions.map((session) => session.id));
- const missingSessionIds = remoteProjectsStore
- .getDeviceSessions(deviceId, status)
- .filter((session) => !incomingIds.has(session.id))
- .map((session) => session.id);
+ const missingSessionIds = missingSessions.map((session) => session.id);
// archived 使用与本地侧栏一致的 1000 条产品窗口,可直接替换并清掉断线期间的
// 删除 / 取消归档陈旧行;active 仍保持 200 条轻量窗口,满窗时有界补查缺席缓存。
if (status === 'archived' || sessions.length < LIST_LIMIT) {
if (status === 'active') {
- missingStatusProbeQueues.delete(deviceId);
- for (const sessionId of missingSessionIds) {
- removeRemoteSessionActivityEntry(sessionId);
+ for (const session of missingSessions) {
+ if (session.source !== 'bot') removeRemoteSessionActivityEntry(session.id);
}
}
remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions, status);
+ await probeMissingSessionStatuses(deviceId, epoch, missingCompanionIds, status);
} else {
remoteProjectsStore.mergeDeviceSessions(deviceId, deviceName, sessions, status);
if (status === 'active') {
- await probeMissingSessionStatuses(deviceId, epoch, missingSessionIds);
+ await probeMissingSessionStatuses(deviceId, epoch, missingSessionIds, status);
}
}
} else {
remoteProjectsStore.setDeviceSessions(deviceId, deviceName, sessions, status);
+ await probeMissingSessionStatuses(deviceId, epoch, missingCompanionIds, status);
}
}
if (opts.scope === 'schedule' || opts.scope === 'both') {
@@ -477,7 +496,9 @@ async function runRefreshRemoteDeviceSessions(
log.debug('remote schedule index unavailable');
}
}
- return 'ok'; // 成功
+ return remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)
+ ? 'ok'
+ : 'superseded';
} catch (err) {
if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) {
return 'superseded';
diff --git a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
index 8ed2297de3..3faed93c54 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteProjectsStore.ts
@@ -447,7 +447,13 @@ const actions = {
const incomingIds = new Set(stamped.map((session) => session.id));
const preserved =
existing?.sessions
- .filter((session) => session.status !== status && !incomingIds.has(session.id))
+ // The ordinary sessions:list excludes companions. Absence from that
+ // snapshot cannot retire a companion loaded through its resource link.
+ // Its own authoritative patch/get still controls status and deletion.
+ .filter(
+ (session) =>
+ (session.status !== status || session.source === 'bot') && !incomingIds.has(session.id),
+ )
.map((session) =>
session.deviceLinkDeviceName === deviceName &&
session.deviceLinkConnectionStatus === connectionStatus
diff --git a/apps/desktop/src/renderer/features/device-link/selectedMachineStore.ts b/apps/desktop/src/renderer/features/device-link/selectedMachineStore.ts
index 983b967b76..1eeee69ed9 100644
--- a/apps/desktop/src/renderer/features/device-link/selectedMachineStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/selectedMachineStore.ts
@@ -205,10 +205,13 @@ export function selectVisibleSessions(
remoteSessions: Session[],
selection: MachineSelection,
): Session[] {
- if (selection === MACHINE_ALL) return [...localSessions, ...remoteSessions];
+ // Companion metadata remains in the mirror for chat, but belongs only to the Bots UI.
+ const visibleLocal = localSessions.filter((session) => session.source !== 'bot');
+ const visibleRemote = remoteSessions.filter((session) => session.source !== 'bot');
+ if (selection === MACHINE_ALL) return [...visibleLocal, ...visibleRemote];
const set = new Set(selection);
- const out = set.has(MACHINE_LOCAL) ? [...localSessions] : [];
- for (const s of remoteSessions) {
+ const out = set.has(MACHINE_LOCAL) ? [...visibleLocal] : [];
+ for (const s of visibleRemote) {
if (s.deviceLinkDeviceId && set.has(s.deviceLinkDeviceId)) out.push(s);
}
return out;
diff --git a/apps/desktop/src/renderer/lib/__tests__/conversationSearchFanout.test.ts b/apps/desktop/src/renderer/lib/__tests__/conversationSearchFanout.test.ts
index a3d622c021..24522f981c 100644
--- a/apps/desktop/src/renderer/lib/__tests__/conversationSearchFanout.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/conversationSearchFanout.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import type { Session } from '@/lib/ccAgent.types';
import {
@@ -16,12 +16,13 @@ import {
shouldReleaseConversationSearchLock,
stampRemoteSearchResponse,
} from '@/lib/conversationSearchFanout';
-import { searchConversationsAcrossOrigins } from '@/lib/conversationSearchService';
+import { searchConversations, searchConversationsAcrossOrigins } from '@/lib/conversationSearchService';
import type {
ConversationSearchRequest,
ConversationSearchResponse,
ConversationSearchResultItem,
} from '../../../shared/conversationSearch';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { MACHINE_ALL, MACHINE_LOCAL } from '@/features/device-link/selectedMachineStore';
function session(partial: Partial<Session> & Pick<Session, 'id' | 'title'>): Session {
@@ -300,6 +301,23 @@ describe('merge and stamp', () => {
});
describe('searchCachedSessionsByTitle', () => {
+ it('excludes active and archived companions before ranking and limiting title matches', () => {
+ const rows = [
+ session({ id: 'bot-active', title: 'needle', source: 'bot' }),
+ session({ id: 'bot-archived', title: 'needle', source: 'bot', status: 'archived' }),
+ session({ id: 'ordinary', title: 'Needle planning', source: 'desktop' }),
+ session({ id: 'legacy', title: 'Needle notes' }),
+ ];
+ const page = searchCachedSessionsByTitle(rows, { query: 'needle', limit: 2 });
+ expect(page.results.map((item) => item.session.id).sort()).toEqual(['legacy', 'ordinary']);
+ expect(
+ searchCachedSessionsByTitle(rows, {
+ query: 'needle',
+ filters: { sessionIds: ['bot-active', 'bot-archived'] },
+ }).results,
+ ).toEqual([]);
+ });
+
it('matches visible titles and skips workers', () => {
const request: ConversationSearchRequest = { query: 'remote', limit: 10 };
const page = searchCachedSessionsByTitle(
@@ -320,6 +338,79 @@ describe('searchCachedSessionsByTitle', () => {
});
});
+describe('ordinary search against a retained remote companion mirror', () => {
+ afterEach(() => {
+ remoteProjectsStore.clear();
+ vi.unstubAllGlobals();
+ });
+
+ it.each(['offline', 'disconnect', 'timeout', 'legacy-list', 'legacy-cache'] as const)(
+ 'hides companion titles on %s fallback while preserving their model metadata',
+ async (mode) => {
+ const deviceId = 'companion-search-host';
+ const bot = session({
+ id: 'bot-active',
+ title: 'needle',
+ source: 'bot',
+ model: 'gpt-6-astra',
+ agentKind: 'codex',
+ });
+ const archivedBot = { ...bot, id: 'bot-archived', status: 'archived' as const };
+ const ordinary = session({ id: 'ordinary', title: 'Needle planning', source: 'desktop' });
+ remoteProjectsStore.pinSessionOrigin(deviceId, bot.id);
+ remoteProjectsStore.mergeDeviceSessions(deviceId, 'MacBook', [bot, ordinary]);
+ remoteProjectsStore.mergeDeviceSessions(deviceId, 'MacBook', [archivedBot], 'archived');
+ // An ordinary list excludes companions; their chat metadata survives its refresh.
+ remoteProjectsStore.setDeviceSessions(deviceId, 'MacBook', [ordinary]);
+ remoteProjectsStore.markDeviceDisconnected(deviceId);
+ const snapshot = remoteProjectsStore.getDeviceSessions(deviceId);
+ const invoke = vi.fn(async (_device, channel) => {
+ if (mode === 'disconnect') throw new Error('[DEVICE_LINK_NOT_CONNECTED] closed');
+ if (mode === 'timeout') throw new Error('[DEVICE_LINK_TIMEOUT] unavailable');
+ if (channel === 'local-db:conversations:search')
+ throw new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] unsupported');
+ if (mode === 'legacy-list') return [bot, archivedBot, ordinary];
+ throw new Error('[DEVICE_LINK_TIMEOUT] list unavailable');
+ });
+ vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke } } });
+ const page = await searchConversations(
+ { query: 'needle', limit: 1 },
+ {
+ origins: [
+ {
+ kind: 'remote',
+ deviceId,
+ deviceName: 'MacBook',
+ connected: mode !== 'offline',
+ sessionIds: null,
+ },
+ ],
+ },
+ );
+ expect(page.results.map((item) => item.session.id)).toEqual(['ordinary']);
+ expect(page.remoteResults?.map((item) => item.session.id)).toEqual(['ordinary']);
+ expect(page.results[0]?.session.deviceLinkDeviceId).toBe(deviceId);
+ expect(invoke).toHaveBeenCalledTimes(
+ mode === 'offline' ? 0 : mode.startsWith('legacy') ? 2 : 1,
+ );
+ expect(remoteProjectsStore.getDeviceSessions(deviceId)).toBe(snapshot);
+ expect(snapshot.filter((row) => row.source === 'bot')).toEqual(
+ expect.arrayContaining(
+ [bot, archivedBot].map((row) =>
+ expect.objectContaining({
+ id: row.id,
+ status: row.status,
+ model: 'gpt-6-astra',
+ agentKind: 'codex',
+ deviceLinkDeviceId: deviceId,
+ }),
+ ),
+ ),
+ );
+ },
+ );
+});
+
describe('searchConversationsAcrossOrigins', () => {
const request: ConversationSearchRequest = {
query: 'needle',
diff --git a/apps/desktop/src/renderer/lib/conversationSearchFanout.ts b/apps/desktop/src/renderer/lib/conversationSearchFanout.ts
index f0a348648b..b47c4234ba 100644
--- a/apps/desktop/src/renderer/lib/conversationSearchFanout.ts
+++ b/apps/desktop/src/renderer/lib/conversationSearchFanout.ts
@@ -320,7 +320,8 @@ export function searchCachedSessionsByTitle(
}> = [];
sessions.forEach((session, index) => {
- if (isOrcaWorkerSession(session)) return;
+ // The mirror includes companion chat metadata; ordinary search must not expose it.
+ if (session.source === 'bot' || isOrcaWorkerSession(session)) return;
if (allowed && !allowed.has(session.id)) return;
if (!matchesWorkingDirSet(session.workingDir, workingDirs)) return;
if (!matchesStatus(session.status, filters.status ?? 'all')) return;