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(search): 侧栏和手机搜索覆盖伙伴个人聊天与归档历史 (#6548)

Chris Zhang24fab987dff7
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 ea6e377802..96cbf77d17 100644
--- a/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/remoteBotSessionBoundary.test.ts
@@ -204,3 +204,15 @@ it('does not let another computer message a hidden teammate task through session
.rejects.toThrow('[NOT_FOUND] Session does not exist');
await expect(assertRemoteBotInvocationAllowed(request('normal'), 'maker:session:handoff')).resolves.toBeUndefined();
});
+
+// A cached search reply must respect a later hide just like a fresh query. Unit tier.
+it('rechecks companion search snippets on queued delivery without hiding ordinary tasks', async () => {
+ let hidden = false;
+ setRemoteBotSessionLookup(async () => hidden ? 'hidden' : 'visible');
+ const ordinary = { session: { id: 'task' } };
+ const personal = { session: { id: 'chat', companion: { id: 'bot' } }, contentHit: { preview: 'private' } };
+ const page = { results: [ordinary, personal] };
+ expect(await projectRemoteSessionResult('local-db:conversations:search', page)).toEqual(page);
+ hidden = true;
+ expect(await projectRemoteSessionResult('local-db:conversations:search', page)).toEqual({ results: [ordinary] });
+});
diff --git a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
index 0177995d01..59f5d9564f 100644
--- a/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
+++ b/apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts
@@ -178,6 +178,25 @@ export async function assertRemoteBotInvocationAllowed(args: unknown[], channel
}
export async function projectRemoteSessionResult(channel: string, value: unknown): Promise<unknown> {
+ if (channel === 'local-db:conversations:search') {
+ if (!lookup) throw new Error('[HOST_NOT_READY] History visibility is not ready');
+ const row = record(value);
+ if (!row || !Array.isArray(row.results)) return value;
+ // Search pages can wait in the transport cache while a companion is hidden.
+ // Re-check personal ownership before returning snippets or identity metadata.
+ const ids = [...new Set(row.results.flatMap(item => {
+ const id = record(record(record(item)?.session)?.companion)?.id;
+ return typeof id === 'string' ? [id] : [];
+ }))];
+ const access = batchLookup
+ ? await batchLookup(ids, 'bot')
+ : new Map(await Promise.all(ids.map(async id => [id, await lookup!(id, 'bot')] as const)));
+ const results = row.results.filter(item => {
+ const id = record(record(record(item)?.session)?.companion)?.id;
+ return typeof id !== 'string' || access.get(id) === 'visible';
+ });
+ return { ...row, results };
+ }
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.
diff --git a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
index 4772dad8ef..9c3d528b44 100644
--- a/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/conversationSearch.test.ts
@@ -46,14 +46,6 @@ describe('conversationSearch source invariants', () => {
expect(conversationSearchSource).toContain('title: row.title,');
});
- it('keeps ordinary task search on the task-list source boundary by default', () => {
- // Same boundary as the sidebar: /review Reviewer tasks are opened from their
- // source card, not found as ordinary tasks.
- expect(conversationSearchSource).toContain(
- 'hostScope.sessionSources === undefined\n ? DESKTOP_TASK_LIST_SESSION_SOURCES',
- );
- });
-
it('applies grouping-normalized workingDirs so remote project search is not window-bound', () => {
expect(conversationSearchSource).toContain('applyWorkingDirFilter');
expect(conversationSearchSource).toContain('normalizeWorkingDirForGrouping');
@@ -146,6 +138,12 @@ function createSearchDb(): Database.Database {
created_at INTEGER NOT NULL,
rewind_at INTEGER
);
+ CREATE TABLE bot_profiles (
+ id TEXT PRIMARY KEY, display_name TEXT NOT NULL, status TEXT NOT NULL, hidden_at INTEGER
+ );
+ CREATE TABLE bot_session_links (
+ session_id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, role TEXT NOT NULL
+ );
`);
return db;
}
@@ -246,3 +244,51 @@ describe('conversationSearch plugin background tasks', () => {
}
});
});
+
+// Production search entry + real SQLite. The prior source-only test could not
+// catch missing personal history or leaked imported channel lanes. Unit tier.
+describe('conversationSearch personal companion chats', () => {
+ it('finds hidden/archived personal threads and imported history, excluding internal lanes and deleted tasks', async () => {
+ const db = createSearchDb();
+ const client = makeSearchDbClient(db);
+ setCurrentDbClient(client, 'test-user');
+ mocks.searchChatHistoryHybrid.mockResolvedValue({
+ hits: [], sessions: {}, vectorUsed: false, vectorSkipReason: null,
+ nextOffset: null, hasMore: false, poolSize: 0, poolCapped: false,
+ });
+ try {
+ db.exec("INSERT INTO bot_profiles VALUES ('bot', 'Melody', 'active', 5)");
+ for (const [id, source, role, status] of [
+ ['main', 'bot', 'canonical', 'active'],
+ ['old', 'bot', 'history', 'archived'],
+ ['imported', 'feishu', 'history', 'archived'],
+ ['group', 'bot', 'group', 'active'],
+ ['channel', 'desktop', 'channel', 'active'],
+ ['deleted', 'bot', 'history', 'deleted'],
+ ['task', 'desktop', 'delegation', 'active'],
+ ['review', 'review', null, 'active'],
+ ]) {
+ insertSearchSession(db, id!, 10, null);
+ db.prepare('UPDATE sessions SET source = ?, status = ? WHERE id = ?').run(source, status, id);
+ if (role) db.prepare('INSERT INTO bot_session_links VALUES (?, ?, ?)').run(id, 'bot', role);
+ }
+ const result = await searchConversations({ query: 'needle', semanticMode: 'keyword' });
+ expect(result.results.map(item => item.session.id).sort()).toEqual(['imported', 'main', 'old', 'task']);
+ expect(result.results.find(item => item.session.id === 'old')?.session.companion).toEqual({
+ id: 'bot', name: 'Melody', role: 'history', readOnly: true,
+ });
+ expect(result.results.find(item => item.session.id === 'main')?.session.companion?.readOnly).toBe(false);
+ expect(result.results.find(item => item.session.id === 'task')?.session.companion).toBeUndefined();
+ expect(mocks.searchChatHistoryHybrid.mock.calls[0][0].sessionIds.sort()).toEqual(['imported', 'main', 'old', 'task']);
+ expect(mocks.searchChatHistoryHybrid.mock.calls[0][0].sessionSources).toBeNull();
+ const remote = await searchConversations({ query: 'needle' }, { remoteVisibleOnly: true });
+ expect(remote.results.map(item => item.session.id)).toEqual(['task']);
+ db.exec("UPDATE bot_profiles SET hidden_at = NULL");
+ const visibleRemote = await searchConversations({ query: 'needle', filters: { status: 'archived' } }, { remoteVisibleOnly: true });
+ expect(visibleRemote.results.map(item => item.session.id).sort()).toEqual(['imported', 'old']);
+ } finally {
+ clearCurrentDbClient(client);
+ db.close();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/localDb/conversationSearch.ts b/apps/desktop/src/main/localDb/conversationSearch.ts
index 08a0fd95e6..9b232d1a92 100644
--- a/apps/desktop/src/main/localDb/conversationSearch.ts
+++ b/apps/desktop/src/main/localDb/conversationSearch.ts
@@ -1,4 +1,4 @@
-import { and, count, desc, eq, gte, inArray, isNull, ne, or } from 'drizzle-orm';
+import { and, count, desc, eq, getTableColumns, gte, inArray, isNull, ne, or } from 'drizzle-orm';
import type {
ConversationSearchAgentFilter,
@@ -17,7 +17,7 @@ import { DESKTOP_TASK_LIST_SESSION_SOURCES } from '../../shared/sessionSource.js
import type { SessionSource } from '../../shared/sessionSource.js';
import { normalizeWorkingDirForGrouping } from '../../shared/workingDir.js';
import { getDbClient } from './client/current.js';
-import { messages, sessions } from './schema.js';
+import { botProfiles, botSessionLinks, messages, sessions } from './schema.js';
import { searchChatHistoryHybrid } from './chatHistorySearch.js';
import { normalizeDbAgentKind } from '../../shared/agentKindConversion.js';
import { visibleTextMatchesMessagesFtsQuery } from './chatHistorySearch.pure.js';
@@ -48,15 +48,21 @@ const LAST_ACTIVITY_DAY_COUNTS: Record<
};
const DAY_MS = 24 * 60 * 60 * 1000;
-type SessionRow = typeof sessions.$inferSelect;
+type SessionRow = typeof sessions.$inferSelect & {
+ companionId: string | null;
+ companionName: string | null;
+ companionStatus: string | null;
+ companionRole: typeof botSessionLinks.$inferSelect.role | null;
+};
export interface ConversationSearchHostScope {
/**
- * Main-owned source scope. Undefined preserves the normal desktop task
- * search boundary; null permits every source only when another authoritative
+ * Main-owned source scope. Undefined includes normal tasks and linked personal
+ * companion chats; null permits every source only when another authoritative
* filter (for example Bot-owned Session ids) already constrains the query.
*/
sessionSources?: readonly SessionSource[] | null;
+ remoteVisibleOnly?: boolean;
}
export async function searchConversations(
@@ -76,9 +82,9 @@ export async function searchConversations(
const limit = clampLimit(request.limit);
const filters = normalizeFilters(request);
- const sessionSources = hostScope.sessionSources === undefined
- ? DESKTOP_TASK_LIST_SESSION_SOURCES
- : hostScope.sessionSources;
+ // Linked personal history may retain an imported IM source. Candidate selection
+ // below owns the boundary; content retrieval uses those exact ids.
+ const sessionSources = hostScope.sessionSources ?? null;
const sortBy = normalizeSortBy(request.sortBy);
const skipVector = request.semanticMode === 'keyword';
if (filters.sessionIds && filters.sessionIds.length === 0) {
@@ -91,7 +97,7 @@ export async function searchConversations(
};
}
const sessionRows = applyWorkingDirFilter(
- await listSearchableSessions(filters, sessionSources),
+ await listSearchableSessions(filters, hostScope.sessionSources, hostScope.remoteVisibleOnly),
filters.workingDirs,
);
if (sessionRows.length === 0) {
@@ -323,9 +329,10 @@ function normalizeSortBy(value: ConversationSearchSortBy | undefined): Conversat
async function listSearchableSessions(
filters: NormalizedConversationSearchFilters,
- sessionSources: readonly SessionSource[] | null,
+ sessionSources: readonly SessionSource[] | null | undefined,
+ remoteVisibleOnly = false,
): Promise<SessionRow[]> {
- if (sessionSources !== null && sessionSources.length === 0) return [];
+ if (sessionSources != null && sessionSources.length === 0) return [];
const db = getDbClient().drizzle;
const statusCond = statusCondition(filters.status);
const agentCond = filters.agentKind === 'all' ? undefined : eq(sessions.agentKind, filters.agentKind);
@@ -339,11 +346,35 @@ async function listSearchableSessions(
const activityCond = activityCutoff === null
? undefined
: or(gte(sessions.updatedAt, activityCutoff), gte(sessions.userSendAt, activityCutoff));
+ const personalChat = and(
+ inArray(botSessionLinks.role, ['canonical', 'history']),
+ ne(botProfiles.status, 'deleting'),
+ );
return db
- .select()
+ .select({
+ ...getTableColumns(sessions),
+ companionId: botProfiles.id,
+ companionName: botProfiles.displayName,
+ companionStatus: botProfiles.status,
+ companionRole: botSessionLinks.role,
+ })
.from(sessions)
+ .leftJoin(botSessionLinks, eq(botSessionLinks.sessionId, sessions.id))
+ .leftJoin(botProfiles, eq(botProfiles.id, botSessionLinks.botId))
.where(and(
- sessionSources === null ? undefined : inArray(sessions.source, sessionSources),
+ sessionSources === undefined
+ ? or(inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES), personalChat)
+ : sessionSources === null ? undefined : inArray(sessions.source, sessionSources),
+ // Migrated channel/group lanes may have an ordinary task source.
+ or(isNull(botSessionLinks.role), and(
+ ne(botSessionLinks.role, 'group'),
+ ne(botSessionLinks.role, 'channel'),
+ )),
+ remoteVisibleOnly ? or(isNull(botProfiles.id), eq(botSessionLinks.role, 'delegation'), and(
+ or(isNull(botProfiles.hiddenAt), eq(botProfiles.hiddenAt, 0)),
+ ne(botProfiles.status, 'archived'),
+ ne(botProfiles.status, 'deleting'),
+ )) : undefined,
statusCond,
agentCond,
sessionIdsCond,
@@ -409,6 +440,15 @@ function sessionSummaryFromRow(
source: row.source,
orcaRole: row.orcaRole,
parentSessionId: row.parentSessionId,
+ ...(row.companionId && row.companionName != null
+ && (row.companionRole === 'canonical' || row.companionRole === 'history')
+ ? { companion: {
+ id: row.companionId,
+ name: row.companionName,
+ role: row.companionRole,
+ readOnly: row.companionRole === 'history' || row.status !== 'active' || row.companionStatus !== 'active',
+ } }
+ : {}),
userSendAt: row.userSendAt === null ? null : new Date(row.userSendAt).toISOString(),
updatedAt: new Date(row.updatedAt).toISOString(),
createdAt: new Date(row.createdAt).toISOString(),
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 56f7bf205f..5b224c2665 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -1128,10 +1128,25 @@ async function readRemoteBotProfile(client: ReturnType<typeof getDbClient>, botI
if (!isBotVisibleRemotely(profile)) return null;
const canonicalResolution = await reconcileCanonicalLink(botId, client);
owner.assertCurrent();
+ // Personal transcript links let search entries open the exact historical task.
+ // No group/channel lanes, prompts, credentials or runtime configuration.
+ const personalSessions = await db.select({
+ id: sessions.id,
+ role: botSessionLinks.role,
+ status: sessions.status,
+ }).from(botSessionLinks)
+ .innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))
+ .where(and(
+ eq(botSessionLinks.botId, botId),
+ inArray(botSessionLinks.role, ['canonical', 'history']),
+ ne(sessions.status, 'deleted'),
+ ));
+ owner.assertCurrent();
const { hiddenAt: _hiddenAt, ...visibleProfile } = profile;
return {
...visibleProfile,
canonicalSessionId: canonicalResolution.canonicalSessionId ?? undefined,
+ sessions: personalSessions,
};
}
diff --git a/apps/desktop/src/main/localDb/ipc/search.ts b/apps/desktop/src/main/localDb/ipc/search.ts
index 67d03c3c24..5cef9c0041 100644
--- a/apps/desktop/src/main/localDb/ipc/search.ts
+++ b/apps/desktop/src/main/localDb/ipc/search.ts
@@ -1,4 +1,5 @@
import { ipcMain } from 'electron';
+import { isDeviceLinkInvoke } from '../../device-link/invoke-context.js';
import { searchConversations } from '../conversationSearch.js';
import type {
@@ -36,7 +37,7 @@ export function registerSearchIpc(): void {
| undefined;
const filters = parseFilters(body.filters);
const unnamedLabel = parseUnnamedLabel(body.unnamedLabel);
- return searchConversations({
+ const request = {
query,
limit,
includeArchived,
@@ -44,7 +45,10 @@ export function registerSearchIpc(): void {
semanticMode,
filters,
unnamedLabel,
- });
+ };
+ return isDeviceLinkInvoke()
+ ? searchConversations(request, { remoteVisibleOnly: true })
+ : searchConversations(request);
});
}
diff --git a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts
index 3d5e9e04e6..7d27bcc3ce 100644
--- a/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts
+++ b/apps/desktop/src/renderer/__tests__/conversationSearchBox.test.ts
@@ -751,3 +751,27 @@ describe('ConversationSearchBox live search', () => {
);
});
});
+
+// Real search control: a hidden/unloaded companion must not fall back to an
+// ordinary writable task, and the selected message anchor must survive. Unit tier.
+it.each(['canonical', 'history'] as const)('opens %s companion search results without the loaded roster', async role => {
+ const hit = { messageId: 'message', messageClientId: 'client', role: 'assistant' as const,
+ createdAt: '2026-10-20T00:00:00Z', snippet: null, preview: 'needle reply', score: 1, ftsRank: 1, vectorRank: null };
+ vi.mocked(searchConversations).mockResolvedValue({ query: 'needle', results: [{
+ session: { id: 'chat', title: 'needle thread', workingDir: null, workspaceKind: 'dialogue',
+ agentKind: 'pi', status: role === 'history' ? 'archived' : 'active', source: 'bot',
+ userSendAt: null, updatedAt: '2026-10-20T00:00:00Z', createdAt: '2026-10-20T00:00:00Z', _count: { messages: 1 },
+ companion: { id: 'bot', name: 'Melody', role, readOnly: role === 'history' } },
+ matchKind: 'content', titleMatchIndices: [], titleScore: null, contentHit: hit, contentHits: [hit], rankScore: 1,
+ }], vectorUsed: false, vectorSkipReason: null, poolCapped: false });
+ renderSearchBox();
+ fireEvent.click(screen.getByLabelText('ccAgent.search.open'));
+ fireEvent.change(screen.getByLabelText('ccAgent.search.placeholder'), { target: { value: 'needle' } });
+ const result = await screen.findByRole('button', { name: /needle thread/ });
+ expect(result.textContent).toContain('Melody');
+ fireEvent.click(result);
+ await waitFor(() => expect(navigate).toHaveBeenCalledWith(
+ role === 'history' ? '/bots/bot/history/chat' : '/bots/bot/session/chat',
+ { state: { searchJump: { kind: 'conversation-search', sessionId: 'chat', messageId: 'message', messageClientId: 'client' } } },
+ ));
+});
diff --git a/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx b/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx
index 981b9f7a13..2791485496 100644
--- a/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx
@@ -6,6 +6,9 @@ import { CCAgentSessionView } from '@/features/cc-agent/CCAgentSessionView';
import type { BotChatIdentity } from './BotSessionContentHeader';
import { readIslandEntryRouteState, requestIslandEntryAlertDisposal } from './islandEntryAlert';
import { useBotIslandVisibleSession } from './useBotIslandVisibleSession';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import type { Session } from '@/lib/ccAgent.types';
function readBotChatIdentity(bot: unknown, botId: string): BotChatIdentity | null {
if (!bot || typeof bot !== 'object') return null;
@@ -20,13 +23,13 @@ function readBotChatIdentity(bot: unknown, botId: string): BotChatIdentity | nul
/** Historical Bot transcripts are reviewable but never writable from the history route. */
export function BotHistorySessionView() {
- const { botId, sessionId } = useParams();
- return <BotHistorySessionGateView key={JSON.stringify([botId, sessionId])} />;
+ const { botId, sessionId, deviceId } = useParams();
+ return <BotHistorySessionGateView key={JSON.stringify([deviceId, botId, sessionId])} />;
}
function BotHistorySessionGateView() {
const { t } = useTranslation();
- const { botId, sessionId } = useParams();
+ const { botId, sessionId, deviceId } = useParams();
const [allowed, setAllowed] = useState<boolean | null>(null);
useBotIslandVisibleSession(allowed === true ? sessionId ?? null : null);
// 灵动岛点进来的那张卡,只在本门禁确认并显示了这段历史后才处置;被重定向走则保留。
@@ -43,16 +46,31 @@ function BotHistorySessionGateView() {
useEffect(() => {
let cancelled = false;
+ const owner = getDataOwnerGeneration();
+ const current = () => !cancelled && isDataOwnerGenerationCurrent(owner);
if (!botId || !sessionId) {
setAllowed(false);
return () => {
cancelled = true;
};
}
- void window.electronAPI.localDb.bots
- .history(botId)
- .then((rows) => {
- if (cancelled) return;
+ const profile = deviceId
+ ? window.electronAPI.deviceLink.invoke(deviceId, 'local-db:bots:get', [botId])
+ : window.electronAPI.localDb.bots.get(botId);
+ const personalLink = (bot: unknown) => {
+ const rows = (bot as { sessions?: Array<{ id: string; role?: string; status?: string }> } | null)?.sessions;
+ return rows?.some(row => row.id === sessionId && row.status !== 'deleted'
+ && (row.role === 'history' || row.role === 'canonical')) ?? false;
+ };
+ const history = deviceId
+ ? profile.then(bot => personalLink(bot) ? [{ id: sessionId }] : [])
+ : window.electronAPI.localDb.bots.history(botId).then(async rows =>
+ rows.some(row => (row as { id?: string })?.id === sessionId)
+ ? rows
+ : personalLink(await profile) ? [{ id: sessionId }] : []);
+ void history
+ .then(async (rows) => {
+ if (!current()) return;
const found = rows.some(
(row) =>
!!row &&
@@ -61,24 +79,45 @@ function BotHistorySessionGateView() {
typeof (row as { id?: unknown }).id === 'string' &&
(row as { id: string }).id === sessionId,
);
+ if (found && deviceId) {
+ const origin = remoteProjectsStore.getSessionDeviceId(sessionId);
+ if (origin && origin !== deviceId) throw new Error('Conflicting remote session owner');
+ remoteProjectsStore.pinSessionOrigin(deviceId, sessionId);
+ const isReadCurrent = remoteProjectsStore.captureSessionRead(deviceId, sessionId);
+ const value = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:sessions:get', [sessionId]);
+ if (!current()) return;
+ const readIsCurrent = isReadCurrent();
+ const mirror = remoteProjectsStore.getDeviceSessions(deviceId).find(row => row.id === sessionId);
+ const session = readIsCurrent ? value as Session | null : mirror;
+ if (!session || session.id !== sessionId
+ || (session.status !== 'active' && session.status !== 'archived')
+ || (!readIsCurrent && session.deviceLinkConnectionStatus !== 'connected')) {
+ throw new Error('Invalid remote companion history');
+ }
+ // The shared chat reads remote metadata only from this mirror, including
+ // the header. Preserve the status bucket and any newer push/activity.
+ if (readIsCurrent) remoteProjectsStore.mergeDeviceSessions(
+ deviceId, remoteProjectsStore.getDeviceName(deviceId) ?? deviceId,
+ [isReadCurrent.mergeActivity(session)], session.status,
+ );
+ }
setAllowed(found);
})
.catch(() => {
- if (!cancelled) setAllowed(false);
+ if (current()) setAllowed(false);
});
// Profile 装饰可异步补齐;已验证的伙伴历史始终保持伙伴界面。
- void window.electronAPI.localDb.bots
- .get(botId)
+ void profile
.then((bot) => {
- if (!cancelled) setIdentity(readBotChatIdentity(bot, botId));
+ if (current()) setIdentity(readBotChatIdentity(bot, botId));
})
.catch(() => {
- if (!cancelled) setIdentity(null);
+ if (current()) setIdentity(null);
});
return () => {
cancelled = true;
};
- }, [botId, sessionId]);
+ }, [botId, sessionId, deviceId]);
if (allowed === null) {
return (
@@ -88,12 +127,15 @@ function BotHistorySessionGateView() {
);
}
if (!allowed || !botId || !sessionId) {
- return <Navigate to={botId ? `/bots/${botId}?settings=1` : '/bots'} replace />;
+ return <Navigate to={botId
+ ? deviceId ? `/bots/remote/${encodeURIComponent(deviceId)}/${encodeURIComponent(botId)}`
+ : `/bots/${encodeURIComponent(botId)}?settings=1`
+ : '/bots'} replace />;
}
return (
<CCAgentSessionView
readOnly
- botIdentity={{ ...(identity ?? { id: botId, name: '' }), sessionId }}
+ botIdentity={{ ...(identity ?? { id: botId, name: '' }), sessionId, ...(deviceId ? { deviceId } : {}) }}
/>
);
}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.ts
index 1404df1b9f..9dc18e597b 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.ts
@@ -172,15 +172,8 @@ describe('Bot task route recovery', () => {
expect(source).toContain('botUnreadBoundaryAt={gate.unreadBoundaryAt}');
});
- it.each(['\n', '\r\n'])('keeps the teammate a teammate in archived transcripts with line ending %j, without touching the write path', (lineEnding) => {
- const history = readFileSync(resolve(__dirname, '..', 'BotHistorySessionView.tsx'), 'utf8')
- .replace(/\r?\n/g, lineEnding);
- // 只读历史也带头像与伙伴 lockup:这个视图本来就已经查过 history(botId) 确认归属。
- expect(history).toMatch(/window\.electronAPI\.localDb\.bots\s*\.get\(botId\)/);
- expect(history).toContain(
- "botIdentity={{ ...(identity ?? { id: botId, name: '' }), sessionId }}",
- );
- });
+ // Archived transcript identity/read-only coverage lives in the rendered
+ // BotHistorySessionView cases in botSessionPresentation.test.tsx.
it('keeps welcome delivery out of the renderer navigation projection', () => {
// 欢迎语由 main 在创建伙伴和持久任务关系的同一边界内落库。URL 只负责
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx
index 9192bcd1df..7df0542c77 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionPresentation.test.tsx
@@ -2,10 +2,11 @@
import { act, cleanup, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { resolveBotChatIdentity, type BotChatBinding } from '../botChatPresentation';
+import { remoteProjectsStore, useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';
const h = vi.hoisted(() => ({
- params: { botId: 'bot', sessionId: 'chat' },
- get: vi.fn(), list: vi.fn(), history: vi.fn(),
+ params: { botId: 'bot', sessionId: 'chat', deviceId: undefined as string | undefined },
+ get: vi.fn(), list: vi.fn(), history: vi.fn(), invoke: vi.fn(),
profiles: [] as Array<{ id: string; name: string; avatar: string; avatarColor: string; invitation?: { stage: string } }>,
profileListeners: new Set<() => void>(),
}));
@@ -29,21 +30,26 @@ vi.mock('react-router-dom', () => ({
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('../useBotIslandVisibleSession', () => ({ useBotIslandVisibleSession: () => {} }));
vi.mock('@/features/cc-agent/CCAgentSessionView', () => ({
- CCAgentSessionView: ({ botIdentity, botInvitationStage }: { botIdentity?: BotChatBinding; botInvitationStage?: string }) => {
+ CCAgentSessionView: ({ botIdentity, botInvitationStage, readOnly }: { botIdentity?: BotChatBinding; botInvitationStage?: string; readOnly?: boolean }) => {
+ const sessions = useRemoteProjectSessions();
const identity = resolveBotChatIdentity(botIdentity, h.params.sessionId);
- return <div data-name={identity?.name} data-invitation-stage={botInvitationStage ?? ''}>{identity ? `companion:${identity.id}` : 'task controls'}</div>;
+ // The real chat header requires session metadata from this mirror. Keep the
+ // production gate/store path; omit the unrelated editor and transcript tree.
+ if (h.params.deviceId && !sessions.some(row => row.id === h.params.sessionId)) return <div>metadata-loading</div>;
+ return <div data-name={identity?.name} data-avatar={identity?.avatar} data-device-id={identity?.deviceId} data-read-only={readOnly} data-invitation-stage={botInvitationStage ?? ''}>{identity ? `companion:${identity.id}` : 'task controls'}</div>;
},
}));
import { BotSessionView } from '../BotSessionView';
import { BotHistorySessionView } from '../BotHistorySessionView';
beforeEach(() => {
- h.params = { botId: 'bot', sessionId: 'chat' };
+ h.params = { botId: 'bot', sessionId: 'chat', deviceId: undefined };
h.get.mockReset(); h.list.mockReset().mockResolvedValue([]); h.history.mockReset();
+ h.invoke.mockReset(); remoteProjectsStore.clear(); remoteProjectsStore.__resetPinnedOriginsForTest();
h.profiles = []; h.profileListeners.clear();
- window.electronAPI = { localDb: { bots: { get: h.get, list: h.list, history: h.history } } } as unknown as Window['electronAPI'];
+ window.electronAPI = { localDb: { bots: { get: h.get, list: h.list, history: h.history } }, deviceLink: { invoke: h.invoke } } as unknown as Window['electronAPI'];
});
-afterEach(cleanup);
+afterEach(() => { cleanup(); remoteProjectsStore.clear(); remoteProjectsStore.__resetPinnedOriginsForTest(); });
it('mounts the simplified chat only after verifying the durable link, without another session GET', async () => {
let resolve!: (value: unknown) => void;
h.get.mockReturnValue(new Promise((done) => { resolve = done; }));
@@ -78,7 +84,7 @@ it('drops the previous binding synchronously when navigating to a different Bot
const view = render(<BotSessionView />);
await screen.findByText('companion:bot');
h.get.mockReturnValue(new Promise(() => {}));
- h.params = { botId: 'other', sessionId: 'other-chat' };
+ h.params = { botId: 'other', sessionId: 'other-chat', deviceId: undefined };
view.rerender(<BotSessionView />);
expect(screen.queryByText('companion:bot')).toBeNull();
expect(screen.queryByText('task controls')).toBeNull();
@@ -117,3 +123,44 @@ it('never shows the first-hello wait in a channel-routed (non-canonical) task of
render(<BotSessionView />);
expect((await screen.findByText('companion:bot')).getAttribute('data-invitation-stage')).toBe('');
});
+
+// Search can open archived canonical transcripts outside the history menu.
+it('opens an archived canonical link read-only when absent from the history list', async () => {
+ h.history.mockResolvedValue([]);
+ h.get.mockResolvedValue({ id: 'bot', name: 'Melody', avatar: '🎵', sessions: [
+ { id: 'chat', role: 'canonical', status: 'archived' },
+ ] });
+ await act(async () => { render(<BotHistorySessionView />); });
+ const chat = screen.getByText('companion:bot');
+ expect(h.get).toHaveBeenCalledWith('bot');
+ expect(chat.getAttribute('data-name')).toBe('Melody');
+ expect(chat.getAttribute('data-avatar')).toBe('🎵');
+ expect(chat.getAttribute('data-device-id')).toBeNull();
+ expect(chat.getAttribute('data-read-only')).toBe('true');
+});
+
+it.each(['history', 'channel'])('checks remote %s links before displaying a searched transcript', async role => {
+ h.params.deviceId = 'remote';
+ h.invoke.mockResolvedValueOnce({ id: 'bot', name: 'Melody', avatar: '🎵', sessions: [
+ { id: 'chat', role, status: 'archived' },
+ ] }).mockResolvedValue({ id: 'chat', source: 'bot', title: 'Old conversation', status: 'archived' });
+ await act(async () => { render(<BotHistorySessionView />); });
+ expect(h.invoke).toHaveBeenCalledWith('remote', 'local-db:bots:get', ['bot']);
+ expect(h.history).not.toHaveBeenCalled();
+ if (role === 'history') {
+ const chat = screen.getByText('companion:bot');
+ expect(chat.getAttribute('data-name')).toBe('Melody');
+ expect(chat.getAttribute('data-avatar')).toBe('🎵');
+ expect(chat.getAttribute('data-device-id')).toBe('remote');
+ expect(chat.getAttribute('data-read-only')).toBe('true');
+ expect(h.invoke).toHaveBeenCalledWith('remote', 'local-db:sessions:get', ['chat']);
+ expect(remoteProjectsStore.getSessionDeviceId('chat')).toBe('remote');
+ expect(remoteProjectsStore.getDeviceSessions('remote', 'archived')).toEqual([
+ expect.objectContaining({ id: 'chat', status: 'archived', title: 'Old conversation' }),
+ ]);
+ } else {
+ expect(screen.getByText('unavailable')).toBeTruthy();
+ expect(remoteProjectsStore.getSessionDeviceId('chat')).toBeUndefined();
+ expect(h.invoke).toHaveBeenCalledTimes(1);
+ }
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx
index dfd85c876a..6b37149e72 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/ConversationSearchBox.tsx
@@ -520,7 +520,17 @@ export function useConversationSearch({
if (remoteDeviceId) {
remoteProjectsStore.pinSessionOrigin(remoteDeviceId, item.session.id);
}
- const baseRoute = await resolveSessionRoute(item.session.id, item.session);
+ const companion = item.session.companion;
+ const companionRoute = companion
+ ? remoteDeviceId
+ ? `/bots/remote/${encodeURIComponent(remoteDeviceId)}/${encodeURIComponent(companion.id)}`
+ : `/bots/${encodeURIComponent(companion.id)}`
+ : null;
+ const baseRoute = companionRoute
+ ? companion?.readOnly
+ ? `${companionRoute}/history/${encodeURIComponent(item.session.id)}`
+ : remoteDeviceId ? companionRoute : `${companionRoute}/session/${encodeURIComponent(item.session.id)}`
+ : await resolveSessionRoute(item.session.id, item.session);
const hit = hitOverride ?? item.contentHit;
// popover 形态:onResultChosen 关闭面板并通知托盘(SidebarActionBar 减 openChildCount),
// 其 reset() 会清空 query。内联展开态不传 onResultChosen——选中结果后**刻意保留 query**,
@@ -1219,10 +1229,11 @@ function SearchResultRow({
const sourceText = primaryHit ? searchSourceLabel(primaryHit, t) : t('ccAgent.search.source.titleOnly');
const deviceLabel = item.session.deviceLinkDeviceName?.trim() || null;
const meta = [
+ item.session.companion?.name,
sourceText,
activityText,
deviceLabel,
- item.session.workingDir,
+ item.session.companion ? null : item.session.workingDir,
].filter(Boolean).join(' · ');
const tooltip = (
<div className="space-y-2">
diff --git a/apps/desktop/src/renderer/router.tsx b/apps/desktop/src/renderer/router.tsx
index 10c3b7881f..8efc2f14f9 100644
--- a/apps/desktop/src/renderer/router.tsx
+++ b/apps/desktop/src/renderer/router.tsx
@@ -132,6 +132,7 @@ export const router = createHashRouter([
// :botId 之前,/bots/groups/<id> 不会被当成一个叫 "groups" 的伙伴。
{ path: 'groups/:groupId', element: <BotGroupChatView /> },
{ path: 'remote/:deviceId/:botId', element: <RemoteBotSessionView /> },
+ { path: 'remote/:deviceId/:botId/history/:sessionId', element: <BotHistorySessionView /> },
// 伙伴私聊只从双方时间线里的消息入口打开,不出现在左侧伙伴列表。
{ path: ':botId/direct/:threadId', element: <BotDirectMessageView /> },
{ path: ':botId', element: <BotsHomeView /> },
diff --git a/apps/desktop/src/shared/conversationSearch.ts b/apps/desktop/src/shared/conversationSearch.ts
index c540cd2c51..b25528e48f 100644
--- a/apps/desktop/src/shared/conversationSearch.ts
+++ b/apps/desktop/src/shared/conversationSearch.ts
@@ -62,6 +62,13 @@ export interface ConversationSearchSessionSummary {
source?: SessionSource;
orcaRole?: ConversationSearchOrcaRole | null;
parentSessionId?: string | null;
+ /** Host-verified personal companion chat; absent for ordinary/background tasks. */
+ companion?: {
+ id: string;
+ name: string;
+ role: 'canonical' | 'history';
+ readOnly: boolean;
+ };
userSendAt: string | null;
updatedAt: string;
createdAt: string;
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index c63b00dfe5..6c7cb3408e 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -74,6 +74,7 @@ import { useConversationSearchFilterMenu } from '@/session/useConversationSearch
import { HomeSearchBar } from '@/session/HomeSearchBar';
import {
conversationSearchAllowsLocalWrites,
+ conversationSearchCompanionParams,
listConversationSearchProjects,
shouldReplaceListWithSearchResults,
} from '@/session/conversationSearch';
@@ -523,7 +524,7 @@ function DeviceDetailScreenContent() {
setBulkNotice(null);
}, []);
- const openSession = useCallback((targetSessionId: string, focusClientId?: string) => {
+ const openSession = useCallback((targetSessionId: string, focusClientId?: string, companionParams?: Record<string, string>) => {
if (swipeRegistry.closeOpenRow()) return;
// 打开会话是远端交互,用当前(可达)设备 endpoint = 页面级 deviceId(对被认领会话即 canonical 当前设备,
// 其物理机就是当前设备、可达)。不用会话物理旧 shard id:re-link 后旧设备不可达会导致会话根本打不开。
@@ -536,6 +537,7 @@ function DeviceDetailScreenContent() {
deviceId,
deviceName,
...(focusClientId ? { focusClientId } : {}),
+ ...companionParams,
},
});
}, [deviceId, deviceName, guardedPush, swipeRegistry]);
@@ -756,6 +758,7 @@ function DeviceDetailScreenContent() {
onOpenSession={(it) => openSession(
it.session.id,
'searchFocusClientId' in it ? (it as { searchFocusClientId?: string }).searchFocusClientId : undefined,
+ conversationSearchCompanionParams(it),
)}
swipe={sessionSwipeControls}
testID={`deviceDetail.automationRunRow.${item.session.id}`}
@@ -892,6 +895,7 @@ function DeviceDetailScreenContent() {
onOpenSession={(it) => openSession(
it.session.id,
'searchFocusClientId' in it ? (it as { searchFocusClientId?: string }).searchFocusClientId : undefined,
+ conversationSearchCompanionParams(it),
)}
onToggleAutomationGroup={toggleAutomationGroup}
suppressBlockTopBorder={!!section.data[index - 1]?.automationGroup}
@@ -1258,6 +1262,7 @@ function DeviceDetailScreenContent() {
onOpenSession={(it) => openSession(
it.session.id,
'searchFocusClientId' in it ? (it as { searchFocusClientId?: string }).searchFocusClientId : undefined,
+ conversationSearchCompanionParams(it),
)}
onPressSelection={conversationSearchAllowsLocalWrites(item)
? () => toggleSelection(sessionIdsForListItem(item))
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index d668973c04..9dd9e1628d 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -5,6 +5,7 @@ import { getCachedDeviceProviders } from '@/device-link/deviceProvidersCache';
import { MountOnFirstOpen } from '@/session/MountOnFirstOpen';
import { RunningTokenRatePopover } from '@/session/RunningTokenRatePopover';
import { companionConversationItems } from '@/session/companionConversationPresentation';
+import { conversationSearchCompanionParams } from '@/session/conversationSearch';
import { useRunningTokenRateHistory } from '@/session/useRunningTokenRateHistory';
import { HomeHeaderGlassButton } from '@/session/HomeHeaderGlassButton';
import { HomeNewTaskButton } from '@/session/HomeNewTaskButton';
@@ -2523,7 +2524,8 @@ function SessionScreenContent() {
const composerDisabledReasonKey = composerDisabledReasonI18nKey(
sessionOperationLayout.composerDisabledReasonSource,
);
- const composerDisabledReason = !companionEntry.canCompose ? t('shared.syncing') : composerDisabledReasonKey
+ const composerDisabledReason = companionEntry.readOnly ? t('session.presentation.overview.readOnly')
+ : !companionEntry.canCompose ? t('shared.syncing') : composerDisabledReasonKey
? t(composerDisabledReasonKey)
: sessionOperationLayout.composerDisabledReason
?? (sessionResourceCards.blocked
@@ -3067,6 +3069,7 @@ function SessionScreenContent() {
deviceName: targetSession.deviceLinkDeviceName ?? targetDeviceId,
sessionId: targetSession.id,
...(focusClientId ? { focusClientId } : {}),
+ ...conversationSearchCompanionParams(item),
});
});
}, [closeSessionListDrawer, navigation, queueDrawerNavigation, sessionId, t]);
diff --git a/apps/mobile/src/__tests__/conversationSearch.test.ts b/apps/mobile/src/__tests__/conversationSearch.test.ts
index b82ff1c285..0fc040ea3d 100644
--- a/apps/mobile/src/__tests__/conversationSearch.test.ts
+++ b/apps/mobile/src/__tests__/conversationSearch.test.ts
@@ -3,6 +3,7 @@ import {
cachedSessionForSearchResult,
conversationSearchActiveFilterCount,
conversationSearchAllowsLocalWrites,
+ conversationSearchCompanionParams,
conversationSearchOriginsFromDeviceModels,
conversationSearchSessionCacheKey,
isConversationSearchChannelNotAllowed,
@@ -446,3 +447,14 @@ describe('helpers', () => {
expect(conversationSearchAllowsLocalWrites({ session: { id: 'plain' } })).toBe(true);
});
});
+
+// Search projection + routing: old coverage had only ordinary tasks. Unit tier.
+it('preserves companion identity and the selected archived transcript', () => {
+ const hit = searchCachedDeviceSessions(studio, { query: 'planning' }, [session({ id: 'old', title: 'Remote planning' })]).results[0];
+ hit.session.companion = { id: 'bot', name: 'Melody', role: 'history', readOnly: true };
+ const item = toSearchListItem(hit, Date.now());
+ expect(item.title).toBe('Melody · Remote planning');
+ expect(conversationSearchCompanionParams(item)).toEqual({
+ resourceCollectionId: 'teammates', resourceKind: 'bot', resourceId: 'bot', resourceHistorySessionId: 'old',
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionDrawerNavigation.test.ts b/apps/mobile/src/__tests__/sessionDrawerNavigation.test.ts
index 5a06afff5a..1efce38ca5 100644
--- a/apps/mobile/src/__tests__/sessionDrawerNavigation.test.ts
+++ b/apps/mobile/src/__tests__/sessionDrawerNavigation.test.ts
@@ -21,4 +21,22 @@ describe('wide session drawer navigation', () => {
sessionId: 'session-b',
});
});
+
+ it('keeps companion history identity and the matched message when opening a search result', () => {
+ const replaceParams = vi.fn();
+ const target = {
+ deviceId: 'device-b',
+ deviceName: 'Desktop B',
+ sessionId: 'old-chat',
+ focusClientId: 'matched-message',
+ resourceCollectionId: 'teammates',
+ resourceKind: 'bot',
+ resourceId: 'companion-b',
+ resourceHistorySessionId: 'old-chat',
+ };
+
+ switchDrawerSessionInPlace({ replaceParams }, target);
+
+ expect(replaceParams).toHaveBeenCalledWith(target);
+ });
});
diff --git a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx
index cfb83de22e..7c952f7afd 100644
--- a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx
+++ b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx
@@ -12,7 +12,7 @@ const h = vi.hoisted(() => ({
get: vi.fn(),
language: "en", focused: true,
t: (key: string) => key, metadataVerified: true,
- resourceId: 'bot-1', sessionId: 'task-1', openSearch: '',
+ resourceId: 'bot-1', sessionId: 'task-1', openSearch: '', resourceHistorySessionId: '',
markRead: vi.fn(),
store: { getSessionDeviceId: vi.fn(), upsertDeviceSession: vi.fn() },
router: { replace: vi.fn(), setParams: vi.fn() },
@@ -27,7 +27,7 @@ vi.mock('expo-router', async () => {
return {
useIsFocused: () => h.focused,
useFocusEffect: (effect: () => void | (() => void)) => useEffect(() => h.focused ? effect() : undefined, [effect, h.focused]),
- useLocalSearchParams: () => ({ resourceCollectionId: 'teammates', resourceId: h.resourceId, resourceKind: 'bot', openSearch: h.openSearch }),
+ useLocalSearchParams: () => ({ resourceCollectionId: 'teammates', resourceId: h.resourceId, resourceKind: 'bot', openSearch: h.openSearch, resourceHistorySessionId: h.resourceHistorySessionId }),
useRouter: () => h.router,
};
});
@@ -77,7 +77,7 @@ async function render(canMarkRead = false) {
// A viewport receipt is separate from loading/entering the chat.
result.markReadThrough(200);
}
-beforeEach(() => { vi.clearAllMocks(); h.link.openLink.mockResolvedValue(undefined); h.openSearch = ''; h.auth.accountGeneration = 1; h.metadataVerified = true; h.focused = true; h.language = "en"; h.resourceId = 'bot-1'; h.sessionId = 'task-1'; h.link.status = 'online'; h.link.connectionEpoch = 1; h.store.getSessionDeviceId.mockReturnValue(undefined); });
+beforeEach(() => { vi.clearAllMocks(); h.link.openLink.mockResolvedValue(undefined); h.openSearch = ''; h.resourceHistorySessionId = ''; h.auth.accountGeneration = 1; h.metadataVerified = true; h.focused = true; h.language = "en"; h.resourceId = 'bot-1'; h.sessionId = 'task-1'; h.link.status = 'online'; h.link.connectionEpoch = 1; h.store.getSessionDeviceId.mockReturnValue(undefined); });
afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });
describe('companion task visibility refresh', () => {
@@ -309,6 +309,7 @@ it.each(['failed', 'identity'])('keeps %s invitation history visible without ena
// The same invitation still redirects on ordinary entry.
h.openSearch = '';
+ h.resourceHistorySessionId = '';
await render(true);
expect(h.router.replace).toHaveBeenCalledWith(expect.objectContaining({ pathname: '/resources/[collectionId]/[resourceId]' }));
});
@@ -396,3 +397,17 @@ it.each(['/context', '/learn keep this', '/help', 'keep this message'])('preserv
expect(error).toHaveBeenCalledTimes(remote ? 1 : 0);
}
});
+
+// A search hit in an old thread must not silently jump to today's main chat.
+// Real hook entry; existing cases only covered following the canonical link. Unit tier.
+it.each([true, false])('keeps a searched historical transcript read-only after verifying ownership (%s)', async owned => {
+ h.resourceHistorySessionId = 'task-1';
+ h.get.mockResolvedValue({ display: { title: 'Melody' }, links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'current-chat' } }] });
+ h.link.invoke.mockResolvedValue({ sessions: [{ id: owned ? 'task-1' : 'unrelated', role: 'history', status: 'archived' }] });
+ await render(true);
+ expect(result.canCompose).toBe(false);
+ expect(result.ready).toBe(false);
+ expect(result.error === null).toBe(owned);
+ expect(h.router.setParams).not.toHaveBeenCalled();
+ expect(h.markRead).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index aea8c1fa6c..b7de575dd9 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -173,6 +173,7 @@ import {
import { ConversationSearchFilterSheet } from '@/session/ConversationSearchFilterSheet';
import {
conversationSearchAllowsLocalWrites,
+ conversationSearchCompanionParams,
conversationSearchOriginsFromDeviceModels,
listConversationSearchProjects,
shouldReplaceListWithSearchResults,
@@ -2363,6 +2364,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
deviceName: session.deviceLinkDeviceName ?? deviceId,
sessionId: session.id,
...(focusClientId ? { focusClientId } : {}),
+ ...conversationSearchCompanionParams(item),
},
} as const;
rememberTask(href);
diff --git a/apps/mobile/src/session/conversationSearch.ts b/apps/mobile/src/session/conversationSearch.ts
index b43f1d3f74..8d836186ae 100644
--- a/apps/mobile/src/session/conversationSearch.ts
+++ b/apps/mobile/src/session/conversationSearch.ts
@@ -247,9 +247,24 @@ function sessionToSearchSummary(
export type ConversationSearchListItem = RemoteSessionListItem & {
searchFocusClientId?: string;
+ searchCompanion?: ConversationSearchSessionSummary['companion'];
searchLocallyCached: boolean;
};
+/** Keep the exact transcript selected by search, including an archived personal thread. */
+export function conversationSearchCompanionParams(item: object): Record<string, string> {
+ const companion = (item as Partial<ConversationSearchListItem>).searchCompanion;
+ if (!companion) return {};
+ return {
+ resourceCollectionId: 'teammates',
+ resourceKind: 'bot',
+ resourceId: companion.id,
+ ...(companion.readOnly
+ ? { resourceHistorySessionId: (item as ConversationSearchListItem).session.id }
+ : {}),
+ };
+}
+
export function conversationSearchSessionCacheKey(
session: Pick<RemoteSession, 'id'> & {
canonicalDeviceId?: string | null;
@@ -321,6 +336,10 @@ export function toSearchListItem(
const searchFocusClientId = item.contentHit?.messageClientId?.trim();
return {
...listItem,
+ ...(item.session.companion ? {
+ title: `${item.session.companion.name} · ${listItem.title}`,
+ searchCompanion: item.session.companion,
+ } : {}),
searchLocallyCached: !!cached,
...(searchFocusClientId ? { searchFocusClientId } : {}),
};
diff --git a/apps/mobile/src/session/sessionDrawerNavigation.ts b/apps/mobile/src/session/sessionDrawerNavigation.ts
index 82224ef3eb..0c547a52ed 100644
--- a/apps/mobile/src/session/sessionDrawerNavigation.ts
+++ b/apps/mobile/src/session/sessionDrawerNavigation.ts
@@ -3,6 +3,10 @@ export interface SessionDrawerRouteTarget {
deviceName: string;
sessionId: string;
focusClientId?: string;
+ resourceCollectionId?: string;
+ resourceKind?: string;
+ resourceId?: string;
+ resourceHistorySessionId?: string;
}
export interface SessionRouteParamsNavigation {
@@ -27,5 +31,11 @@ export function switchDrawerSessionInPlace(
deviceName: target.deviceName,
sessionId: target.sessionId,
...(target.focusClientId ? { focusClientId: target.focusClientId } : {}),
+ ...(target.resourceId ? {
+ resourceCollectionId: target.resourceCollectionId,
+ resourceKind: target.resourceKind,
+ resourceId: target.resourceId,
+ resourceHistorySessionId: target.resourceHistorySessionId,
+ } : {}),
});
}
diff --git a/apps/mobile/src/session/useRemoteResourceSession.ts b/apps/mobile/src/session/useRemoteResourceSession.ts
index 0f3edbc0e1..b81f79a678 100644
--- a/apps/mobile/src/session/useRemoteResourceSession.ts
+++ b/apps/mobile/src/session/useRemoteResourceSession.ts
@@ -17,17 +17,18 @@ import type { RemoteSession } from './types';
/** Follow a companion's current host-owned task on focus/reconnect, retaining its permanent identity. */
export function useRemoteResourceSession(deviceId: string, deviceName: string, sessionId: string, canMarkRead: boolean, metadataVerified = false) {
- const params = useLocalSearchParams<{ resourceCollectionId?: string; resourceId?: string; resourceKind?: string; openSearch?: string }>();
+ const params = useLocalSearchParams<{ resourceCollectionId?: string; resourceId?: string; resourceKind?: string; openSearch?: string; resourceHistorySessionId?: string }>();
const collectionId = typeof params.resourceCollectionId === 'string' ? params.resourceCollectionId : '';
const resourceId = typeof params.resourceId === 'string' ? params.resourceId : '';
const resourceKind = typeof params.resourceKind === 'string' ? params.resourceKind : '';
const historyEntry = params.openSearch === '1';
+ const transcriptEntry = params.resourceHistorySessionId === sessionId;
const { invoke, openLink, connectionEpoch, status, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();
const { user, accountGeneration } = useAuth();
const { t, i18n } = useTranslation();
const router = useRouter();
const focused = useIsFocused();
- const identity = JSON.stringify([accountGeneration, deviceId, sessionId, collectionId, resourceKind, resourceId, historyEntry]);
+ const identity = JSON.stringify([accountGeneration, deviceId, sessionId, collectionId, resourceKind, resourceId, historyEntry, transcriptEntry]);
const [display, setDisplay] = useState<{ identity: string; resource: RemoteResource } | null>(null);
const binding = JSON.stringify([identity, connectionEpoch, i18n.language]);
const current = useRef(binding); current.current = binding;
@@ -44,14 +45,15 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, s
: undefined)?.stage;
const cachedTarget = resource?.links.find(link => link.rel === 'conversation')?.target;
// Local editing and durable queuing do not confer permission to dispatch.
- const canCompose = !required || (!!resource && cachedTarget?.kind === 'session' && cachedTarget.sessionId === sessionId
- && (!stage || stage === 'ready') && (!failure || failure.binding !== binding || isAutoRecoveringRemoteError(failure.message)));
- const ready = !required || (focused && AppState.currentState === 'active' && status === 'online' && verified === binding && metadataVerified);
+ const canCompose = !transcriptEntry && (!required || (!!resource && cachedTarget?.kind === 'session' && cachedTarget.sessionId === sessionId
+ && (!stage || stage === 'ready') && (!failure || failure.binding !== binding || isAutoRecoveringRemoteError(failure.message))));
+ // `ready` also unlocks queued sends and runtime controls in the session screen.
+ const ready = !transcriptEntry && (!required || (focused && AppState.currentState === 'active' && status === 'online' && verified === binding && metadataVerified));
const markReadThrough = useCallback((at: number) => {
- if (current.current === binding && AppState.currentState === 'active' && ready && canMarkRead && resourceKind === 'bot' && resource && Number.isFinite(at) && at > 0) {
+ if (!transcriptEntry && current.current === binding && AppState.currentState === 'active' && ready && canMarkRead && resourceKind === 'bot' && resource && Number.isFinite(at) && at > 0) {
void markRemoteResourceRead(user?.id ?? '', deviceId, resourceId, Math.min(at, resource.display.lastReplyAt ?? 0));
}
- }, [binding, canMarkRead, deviceId, ready, resource, resourceId, resourceKind, user?.id]);
+ }, [binding, canMarkRead, deviceId, ready, resource, resourceId, resourceKind, user?.id, transcriptEntry]);
useFocusEffect(useCallback(() => {
if (!collectionId || !resourceId || !resourceKind || !deviceId || status !== 'online') return;
setVerified(null);
@@ -70,6 +72,21 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, s
return getRemoteResource(invoke, { deviceId, deviceName }, { collectionId, id: resourceId, kind: resourceKind }, i18n.language);
});
if (!valid()) return;
+ if (transcriptEntry) {
+ const profile = await retryRemoteSyncRead(run, () => invoke<{
+ sessions?: Array<{ id: string; role: string; status: string }>;
+ }>(deviceId, 'local-db:bots:get', [resourceId]));
+ if (!valid()) return;
+ if (!profile?.sessions?.some(row => row.id === sessionId && row.status !== 'deleted'
+ && (row.role === 'canonical' || row.role === 'history'))) {
+ throw new Error(t('devices.resources.noConversation'));
+ }
+ setDisplay({ identity, resource });
+ setFailure(null);
+ setVerified(binding);
+ recovery.succeeded();
+ return;
+ }
// Reuse this existing read rather than issuing a second profile request per turn.
setDisplay({ identity, resource });
setFailure(null);
@@ -130,6 +147,6 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, s
const appState = AppState.addEventListener('change', (state) => { generation += 1; setVerified(null); if (state === 'active') { coordinator.setContext(binding); refresh(); } else coordinator.setContext('background'); });
refresh();
return () => { disposed = true; recovery.dispose(); coordinator.setContext('disposed'); setVerified(null); offPush(); offTopic(); appState.remove(); if (timer) clearTimeout(timer); };
- }, [attempt, binding, historyEntry, collectionId, deviceId, deviceName, identity, invoke, openLink, i18n.language, onRemoteResourceChanged, resourceId, resourceKind, router, sessionId, status, subscribe, t, unsubscribe, user?.id]));
- return { resource, ready, canCompose, markReadThrough, error: failure?.binding === binding ? failure.message : null, retry };
+ }, [attempt, binding, historyEntry, transcriptEntry, collectionId, deviceId, deviceName, identity, invoke, openLink, i18n.language, onRemoteResourceChanged, resourceId, resourceKind, router, sessionId, status, subscribe, t, unsubscribe, user?.id]));
+ return { resource, ready, canCompose, readOnly: transcriptEntry, markReadThrough, error: failure?.binding === binding ? failure.message : null, retry };
}
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index 32eb769bce..b8f9260662 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -86,6 +86,7 @@
| `/bots/list` | BotsListView | `desktop.bots` |
| `/bots/market/:packageId?` | BotMarketRoute | `desktop.bots` |
| `/bots/remote/:deviceId/:botId` | RemoteBotSessionView | `desktop.bots` |
+| `/bots/remote/:deviceId/:botId/history/:sessionId` | BotHistorySessionView | `desktop.bots` |
| `/bots/roster` | BotRosterView | `desktop.bots` |
| `/cc-agent/:sessionId` | CCAgentSessionView | `desktop.chat.session` |
| `/cc-agent/boot` | SecondaryWindowBootGate | `desktop.chat.session` |
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 80a2607dc0..944dc2cb56 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1,5 +1,17 @@
# 跨端协议兼容
+## 伙伴个人聊天全文搜索
+
+既有 `local-db:conversations:search` 的结果 `session` 增加可选
+`companion: { id, name, role: 'canonical' | 'history', readOnly }`。
+归属由 Host 的 `bot_session_links` 关联确认;群聊与渠道专线不下发。
+`local-db:bots:get` 的远程精简资料增加个人 `sessions: [{ id, role, status }]`,
+供控制端复核历史归属,不传提示词、工作目录或渠道配置。
+搜索前按远程伙伴可见性筛选,缓存/排队回复投递时再次核查,保持原账号与隐藏边界。
+新控制端连接旧 Host 时缺少 `companion` 就沿用普通搜索结果;旧控制端忽略新增字段。
+历史定位需要更新查看端,旧端可能按普通任务打开;不更改既有请求参数、
+IPC allowlist、relay、数据库 schema 或 Mobile 原生指纹。
+
## 邮件阅读会话
只读 MailMessage 可选增加 conversation(threadId 和按时间排列的 messages 摘要)。
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 361344dcca..73fddcbaa9 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -183,6 +183,15 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭
### 3.3 用户界面
+侧边栏全文搜索覆盖普通任务及伙伴个人主聊天、历史线程,默认包含归档历史。
+搜索结果带伙伴姓名,点击后保持命中的线程与消息位置;不依赖伙伴在侧栏是否展开或已加载。
+历史线程以伙伴身份只读打开,不切回当前主任务、不取消归档、不恢复发送队列。
+群聊/渠道内部专线不进入搜索;伙伴委派的普通后台任务保持普通任务入口。
+手机首页、设备页与任务抽屉采用同一结果归属与消息定位。远程仍遵守既有伙伴可见性:
+整体隐藏或归档的伙伴只在所属电脑本地恢复,不能因新增搜索入口扩大远程权限。
+实现见 `localDb/conversationSearch.ts`、`ConversationSearchBox.tsx` 与 Mobile
+`conversationSearch.ts`、`useRemoteResourceSession.ts`。
+
伙伴开任务时在内部完成模型与 Harness 选择。普通回复只说明必要的工作进度和结果,不复述子任务指令、工具名、参数名、路由 JSON 或任务 ID;用户主动询问调试细节时再解释。任务卡沿用既有简洁结构,不因选模新增配置面板或密集字段;若展示模型,只作为轻量辅助信息。
伙伴界面由入口验证过的持久归属与任务 ID 决定,不随异步运行快照的缺失、刷新或重连回退为普通任务界面。历史资料尚未加载或暂时失败时也保留伙伴呈现;手机保留同一账号、设备与任务内已确认的伙伴身份。切换任务、设备或账号时不得复用旧身份。此呈现规则不替代宿主的权限与归属校验。
diff --git a/packages/maker-shared/src/conversationSearch.ts b/packages/maker-shared/src/conversationSearch.ts
index 88a248f92f..c25086f2a8 100644
--- a/packages/maker-shared/src/conversationSearch.ts
+++ b/packages/maker-shared/src/conversationSearch.ts
@@ -61,6 +61,13 @@ export interface ConversationSearchSessionSummary {
source?: string | null;
orcaRole?: ConversationSearchOrcaRole | null;
parentSessionId?: string | null;
+ /** Host-verified personal companion chat; absent for ordinary/background tasks. */
+ companion?: {
+ id: string;
+ name: string;
+ role: 'canonical' | 'history';
+ readOnly: boolean;
+ };
userSendAt: string | null;
updatedAt: string;
createdAt: string;
diff --git a/scripts/__tests__/design-inventory.test.mjs b/scripts/__tests__/design-inventory.test.mjs
index 96ce6c5e4a..6b4e57a697 100644
--- a/scripts/__tests__/design-inventory.test.mjs
+++ b/scripts/__tests__/design-inventory.test.mjs
@@ -121,6 +121,7 @@ test('extractRouterFacts: 真实 router.tsx 的三类去向逐条钉死', () =>
'/bots/list BotsListView',
'/bots/market/:packageId? BotMarketRoute',
'/bots/remote/:deviceId/:botId RemoteBotSessionView',
+ '/bots/remote/:deviceId/:botId/history/:sessionId BotHistorySessionView',
'/bots/roster BotRosterView',
'/cc-agent/:sessionId CCAgentSessionView',
'/cc-agent/boot SecondaryWindowBootGate',
diff --git a/scripts/shared/design-inventory.mjs b/scripts/shared/design-inventory.mjs
index 33a52ee1ed..27a6f20b91 100644
--- a/scripts/shared/design-inventory.mjs
+++ b/scripts/shared/design-inventory.mjs
@@ -574,6 +574,7 @@ export function catalogSurfaces() {
'/bots/roster',
'/bots/groups/:groupId',
'/bots/remote/:deviceId/:botId',
+ '/bots/remote/:deviceId/:botId/history/:sessionId',
],
routeEntryComponents: {
'/bots': 'BotsHomeView',
@@ -586,6 +587,7 @@ export function catalogSurfaces() {
'/bots/roster': 'BotRosterView',
'/bots/groups/:groupId': 'BotGroupChatView',
'/bots/remote/:deviceId/:botId': 'RemoteBotSessionView',
+ '/bots/remote/:deviceId/:botId/history/:sessionId': 'BotHistorySessionView',
},
},
{
diff --git a/scripts/test-hygiene-baseline.json b/scripts/test-hygiene-baseline.json
index d99ae8ae02..e1f757f791 100644
--- a/scripts/test-hygiene-baseline.json
+++ b/scripts/test-hygiene-baseline.json
@@ -847,7 +847,7 @@
"resetModules": 1
},
"apps/desktop/src/renderer/features/bots/__tests__/botNavigation.test.ts": {
- "sourceReads": 6
+ "sourceReads": 5
},
"apps/desktop/src/renderer/features/bots/__tests__/botStore.lifecycle.test.ts": {
"resetModules": 2