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(agent): 支持本机与在线授权设备的历史发现和搜索 (#5415)

Dash905f7ed4bc0d
diff --git a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts
index 1a1d8a5fd6..51412845f5 100644
--- a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts
@@ -5,6 +5,52 @@ import {
afterEach(() => setRemoteBotSessionLookup(null));
+it.each([false, true])('rechecks parent references on repeated history delivery (batch=%s)', async (useBatch) => {
+ let parentAccess: 'visible' | 'hidden' | 'missing' = 'visible';
+ const single = vi.fn(async (id: string) => id === 'parent' ? parentAccess : 'ordinary' as const);
+ const batch = vi.fn(async (ids: readonly string[]) => new Map(ids.map((id) => [id, id === 'parent' ? parentAccess : 'ordinary' as const])));
+ setRemoteBotSessionLookup(single, useBatch ? batch : null);
+ const result = { ok: true, sessions: [{ id: 'child', parentSessionId: 'parent' }], nextCursor: 'cursor', hasMore: true };
+ expect(await projectRemoteSessionResult('local-db:history:query', result)).toEqual(result);
+ for (const status of ['hidden', 'missing'] as const) {
+ parentAccess = status;
+ expect(await projectRemoteSessionResult('local-db:history:query', result)).toEqual({
+ ...result, sessions: [{ id: 'child' }],
+ });
+ }
+ expect(result.sessions[0].parentSessionId).toBe('parent');
+ if (useBatch) {
+ expect(batch).toHaveBeenLastCalledWith(['child', 'parent'], 'session');
+ expect(single).not.toHaveBeenCalled();
+ }
+});
+
+it('rejects stale history pages without returning hidden content or pagination metadata', async () => {
+ let hide = false;
+ setRemoteBotSessionLookup(async (id) => hide && id === 'secret' ? 'hidden' : 'ordinary');
+ const result = { ok: true, hits: [
+ { sessionId: 'normal', context: [{ content: 'visible' }] },
+ { sessionId: 'secret', context: [{ content: 'private' }] },
+ ], sessions: { normal: { title: 'Normal' }, secret: { title: 'Private title' } }, pool_size: 2, pool_capped: true, nextCursor: 'opaque', hasMore: true };
+ expect(await projectRemoteSessionResult('local-db:history:query', result)).toMatchObject({ hits: result.hits });
+ hide = true;
+ await expect(projectRemoteSessionResult('local-db:history:query', result)).rejects.toThrow('[NOT_FOUND] History page is no longer available');
+ for (const sessions of [[{ id: 'normal' }, { id: 'secret' }], [{ id: 'secret' }]]) {
+ await expect(projectRemoteSessionResult('local-db:history:query', { ok: true, sessions, nextCursor: 'cursor', hasMore: true })).rejects.toThrow('[NOT_FOUND] History page is no longer available');
+ }
+ await expect(projectRemoteSessionResult('local-db:history:query', { ...result, hits: [result.hits[1]] })).rejects.toThrow('[NOT_FOUND] History page is no longer available');
+});
+
+it('validates history target IDs without probing existence and fails closed before initialization', async () => {
+ const args = [{ tool: 'search_chat_history', args: { session_ids: ['secret'] } }];
+ await expect(assertRemoteBotInvocationAllowed(args, 'local-db:history:query')).rejects.toThrow('HOST_NOT_READY');
+ const lookup = vi.fn(async () => 'hidden' as const);
+ setRemoteBotSessionLookup(lookup);
+ await expect(assertRemoteBotInvocationAllowed(args, 'local-db:history:query')).resolves.toBeUndefined();
+ await expect(assertRemoteBotInvocationAllowed([{ tool: 'search_chat_history', args: { session_ids: Array(51).fill('id') } }], 'local-db:history:query')).rejects.toThrow('INVALID_PARAMS');
+ expect(lookup).not.toHaveBeenCalled();
+});
+
it('checks the normalized source task before remote Review and rechecks visibility changes', async () => {
let hidden = false;
const lookup = vi.fn(async () => hidden ? 'hidden' as const : 'ordinary' as const);
diff --git a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
index 536019abae..c858e9092b 100644
--- a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
+++ b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
@@ -1,3 +1,5 @@
+import { DL_HISTORY_QUERY_CHANNEL } from '@cindy/device-link';
+
export type RemoteBotSessionAccess = 'ordinary' | 'visible' | 'hidden' | 'missing';
type Lookup = (sessionId: string, kind?: 'session' | 'bot') => Promise<RemoteBotSessionAccess>;
export type RemoteBotSessionBatchLookup = (ids: readonly string[], kind: 'session' | 'bot') => Promise<ReadonlyMap<string, RemoteBotSessionAccess>>;
@@ -24,6 +26,16 @@ function sessionIds(value: unknown): string[] {
/** Resolve channel-specific Bot IDs before checking generic Session references. */
export async function assertRemoteBotInvocationAllowed(args: unknown[], channel = ''): Promise<void> {
+ if (channel === DL_HISTORY_QUERY_CHANNEL) {
+ if (!lookup) throw new Error('[HOST_NOT_READY] History visibility is not ready');
+ const ids = record(record(args[0])?.args)?.session_ids;
+ if (ids !== undefined && (!Array.isArray(ids) || ids.length > 50 || ids.some((id) => typeof id !== 'string' || !id || id.length > 512))) {
+ throw new Error('[INVALID_PARAMS] Invalid history session IDs');
+ }
+ // The source query applies visibility before ranking/pagination. Looking up
+ // requested IDs here would distinguish hidden sessions from missing ones.
+ return;
+ }
if (channel === 'maker:review:start') {
const id = record(args[0])?.sourceSessionId;
if (typeof id !== 'string' || !id.trim() || id.length > 512) {
@@ -95,6 +107,47 @@ export async function assertRemoteBotInvocationAllowed(args: unknown[], channel
}
export async function projectRemoteSessionResult(channel: string, value: unknown): Promise<unknown> {
+ if (channel === DL_HISTORY_QUERY_CHANNEL) {
+ if (!lookup) throw new Error('[HOST_NOT_READY] History visibility is not ready');
+ // Rechecked on normal, cached and queued delivery by the existing dispatch path.
+ const row = record(value);
+ if (!row || row.ok !== true) return value;
+ const listing = Array.isArray(row.sessions);
+ if (!listing && !Array.isArray(row.hits)) throw new Error('[INVALID_PARAMS] Invalid history result');
+ const entries = (listing ? row.sessions : row.hits) as unknown[];
+ const ids = [...new Set(entries.flatMap((item) => {
+ const entry = record(item);
+ return [listing ? entry?.id : entry?.sessionId, ...(listing ? [entry?.parentSessionId] : [])]
+ .filter((id): id is string => typeof id === 'string');
+ }))];
+ const access = new Map<string, RemoteBotSessionAccess>();
+ if (batchLookup) {
+ for (const [id, status] of await batchLookup(ids, 'session')) access.set(id, status);
+ } else {
+ for (const id of ids) access.set(id, await lookup(id, 'session'));
+ }
+ const visible = (id: unknown) => typeof id === 'string'
+ && (access.get(id) === 'ordinary' || access.get(id) === 'visible');
+ // The page and its foreign references share one fresh, source-owned lookup.
+ // Missing or hidden page members invalidate pagination; optional parents
+ // are simply omitted, including on cached/queued delivery after a hide.
+ if (entries.some((item) => !visible(listing ? record(item)?.id : record(item)?.sessionId))) {
+ throw new Error('[NOT_FOUND] History page is no longer available');
+ }
+ if (Array.isArray(row.sessions)) {
+ const sessions = row.sessions.map((item) => {
+ const { parentSessionId, ...session } = record(item)!;
+ return visible(parentSessionId) ? { ...session, parentSessionId } : session;
+ });
+ return { ...row, sessions };
+ }
+ const allowed = new Set(entries.map((hit) => record(hit)?.sessionId));
+ return { ...row,
+ sessions: Object.fromEntries(Object.entries(record(row.sessions) ?? {}).filter(([id]) => allowed.has(id))),
+ // Hidden results must not reveal their content, metadata or candidate count.
+ pool_size: undefined,
+ };
+ }
if (!lookup || ![
'local-db:task-tags:execute',
'local-db:sessions:get', 'local-db:sessions:get-many', 'local-db:sessions:list', 'maker:list-active', 'local-db:sessions:interrupted-pending', 'local-db:bots:get', 'local-db:bots:list', 'maker:remote-resources:get', 'maker:remote-resources:list'].includes(channel)) return value;
diff --git a/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts b/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts
new file mode 100644
index 0000000000..7059f8263d
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/remoteHistoryPagination.test.ts
@@ -0,0 +1,322 @@
+import path from 'node:path';
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { listSessionsForHistory } from '../chatHistoryReader';
+import { searchChatHistoryHybrid } from '../chatHistorySearch';
+import { readRemoteBotSessionAccessBatch } from '../ipc/botRemoteSessionAccess';
+import { setChatEmbeddingEnabled } from '../../embedders/chat-history-embedder';
+import { registerHistoryQueryIpc } from '../ipc/historyQuery';
+import { runDeviceLinkInvokeContext } from '../../device-link/invoke-context';
+import {
+ assertRemoteBotInvocationAllowed,
+ projectRemoteSessionResult,
+ setRemoteBotSessionLookup,
+} from '../../device-link/remoteBotSessionBoundary';
+
+const state = vi.hoisted(() => ({ client: null as any }));
+const handlers = vi.hoisted(() => new Map<string, (...args: any[]) => any>());
+vi.mock('../client/current', () => ({ getDbClient: () => state.client }));
+vi.mock('../../embedding-host', () => ({
+ getEmbeddingService: () => ({ embedSync: async () => ({ embeddings: [[1]] }) }),
+}));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => 1,
+ isDataOwnerBroadcastScopeCurrent: () => true,
+}));
+vi.mock('electron', () => ({
+ app: { getPath: () => '' },
+ ipcMain: {
+ handle: (name: string, handler: (...args: any[]) => any) => handlers.set(name, handler),
+ },
+}));
+vi.mock('../../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));
+
+// Linux has no bundled sqlite-vec; keep the SQL fixture on every platform.
+const modes = [
+ 'sql-fixture',
+ ...(['darwin', 'win32'].includes(process.platform) ? ['native-vec'] : []),
+];
+describe.each(modes)('%s remote history visibility', (mode) => {
+ let db: Database.Database;
+ beforeEach(() => {
+ db = new Database(':memory:');
+ db.exec(`
+ CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT DEFAULT '', working_dir TEXT,
+ agent_kind TEXT DEFAULT 'codex', workspace_kind TEXT DEFAULT 'project', model TEXT DEFAULT '',
+ status TEXT DEFAULT 'active', source TEXT DEFAULT 'desktop', orca_role TEXT,
+ parent_session_id TEXT, created_at INTEGER, updated_at INTEGER, user_send_at INTEGER);
+ CREATE TABLE messages (id TEXT PRIMARY KEY, client_id TEXT, session_id TEXT, role TEXT,
+ content TEXT, tool_use_id TEXT, agent_meta TEXT, agent_kind TEXT, created_at INTEGER, rewind_at INTEGER);
+ CREATE VIRTUAL TABLE messages_fts USING fts5(message_id UNINDEXED, content);
+ CREATE TABLE bot_profiles (id TEXT PRIMARY KEY, hidden_at INTEGER, status TEXT);
+ CREATE TABLE bot_session_links (session_id TEXT PRIMARY KEY, bot_id TEXT);
+ CREATE TABLE embedding_jobs (source_id TEXT);
+ CREATE TABLE chat_messages_vec_v1 (distance REAL);
+ INSERT INTO bot_profiles VALUES ('visible', NULL, 'active'), ('zero', 0, 'active'),
+ ('hidden', 1, 'active'), ('archived', NULL, 'archived');
+ `);
+ // Hidden matches exceed both the FTS limit (50) and KNN over-fetch limit (250).
+ const ids = [
+ ...Array.from({ length: 300 }, (_, i) => `hidden-${i}`),
+ 'archived',
+ 'orphan',
+ 'ordinary',
+ 'visible',
+ 'zero',
+ ];
+ for (const [i, id] of ids.entries()) {
+ const bot = id.startsWith('hidden-') ? 'hidden' : id;
+ db.prepare(
+ 'INSERT INTO sessions (id, source, created_at, updated_at) VALUES (?, ?, ?, ?)',
+ ).run(id, id === 'ordinary' ? 'desktop' : 'bot', i + 1, i + 1);
+ if (id !== 'orphan' && id !== 'ordinary')
+ db.prepare('INSERT INTO bot_session_links VALUES (?, ?)').run(id, bot);
+ db.prepare(
+ "INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, 'user', ?, ?)",
+ ).run(id, id, id, JSON.stringify('needle'), i + 1);
+ db.prepare('INSERT INTO messages_fts VALUES (?, ?)').run(id, 'needle');
+ db.prepare('INSERT INTO embedding_jobs VALUES (?)').run(id);
+ db.prepare('INSERT INTO chat_messages_vec_v1 VALUES (?)').run(i + 1);
+ }
+ if (mode === 'native-vec') {
+ db.loadExtension(
+ path.resolve(
+ __dirname,
+ '../../../../native/sqlite-vec',
+ `${process.platform}-${process.arch}`,
+ process.platform === 'win32' ? 'vec0.dll' : 'vec0.dylib',
+ ),
+ );
+ db.exec(
+ 'DROP TABLE chat_messages_vec_v1; CREATE VIRTUAL TABLE chat_messages_vec_v1 USING vec0(embedding float[1])',
+ );
+ for (const [i] of ids.entries()) {
+ db.prepare('INSERT INTO chat_messages_vec_v1(rowid, embedding) VALUES (?, ?)').run(
+ BigInt(i + 1),
+ JSON.stringify([i + 2]),
+ );
+ }
+ }
+ state.client = {
+ drizzle: drizzle(db),
+ vecAvailable: true,
+ // Deterministic KNN fixture; all production joins, visibility filters and limits execute in SQLite.
+ query: async (sql: string, params: unknown[] = []) =>
+ db
+ .prepare(mode === 'native-vec' ? sql : sql.replace('embedding MATCH ?', '? IS NOT NULL'))
+ .all(...params),
+ queryOne: async (sql: string, params: unknown[] = []) => db.prepare(sql).get(...params),
+ };
+ setChatEmbeddingEnabled(true);
+ setRemoteBotSessionLookup(async (id, kind) =>
+ (await readRemoteBotSessionAccessBatch([id], kind)).get(id) ?? 'hidden',
+ readRemoteBotSessionAccessBatch,
+ );
+ registerHistoryQueryIpc();
+ });
+ afterEach(() => {
+ setRemoteBotSessionLookup(null);
+ handlers.clear();
+ db.close();
+ state.client = null;
+ });
+
+ const listArgs = {
+ workdir: null,
+ fromMs: null,
+ toMs: null,
+ agentKind: null,
+ includeDeleted: false,
+ limit: 1,
+ cursor: null,
+ order: 'asc' as const,
+ remoteVisibleOnly: true,
+ };
+ const searchArgs = {
+ query: 'needle',
+ sessionIds: null,
+ workdir: null,
+ fromMs: null,
+ toMs: null,
+ agentKind: null,
+ roles: null,
+ contextRadius: 0,
+ limit: 1,
+ offset: 0,
+ remoteVisibleOnly: true,
+ };
+
+ const invokeHistory = async (tool: string, args: Record<string, unknown>) => {
+ const channel = 'local-db:history:query';
+ const request = { tool, args };
+ await assertRemoteBotInvocationAllowed([request], channel);
+ const result = await runDeviceLinkInvokeContext(
+ { controllerDeviceId: 'owner', channel },
+ () => handlers.get(channel)!({}, request),
+ );
+ await assertRemoteBotInvocationAllowed([request], channel);
+ return projectRemoteSessionResult(channel, result);
+ };
+
+ it('paginates the visible list without hidden rows consuming slots or cursors', async () => {
+ const first = await listSessionsForHistory(listArgs);
+ const second = await listSessionsForHistory({ ...listArgs, cursor: first.nextCursor });
+ const last = await listSessionsForHistory({ ...listArgs, cursor: second.nextCursor });
+ expect([first, second, last].map((page) => page.items.map((row) => row.id))).toEqual([
+ ['ordinary'],
+ ['visible'],
+ ['zero'],
+ ]);
+ expect(first.nextCursor?.id).toBe('ordinary');
+ expect(last).toMatchObject({ hasMore: false, nextCursor: null });
+ expect(
+ (await listSessionsForHistory({ ...listArgs, remoteVisibleOnly: false })).items[0].id,
+ ).toBe('hidden-0');
+ expect(
+ Object.fromEntries(
+ await readRemoteBotSessionAccessBatch([
+ 'ordinary',
+ 'visible',
+ 'zero',
+ 'hidden-0',
+ 'archived',
+ 'orphan',
+ ]),
+ ),
+ ).toEqual({
+ ordinary: 'ordinary',
+ visible: 'visible',
+ zero: 'visible',
+ 'hidden-0': 'hidden',
+ archived: 'hidden',
+ orphan: 'hidden',
+ });
+ });
+
+ it.each([true, false])(
+ 'filters both retrieval arms before ranks, pool metadata and pagination (FTS only=%s)',
+ async (skipVector) => {
+ const pages = await Promise.all(
+ [0, 1, 2].map((offset) => searchChatHistoryHybrid({ ...searchArgs, skipVector, offset })),
+ );
+ expect(pages.map((page) => page.hits.map((hit) => hit.sessionId))).toEqual([
+ ['ordinary'],
+ ['visible'],
+ ['zero'],
+ ]);
+ expect(pages.map((page) => page.nextOffset)).toEqual([1, 2, null]);
+ expect(pages.map((page) => page.hasMore)).toEqual([true, true, false]);
+ expect(pages.every((page) => page.poolSize === 3 && !page.poolCapped)).toBe(true);
+ expect(pages[0].hits[0]).toMatchObject({ ftsRank: 1, vectorRank: skipVector ? null : 1 });
+ expect(pages[0].vectorUsed).toBe(!skipVector);
+ // Removing inaccessible data leaves visible ranking and pagination unchanged.
+ db.exec("DELETE FROM messages_fts WHERE message_id NOT IN ('ordinary', 'visible', 'zero')");
+ const withoutHidden = await searchChatHistoryHybrid({ ...searchArgs, skipVector });
+ expect(withoutHidden).toEqual(pages[0]);
+ },
+ );
+
+ it('returns a terminal empty page for an all-hidden scope', async () => {
+ const page = await listSessionsForHistory({
+ ...listArgs,
+ sessionIds: ['hidden-0', 'archived', 'orphan'],
+ });
+ expect(page).toEqual({ items: [], nextCursor: null, hasMore: false });
+ const result = await searchChatHistoryHybrid({
+ ...searchArgs,
+ sessionIds: ['hidden-0', 'archived', 'orphan'],
+ });
+ expect(result).toMatchObject({
+ hits: [],
+ sessions: {},
+ nextOffset: null,
+ hasMore: false,
+ poolSize: 0,
+ poolCapped: false,
+ vectorUsed: false,
+ });
+ });
+
+ it('retrieves semantic-only visible hits beyond 250 closer hidden vectors', async () => {
+ db.exec('DELETE FROM messages_fts');
+ const result = await searchChatHistoryHybrid({ ...searchArgs, limit: 10 });
+ expect(result.vectorUsed).toBe(true);
+ expect(result.hits.map((hit) => hit.sessionId)).toEqual(['ordinary', 'visible', 'zero']);
+ expect(result.hits.every((hit) => hit.ftsRank === null)).toBe(true);
+ expect(result).toMatchObject({
+ poolSize: 3,
+ poolCapped: false,
+ hasMore: false,
+ nextOffset: null,
+ });
+ const scoped = await searchChatHistoryHybrid({
+ ...searchArgs,
+ sessionIds: ['visible'],
+ roles: ['user'],
+ fromMs: 0,
+ });
+ expect(scoped.vectorUsed).toBe(true);
+ expect(scoped.hits.map((hit) => hit.sessionId)).toEqual(['visible']);
+ });
+
+ it.each([true, false])('does not distinguish inaccessible IDs from missing IDs across the remote query (FTS only=%s)', async (ftsOnly) => {
+ setChatEmbeddingEnabled(!ftsOnly);
+ const invoke = (session_ids: string[]) => invokeHistory('search_chat_history', { query: 'needle', session_ids, limit: 1 });
+ for (const ids of [['hidden-0'], ['archived'], ['orphan'], ['hidden-0', 'archived', 'orphan', 'missing']]) {
+ const empty = await invoke(ids);
+ expect(empty).toMatchObject({ ok: true, hits: [], sessions: {}, hasMore: false, nextCursor: null });
+ const mixedIds = ['ordinary', 'visible', ...ids];
+ const visible = await invoke(mixedIds);
+ expect(visible).toMatchObject({ ok: true, hits: [{ sessionId: 'ordinary' }], hasMore: true });
+ // Use identical requests before/after deletion, including the echoed scope.
+ // No response field may reveal whether inaccessible targets still exist.
+ db.exec('SAVEPOINT inaccessible');
+ try {
+ for (const id of ids) db.prepare('DELETE FROM sessions WHERE id = ?').run(id);
+ expect(await invoke(ids)).toEqual(empty);
+ expect(await invoke(mixedIds)).toEqual(visible);
+ } finally {
+ db.exec('ROLLBACK TO inaccessible; RELEASE inaccessible');
+ }
+ }
+ });
+
+ it('projects parent references using current source visibility without changing local history', async () => {
+ for (const parent of ['visible', 'zero', 'hidden-0', 'archived', 'orphan', 'missing']) {
+ db.prepare("UPDATE sessions SET parent_session_id = ? WHERE id = 'ordinary'").run(parent);
+ const result = await invokeHistory('list_sessions', { order: 'asc', limit: 1 });
+ expect(result).toMatchObject({
+ ok: true,
+ sessions: [{ id: 'ordinary' }],
+ hasMore: true,
+ });
+ if (['visible', 'zero'].includes(parent)) {
+ expect(result).toHaveProperty('sessions.0.parentSessionId', parent);
+ } else {
+ expect(result).not.toHaveProperty('sessions.0.parentSessionId');
+ }
+ const local = await listSessionsForHistory({ ...listArgs, sessionIds: ['ordinary'], remoteVisibleOnly: false });
+ expect(local.items[0].parentSessionId).toBe(parent);
+ }
+ });
+
+ it('keeps all diagnostics identical with hidden-only vectors and no vectors', async () => {
+ db.exec(`DELETE FROM chat_messages_vec_v1 WHERE rowid IN (
+ SELECT rowid FROM embedding_jobs WHERE source_id IN ('ordinary', 'visible', 'zero'))`);
+ const before = await invokeHistory('search_chat_history', { query: 'needle' });
+ expect(before).toMatchObject({ ok: true, vector_used: false });
+ db.exec('DELETE FROM chat_messages_vec_v1');
+ expect(await invokeHistory('search_chat_history', { query: 'needle' })).toEqual(before);
+ });
+
+ it('does not expose an invisible-only workdir through empty-scope diagnostics', async () => {
+ // Host filesystem paths use the platform path implementation.
+ const workdir = path.resolve('hidden-workdir');
+ db.prepare("UPDATE sessions SET working_dir = ? WHERE id = 'hidden-0'").run(workdir);
+ const before = await invokeHistory('search_chat_history', { query: 'needle', workdir });
+ expect(before).toMatchObject({ ok: true, hits: [], vector_used: false });
+ db.exec("DELETE FROM sessions WHERE id = 'hidden-0'");
+ expect(await invokeHistory('search_chat_history', { query: 'needle', workdir })).toEqual(before);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/chatHistoryReader.ts b/apps/desktop/src/main/localDb/chatHistoryReader.ts
index d819d35d7a..de5ea9a5d7 100644
--- a/apps/desktop/src/main/localDb/chatHistoryReader.ts
+++ b/apps/desktop/src/main/localDb/chatHistoryReader.ts
@@ -18,6 +18,7 @@ import { and, asc, desc, eq, gt, gte, lt, inArray, isNotNull, isNull, ne, or, sq
import { getDbClient } from './client/current';
import { sessions, messages } from './schema';
import { messageToCamel } from './mapper';
+import { remoteVisibleSessionSql } from './ipc/botRemoteVisibility.js';
import {
managedDialogueRootLikePatterns,
normalizeHistoryWorkingDir,
@@ -163,6 +164,8 @@ export async function listWorkdirsForHistory(
// ── list_sessions ───────────────────────────────────────────────────────────
export interface ListSessionsParams {
+ /** Set only by the authorized remote history handler, never by tool input. */
+ remoteVisibleOnly?: boolean;
sessionIds?: string[] | null;
workdir: string | null;
fromMs: number | null;
@@ -202,6 +205,7 @@ export async function listSessionsForHistory(
const orderFn = params.order === 'asc' ? asc : desc;
const conds = [];
+ if (params.remoteVisibleOnly) conds.push(sql.raw(remoteVisibleSessionSql('sessions')));
if (scopedSessionIds !== null) conds.push(inArray(sessions.id, scopedSessionIds));
if (!params.includeDeleted) conds.push(ne(sessions.status, 'deleted'));
if (params.workdir !== null) {
diff --git a/apps/desktop/src/main/localDb/chatHistorySearch.ts b/apps/desktop/src/main/localDb/chatHistorySearch.ts
index ed5aae7448..71b1da9ae1 100644
--- a/apps/desktop/src/main/localDb/chatHistorySearch.ts
+++ b/apps/desktop/src/main/localDb/chatHistorySearch.ts
@@ -43,6 +43,7 @@ import { messageToCamel } from './mapper';
import { fuseRRF, buildMessagesFtsMatch, extractMessagesFtsTokens } from './chatHistorySearch.pure';
import { buildSnippetFromContent, SNIPPET_SOURCE_MAX_CHARS } from './cjkSeg';
import { resolveStoredWorkingDirCandidates } from './workingDirHistoryFilter';
+import { remoteVisibleSessionSql } from './ipc/botRemoteVisibility.js';
import { createLogger } from '../logger';
import { getEmbeddingService } from '../embedding-host';
import {
@@ -86,6 +87,8 @@ interface HitMeta {
type SearchSessionStatus = 'active' | 'archived' | 'deleted';
interface SearchChatHistoryEngineArgs extends SearchChatHistoryArgs {
+ /** Host-owned remote visibility scope, applied to both retrieval arms before ranking. */
+ remoteVisibleOnly?: boolean;
/**
* Optional host-side filters for product entry points that should only expose
* desktop-visible conversations. MCP callers omit these and keep the original
@@ -130,7 +133,9 @@ export async function searchChatHistoryHybrid(
args.workdir != null ? await resolveStoredWorkingDirCandidates(args.workdir) : null;
// 空候选 ⟺ 库里不存在该目录的任何拼写(typo / 已删),必然零命中——在两路
// arm 之前短路,避免向量 arm 白算一次 query embedding(Codex review)。
- if (workdirCandidates !== null && workdirCandidates.length === 0) {
+ // Remote requests instead use the filtered arm/probe: the diagnostic must be
+ // identical when a directory exists only in hidden sessions or is absent.
+ if (!args.remoteVisibleOnly && workdirCandidates !== null && workdirCandidates.length === 0) {
return {
hits: [],
sessions: {},
@@ -324,11 +329,23 @@ async function runVectorArm(
if (!isDbClientVecAvailable()) {
return { rows: [], skipReason: 'sqlite-vec 扩展未加载, 本次仅用 FTS 全文检索。' };
}
+ const { clause, params } = buildFilterClause(args, workdirCandidates);
+ // The availability probe and KNN must see the same eligible rows. Probing the
+ // full vector table would expose hidden data through vector_used/skip_reason.
+ const eligibleRowids = args.remoteVisibleOnly
+ ? `rowid IN (
+ SELECT j.rowid FROM embedding_jobs j
+ JOIN messages m ON m.id = j.source_id
+ JOIN sessions s ON s.id = m.session_id
+ WHERE ${clause}
+ )`
+ : '';
// gate 3: 向量表里有无数据? 无 → 用户没开"聊天记录语义索引"或尚未嵌完,
// 提前短路, 不浪费一次 query embedding 的 API 调用。
try {
const probe = await getDbClient().queryOne<{ rowid: number }>(
- `SELECT rowid FROM "${CHAT_VEC_TABLE}" LIMIT 1`,
+ `SELECT rowid FROM "${CHAT_VEC_TABLE}" ${eligibleRowids ? `WHERE ${eligibleRowids}` : ''} LIMIT 1`,
+ args.remoteVisibleOnly ? params : [],
);
if (!probe) {
return {
@@ -372,13 +389,16 @@ async function runVectorArm(
// flatten 回外层重新触发该错误。
// float32 必须以 Buffer(little-endian)绑定为 BLOB(better-sqlite3 不接受裸 Float32Array)。
const f32 = Buffer.from(Float32Array.from(queryVec).buffer);
- const { clause, params } = buildFilterClause(args, workdirCandidates);
const vectorPoolLimit = clampInternalPoolLimit(args.vectorPoolLimit, ARM_POOL);
+ // vec0 supports rowid IN within its KNN cursor. Apply the remote scope before
+ // its candidate limit: filtering only outside the CTE lets hidden rows starve
+ // visible semantic hits. Reuse the arm predicate; local search stays unchanged.
const sql = `
WITH knn AS (
SELECT rowid, distance
FROM "${CHAT_VEC_TABLE}"
WHERE embedding MATCH ?
+ ${eligibleRowids ? `AND ${eligibleRowids}` : ''}
ORDER BY distance
LIMIT ?
)
@@ -401,7 +421,13 @@ async function runVectorArm(
role: string;
createdAt: number;
distance: number;
- }>(sql, [f32, vectorPoolLimit * VEC_OVERFETCH, ...params, vectorPoolLimit]);
+ }>(sql, [
+ f32,
+ ...(args.remoteVisibleOnly ? params : []),
+ vectorPoolLimit * VEC_OVERFETCH,
+ ...params,
+ vectorPoolLimit,
+ ]);
return {
rows: rows.map((r) => ({
messageId: r.messageId,
@@ -426,6 +452,7 @@ function buildFilterClause(
workdirCandidates: string[] | null,
): { clause: string; params: unknown[] } {
const conds: string[] = ['m.rewind_at IS NULL'];
+ if (args.remoteVisibleOnly) conds.push(remoteVisibleSessionSql('s'));
const params: unknown[] = [];
if (args.sessionIds && args.sessionIds.length > 0) {
conds.push(`m.session_id IN (${args.sessionIds.map(() => '?').join(',')})`);
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/historyQuery.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/historyQuery.test.ts
new file mode 100644
index 0000000000..43bb8335d2
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/historyQuery.test.ts
@@ -0,0 +1,185 @@
+import { describe, expect, it, vi } from 'vitest';
+import { DL_HISTORY_QUERY_CHANNEL, REMOTE_INVOKE_ALLOWLIST } from '@cindy/device-link';
+import { createHistoryQueryHandler, registerHistoryQueryIpc } from '../historyQuery.js';
+import { runDeviceLinkInvokeContext } from '../../../device-link/invoke-context.js';
+import { listSessionsForHistory } from '../../chatHistoryReader.js';
+import { searchChatHistoryHybrid } from '../../chatHistorySearch.js';
+
+const handlers = vi.hoisted(() => new Map<string, (...args: any[]) => any>());
+vi.mock('electron', () => ({
+ ipcMain: {
+ handle: (name: string, handler: (...args: any[]) => any) => handlers.set(name, handler),
+ },
+}));
+vi.mock('../../chatHistorySearch.js', () => ({ searchChatHistoryHybrid: vi.fn() }));
+vi.mock('../../chatHistoryReader.js', () => ({
+ listSessionsForHistory: vi.fn(),
+ getMessagesForHistory: vi.fn(),
+}));
+
+function setup() {
+ const listSessions = vi.fn(async () => ({
+ ok: true as const,
+ page: { items: [], nextCursor: { createdAt: 4, id: 'source-cursor' }, hasMore: true },
+ }));
+ const searchChatHistory = vi.fn(async () => ({
+ ok: true as const,
+ result: {
+ hits: [],
+ sessions: {},
+ vectorUsed: false,
+ vectorSkipReason: 'disabled',
+ nextOffset: null,
+ hasMore: false,
+ poolSize: 0,
+ poolCapped: false,
+ },
+ }));
+ return {
+ listSessions,
+ searchChatHistory,
+ execute: createHistoryQueryHandler({ listSessions, searchChatHistory }),
+ };
+}
+describe('remote history query handler', () => {
+ it('preserves listing filters and source cursor with the same MCP schema', async () => {
+ const s = setup();
+ const first = await s.execute({
+ tool: 'list_sessions',
+ args: { from: '2026-10-01', order: 'asc', limit: 3 },
+ });
+ expect(first).toMatchObject({ ok: true, hasMore: true, sessions: [] });
+ expect(s.listSessions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fromMs: Date.parse('2026-10-01'),
+ order: 'asc',
+ limit: 3,
+ cursor: null,
+ }),
+ );
+ await s.execute({ tool: 'list_sessions', args: { cursor: first.nextCursor } });
+ expect(s.listSessions).toHaveBeenLastCalledWith(
+ expect.objectContaining({ cursor: { createdAt: 4, id: 'source-cursor' } }),
+ );
+ });
+ it('rejects unknown tools, recursive forwarding and invalid filters without querying', async () => {
+ const s = setup();
+ await expect(s.execute({ tool: 'get_chat_history', args: {} })).rejects.toThrow(
+ 'Unsupported history query',
+ );
+ await expect(s.execute({ tool: 'list_sessions', args: { device: 'all' } })).rejects.toThrow(
+ 'cannot forward',
+ );
+ for (const args of [{ limit: 1001 }, { from: 'invalid' }, { sessionIds: ['guess'] }]) {
+ expect(await s.execute({ tool: 'list_sessions', args })).toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_ARGS',
+ });
+ }
+ expect(s.listSessions).not.toHaveBeenCalled();
+ });
+ it('searches on the source host and bounds context while marking truncated text', async () => {
+ const s = setup();
+ s.searchChatHistory.mockResolvedValueOnce({
+ ok: true,
+ result: {
+ hits: [
+ {
+ messageId: 'm',
+ sessionId: 's',
+ role: 'user',
+ createdAt: 1,
+ snippet: 'found',
+ score: 1,
+ ftsRank: 1,
+ vectorRank: null,
+ vectorDistance: null,
+ context: [
+ {
+ id: 'm',
+ sessionId: 's',
+ role: 'user',
+ content: 'x'.repeat(3000),
+ createdAt: 1,
+ isHit: true,
+ toolUseId: null,
+ agentMeta: { private: 'metadata' },
+ rewindAt: null,
+ },
+ ],
+ },
+ ],
+ sessions: { s: { title: 'Found', workingDir: null, agentKind: 'codex' } },
+ vectorUsed: false,
+ vectorSkipReason: 'disabled',
+ nextOffset: 1,
+ hasMore: true,
+ poolSize: 2,
+ poolCapped: false,
+ },
+ } as any);
+ const result = await s.execute({
+ tool: 'search_chat_history',
+ args: { query: 'found', session_ids: ['s'], context_radius: 1, limit: 1 },
+ });
+ expect(s.searchChatHistory).toHaveBeenCalledWith(
+ expect.objectContaining({ query: 'found', sessionIds: ['s'], contextRadius: 1, limit: 1 }),
+ );
+ expect(result).toMatchObject({ ok: true, hasMore: true, vector_used: false });
+ const row = (result.hits as any[])[0].context[0];
+ expect(row.content).toHaveLength(2000);
+ expect(row.agentMeta).toEqual({ remoteContentTruncated: true });
+ });
+ it('registers a linked read-only channel and rejects local/guest IPC calls', async () => {
+ expect(REMOTE_INVOKE_ALLOWLIST.has(DL_HISTORY_QUERY_CHANNEL)).toBe(true);
+ registerHistoryQueryIpc();
+ const handler = handlers.get(DL_HISTORY_QUERY_CHANNEL)!;
+ await expect(handler({}, { tool: 'list_sessions', args: {} })).rejects.toThrow(
+ 'authorized device link',
+ );
+ await expect(
+ runDeviceLinkInvokeContext(
+ { controllerDeviceId: 'guest', channel: DL_HISTORY_QUERY_CHANNEL, sharedTask: {} as any },
+ () => handler({}, {}),
+ ),
+ ).rejects.toThrow('authorized device link');
+ });
+ it('forces source-side visibility on both readers without accepting an override from the wire', async () => {
+ vi.mocked(listSessionsForHistory).mockResolvedValue({
+ items: [],
+ hasMore: false,
+ nextCursor: null,
+ });
+ vi.mocked(searchChatHistoryHybrid).mockResolvedValue({
+ hits: [],
+ sessions: {},
+ hasMore: false,
+ nextOffset: null,
+ poolSize: 0,
+ poolCapped: false,
+ vectorUsed: false,
+ vectorSkipReason: 'disabled',
+ });
+ registerHistoryQueryIpc();
+ const handler = handlers.get(DL_HISTORY_QUERY_CHANNEL)!;
+ for (const tool of ['list_sessions', 'search_chat_history']) {
+ const invoke = (args: Record<string, unknown>) =>
+ runDeviceLinkInvokeContext(
+ { controllerDeviceId: 'owner', channel: DL_HISTORY_QUERY_CHANNEL },
+ () => handler({}, { tool, args }),
+ );
+ const args = tool === 'list_sessions' ? {} : { query: 'needle' };
+ expect(await invoke(args)).toMatchObject({ ok: true });
+ expect(await invoke({ ...args, remoteVisibleOnly: false })).toMatchObject({
+ ok: false,
+ errorCode: 'INVALID_ARGS',
+ });
+ }
+ expect(listSessionsForHistory).toHaveBeenCalledWith(
+ expect.objectContaining({ remoteVisibleOnly: true }),
+ );
+ expect(searchChatHistoryHybrid).toHaveBeenCalledWith(
+ expect.objectContaining({ remoteVisibleOnly: true }),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts b/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts
index 674a0a46a2..996234f86b 100644
--- a/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts
+++ b/apps/desktop/src/main/localDb/ipc/botRemoteSessionAccess.ts
@@ -1,7 +1,7 @@
-import { eq, inArray } from 'drizzle-orm';
+import { inArray, sql } from 'drizzle-orm';
import { getDbClient } from '../client/current.js';
-import { botProfiles, botSessionLinks, sessions } from '../schema.js';
-import { isBotVisibleRemotely } from './botRemoteVisibility.js';
+import { botProfiles, sessions } from '../schema.js';
+import { isBotVisibleRemotely, remoteVisibleSessionSql } from './botRemoteVisibility.js';
import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from '../../device-link/broadcast-tap.js';
import type { RemoteBotSessionAccess } from '../../device-link/remoteBotSessionBoundary.js';
@@ -33,18 +33,13 @@ export async function readRemoteBotSessionAccessBatch(
const rows = await db.select({
id: sessions.id,
source: sessions.source,
- botId: botProfiles.id,
- hiddenAt: botProfiles.hiddenAt,
- status: botProfiles.status,
+ visible: sql<number>`${sql.raw(remoteVisibleSessionSql('sessions'))}`,
}).from(sessions)
- .leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))
- .leftJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))
.where(inArray(sessions.id, chunk));
if (!isDataOwnerBroadcastScopeCurrent(owner)) return denyAll();
for (const row of rows) {
access.set(row.id, row.source !== 'bot' ? 'ordinary'
- : row.botId && row.status && isBotVisibleRemotely({ hiddenAt: row.hiddenAt, status: row.status })
- ? 'visible' : 'hidden');
+ : row.visible ? 'visible' : 'hidden');
}
}
}
diff --git a/apps/desktop/src/main/localDb/ipc/botRemoteVisibility.ts b/apps/desktop/src/main/localDb/ipc/botRemoteVisibility.ts
index 7a8966614a..5610f03ede 100644
--- a/apps/desktop/src/main/localDb/ipc/botRemoteVisibility.ts
+++ b/apps/desktop/src/main/localDb/ipc/botRemoteVisibility.ts
@@ -2,3 +2,15 @@
export function isBotVisibleRemotely(profile: { hiddenAt: number | null; status: string }): boolean {
return !profile.hiddenAt && profile.status !== 'archived';
}
+
+/** Host-owned SQL scope, applied before history ranking, limits and pagination. */
+export function remoteVisibleSessionSql(alias: 'sessions' | 's'): string {
+ return `(${alias}.source <> 'bot' OR EXISTS (
+ SELECT 1 FROM bot_session_links AS remote_link
+ JOIN bot_profiles AS remote_bot ON remote_bot.id = remote_link.bot_id
+ WHERE remote_link.session_id = ${alias}.id
+ AND (remote_bot.hidden_at IS NULL OR remote_bot.hidden_at = 0)
+ AND remote_bot.status IS NOT NULL AND remote_bot.status <> ''
+ AND remote_bot.status <> 'archived'
+ ))`;
+}
diff --git a/apps/desktop/src/main/localDb/ipc/historyQuery.ts b/apps/desktop/src/main/localDb/ipc/historyQuery.ts
new file mode 100644
index 0000000000..cfb0f71230
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/historyQuery.ts
@@ -0,0 +1,76 @@
+import { ipcMain } from 'electron';
+import { DL_HISTORY_QUERY_CHANNEL } from '@cindy/device-link';
+import {
+ XdtHelperToolRegistry,
+ registerListSessionsTool,
+ registerSearchChatHistoryTool,
+ historyPayload,
+ type XdtHelperHistoryDeps,
+} from '@cindy/mcps';
+import { listSessionsForHistory } from '../chatHistoryReader.js';
+import { searchChatHistoryHybrid } from '../chatHistorySearch.js';
+import { capReferenceMessageRows } from './history.js';
+import { getDeviceLinkInvokeContext } from '../../device-link/invoke-context.js';
+import { requireObject, throwIpcError } from '../../utils/ipcValidate.js';
+
+/** Reuse MCP's strict input validation and the exact same readers/formatters on the source host. */
+export function createHistoryQueryHandler(
+ deps: Pick<XdtHelperHistoryDeps, 'listSessions' | 'searchChatHistory'>,
+) {
+ const registry = new XdtHelperToolRegistry();
+ const unsupported = async () => ({
+ ok: false as const,
+ errorCode: 'INTERNAL' as const,
+ message: 'Unsupported history operation',
+ });
+ const history: XdtHelperHistoryDeps = {
+ ...deps,
+ listWorkdirs: unsupported,
+ getMessages: unsupported,
+ };
+ registerListSessionsTool(registry, { history });
+ registerSearchChatHistoryTool(registry, { history });
+ return async (value: unknown) => {
+ const request = requireObject(value, 'request');
+ if (request.tool !== 'list_sessions' && request.tool !== 'search_chat_history') {
+ throwIpcError('INVALID_PARAMS', 'Unsupported history query');
+ }
+ const args = requireObject(request.args, 'args');
+ if (args.device !== undefined && args.device !== 'local') {
+ throwIpcError('INVALID_PARAMS', 'History queries cannot forward to another device');
+ }
+ const result = historyPayload(await registry.call(request.tool, args));
+ if (Array.isArray(result.hits)) {
+ result.hits = result.hits.map((hit) => ({
+ ...hit,
+ // Snippets are bounded; full text remains available via get_chat_history.
+ context: capReferenceMessageRows(
+ hit.context.map((row: Record<string, unknown>) => ({ ...row, agentMeta: null })),
+ 2000,
+ ),
+ }));
+ }
+ return result;
+ };
+}
+
+export function registerHistoryQueryIpc(): void {
+ const execute = createHistoryQueryHandler({
+ listSessions: async (args) => ({
+ ok: true,
+ page: await listSessionsForHistory({ ...args, remoteVisibleOnly: true }),
+ }),
+ searchChatHistory: async (args) => ({
+ ok: true,
+ result: await searchChatHistoryHybrid({ ...args, remoteVisibleOnly: true }),
+ }),
+ });
+ ipcMain.handle(DL_HISTORY_QUERY_CHANNEL, async (_event, value: unknown) => {
+ const context = getDeviceLinkInvokeContext();
+ // Not exposed through preload. Only the authenticated same-account tunnel may dispatch it.
+ if (!context || context.sharedTask || context.channel !== DL_HISTORY_QUERY_CHANNEL) {
+ throwIpcError('PERMISSION_DENIED', 'An authorized device link is required');
+ }
+ return execute(value);
+ });
+}
diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.ts
index 4aa44929c8..20301f1f4a 100644
--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts
+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts
@@ -34,6 +34,7 @@ import { enqueueDurableWrite } from '../../messagePersistBroadcaster';
import { registerDevSqliteVecIpc } from './dev/sqliteVec';
import { registerSearchIpc } from './search';
import { registerRemoteHistoryIpc } from './history';
+import { registerHistoryQueryIpc } from './historyQuery';
import { recoverActiveTeammateInvitations, registerBotIpc } from './bots';
import { botRemoteManagement } from './botRemoteManagement';
import { registerBotRemoteResourceProvider } from './botRemoteResourceProvider';
@@ -260,6 +261,7 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {
});
registerMessageIpc(opts.isSessionTurnPendingCompletion, opts.readHistoryLiveMessages);
registerRemoteHistoryIpc();
+ registerHistoryQueryIpc();
registerBotIpc();
registerCompanionImport();
registerRoutinesIpc();
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 02e19fb4ea..d6e5d04b75 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -117,6 +117,8 @@ import {
import { MAKER_PUSH } from '../maker-ipc/channels.js';
import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';
import { remoteInvoke } from '../device-link/index.js';
+import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';
+import { createHistoryRemoteDeps } from '../mcp-integrations/historyDevices.js';
import { WorktreePool } from '../worktree/index.js';
import { getReadyBinaryPath, getCachedBinaryStatus } from '../agent-binaries/index.js';
import {
@@ -976,6 +978,18 @@ export function getMaker(): Maker {
pluginRegistry,
resolveIOSSimulatorAccess,
invokeRemote: remoteInvoke,
+ historyRemote: createHistoryRemoteDeps({
+ listDevices: () => handleListDevices(deviceDirectoryDeps()),
+ invoke: remoteInvoke,
+ captureAccess: () => {
+ const owner = captureDataOwnerBroadcastScope();
+ const assertCurrent = () => {
+ if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('History owner changed');
+ };
+ assertCurrent();
+ return assertCurrent;
+ },
+ }),
isCurrentLocalSessionInstance: (
sessionId: string,
sessionInstanceId: string | undefined,
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/historyDevices.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/historyDevices.test.ts
new file mode 100644
index 0000000000..15ba80de79
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/historyDevices.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it, vi } from 'vitest';
+import { DL_HISTORY_QUERY_CHANNEL, DeviceLinkError } from '@cindy/device-link';
+import type { DeviceLinkDeviceView } from '../../../shared/deviceLinkIpc.js';
+import { createHistoryRemoteDeps } from '../historyDevices.js';
+
+function device(id: string, changes: Partial<DeviceLinkDeviceView> = {}): DeviceLinkDeviceView {
+ return {
+ deviceId: id,
+ name: id,
+ platform: 'darwin',
+ appVersion: null,
+ lastSeenAt: null,
+ online: true,
+ busy: false,
+ remoteControlEnabled: true,
+ controlEnabled: true,
+ isSelf: false,
+ ...changes,
+ };
+}
+function setup(devices: DeviceLinkDeviceView[] = []) {
+ const invoke = vi.fn(async () => ({
+ ok: true as const,
+ result: { ok: true, sessions: [], hasMore: false, nextCursor: null },
+ }));
+ let owner = 1;
+ const captureAccess = () => {
+ const captured = owner;
+ return () => {
+ if (captured !== owner) throw new Error('Owner changed');
+ };
+ };
+ const listDevices = vi.fn(async () => ({ devices }));
+ return {
+ invoke,
+ listDevices,
+ changeOwner: () => owner++,
+ remote: createHistoryRemoteDeps({ invoke, listDevices, captureAccess }),
+ };
+}
+describe('desktop history discovery/transport', () => {
+ it('includes local and candidate desktops with explicit disabled/offline reasons, excluding phones', async () => {
+ const s = setup([
+ device('self', { isSelf: true }),
+ device('mac'),
+ device('phone', { platform: 'ios' }),
+ device('disabled', { controlEnabled: false }),
+ device('sleeping', { online: false }),
+ ]);
+ expect(await s.remote.listDevices()).toEqual([
+ { deviceId: 'local', deviceName: 'self', local: true, available: true },
+ { deviceId: 'mac', deviceName: 'mac', local: false, available: true },
+ {
+ deviceId: 'disabled',
+ deviceName: 'disabled',
+ local: false,
+ available: false,
+ unavailableReason: 'REMOTE_DISABLED',
+ },
+ {
+ deviceId: 'sleeping',
+ deviceName: 'sleeping',
+ local: false,
+ available: false,
+ unavailableReason: 'REMOTE_DEVICE_OFFLINE',
+ },
+ ]);
+ expect(s.invoke).not.toHaveBeenCalled();
+ });
+ it('keeps local available even before the relay registers this host', async () => {
+ expect(await setup().remote.listDevices()).toEqual([
+ { deviceId: 'local', deviceName: 'Local', local: true, available: true },
+ ]);
+ });
+ it('uses the read-only channel and preserves source pagination', async () => {
+ const s = setup();
+ expect(await s.remote.query('mac', 'list_sessions', { limit: 5 })).toMatchObject({ ok: true });
+ expect(s.invoke).toHaveBeenCalledWith(
+ 'mac',
+ DL_HISTORY_QUERY_CHANNEL,
+ [{ tool: 'list_sessions', args: { limit: 5 } }],
+ { preSend: expect.any(Function) },
+ );
+ });
+ it.each([
+ ['CHANNEL_NOT_ALLOWED', 'REMOTE_UNSUPPORTED'],
+ ['ACCESS_REVOKED', 'REMOTE_ACCESS_REVOKED'],
+ ['DEVICE_OFFLINE', 'REMOTE_DEVICE_OFFLINE'],
+ ['INVOKE_TIMEOUT', 'REMOTE_TIMEOUT'],
+ ['PAYLOAD_TOO_LARGE', 'REMOTE_PAYLOAD_TOO_LARGE'],
+ ])('reports %s without retries or local fallback', async (code, expected) => {
+ const s = setup();
+ s.invoke.mockResolvedValueOnce({ ok: false, error: { code, message: 'Unavailable' } } as any);
+ expect(await s.remote.query('mac', 'search_chat_history', { query: 'x' })).toMatchObject({
+ ok: false,
+ errorCode: expected,
+ });
+ expect(s.invoke).toHaveBeenCalledTimes(1);
+ });
+ it('maps thrown transport errors and rejects malformed responses', async () => {
+ const s = setup();
+ s.invoke.mockRejectedValueOnce(new DeviceLinkError('ACCESS_REVOKED', 'revoked'));
+ expect(await s.remote.query('mac', 'list_sessions', {})).toMatchObject({
+ errorCode: 'REMOTE_ACCESS_REVOKED',
+ });
+ s.invoke.mockResolvedValueOnce({ ok: true, result: [] } as any);
+ expect(await s.remote.query('mac', 'list_sessions', {})).toMatchObject({
+ errorCode: 'REMOTE_INVALID_RESPONSE',
+ });
+ });
+ it('rejects discovery and late query replies across account changes', async () => {
+ const s = setup();
+ s.listDevices.mockImplementationOnce(async () => {
+ s.changeOwner();
+ return { devices: [] };
+ });
+ await expect(s.remote.listDevices()).rejects.toThrow('Owner changed');
+ s.invoke.mockImplementationOnce(async () => {
+ s.changeOwner();
+ return { ok: true, result: { ok: true, sessions: [], hasMore: false, nextCursor: null } };
+ });
+ await expect(s.remote.query('mac', 'list_sessions', {})).rejects.toThrow('Owner changed');
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/historyDevices.ts b/apps/desktop/src/main/mcp-integrations/historyDevices.ts
new file mode 100644
index 0000000000..93d15ab74d
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/historyDevices.ts
@@ -0,0 +1,73 @@
+import {
+ DL_HISTORY_QUERY_CHANNEL,
+ DeviceLinkError,
+ type InvokeResultPayload,
+} from '@cindy/device-link';
+import type { HistoryRemoteDeps } from '@cindy/mcps';
+import type { DeviceLinkDeviceView } from '../../shared/deviceLinkIpc.js';
+import { classifyRemoteHistoryError } from './remoteChatHistory.js';
+
+export function createHistoryRemoteDeps(deps: {
+ listDevices(): Promise<{ devices: DeviceLinkDeviceView[] }>;
+ captureAccess(): () => void;
+ invoke(
+ deviceId: string,
+ channel: string,
+ args: unknown[],
+ options?: { preSend?: () => void },
+ ): Promise<InvokeResultPayload>;
+}): HistoryRemoteDeps {
+ return {
+ captureAccess: deps.captureAccess,
+ async listDevices() {
+ const assertCurrent = deps.captureAccess();
+ const { devices } = await deps.listDevices();
+ assertCurrent();
+ const result = devices
+ .filter((d) => d.isSelf || !['ios', 'android'].includes(d.platform ?? ''))
+ .map((d) => ({
+ deviceId: d.isSelf ? 'local' : d.deviceId,
+ deviceName: d.name,
+ local: d.isSelf,
+ available: d.isSelf || (d.online && d.controlEnabled && d.remoteControlEnabled),
+ ...(!d.isSelf && (!d.online || !d.controlEnabled || !d.remoteControlEnabled)
+ ? { unavailableReason: !d.online ? 'REMOTE_DEVICE_OFFLINE' : 'REMOTE_DISABLED' }
+ : {}),
+ }));
+ if (!result.some((d) => d.local))
+ result.unshift({ deviceId: 'local', deviceName: 'Local', local: true, available: true });
+ return result;
+ },
+ async query(deviceId, tool, args) {
+ const assertCurrent = deps.captureAccess();
+ try {
+ const response = await deps.invoke(deviceId, DL_HISTORY_QUERY_CHANNEL, [{ tool, args }], {
+ preSend: assertCurrent,
+ });
+ assertCurrent();
+ if (!response.ok)
+ return {
+ ok: false,
+ ...classifyRemoteHistoryError(response.error.code, response.error.message),
+ };
+ if (
+ !response.result ||
+ typeof response.result !== 'object' ||
+ Array.isArray(response.result) ||
+ typeof (response.result as Record<string, unknown>).ok !== 'boolean'
+ ) {
+ return { ok: false, errorCode: 'REMOTE_INVALID_RESPONSE' };
+ }
+ return response.result as Record<string, unknown>;
+ } catch (error) {
+ assertCurrent();
+ return {
+ ok: false,
+ ...(error instanceof DeviceLinkError
+ ? classifyRemoteHistoryError(error.code, error.message)
+ : { errorCode: 'REMOTE_UNAVAILABLE' }),
+ };
+ }
+ },
+ };
+}
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index c31f84bbdc..2d085ead40 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -121,6 +121,7 @@ export interface DesktopMcpProvidersDeps {
) => IOSSimulatorMcpAccessDecision;
/** Device-link transport stays host-injected so provider tests do not load Electron runtime services. */
invokeRemote: ChatHistoryReaderDeps['invokeRemote'];
+ historyRemote?: import('@cindy/mcps').HistoryRemoteDeps;
/** 插件文件交接只认活跃 Session 的实时权限;缺失时由 ghost.ts fail closed。 */
getLiveSessionGrantState?: (
sessionId: string,
@@ -911,6 +912,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
authorizePath: (request) => authorizeDesktopSessionPath(request, deps.getLiveSessionGrantState),
}),
history: {
+ remote: deps.historyRemote,
resolveSessionScope: async ({ callerSessionId, callerMemoryScopeKey }) => {
try {
if (await botReadsAccountHistory(callerSessionId)) return { ok: true, sessionIds: null };
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index fe04c73026..4a8146d830 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -11,6 +11,38 @@
> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
+## Agent 跨设备历史发现与搜索
+
+`cindy_helper` 的 `list_history_devices` 使用现有同账号设备目录;`list_sessions` 和
+`search_chat_history` 新增 `device` 参数,默认 `local` 保留原行为,`all` 查询本机和在线且
+允许访问的电脑,也可指定目录返回的设备 ID。跨设备响应按设备分组;`limit`、排序、
+`nextCursor` 和搜索相关性均属于单台设备,翻页使用该组设备 ID 和游标,不能把一个游标
+用于所有设备。离线、禁用、撤权、超时或不支持的设备明确列入结果,`partial` 表示覆盖不全;
+目录失败仍可返回本机结果,但不能声称已搜索全部设备。搜索候选池上限仍以每组的
+`pool_capped` 表示,不保证无限召回。
+
+新增只读 `local-db:history:query` channel,仅接受 `list_sessions` 或
+`search_chat_history`,复用原工具的参数校验、本机查询和输出格式。远端不允许继续转发,
+不加入 unlinked/shared-task 白名单,不增加自动重试、缓存或聊天同步。沿用同账号
+device-link 授权、撤权与 owner fence;仅有归属范围权限的调用方不能扩展历史范围。远端任务
+列表及搜索两路召回在排名、限量和分页前应用同一条伙伴可见性条件,隐藏任务不占分页名额,
+游标和候选池信息只基于可见结果。指定 `session_ids` 时也由源端 SQL 统一过滤,隐藏、归档、
+失去伙伴关联及不存在的 ID 均不产生命中;不通过请求前的存在性检查返回不同错误,混合查询
+仍返回其中可见任务的结果。普通回复、缓存回复与离线重发仍重新核验;页内任务若已
+变为隐藏,整页返回 `NOT_FOUND`,不发送该页的内容或过期分页信息,调用方可重新查询。
+列表中的 `parentSessionId` 与页内任务共用一次源端可见性查询,不可见或已不存在的父任务
+引用省略;缓存与排队回复也重新投影。向量可用性探针与 KNN 使用同一可见范围和查询过滤,
+仅有隐藏向量与没有向量时返回相同诊断;只存在于隐藏任务的目录与不存在的目录也不可区分。
+
+远程结果中的任务 ID 为 `deviceId::sessionId`,可直接供现有 `get_chat_history` 读取。
+搜索上下文每条最多 2000 字符,省略时带 `remoteContentTruncated`;完整阅读继续使用历史
+读取接口。超出传输预算返回明确错误,调用方缩小 `limit` 或 `context_radius`,不能静默
+当作未命中。旧被控端返回 `CHANNEL_NOT_ALLOWED` 时标为 `REMOTE_UNSUPPORTED`,其他设备
+仍正常返回;完整跨机发现和搜索需要两端均支持此 channel,旧工具调用默认本机不变。
+本次不改服务端和数据库 schema;手机与 IM 通过所在电脑的 Agent 使用能力,无新增界面。
+SSH 主机不自动成为设备目录成员。实现与回归见 `mcp-integrations/historyDevices.ts`、
+`localDb/ipc/historyQuery.ts` 和 `packages/lizi-mcps/src/__tests__/historyDevices.test.ts`。
+
## Desktop 设备互联 Review
桌面控制端的 /review 通过 maker:review:start 请求被控 Desktop 执行。证据收集、Reviewer
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 6f17cb83ad..72bdba2a36 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -51,6 +51,8 @@ export const DL_UNSUBSCRIBE_CHANNEL = 'device-link:unsubscribe';
* 不出被控端。老被控端响应无此字段 → 控制端按无终态降级。
*/
export const DL_HISTORY_MESSAGES_CHANNEL = 'local-db:history:messages';
+/** Same-account, linked, read-only history discovery/search. No shared-task or unlinked access. */
+export const DL_HISTORY_QUERY_CHANNEL = 'local-db:history:query';
/**
* 会话引用消费能力探针。控制端在发送含引用快照的队列消息前必须先调用;
@@ -281,6 +283,7 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [
// projection.
'local-db:conversations:search',
DL_HISTORY_MESSAGES_CHANNEL,
+ DL_HISTORY_QUERY_CHANNEL,
'local-db:messages:list',
// Read-only visible history and recoverable work ranges; same session authorization as list.
'local-db:messages:view',
diff --git a/packages/lizi-mcps/src/__tests__/getChatHistoryToolContract.test.ts b/packages/lizi-mcps/src/__tests__/getChatHistoryToolContract.test.ts
index e71c9fd6b8..ebefef3dd3 100644
--- a/packages/lizi-mcps/src/__tests__/getChatHistoryToolContract.test.ts
+++ b/packages/lizi-mcps/src/__tests__/getChatHistoryToolContract.test.ts
@@ -22,8 +22,17 @@ describe('get_chat_history published contract', () => {
const capability = CAPABILITIES.find((entry) => entry.key === 'chat-history-query');
expect(capability).toBeDefined();
- expect(capability!.detail).toContain('开放了五个只读查询入口');
- expect(capability!.detail).not.toContain('开放了四个只读查询入口');
+ expect(capability!.detail).toContain('【六个工具】');
+ for (const name of [
+ 'list_workdirs',
+ 'list_sessions',
+ 'list_session_queue',
+ 'get_chat_history',
+ 'search_chat_history',
+ 'list_history_devices',
+ ]) {
+ expect(capability!.detail).toContain(name);
+ }
expect(capability!.detail).toContain('get_chat_history({session_ids: [...]})');
expect(capability!.detail).not.toContain('get_chat_history({sessionIds: [...]})');
});
diff --git a/packages/lizi-mcps/src/__tests__/historyDevices.test.ts b/packages/lizi-mcps/src/__tests__/historyDevices.test.ts
new file mode 100644
index 0000000000..bba3b6b7b3
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/historyDevices.test.ts
@@ -0,0 +1,254 @@
+import { describe, expect, it, vi } from "vitest";
+import { XdtHelperToolRegistry } from "../lizi_xdtHelperToolRegistry.js";
+import { registerListSessionsTool } from "../xdt-helper/list_sessions.js";
+import { registerSearchChatHistoryTool } from "../xdt-helper/search_chat_history.js";
+import { registerGetChatHistoryTool } from "../xdt-helper/get_chat_history.js";
+import {
+ historyPayload,
+ registerHistoryDevicesTool,
+} from "../xdt-helper/_history_devices.js";
+import type { XdtHelperHistoryDeps } from "../xdt-helper/_history_types.js";
+
+function setup() {
+ const registry = new XdtHelperToolRegistry();
+ const remoteQuery = vi.fn(async () => ({
+ ok: true,
+ sessions: [{ id: "same", title: "Remote", parentSessionId: "parent" }],
+ hasMore: true,
+ nextCursor: "remote-cursor",
+ }));
+ const listDevices = vi.fn(async () => [
+ {
+ deviceId: "local",
+ deviceName: "This computer",
+ local: true,
+ available: true,
+ },
+ {
+ deviceId: "mac",
+ deviceName: "Other computer",
+ local: false,
+ available: true,
+ },
+ {
+ deviceId: "offline",
+ deviceName: "Sleeping",
+ local: false,
+ available: false,
+ unavailableReason: "REMOTE_DEVICE_OFFLINE",
+ },
+ ]);
+ const history: XdtHelperHistoryDeps = {
+ listWorkdirs: vi.fn(),
+ getMessages: vi.fn(async () => ({
+ ok: true as const,
+ page: { items: [], nextCursor: null, hasMore: false },
+ })),
+ listSessions: vi.fn(async () => ({
+ ok: true as const,
+ page: {
+ items: [
+ {
+ id: "same",
+ title: "Local",
+ workingDir: null,
+ agentKind: "codex",
+ workspaceKind: "chat",
+ model: "model",
+ status: "active",
+ source: "desktop",
+ orcaRole: null,
+ parentSessionId: null,
+ createdAt: 1,
+ updatedAt: 2,
+ userSendAt: null,
+ messageCount: 1,
+ },
+ ],
+ nextCursor: null,
+ hasMore: false,
+ },
+ })),
+ searchChatHistory: vi.fn(async () => ({
+ ok: true as const,
+ result: {
+ hits: [],
+ sessions: {},
+ vectorUsed: false,
+ vectorSkipReason: "disabled",
+ nextOffset: null,
+ hasMore: false,
+ poolSize: 0,
+ poolCapped: false,
+ },
+ })),
+ remote: { listDevices, query: remoteQuery, captureAccess: () => () => {} },
+ };
+ registerListSessionsTool(registry, { history });
+ registerSearchChatHistoryTool(registry, { history });
+ registerHistoryDevicesTool(registry, { history });
+ registerGetChatHistoryTool(registry, { history });
+ return {
+ registry,
+ history,
+ remoteQuery,
+ listDevices,
+ call: async (name: string, args = {}) =>
+ historyPayload(await registry.call(name, args)) as any,
+ };
+}
+
+describe("history device discovery and queries", () => {
+ it("keeps legacy local queries local and preserves their response", async () => {
+ const s = setup();
+ expect(await s.call("list_sessions")).toMatchObject({
+ ok: true,
+ sessions: [{ id: "same" }],
+ hasMore: false,
+ });
+ expect(s.listDevices).not.toHaveBeenCalled();
+ });
+ it("groups devices, qualifies identities and reports skipped offline computers", async () => {
+ const s = setup();
+ const result = await s.call("list_sessions", { device: "all", limit: 2 });
+ expect(result).toMatchObject({
+ partial: true,
+ hasMore: true,
+ groups: [
+ { deviceId: "local", sessions: [{ id: "same" }] },
+ {
+ deviceId: "mac",
+ sessions: [{ id: "mac::same", parentSessionId: "mac::parent" }],
+ nextCursor: "remote-cursor",
+ },
+ { deviceId: "offline", ok: false, errorCode: "REMOTE_DEVICE_OFFLINE" },
+ ],
+ });
+ expect(s.remoteQuery).toHaveBeenCalledTimes(1);
+ await s.call("list_sessions", {
+ device: "mac",
+ cursor: result.groups[1].nextCursor,
+ });
+ expect(s.remoteQuery).toHaveBeenLastCalledWith(
+ "mac",
+ "list_sessions",
+ expect.objectContaining({ device: "local", cursor: "remote-cursor" }),
+ );
+ });
+ it("qualifies search hits, metadata and context and supports reading the returned identity", async () => {
+ const s = setup();
+ s.remoteQuery.mockResolvedValueOnce({
+ ok: true,
+ hits: [
+ {
+ messageId: "m",
+ sessionId: "same",
+ context: [{ id: "m", sessionId: "same", content: "found" }],
+ },
+ ],
+ sessions: { same: { title: "Remote" } },
+ nextCursor: null,
+ hasMore: false,
+ } as any);
+ const result = await s.call("search_chat_history", {
+ device: "mac",
+ query: "find",
+ session_ids: ["mac::same"],
+ });
+ expect(s.remoteQuery).toHaveBeenCalledWith(
+ "mac",
+ "search_chat_history",
+ expect.objectContaining({ session_ids: ["same"] }),
+ );
+ expect(result.groups[0]).toMatchObject({
+ sessions: { "mac::same": { title: "Remote" } },
+ hits: [{ sessionId: "mac::same", context: [{ sessionId: "mac::same" }] }],
+ });
+ await s.call("get_chat_history", {
+ session_ids: [result.groups[0].hits[0].sessionId],
+ });
+ expect(s.history.getMessages).toHaveBeenCalledWith(
+ expect.objectContaining({ sessionIds: ["mac::same"] }),
+ );
+ });
+ it("does not widen Bot scope, including denied/missing ownership", async () => {
+ const s = setup();
+ s.history.resolveSessionScope = async () => ({ ok: true, sessionIds: [] });
+ for (const name of [
+ "list_history_devices",
+ "list_sessions",
+ "search_chat_history",
+ ]) {
+ expect(
+ await s.call(
+ name,
+ name === "list_history_devices"
+ ? {}
+ : {
+ device: "all",
+ ...(name === "search_chat_history" ? { query: "x" } : {}),
+ },
+ ),
+ ).toMatchObject({ ok: false, errorCode: "HISTORY_SCOPE_DENIED" });
+ }
+ expect(s.listDevices).not.toHaveBeenCalled();
+ expect(s.remoteQuery).not.toHaveBeenCalled();
+ });
+ it("keeps local results when discovery fails and isolates remote query failures", async () => {
+ const s = setup();
+ s.listDevices.mockRejectedValueOnce(new Error("offline"));
+ expect(await s.call("list_sessions", { device: "all" })).toMatchObject({
+ partial: true,
+ discoveryError: "DEVICE_DISCOVERY_FAILED",
+ groups: [{ sessions: [{ id: "same" }] }],
+ });
+ s.remoteQuery.mockRejectedValueOnce(new Error("timeout"));
+ expect(await s.call("list_sessions", { device: "all" })).toMatchObject({
+ partial: true,
+ groups: [
+ { ok: true },
+ { ok: false, errorCode: "REMOTE_UNAVAILABLE" },
+ { ok: false },
+ ],
+ });
+ });
+ it("rejects ambiguous cursors, device IDs and mixed session identity routes", async () => {
+ const s = setup();
+ expect(
+ await s.call("list_sessions", { device: "all", cursor: "cursor" }),
+ ).toMatchObject({ ok: false, errorCode: "INVALID_ARGS" });
+ expect(await s.call("list_sessions", { device: "unknown" })).toMatchObject({
+ ok: false,
+ errorCode: "NOT_FOUND",
+ });
+ for (const args of [
+ { device: "local", session_ids: ["mac::same"] },
+ { device: "mac", session_ids: ["other::same"] },
+ { device: "all", session_ids: ["mac::same"] },
+ ]) {
+ expect(
+ await s.call("search_chat_history", { query: "x", ...args }),
+ ).toMatchObject({ ok: false, errorCode: "INVALID_ARGS" });
+ }
+ expect(s.remoteQuery).not.toHaveBeenCalled();
+ });
+ it("discards all results if the owner changes during a query", async () => {
+ const s = setup();
+ let current = true;
+ s.history.remote!.captureAccess = () => () => {
+ if (!current) throw new Error("Owner changed");
+ };
+ s.remoteQuery.mockImplementationOnce(async () => {
+ current = false;
+ return {
+ ok: true,
+ sessions: [],
+ hasMore: false,
+ nextCursor: null,
+ } as any;
+ });
+ await expect(s.call("list_sessions", { device: "all" })).rejects.toThrow(
+ "Owner changed",
+ );
+ });
+});
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
index ae19b47a1f..3801d2934f 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@ -50,6 +50,7 @@ import {
registerUnarchiveSessionsTool,
registerSendToSessionTool,
registerListWorkdirsTool,
+ registerHistoryDevicesTool,
registerListSessionsTool,
registerListSessionQueueTool,
registerUpdateSessionQueuedMessageTool,
@@ -905,6 +906,7 @@ export function createXdtHelperMcpServer(
history: deps.history,
getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),
};
+ registerHistoryDevicesTool(registry, historyDeps);
registerListWorkdirsTool(registry, historyDeps);
registerListSessionsTool(registry, {
...historyDeps,
diff --git a/packages/lizi-mcps/src/xdt-helper/_history_devices.ts b/packages/lizi-mcps/src/xdt-helper/_history_devices.ts
new file mode 100644
index 0000000000..f7fc27d1a5
--- /dev/null
+++ b/packages/lizi-mcps/src/xdt-helper/_history_devices.ts
@@ -0,0 +1,267 @@
+import { z } from "zod";
+import type {
+ XdtHelperToolRegistry,
+ XdtHelperToolResult,
+} from "../lizi_xdtHelperToolRegistry.js";
+import type { LiziMcpSessionContext } from "../types.js";
+import type { XdtHelperHistoryDeps } from "./_history_types.js";
+import { resolveHistoryScope } from "./_history_scope.js";
+import { errorPayload, okPayload } from "./_payload.js";
+
+export type HistoryQueryTool = "list_sessions" | "search_chat_history";
+export interface HistoryDevice {
+ deviceId: string;
+ deviceName: string;
+ local: boolean;
+ available: boolean;
+ unavailableReason?: string;
+}
+export interface HistoryRemoteDeps {
+ captureAccess(): () => void;
+ listDevices(): Promise<HistoryDevice[]>;
+ query(
+ deviceId: string,
+ tool: HistoryQueryTool,
+ args: Record<string, unknown>,
+ ): Promise<Record<string, unknown>>;
+}
+
+export const historyDeviceShape = {
+ device: z
+ .string()
+ .min(1)
+ .max(256)
+ .default("local")
+ .describe(
+ "local (default), all (local + online authorized computers), or exact deviceId from list_history_devices. Cross-device results are grouped by device; limit applies per device. Continue each group with its deviceId and nextCursor.",
+ ),
+};
+export const HISTORY_DEVICE_DESCRIPTION =
+ 'Use device="all" to discover/query local and online authorized computers, or list_history_devices then device=<exact id>. Results are grouped per device, with independent nextCursor values; paginate each device separately. Unavailable devices and partial coverage are explicit. Remote session IDs can be passed directly to get_chat_history. Local-only remains the default.';
+
+export function historyPayload(
+ result: XdtHelperToolResult,
+): Record<string, unknown> {
+ const block = result.content.find((item) => item.type === "text");
+ if (!block || block.type !== "text")
+ throw new Error("Invalid history response");
+ const value: unknown = JSON.parse(block.text);
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ throw new Error("Invalid history response");
+ return value as Record<string, unknown>;
+}
+
+/** Qualify only Session identities; source-local cursors and message IDs stay opaque. */
+export function qualifyHistoryPayload(
+ value: Record<string, unknown>,
+ deviceId: string,
+): Record<string, unknown> {
+ if (value.ok !== true) return value;
+ const qualify = (id: string) => `${deviceId}::${id}`;
+ if (Array.isArray(value.sessions)) {
+ return {
+ ...value,
+ sessions: value.sessions.map((s: Record<string, unknown>) => ({
+ ...s,
+ id: qualify(String(s.id)),
+ ...(typeof s.parentSessionId === "string"
+ ? { parentSessionId: qualify(s.parentSessionId) }
+ : {}),
+ })),
+ };
+ }
+ const sessions = value.sessions as Record<string, unknown> | undefined;
+ return {
+ ...value,
+ ...(sessions
+ ? {
+ sessions: Object.fromEntries(
+ Object.entries(sessions).map(([id, meta]) => [qualify(id), meta]),
+ ),
+ }
+ : {}),
+ ...(Array.isArray(value.hits)
+ ? {
+ hits: value.hits.map((h: Record<string, unknown>) => ({
+ ...h,
+ sessionId: qualify(String(h.sessionId)),
+ context: (h.context as Record<string, unknown>[]).map((c) => ({
+ ...c,
+ sessionId: qualify(String(c.sessionId)),
+ })),
+ })),
+ }
+ : {}),
+ };
+}
+
+export interface HistoryDeviceToolDeps {
+ history: XdtHelperHistoryDeps;
+ getSessionContext?: () => LiziMcpSessionContext | undefined;
+}
+
+export function registerHistoryDevicesTool(
+ registry: XdtHelperToolRegistry,
+ deps: HistoryDeviceToolDeps,
+): void {
+ registry.register({
+ name: "list_history_devices",
+ category: "history",
+ description:
+ "Discover computers for history queries. Returns exact device IDs, names, availability and reasons for unavailable devices. Does not enable remote access or read offline caches. Ownership-scoped callers cannot expand their history access.",
+ inputShape: {},
+ handler: async () => {
+ const assertCurrent = deps.history.remote?.captureAccess();
+ const scope = await resolveHistoryScope(
+ deps.history,
+ deps.getSessionContext,
+ null,
+ );
+ assertCurrent?.();
+ if (!scope.ok) return errorPayload(scope.errorCode, scope.message);
+ if (scope.sessionIds !== null)
+ return errorPayload(
+ "HISTORY_SCOPE_DENIED",
+ "当前伙伴只能查询自己的本机历史。",
+ );
+ if (!deps.history.remote)
+ return errorPayload(
+ "REMOTE_UNSUPPORTED",
+ "当前宿主不支持跨设备历史发现。",
+ );
+ try {
+ const devices = await deps.history.remote.listDevices();
+ assertCurrent?.();
+ return okPayload({ devices });
+ } catch {
+ return errorPayload(
+ "DEVICE_DISCOVERY_FAILED",
+ "无法取得设备列表,请稍后重试。",
+ );
+ }
+ },
+ });
+}
+
+/** Reuses the same local tool handler on both hosts, without a second query/formatting implementation. */
+export async function queryHistoryDevices(
+ registry: XdtHelperToolRegistry,
+ deps: HistoryDeviceToolDeps,
+ tool: HistoryQueryTool,
+ args: Record<string, unknown> & { device: string },
+): Promise<XdtHelperToolResult> {
+ const assertCurrent = deps.history.remote?.captureAccess() ?? (() => {});
+ const scope = await resolveHistoryScope(
+ deps.history,
+ deps.getSessionContext,
+ null,
+ );
+ assertCurrent();
+ if (!scope.ok) return errorPayload(scope.errorCode, scope.message);
+ if (scope.sessionIds !== null)
+ return errorPayload(
+ "HISTORY_SCOPE_DENIED",
+ "当前伙伴只能查询自己的本机历史。",
+ );
+ if (!deps.history.remote)
+ return errorPayload("REMOTE_UNSUPPORTED", "当前宿主不支持跨设备历史查询。");
+ if (args.device === "all" && args.cursor)
+ return errorPayload(
+ "INVALID_ARGS",
+ "跨设备翻页请使用对应组的 deviceId 和 nextCursor。",
+ );
+ // Qualified IDs must be routed to exactly their source. Never search a same-named local ID.
+ const requested = args.session_ids as string[] | undefined;
+ if (args.device === "all" && requested?.length)
+ return errorPayload(
+ "INVALID_ARGS",
+ "指定 session_ids 时请同时指定单台 device。",
+ );
+ if (
+ requested?.some((id) => id.includes("::")) &&
+ (args.device === "all" ||
+ requested.some((id) => !id.startsWith(`${args.device}::`)))
+ ) {
+ return errorPayload(
+ "INVALID_ARGS",
+ "带设备前缀的 session_ids 必须全部属于指定 device。",
+ );
+ }
+ let devices: HistoryDevice[];
+ let discoveryFailed = false;
+ try {
+ devices = await deps.history.remote.listDevices();
+ } catch {
+ if (args.device !== "all")
+ return errorPayload(
+ "DEVICE_DISCOVERY_FAILED",
+ "无法取得设备列表,请稍后重试。",
+ );
+ discoveryFailed = true;
+ devices = [
+ { deviceId: "local", deviceName: "Local", local: true, available: true },
+ ];
+ }
+ const targets =
+ args.device === "all"
+ ? devices
+ : devices.filter((d) => d.deviceId === args.device);
+ assertCurrent();
+ if (!targets.length)
+ return errorPayload("NOT_FOUND", "设备不在当前账号的可访问设备列表中。");
+ const groups: Record<string, unknown>[] = [];
+ // Small bounded batches, no persistent state, background retries or new connections outside existing policy.
+ for (let start = 0; start < targets.length; start += 3) {
+ groups.push(
+ ...(await Promise.all(
+ targets.slice(start, start + 3).map(async (device) => {
+ if (!device.available)
+ return {
+ ...device,
+ ok: false,
+ errorCode: device.unavailableReason,
+ };
+ const queryArgs = {
+ ...args,
+ device: "local",
+ ...(requested
+ ? {
+ session_ids: requested.map((id) =>
+ id.startsWith(`${device.deviceId}::`)
+ ? id.slice(device.deviceId.length + 2)
+ : id,
+ ),
+ }
+ : {}),
+ };
+ try {
+ assertCurrent();
+ const result = device.local
+ ? historyPayload(await registry.call(tool, queryArgs))
+ : qualifyHistoryPayload(
+ await deps.history.remote!.query(
+ device.deviceId,
+ tool,
+ queryArgs,
+ ),
+ device.deviceId,
+ );
+ assertCurrent();
+ return { ...result, ...device };
+ } catch {
+ return { ...device, ok: false, errorCode: "REMOTE_UNAVAILABLE" };
+ }
+ }),
+ )),
+ );
+ }
+ assertCurrent();
+ return okPayload({
+ groups,
+ partial: discoveryFailed || groups.some((group) => group.ok !== true),
+ ...(discoveryFailed ? { discoveryError: "DEVICE_DISCOVERY_FAILED" } : {}),
+ hasMore: groups.some((group) => group.hasMore === true),
+ pagination:
+ "Continue each successful group using device=<deviceId> and cursor=<nextCursor>, preserving query filters. Scores are comparable only within a device.",
+ });
+}
diff --git a/packages/lizi-mcps/src/xdt-helper/_history_types.ts b/packages/lizi-mcps/src/xdt-helper/_history_types.ts
index 11dc475b06..5c5ee1acc6 100644
--- a/packages/lizi-mcps/src/xdt-helper/_history_types.ts
+++ b/packages/lizi-mcps/src/xdt-helper/_history_types.ts
@@ -209,6 +209,7 @@ export interface SearchChatHistoryResult {
// ── Deps interface ─────────────────────────────────────────────────────────
export interface XdtHelperHistoryDeps {
+ remote?: import('./_history_devices.js').HistoryRemoteDeps;
/** Resolve the maximum history scope for the current runtime Session. */
resolveSessionScope?: (args: {
callerSessionId?: string;
diff --git a/packages/lizi-mcps/src/xdt-helper/capabilities.ts b/packages/lizi-mcps/src/xdt-helper/capabilities.ts
index 305ba4bbec..1ef3661df4 100644
--- a/packages/lizi-mcps/src/xdt-helper/capabilities.ts
+++ b/packages/lizi-mcps/src/xdt-helper/capabilities.ts
@@ -170,15 +170,16 @@ export const CAPABILITIES: readonly CapabilityEntry[] = [
},
{
key: 'chat-history-query',
- title: '聊天历史查询(给 LLM 自助拉本地对话数据)',
- oneLiner: 'agent 通过 MCP 工具拉本地 SQLite 里所有 session / message 原始数据,适合做用户级 memory / 知识库整理。',
+ title: '聊天历史查询(本机与在线已授权电脑)',
+ oneLiner: 'agent 可发现、列出和搜索本机与在线已授权电脑的聊天历史,并按任务读取内容。',
detail: [
- `【是什么】${BRAND_NAME} 所有用户和 agent 的对话全部存在本地 SQLite(按 userId 物理隔离), 但用户原本看不到这些数据, 也无法让 agent 帮忙整理。cindy_helper 的 history 类工具开放了五个只读查询入口, 让 agent 能拿到原始 raw data 与当前输入队列协助用户组织自己的 memory / 知识库系统。`,
- '【五个工具】(1)list_workdirs: 列出所有出现过的工作目录 + session 数 / 首末活动时间; (2)list_sessions: 按 workdir / 时间段 / agent_kind 过滤 session 元数据,并附当前 queuedCount; (3)list_session_queue: 按 session_id 查看尚未消费消息的位置、来源、入队时间、正文摘要与投递状态; (4)get_chat_history: 按 session_ids / workdir / 时间段 / role "按元数据精确捞"原始消息(content / agentMeta JSON 解析后透传); (5)search_chat_history: 跨 session "按内容语义找"——自然语言 query, FTS5 全文(全量、永远可用)+ 向量语义(开启"聊天记录语义索引"后生效)RRF 融合, 返回命中 + 上下文窗口。',
+ `【是什么】${BRAND_NAME} 的对话历史保存在各电脑的本地 SQLite。cindy_helper 的 history 类提供只读查询入口,让 agent 按宿主授予的范围读取历史,协助用户组织 memory / 知识库。`,
+ '【六个工具】(1)list_workdirs: 列出所有出现过的工作目录 + session 数 / 首末活动时间; (2)list_sessions: 按 workdir / 时间段 / agent_kind 过滤 session 元数据,并附当前 queuedCount; (3)list_session_queue: 按 session_id 查看尚未消费消息的位置、来源、入队时间、正文摘要与投递状态; (4)get_chat_history: 按 session_ids / workdir / 时间段 / role "按元数据精确捞"原始消息(content / agentMeta JSON 解析后透传); (5)search_chat_history: 跨 session "按内容语义找"——自然语言 query, FTS5 全文(全量、永远可用)+ 向量语义(开启"聊天记录语义索引"后生效)RRF 融合, 返回命中 + 上下文窗口; (6)list_history_devices: 发现本机与在线已授权电脑。',
'【典型用法】"帮我总结这周和 agent 的讨论, 写成 memory 条目" → list_sessions({from: 周一 ISO}) 拿 sessionId 列表 → get_chat_history({session_ids: [...]}) 拿对话 → LLM 提炼成 memory。"我之前聊过 X / 上次怎么解决那个 bug"(只记得内容、不知道在哪) → search_chat_history({query}) 直接语义召回。"我在 xxx 项目里都聊过啥" → list_sessions({workdir}) → get_chat_history。',
+ '【跨设备】list_history_devices 发现设备;list_sessions / search_chat_history 传 device="all" 查询本机与在线已授权电脑,或 device=<设备 ID> 指定电脑。结果按设备分组,每组独立翻页,partial 表示有设备未查到。远程任务 ID 带 deviceId:: 前缀,可直接传给 get_chat_history;不读取离线缓存,旧端不支持会明确报告。默认 device="local" 保持原本机查询。',
'【向量是增益不是依赖】search_chat_history 在用户没开 embedding / sqlite-vec 不可用时静默退化为纯 FTS, 搜索照常工作; 响应里 vector_used 标明向量是否生效。',
- '【分页】所有工具游标分页, 单次硬上限防炸 context, 但 hasMore + nextCursor 串联多次调用可拿全量, 不会丢信息。',
- '【权限】数据按 userId 物理隔离, 工具允许查当前用户所有 session 的全量历史。',
+ '【分页】任务列表与聊天读取可用 hasMore + nextCursor 持续翻页;跨设备时每台电脑独立翻页。搜索受候选池上限约束,pool_capped=true 时应缩小查询范围,不能声称已经穷尽全部匹配。',
+ '【权限】遵循宿主授予的账号历史权限与设备授权;仅有归属范围权限的调用方不能扩大范围,远程查询保留任务可见性限制。',
'【与 memory-system 的区别】memory-system(cindy_memory)管理的是已经提炼好的 markdown 记忆条目; chat-history-query 给的是原始对话数据本身, 是上游素材。两者通常配合用: 先 get_chat_history 拉素材, 再 memory_write 落条目。',
].join(' '),
},
diff --git a/packages/lizi-mcps/src/xdt-helper/index.ts b/packages/lizi-mcps/src/xdt-helper/index.ts
index 679472ec33..14d6d8fc94 100644
--- a/packages/lizi-mcps/src/xdt-helper/index.ts
+++ b/packages/lizi-mcps/src/xdt-helper/index.ts
@@ -100,6 +100,8 @@ export {
type ModelDescriptor,
} from './list_available_models.js';
// history tools (split out from xdt-helper but kept exports here)
+export { registerHistoryDevicesTool, historyPayload } from './_history_devices.js';
+export type { HistoryRemoteDeps, HistoryDevice, HistoryQueryTool } from './_history_devices.js';
export {
registerListWorkdirsTool,
type ListWorkdirsToolDeps,
diff --git a/packages/lizi-mcps/src/xdt-helper/list_sessions.ts b/packages/lizi-mcps/src/xdt-helper/list_sessions.ts
index 702ffc2b60..0036eff287 100644
--- a/packages/lizi-mcps/src/xdt-helper/list_sessions.ts
+++ b/packages/lizi-mcps/src/xdt-helper/list_sessions.ts
@@ -19,9 +19,11 @@ import type { SessionQueueDeps } from './list_session_queue.js';
import { okPayload, errorPayload } from './_payload.js';
import { encodeCursor, decodeCursor } from './_history_cursor.js';
import { resolveHistoryScope } from './_history_scope.js';
+import { historyDeviceShape, HISTORY_DEVICE_DESCRIPTION, queryHistoryDevices } from './_history_devices.js';
const DESCRIPTION = [
- '列出本地数据库里的 session 元数据(id / title / workingDir / agentKind / model /',
+ HISTORY_DEVICE_DESCRIPTION,
+ '列出所选电脑数据库里的 session 元数据(id / title / workingDir / agentKind / model /',
'时间戳 / messageCount 等), 按多种过滤条件组合查。**不返回 messages 内容** —',
'要拉具体聊天内容请用 get_chat_history。',
'',
@@ -35,7 +37,7 @@ const DESCRIPTION = [
' - include_deleted: 默认 false (排除 status=deleted)',
'',
'【输出】messageCount 已过滤被 rewind 软删的消息, 是用户可见的真实条数。',
- 'queuedCount 是当前尚未消费的输入队列条数,可用 list_session_queue 查看明细。',
+ '本机结果的 queuedCount 是当前尚未消费的输入队列条数,可用 list_session_queue 查看本机明细;远程结果不含队列计数。',
'时间戳均为 ISO 8601 字符串(对应 DB 里的 unix ms 转换)。',
'orcaRole / parentSessionId / userSendAt 仅在非 null 时出现(默认场景几乎全为 null, 已 omit)。',
'',
@@ -57,6 +59,7 @@ export function registerListSessionsTool(
category: 'history',
description: DESCRIPTION,
inputShape: {
+ ...historyDeviceShape,
workdir: z
.string()
.optional()
@@ -84,7 +87,9 @@ export function registerListSessionsTool(
.default('desc')
.describe('按 sessions.createdAt 排序, desc = 最新在前(默认)。'),
},
- handler: async ({ workdir, from, to, agent_kind, include_deleted, limit, cursor, order }) => {
+ handler: async (args) => {
+ if (args.device !== 'local') return queryHistoryDevices(registry, deps, 'list_sessions', args);
+ const { workdir, from, to, agent_kind, include_deleted, limit, cursor, order } = args;
const scope = await resolveHistoryScope(deps.history, deps.getSessionContext, null);
if (!scope.ok) return errorPayload(scope.errorCode, scope.message);
const fromMs = parseIsoMs(from);
diff --git a/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts b/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts
index 82fa1a54cb..9c554727bf 100644
--- a/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts
+++ b/packages/lizi-mcps/src/xdt-helper/search_chat_history.ts
@@ -30,6 +30,7 @@ import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
import type { XdtHelperHistoryDeps, HistoryRole } from './_history_types.js';
import { okPayload, errorPayload } from './_payload.js';
import { resolveHistoryScope } from './_history_scope.js';
+import { historyDeviceShape, HISTORY_DEVICE_DESCRIPTION, queryHistoryDevices } from './_history_devices.js';
const ROLE_VALUES = [
'user',
@@ -45,6 +46,7 @@ const ROLE_VALUES = [
const DEFAULT_QA_ROLES = ['user', 'assistant', 'ask_user', 'plan_review'] as const satisfies readonly HistoryRole[];
const DESCRIPTION = [
+ HISTORY_DEVICE_DESCRIPTION,
'跨所有 session 用自然语言语义检索历史聊天记录, 返回相关命中 + 上下文窗口的原始数据。',
'',
'【何时调用】用户"我之前聊过 X / 上次怎么解决那个 bug / 关于 Y 我们讨论过啥"等',
@@ -84,6 +86,7 @@ export function registerSearchChatHistoryTool(
category: 'history',
description: DESCRIPTION,
inputShape: {
+ ...historyDeviceShape,
query: z.string().min(1).max(256).describe('自然语言查询(必填, 最长 256)。例: "上次怎么修的语音输入授权问题"。'),
session_ids: z
.array(z.string().min(1))
@@ -114,18 +117,21 @@ export function registerSearchChatHistoryTool(
limit: z.number().int().min(1).max(50).default(10).describe('融合后返回命中条数, 1-50, 默认 10。'),
cursor: z.string().optional().describe('上次响应的 nextCursor; 不传 = 第一页。坏 cursor 自动回第一页。'),
},
- handler: async ({
- query,
- session_ids,
- workdir,
- from,
- to,
- agent_kind,
- roles,
- context_radius,
- limit,
- cursor,
- }) => {
+ handler: async (args) => {
+ if (args.device !== 'local') return queryHistoryDevices(registry, deps, 'search_chat_history', args);
+ if (args.session_ids?.some((id) => id.includes('::'))) return errorPayload('INVALID_ARGS', '远程 session_ids 必须指定对应 device,不能作为本机 ID 查询。');
+ const {
+ query,
+ session_ids,
+ workdir,
+ from,
+ to,
+ agent_kind,
+ roles,
+ context_radius,
+ limit,
+ cursor,
+ } = args;
const scope = await resolveHistoryScope(
deps.history,
deps.getSessionContext,