Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 同步桌面项目别名到手机 #6916
DavidShen43932d5afc8f
diff --git a/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts b/apps/desktop/src/main/localDb/__tests__/projectAliases.test.tsindex 92b8182760..d70eabfd1a 100644--- a/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts@@ -6,7 +6,15 @@ import type { DbClient } from '../client/DbClient.js';import { clearCurrentDbClient, setCurrentDbClient } from '../client/current.js';import * as schema from '../schema.js';import { tx as runDbTx } from '../worker/opHandlers/tx.js';-const send = vi.hoisted(() => vi.fn());+import { setBroadcastTapListener } from '../../device-link/broadcast-tap.js';+import { upsertProjectAlias, listProjectAliases } from '../ipc/projectAliases.js';+const { send, owner } = vi.hoisted(() => ({ send: vi.fn(), owner: { generation: 1 } }));++vi.mock('../../appSessionState.js', () => ({+ activeOwnerScopeKey: () => `test-owner:${owner.generation}`,+ getActiveDataOwnerPushStamp: () => ({ dataOwnerId: 'test-user', ownerGeneration: owner.generation }),+ isAppSessionBoundaryPending: () => false,+}));vi.mock('electron', () => ({BrowserWindow: {@@ -22,7 +30,9 @@ describe('projectAliases localDb helpers', () => {let rawDb: Database.Database | null = null;afterEach(() => {+ setBroadcastTapListener(null);send.mockClear();+ owner.generation = 1;if (currentClient) {clearCurrentDbClient(currentClient);currentClient = null;@@ -34,7 +44,6 @@ describe('projectAliases localDb helpers', () => {it('normalizes project keys and trims aliases through the IPC-equivalent path', async () => {const client = createTestDbClient();setCurrentDbClient(client, 'test-user');- const { upsertProjectAlias, listProjectAliases } = await import('../ipc/projectAliases.js');const saved = await upsertProjectAlias('local:D:\\repo\\app\\', ' Main App ');const rows = await listProjectAliases();@@ -47,12 +56,19 @@ describe('projectAliases localDb helpers', () => {it('deletes the alias when the new value is blank', async () => {const client = createTestDbClient();setCurrentDbClient(client, 'test-user');- const { upsertProjectAlias, listProjectAliases } = await import('../ipc/projectAliases.js');+ // #6916: persisted rename/clear must invalidate remote project lists, not only+ // local windows. Existing DB cases did not observe the device-link boundary.+ const pushed: unknown[] = [];+ setBroadcastTapListener((channel, payload) => { pushed.push({ channel, payload }); });await upsertProjectAlias('local:/repo/app', 'App');await upsertProjectAlias('local:/repo/app', ' ');expect(await listProjectAliases()).toEqual([]);+ expect(pushed).toEqual([+ { channel: 'local-db:project-aliases:changed', payload: undefined },+ { channel: 'local-db:project-aliases:changed', payload: undefined },+ ]);});it('atomically replaces every Unicode Windows casing variant', async () => {@@ -70,7 +86,6 @@ describe('projectAliases localDb helpers', () => {'Older alias',1_000,);- const { upsertProjectAlias, listProjectAliases } = await import('../ipc/projectAliases.js');await upsertProjectAlias('local:D:/ÉCOLE/PROJECT-A', 'Replacement', 'win32');@@ -97,7 +112,6 @@ describe('projectAliases localDb helpers', () => {'Older alias',1_000,);- const { upsertProjectAlias, listProjectAliases } = await import('../ipc/projectAliases.js');await upsertProjectAlias('local:D:/ÉCOLE/PROJECT-A', '', 'win32');@@ -107,7 +121,6 @@ describe('projectAliases localDb helpers', () => {it('uses the captured client and checks ownership before writing and broadcasting', async () => {const client = createTestDbClient();setCurrentDbClient(client, 'test-user');- const { upsertProjectAlias, listProjectAliases } = await import('../ipc/projectAliases.js');const assertCurrent = vi.fn();await upsertProjectAlias('local:/repo/app', 'App', process.platform, { client, assertCurrent });expect(assertCurrent).toHaveBeenCalledTimes(2);@@ -122,6 +135,23 @@ describe('projectAliases localDb helpers', () => {expect(send).not.toHaveBeenCalled();});+ // #6916, unit: remote reads and broadcasts must not cross an account switch while awaiting DB work.+ it('rejects stale reads and suppresses stale rename notifications after an owner switch', async () => {+ const client = createTestDbClient();+ setCurrentDbClient(client, 'test-user');+ const pushed = vi.fn();+ setBroadcastTapListener(pushed);+ const rename = upsertProjectAlias('local:/repo/app', 'Old owner');+ owner.generation++;+ await rename;+ expect(pushed).not.toHaveBeenCalled();+ expect(send).not.toHaveBeenCalled();++ const read = listProjectAliases();+ owner.generation++;+ await expect(read).rejects.toThrow('Owner changed');+ });+function createTestDbClient(): DbClient {const dbHandle = new Database(':memory:');rawDb = dbHandle;diff --git a/apps/desktop/src/main/localDb/ipc/projectAliases.ts b/apps/desktop/src/main/localDb/ipc/projectAliases.tsindex 2703967d88..a2b42c9795 100644--- a/apps/desktop/src/main/localDb/ipc/projectAliases.ts+++ b/apps/desktop/src/main/localDb/ipc/projectAliases.ts@@ -7,6 +7,12 @@ import type { DbClient } from '../client/DbClient.js';import { getDbClient } from '../client/current';import { projectAliases } from '../schema';import { requireObject, requireString, throwIpcError } from '../../utils/ipcValidate';+import {+ captureDataOwnerBroadcastScope,+ isDataOwnerBroadcastScopeCurrent,+ tapWindowBroadcast,+ type DataOwnerBroadcastScope,+} from '../../device-link/broadcast-tap.js';const MAX_ALIAS_LENGTH = 80;@@ -39,18 +45,22 @@ function requireProjectKey(raw: unknown): string {return normalized;}-function broadcastProjectAliasesChanged(): void {+function broadcastProjectAliasesChanged(scope: DataOwnerBroadcastScope): void {+ if (!isDataOwnerBroadcastScopeCurrent(scope)) return;+ tapWindowBroadcast('local-db:project-aliases:changed', undefined, scope.ownerStamp);for (const w of BrowserWindow.getAllWindows()) {if (!w.isDestroyed()) w.webContents.send('local-db:project-aliases:changed');}}export async function listProjectAliases(client: DbClient = getDbClient()): Promise<ProjectAlias[]> {+ const scope = captureDataOwnerBroadcastScope();const db = client.drizzle;const rows = await db.select().from(projectAliases).orderBy(desc(projectAliases.updatedAt));+ if (!isDataOwnerBroadcastScopeCurrent(scope)) throwIpcError('NOT_FOUND', 'Owner changed');return rows.map(aliasToCamel);}@@ -60,6 +70,7 @@ export async function upsertProjectAlias(localPlatform: NodeJS.Platform = process.platform,scope?: { client: DbClient; assertCurrent: () => void },): Promise<ProjectAlias | null> {+ const broadcastScope = captureDataOwnerBroadcastScope();const projectKey = requireProjectKey(projectKeyRaw);const alias = sanitizeAlias(aliasRaw);const now = Date.now();@@ -78,7 +89,7 @@ export async function upsertProjectAlias(updatedAt: now,});scope?.assertCurrent();- broadcastProjectAliasesChanged();+ broadcastProjectAliasesChanged(broadcastScope);return saved == null? null: {diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsxindex 3adc955945..f00b676955 100644--- a/apps/mobile/app/sessions/new.tsx+++ b/apps/mobile/app/sessions/new.tsx@@ -29,6 +29,7 @@ import {useNewSessionWorkspaceActions,useNewSessionInitialWorkspace,} from '@/session/useNewSessionWorkspace';+import { useRemoteProjectAliases } from '@/session/useRemoteProjectAliases';import { useIncomingShareComposer } from '@/session/useIncomingShareComposer';import { ModelSpeedIcon } from '@/session/ModelSpeedIcon';import { useNewSessionHostDefaults } from '@/session/useNewSessionHostDefaults';@@ -570,12 +571,15 @@ export default function NewRemoteSessionScreen() {const selectedDeviceLabel = selectedDeviceOption?.name || selectedDeviceName || selectedDeviceId || t('session.new.selectDevice');const maker = useMobileMakerTransport(selectedDeviceId);const sessions = useRemoteSessions();+ const projectAliases = useRemoteProjectAliases([selectedDeviceId]);const recentWorkspaces = useMemo(() => buildRecentWorkspaceOptions(sessions.filter((session) => session.deviceLinkDeviceId === selectedDeviceId),selectedDeviceId,+ 6,+ projectAliases,),- [selectedDeviceId, sessions],+ [selectedDeviceId, sessions, projectAliases],);const [draft, setDraft] = useState<NewSessionDraft>(() => createInitialNewSessionDraft({initialWorkingDir, visualInitialDraft, routeDraft: params.draft, suggestion: params.suggestion, t,diff --git a/apps/mobile/src/__tests__/conversationSearch.test.ts b/apps/mobile/src/__tests__/conversationSearch.test.tsindex 0fc040ea3d..6f3d1971bd 100644--- a/apps/mobile/src/__tests__/conversationSearch.test.ts+++ b/apps/mobile/src/__tests__/conversationSearch.test.ts@@ -71,6 +71,25 @@ function indexedPage(ids: string[]): ConversationSearchResponse {};}+// #6916: message FTS does not index project display names. Exercise the real+// fan-out/search entry plus project menu with two same-path devices (unit).+it('finds a renamed project without mixing devices and honors project filters', async () => {+ const sessions = [session({ id: 'a', title: 'Task A' }),+ session({ id: 'b', title: 'Task B', deviceLinkDeviceId: 'dev-b' })];+ const aliases = new Map([['device:dev-a:/repo', 'Customer Portal']]);+ const deps = { invoke: vi.fn(async () => indexedPage([])) as ConversationSearchInvoke,+ getCachedSessions: () => sessions, projectAliases: aliases };+ const origins = [{ deviceId: 'dev-a', deviceName: 'A', reachable: true },+ { deviceId: 'dev-b', deviceName: 'B', reachable: true }];+ const result = await searchConversationsAcrossDevices(origins, { query: 'customer' }, deps);+ expect(result.results.map((item) => item.session.id)).toEqual(['a']);+ const filtered = await searchConversationsAcrossDevices(origins, {+ query: 'customer', filters: { workingDirs: ['/another-project'] },+ }, deps);+ expect(filtered.results).toEqual([]);+ expect(listConversationSearchProjects(sessions, undefined, aliases).map((p) => p.title)).toEqual(['Customer Portal', 'repo']);+});+const studio: ConversationSearchDeviceOrigin = {deviceId: 'dev-a',deviceName: 'Studio',diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.tsindex 922166d6b3..cb1dd0efbe 100644--- a/apps/mobile/src/__tests__/newSession.test.ts+++ b/apps/mobile/src/__tests__/newSession.test.ts@@ -1810,6 +1810,19 @@ describe('new session model', () => {]);});+ // #6916, unit: the production picker must display host metadata without changing its path.+ it('uses the selected host alias for recent workspace quick picks', () => {+ const sessions = [remoteSession('app', { workingDir: '/repo/app', deviceLinkDeviceId: 'mac-a' })];+ const aliases = new Map([+ ['device:mac-a:/repo/app', 'Customer Portal'],+ ['device:mac-b:/repo/app', 'Other Portal'],+ ]);+ expect(buildRecentWorkspaceOptions(sessions, 'mac-a', 6, aliases)[0]).toMatchObject({+ title: 'Customer Portal', workingDir: '/repo/app',+ });+ expect(buildRecentWorkspaceOptions(sessions, 'mac-a', 6, new Map())[0].title).toBe('app');+ });+// Remote path strings deliberately model the host OS, not the test runner's filesystem.it.each([['slash direction', 'D:\\projects\\cindy', 'D:/projects/cindy'],diff --git a/apps/mobile/src/__tests__/remoteProjectAliases.test.tsx b/apps/mobile/src/__tests__/remoteProjectAliases.test.tsxnew file mode 100644index 0000000000..79296d02b7--- /dev/null+++ b/apps/mobile/src/__tests__/remoteProjectAliases.test.tsx@@ -0,0 +1,167 @@+// @vitest-environment jsdom+// #6916, unit: mount the production hook and observe names, invalidation, reconnect+// and late replies. Existing project-order tests do not cover alias snapshots.+import { act, createElement } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+const h = vi.hoisted(() => ({+ invoke: vi.fn(),+ push: null as null | ((id: string) => void),+ active: null as null | ((state: string) => void),+ accountGeneration: 1,+ offline: new Set<string>(),+ context: {+ connectionEpoch: 1,+ status: 'online',+ recoveringDeviceIds: new Set<string>(),+ subscribe: vi.fn(async () => {}),+ unsubscribe: vi.fn(async () => {}),+ },+}));+vi.mock('@/auth/AuthContext', () => ({+ useAuth: () => ({ accountGeneration: h.accountGeneration }),+}));+vi.mock('@/device-link/unresponsiveDevicesStore', () => ({+ useUnresponsiveDevices: () => new Set(),+}));+vi.mock('react-native', () => ({+ AppState: {+ addEventListener: (_: string, cb: typeof h.active) => {+ h.active = cb;+ return {+ remove: () => {+ h.active = null;+ },+ };+ },+ },+}));+vi.mock('@/device-link/DeviceLinkContext', () => ({+ useDeviceLink: () => ({+ ...h.context,+ invoke: h.invoke,+ getPresenceAvailability: (id: string) => !h.offline.has(id),+ }),+ subscribeRemoteProjectAliasesChanged: (cb: typeof h.push) => {+ h.push = cb;+ return () => {+ h.push = null;+ };+ },+}));+import { useRemoteProjectAliases } from '@/session/useRemoteProjectAliases';+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';+import { remoteProjectAlias } from '@cindy/maker-shared/mobile-home';+let view: ReadonlyMap<string, string>;+let root: ReturnType<typeof createRoot>;+function Probe({ ids = ['a'] }: { ids?: string[] }) {+ view = useRemoteProjectAliases(ids);+ return createElement(+ 'span',+ null,+ remoteProjectAlias(view, ids[0], '/repo/app') ?? 'app',+ );+}+const rows = (alias: string) => [{ projectKey: 'local:/repo/app', alias }];+const render = async (ids = ['a']) => {+ await act(async () => root.render(createElement(Probe, { ids })));+};+beforeEach(() => {+ (+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+ ).IS_REACT_ACT_ENVIRONMENT = true;+ vi.useFakeTimers();+ h.accountGeneration = 1;+ h.context.connectionEpoch = 1;+ h.context.status = 'online';+ h.context.recoveringDeviceIds.clear();+ h.offline.clear();+ setMobileAuthOwner('alias-owner');+ h.invoke.mockReset().mockResolvedValue(rows('Portal'));+ root = createRoot(document.createElement('div'));+});+afterEach(() => {+ act(() => root.unmount());+ vi.useRealTimers();+});+it('shows host names, refreshes on rename and clear, and isolates same paths on two hosts', async () => {+ h.invoke.mockImplementation(async (id) =>+ rows(id === 'a' ? 'Portal' : 'Other'),+ );+ await render(['a', 'b']);+ expect(remoteProjectAlias(view, 'a', '/repo/app')).toBe('Portal');+ expect(remoteProjectAlias(view, 'b', '/repo/app')).toBe('Other');+ h.invoke.mockResolvedValue(rows('Renamed'));+ await act(async () => h.push?.('a'));+ expect(remoteProjectAlias(view, 'a', '/repo/app')).toBe('Renamed');+ expect(remoteProjectAlias(view, 'b', '/repo/app')).toBe('Other');+ h.invoke.mockResolvedValue([]);+ await act(async () => h.push?.('a'));+ expect(remoteProjectAlias(view, 'a', '/repo/app')).toBeUndefined();+});+it('discards a read overtaken by a rename and rereads after reconnect and foreground', async () => {+ await render();+ let resolve!: (rows: unknown) => void;+ h.invoke.mockImplementationOnce(+ () =>+ new Promise((done) => {+ resolve = done;+ }),+ );+ await act(async () => h.push?.('a'));+ h.invoke.mockResolvedValue(rows('Newest'));+ await act(async () => {+ h.push?.('a');+ resolve(rows('Stale'));+ });+ expect(remoteProjectAlias(view, 'a', '/repo/app')).toBe('Newest');+ h.context.connectionEpoch++;+ h.invoke.mockResolvedValue(rows('Reconnected'));+ await render();+ expect(remoteProjectAlias(view, 'a', '/repo/app')).toBe('Reconnected');+ h.invoke.mockResolvedValue(rows('Foreground'));+ await act(async () => h.active?.('active'));+ expect(remoteProjectAlias(view, 'a', '/repo/app')).toBe('Foreground');+ h.offline.add('a');+ await render();+ const calls = h.invoke.mock.calls.length;+ await act(async () => h.push?.('a'));+ expect(h.invoke.mock.calls).toHaveLength(calls);+ h.offline.clear();+ h.invoke.mockResolvedValue(rows('Online again'));+ await render();+ expect(remoteProjectAlias(view, 'a', '/repo/app')).toBe('Online again');+});+it('keeps transient failures bounded, but clears stale names for an unsupported old host', async () => {+ await render();+ h.invoke.mockRejectedValue(new Error('offline'));+ await act(async () => h.push?.('a'));+ expect(remoteProjectAlias(view, 'a', '/repo/app')).toBe('Portal');+ const calls = h.invoke.mock.calls.length;+ await act(async () => {+ await vi.runAllTimersAsync();+ });+ expect(h.invoke.mock.calls.length - calls).toBe(2);+ h.invoke.mockRejectedValue(+ Object.assign(new Error('Old host'), { code: 'CHANNEL_NOT_ALLOWED' }),+ );+ await act(async () => h.push?.('a'));+ expect(view.size).toBe(0);+});+it('rejects late old-account/device replies and clears old-account names immediately', async () => {+ await render();+ let resolve!: (rows: unknown) => void;+ h.invoke.mockImplementationOnce(+ () =>+ new Promise((done) => {+ resolve = done;+ }),+ );+ await act(async () => h.push?.('a'));+ setMobileAuthOwner('another-owner');+ h.accountGeneration++;+ h.invoke.mockResolvedValue([]);+ await render(['b']);+ await act(async () => resolve(rows('Private old name')));+ expect(view.size).toBe(0);+});diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 57a850aba7..ae6ec13172 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -261,6 +261,11 @@ export function subscribeRemoteTaskTagsChanged(};}const remoteFavoritesChangedListeners = new Set<(deviceId: string) => void>();+const remoteProjectAliasesChangedListeners = new Set<(deviceId: string) => void>();+export function subscribeRemoteProjectAliasesChanged(listener: (deviceId: string) => void): () => void {+ remoteProjectAliasesChangedListeners.add(listener);+ return () => { remoteProjectAliasesChangedListeners.delete(listener); };+}export function subscribeRemoteFavoritesChanged(listener: (deviceId: string) => void): () => void {remoteFavoritesChangedListeners.add(listener);return () => { remoteFavoritesChangedListeners.delete(listener); };@@ -1731,6 +1736,11 @@ export function routeFrame(env: Envelope, handlers: RouteFrameHandlers = {}): vofor (const listener of remoteFavoritesChangedListeners) listener(env.src);return;}+ if (push.channel === 'local-db:project-aliases:changed') {+ // Invalidation only: reread through the current authenticated invoke boundary.+ for (const listener of remoteProjectAliasesChangedListeners) listener(env.src);+ return;+ }if (push.channel === 'maker:provider:changed') {handlers.onProviderChanged?.(env.src);return;diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsxindex 97881ca50b..df23736961 100644--- a/apps/mobile/src/session/HomeSurface.tsx+++ b/apps/mobile/src/session/HomeSurface.tsx@@ -215,6 +215,7 @@ import {rememberRemoteProjectOrderStamp,subscribeRemoteProjectOrderChanged,} from '@/session/remoteProjectOrder';+import { useRemoteProjectAliases } from '@/session/useRemoteProjectAliases';import {createProjectOrderFetchFence,isHostProjectOrderReachable,@@ -1852,18 +1853,21 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSysunresponsiveDeviceIds: unresponsiveDevices,},), [deviceModels, selectedDeviceId, unresponsiveDevices]);+ const projectAliases = useRemoteProjectAliases(searchOrigins.map((origin) => origin.deviceId));const searchProjects = useMemo(() => listConversationSearchProjects(excludeOrcaWorkerSessions(sessions),new Set(searchOrigins.map((origin) => origin.deviceId)),+ projectAliases,),- [searchOrigins, sessions],+ [searchOrigins, sessions, projectAliases],);const indexedSearch = useConversationSearch({enabled: true,retainedState: viewSession,origins: searchOrigins,projects: deviceIdentityCacheReady ? searchProjects : undefined,+ projectAliases,});const searchQuery = indexedSearch.query;const normalizedSearchQuery = searchQuery.trim();@@ -2018,6 +2022,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSysconst homeSessions = useMemo(() => excludeOrcaWorkerSessions(sessions), [sessions]);const home = useMemo(() => buildMobileHomePresentation({+ projectAliases,devices: deviceModels,liveActivityIndex,messagePreviewIndex,@@ -2030,12 +2035,13 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys// 未起名会话的显示文案:共享层不兜中文串,由这里给已解析的 i18n 值。unnamedLabel: t('session.menu.unnamedTitle'),}),- [deviceModels, liveActivityIndex, messagePreviewIndex, pendingInteractionIndex, scheduleIndex, searchQuery, selectedDeviceId, homeSessions, statusFilter, t],+ [deviceModels, liveActivityIndex, messagePreviewIndex, pendingInteractionIndex, scheduleIndex, searchQuery, selectedDeviceId, homeSessions, statusFilter, t, projectAliases],);// 「筛选 › 项目」的候选:设备范围内的项目全集,不受搜索与任务状态影响——否则已选中的项目// 会因搜索没命中或当前状态下没有任务而从菜单里消失,用户无法单独取消它。const projectFilterUniverse = useMemo(() => buildMobileHomePresentation({+ projectAliases,devices: deviceModels,scheduleIndex,selectedDeviceId,@@ -2043,7 +2049,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSysstatusFilter: 'all',unnamedLabel: t('session.menu.unnamedTitle'),}),- [deviceModels, scheduleIndex, selectedDeviceId, homeSessions, t],+ [deviceModels, scheduleIndex, selectedDeviceId, homeSessions, t, projectAliases],);const projectMachineIdentities = useMemo(() => buildHomeProjectMachineIdentities(home, deviceConnectionStates),diff --git a/apps/mobile/src/session/conversationSearch.ts b/apps/mobile/src/session/conversationSearch.tsindex 8d836186ae..a105d8f666 100644--- a/apps/mobile/src/session/conversationSearch.ts+++ b/apps/mobile/src/session/conversationSearch.ts@@ -1,6 +1,6 @@/*** 手机任务搜索集成层:按设备 fan-out `local-db:conversations:search`,- * 老端 / 离线回落到已缓存会话的标题与消息预览,不搜列表元数据。+ * 老端 / 离线回落到已缓存会话的标题与消息预览;项目别名单独补充缓存命中。** 纯函数 + 注入依赖,不直接碰 React / store。*/@@ -20,6 +20,7 @@ import {type ConversationSearchStatusFilter,} from '@cindy/maker-shared/conversation-search';import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';+import { remoteProjectAlias, type RemoteProjectAliasIndex } from '@cindy/maker-shared/mobile-home';import {remoteSessionDisplayTitle,sessionRowMessagePreview,@@ -82,6 +83,7 @@ export function conversationSearchOriginsFromDeviceModels(}export interface SearchConversationsAcrossDevicesDeps {+ projectAliases?: RemoteProjectAliasIndex;invoke: ConversationSearchInvoke;getCachedSessions: () => readonly RemoteSession[];isDeviceUnresponsive?: (deviceId: string) => boolean;@@ -123,6 +125,17 @@ export async function searchConversationsAcrossDevices(origins.map((origin) => searchOneDevice(origin, keywordRequest, deps)),);const present = pages.filter((page): page is ConversationSearchResponse => page != null);+ // A project display name is not part of the host's message FTS index. Supplement+ // only alias matches from the same visible device/project scope; keep content search intact.+ if (deps.projectAliases?.size) {+ const aliasMatches = deps.getCachedSessions().filter((session) =>+ session.workspaceKind === 'project' && remoteProjectAlias(deps.projectAliases,+ session.canonicalDeviceId ?? session.deviceLinkDeviceId, session.workingDir)+ ?.toLowerCase().includes(query.toLowerCase()));+ for (const origin of origins) present.push(searchCachedDeviceSessions(+ origin, requestForOrigin(origin, keywordRequest), aliasMatches, deps.projectAliases,+ ));+ }if (present.length === 0) return emptyConversationSearchResponse(query);const merged = mergeConversationSearchFanout(@@ -177,6 +190,7 @@ export function searchCachedDeviceSessions(origin: ConversationSearchDeviceOrigin,request: ConversationSearchRequest,sessions: readonly RemoteSession[],+ projectAliases?: RemoteProjectAliasIndex,): ConversationSearchResponse {const query = request.query.trim().toLowerCase();if (!query) return emptyConversationSearchResponse('');@@ -185,7 +199,9 @@ export function searchCachedDeviceSessions(sessions.forEach((session, index) => {if ((!CINDY_MAKE_ENABLED && isCindyMakeSource(session.source)) || session.orcaRole === 'worker') return;if (!sessionBelongsToDevice(session, origin.deviceId)) return;- const match = cachedConversationSearchMatch(session, query, request.unnamedLabel);+ const alias = session.workspaceKind === 'project'+ ? remoteProjectAlias(projectAliases, origin.deviceId, session.workingDir) : undefined;+ const match = cachedConversationSearchMatch(session, query, request.unnamedLabel, alias);if (!match) return;hits.push({session: sessionToSearchSummary(session, origin),@@ -214,8 +230,10 @@ function cachedConversationSearchMatch(session: RemoteSession,query: string,unnamedLabel?: string,+ projectAlias?: string,): { matchKind: 'title' | 'content' | 'both' } | null {- const titleHit = remoteSessionDisplayTitle(session, unnamedLabel).toLowerCase().includes(query);+ const titleHit = remoteSessionDisplayTitle(session, unnamedLabel).toLowerCase().includes(query)+ || projectAlias?.toLowerCase().includes(query) === true;const contentHit = (sessionRowMessagePreview(session) ?? '').toLowerCase().includes(query);if (!titleHit && !contentHit) return null;if (titleHit && contentHit) return { matchKind: 'both' };@@ -456,6 +474,7 @@ export function scopedConversationSearchOrigins(export function listConversationSearchProjects(sessions: readonly Pick<RemoteSession, 'canonicalDeviceId' | 'deviceLinkDeviceId' | 'deviceLinkDeviceName' | 'orcaRole' | 'workingDir' | 'workspaceKind'>[],deviceIds?: ReadonlySet<string>,+ projectAliases?: RemoteProjectAliasIndex,): ConversationSearchProjectOption[] {const byKey = new Map<string, ConversationSearchProjectOption>();for (const session of sessions) {@@ -478,7 +497,7 @@ export function listConversationSearchProjects(deviceId,deviceName: session.deviceLinkDeviceName ?? null,key,- title: conversationSearchProjectTitle(workingDir),+ title: remoteProjectAlias(projectAliases, deviceId, dirKey) ?? conversationSearchProjectTitle(workingDir),workingDir: dirKey,});}diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.tsindex 4d86347933..8b20e5137a 100644--- a/apps/mobile/src/session/newSession.ts+++ b/apps/mobile/src/session/newSession.ts@@ -2,6 +2,7 @@ import { modelNeedsReselection } from './modelReselection';import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';import { collapseWorktreeDirForGrouping } from '@cindy/maker-shared/worktree-paths';import { normalizeProjectOrderPath } from '@cindy/maker-shared/project-order-sync';+import { remoteProjectAlias, type RemoteProjectAliasIndex } from '@cindy/maker-shared/mobile-home';import {DEFAULT_DRAFT_SESSION_TITLE,deriveOptimisticSessionTitle,@@ -366,6 +367,7 @@ export function buildRecentWorkspaceOptions(sessions: readonly RemoteSession[],deviceId?: string,limit = 6,+ projectAliases?: RemoteProjectAliasIndex,): RecentWorkspaceOption[] {const byPath = new Map<string, RecentWorkspaceOption>();for (const session of sessions) {@@ -383,7 +385,7 @@ export function buildRecentWorkspaceOptions(if (!current) {byPath.set(pathKey, {workingDir,- title: projectTitle(workingDir),+ title: remoteProjectAlias(projectAliases, deviceId ?? session.deviceLinkDeviceId, workingDir) ?? projectTitle(workingDir),sessionCount: 1,lastActivityAt,});diff --git a/apps/mobile/src/session/useConversationSearch.ts b/apps/mobile/src/session/useConversationSearch.tsindex 2580df4e51..f0f659d179 100644--- a/apps/mobile/src/session/useConversationSearch.ts+++ b/apps/mobile/src/session/useConversationSearch.ts@@ -20,6 +20,7 @@ import {} from '@/session/conversationSearch';import { remoteSessionStore } from '@/session/remoteSessionStore';import { useStableValue } from '@/utils/useStableValue';+import type { RemoteProjectAliasIndex } from '@cindy/maker-shared/mobile-home';import type {ConversationSearchAgentFilter,ConversationSearchLastActivityFilter,@@ -37,12 +38,14 @@ export function useConversationSearch({retainedState,lockedWorkingDirs,projects,+ projectAliases,}: {origins: readonly ConversationSearchDeviceOrigin[];enabled: boolean;retainedState?: HomeViewSession;lockedWorkingDirs?: string[] | null;projects?: readonly ConversationSearchProjectOption[];+ projectAliases?: RemoteProjectAliasIndex;}): {query: string;setQuery: (value: string) => void;@@ -156,6 +159,7 @@ export function useConversationSearch({{invoke,getCachedSessions: () => remoteSessionStore.getSessions(),+ projectAliases,isDeviceUnresponsive: (deviceId) => unresponsiveDevicesStore.has(deviceId),},).then((page) => {@@ -193,6 +197,7 @@ export function useConversationSearch({statusFilter,unnamedLabel,workingDirs,+ projectAliases,]);return {diff --git a/apps/mobile/src/session/useRemoteProjectAliases.ts b/apps/mobile/src/session/useRemoteProjectAliases.tsnew file mode 100644index 0000000000..a6b3cc04ec--- /dev/null+++ b/apps/mobile/src/session/useRemoteProjectAliases.ts@@ -0,0 +1,167 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { AppState } from 'react-native';+import { useAuth } from '@/auth/AuthContext';+import {+ getMobileAuthOwner,+ isMobileAuthOwnerCurrent,+} from '@/auth/authOwnerGeneration';+import {+ useDeviceLink,+ subscribeRemoteProjectAliasesChanged,+} from '@/device-link/DeviceLinkContext';+import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';+import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';+import { isHostProjectOrderChannelMissing } from '@cindy/maker-shared/project-order-sync';+import {+ parseHostProjectAliases,+ PROJECT_ALIASES_LIST_CHANNEL,+ type RemoteProjectAliasIndex,+} from '@cindy/maker-shared/mobile-home';++const EMPTY: RemoteProjectAliasIndex = new Map();++/** Display-only snapshots; no writes, shared-connection resets or persistent storage. */+export function useRemoteProjectAliases(+ deviceIds: readonly string[],+): RemoteProjectAliasIndex {+ const { accountGeneration } = useAuth();+ const {+ invoke,+ status,+ connectionEpoch,+ subscribe,+ unsubscribe,+ recoveringDeviceIds,+ getPresenceAvailability,+ } = useDeviceLink();+ const unresponsive = useUnresponsiveDevices();+ const idsKey = JSON.stringify([...new Set(deviceIds.filter(Boolean))].sort());+ const reachableKey = JSON.stringify(+ (JSON.parse(idsKey) as string[]).filter(+ (id) =>+ !unresponsive.has(id) &&+ !recoveringDeviceIds.has(id) &&+ getPresenceAvailability?.(id) !== false,+ ),+ );+ const binding = JSON.stringify([+ accountGeneration,+ reachableKey,+ status,+ connectionEpoch,+ ]);+ const current = useRef(binding);+ current.current = binding;+ const [state, setState] = useState<{+ owner: number;+ devices: ReadonlyMap<string, RemoteProjectAliasIndex>;+ }>({ owner: accountGeneration, devices: new Map() });++ useEffect(() => {+ if (status !== 'online') return;+ const ids = JSON.parse(reachableKey) as string[];+ const owner = getMobileAuthOwner();+ let disposed = false;+ const valid = () =>+ !disposed &&+ current.current === binding &&+ isMobileAuthOwnerCurrent(owner);+ const pending = new Set<string>();+ const dirty = new Set<string>();+ const attempts = new Map<string, number>();+ const timers = new Map<string, ReturnType<typeof setTimeout>>();+ const refresh = async (id: string): Promise<void> => {+ if (!valid() || !ids.includes(id)) return;+ if (pending.has(id)) {+ dirty.add(id);+ return;+ }+ pending.add(id);+ clearTimeout(timers.get(id));+ try {+ do {+ dirty.delete(id);+ let aliases: RemoteProjectAliasIndex;+ try {+ aliases = parseHostProjectAliases(+ id,+ await invoke(id, PROJECT_ALIASES_LIST_CHANNEL, [], {+ background: true,+ }),+ );+ } catch (error) {+ if (!valid()) return;+ if (isHostProjectOrderChannelMissing(error)) aliases = EMPTY;+ else {+ const attempt = (attempts.get(id) ?? 0) + 1;+ attempts.set(id, attempt);+ // Retry only this read; keep the last good display during transient failures.+ if (attempt < 3)+ timers.set(+ id,+ setTimeout(() => {+ void refresh(id);+ }, 2000),+ );+ return;+ }+ }+ if (!valid()) return;+ if (dirty.has(id)) continue;+ attempts.delete(id);+ setState((previous) => ({+ owner: accountGeneration,+ devices: new Map(+ previous.owner === accountGeneration ? previous.devices : [],+ ).set(id, aliases),+ }));+ } while (dirty.has(id));+ } finally {+ pending.delete(id);+ }+ };+ const off = subscribeRemoteProjectAliasesChanged((id) => {+ attempts.delete(id);+ void refresh(id);+ });+ // Also read after subscription ACK: a rename between the initial read and ACK must not be missed.+ const stops = ids.map((deviceId) =>+ startFocusedTopicSubscription({+ deviceId,+ owner: 'project-aliases',+ topic: 'sessions',+ unsubscribe,+ subscribe: async (...args) => {+ await subscribe(...args);+ if (valid()) void refresh(deviceId);+ },+ }),+ );+ const refreshAll = () => {+ attempts.clear();+ // Uses the existing shared background invoke scheduler.+ for (const id of ids) void refresh(id);+ };+ refreshAll();+ const app = AppState.addEventListener('change', (next) => {+ if (next === 'active') refreshAll();+ });+ return () => {+ disposed = true;+ off();+ app.remove();+ stops.forEach((stop) => stop());+ timers.forEach(clearTimeout);+ };+ }, [binding, invoke, subscribe, unsubscribe]);++ return useMemo(() => {+ if (state.owner !== accountGeneration) return EMPTY;+ const aliases = new Map<string, string>();+ for (const id of JSON.parse(idsKey) as string[]) {+ for (const [key, alias] of state.devices.get(id) ?? [])+ aliases.set(key, alias);+ }+ return aliases;+ }, [state, accountGeneration, idsKey]);+}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 302127b467..87be04ad5c 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1,5 +1,21 @@# 跨端协议兼容+## 手机读取项目别名(#6916)++同账号 device-link 只读白名单增加 `local-db:project-aliases:list`,返回宿主现有的+`{ projectKey, alias, updatedAt }[]`。`local-db:project-aliases:changed` 作为无数据的失效通知+加入 `sessions` topic;写入完成后带捕获的账号代次转发,手机收到后重读宿主。+不开放远程 `set/delete`,不改变路径、项目分组键或任务归属,不涉及服务端及数据库迁移。++手机只采用响应中 `local:` 项,并用来源 deviceId 和规范化路径隔离;不把宿主的 SSH/+另一台电脑的查看端别名套到本机项目。首页、项目筛选、别名搜索及最近工作区共用该投影。+订阅完成、前台恢复、链路重连及设备恢复可达时重读;旧账号/旧连接的迟到回复丢弃。+恢复只影响单台设备的元数据读请求,不重置共享连接、不重放写操作;瞬时失败保留本次+挂载内的快照并最多重试两次。清除别名回到目录名。++新手机连接旧宿主遇到通道不支持时显示目录名;旧手机忽略新增通知,行为不变。+完整同步需要两端都有此改动。没有 Mobile 原生依赖/配置变更。+## Device Link 局域网优先直连可靠链路的 `link-open/link-accept` 增加可选能力 `direct-link-v1`。双方均支持且已完成diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.tsindex b748bb75dc..64f709dba2 100644--- a/packages/device-link/src/__tests__/allowlist.test.ts+++ b/packages/device-link/src/__tests__/allowlist.test.ts@@ -210,6 +210,10 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {});it('放行被控端项目顺序读写(显示偏好,真相在被控端)', () => {+ // #6916: only the host display-name read is remotely callable; local preferences stay local.+ expect(REMOTE_INVOKE_ALLOWLIST.has('local-db:project-aliases:list')).toBe(true);+ expect(REMOTE_INVOKE_ALLOWLIST.has('local-db:project-aliases:set')).toBe(false);+ expect(REMOTE_INVOKE_ALLOWLIST.has('local-db:project-aliases:delete')).toBe(false);expect(REMOTE_INVOKE_ALLOWLIST.has('sidebar-settings:get-project-order')).toBe(true);expect(REMOTE_INVOKE_ALLOWLIST.has('sidebar-settings:apply-project-order')).toBe(true);expect(REMOTE_INVOKE_ALLOWLIST.has('sidebar-settings:set-project-order')).toBe(false);@@ -432,6 +436,7 @@ describe('PUSH_FORWARD_ALLOWLIST', () => {'local-db:messages:deleted','local-db:session:error-persisted','sidebar-settings:project-order-changed',+ 'local-db:project-aliases:changed',SESSION_ACTIVITY_CHANNEL,]) {expect(PUSH_FORWARD_ALLOWLIST.has(ch)).toBe(true);diff --git a/packages/device-link/src/__tests__/topics.test.ts b/packages/device-link/src/__tests__/topics.test.tsindex b65455db2d..a8ef7c9ddd 100644--- a/packages/device-link/src/__tests__/topics.test.ts+++ b/packages/device-link/src/__tests__/topics.test.ts@@ -53,6 +53,7 @@ describe('topicForPush', () => {it('账号 / 全局级 channel → sessions(随列表订阅走)', () => {expect(topicForPush('maker:provider:changed', { revision: 42 })).toBe('sessions');expect(topicForPush('maker:agents:changed', {})).toBe('sessions');+ expect(topicForPush('local-db:project-aliases:changed', undefined)).toBe('sessions');expect(topicForPush('maker:schedule:event', { kind: 'x' })).toBe('sessions');expect(topicForPush('maker:project-automation:event', {})).toBe('sessions');// 被控端当前草稿全量变更(无 sessionId)→ 并入 sessions topic。diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.tsindex 5099883bd9..170ef8e3f8 100644--- a/packages/device-link/src/allowlist.ts+++ b/packages/device-link/src/allowlist.ts@@ -337,6 +337,8 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [// 控制端吞错,仅靠已加载消息 + 实时 turn-cost 推送呈现部分值。'local-db:messages:estimatedSessionValue','local-db:recent-workdirs:list',+ // Host-owned project display names. No remote mutation of viewer preferences.+ 'local-db:project-aliases:list',// 窄口径写:从被控端「最近项目」列表移除一条(专用 handler,path 归一后按主键删,// 幂等,不动 sessions / 磁盘)。控制端项目选择器的删除入口与本机语义对等;// 老被控端无此 handler → CHANNEL_NOT_ALLOWED → 控制端隐藏/忽略删除能力即可。@@ -811,6 +813,7 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set(['local-db:session:error-persisted',// 被控端项目手动顺序变化:控制端 / 手机首页按被控端正本重排。'sidebar-settings:project-order-changed',+ 'local-db:project-aliases:changed',// 被控端「当前 New Maker 草稿」全量变更:被控端草稿 effort/fast/选中 等任意变化时广播,// 控制端的远程项目草稿据此实时刷新显示镜像(remoteDraftState)。账号 / 全局级、无 sessionId →// topics.ts 的 ACCOUNT_CHANNELS 把它并入 `sessions` topic(控制端按设备订阅 sessions)。diff --git a/packages/device-link/src/topics.ts b/packages/device-link/src/topics.tsindex c912fb27e6..b9cb10a23c 100644--- a/packages/device-link/src/topics.ts+++ b/packages/device-link/src/topics.ts@@ -193,6 +193,7 @@ const ACCOUNT_CHANNELS: ReadonlySet<string> = new Set(['learn:event',// 被控端项目手动顺序变化:无 sessionId,并入 sessions topic 随设备列表订阅到达。'sidebar-settings:project-order-changed',+ 'local-db:project-aliases:changed',// Claude 订阅账号余量快照(账号级,无 sessionId):控制端打开远程订阅会话时 chip// 据此实时刷新;并入 sessions topic 随设备列表订阅到达,低频(签名去抖 + 节流)。'usage:claude-subscription-changed',diff --git a/packages/maker-shared/src/__tests__/mobileHome.test.ts b/packages/maker-shared/src/__tests__/mobileHome.test.tsindex fa3b846d93..8cbe91d7f3 100644--- a/packages/maker-shared/src/__tests__/mobileHome.test.ts+++ b/packages/maker-shared/src/__tests__/mobileHome.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from 'vitest';import {buildMobileHomePresentation,+ parseHostProjectAliases,+ remoteProjectAlias,type MobileHomeSessionLike,} from '../mobileHome.js';@@ -26,6 +28,37 @@ function session(id: string, patch: Partial<MobileHomeSessionLike> = {}): Mobile}describe('mobileHome', () => {+ it('maps host aliases with the same Windows/worktree identity as project cards', () => {+ const aliases = parseHostProjectAliases('pc:one', [+ { projectKey: 'local:C:\\Repo\\App\\', alias: 'Newest' },+ { projectKey: 'local:c:/repo/app', alias: 'Older' },+ { projectKey: 'remote:ssh:/repo/app', alias: 'SSH only' },+ { projectKey: 'device:another:/repo/app', alias: 'Viewer only' },+ ]);+ expect(remoteProjectAlias(aliases, 'pc:one', 'c:/REPO/app/.cindy-worktrees/branch')).toBe('Newest');+ expect(remoteProjectAlias(aliases, 'pc:two', 'c:/repo/app')).toBeUndefined();+ expect(aliases.size).toBe(1);+ expect(() => parseHostProjectAliases('pc:one', {})).toThrow();+ });+ // #6916: existing grouping tests only exercised directory names. A host alias must+ // change visible titles/search, without changing project identity (unit tier).+ it('uses device-scoped project aliases for titles and search, and falls back after clearing', () => {+ const sessions = ['mac-a', 'mac-b'].map((deviceLinkDeviceId) => session(deviceLinkDeviceId, {+ deviceLinkDeviceId,+ }));+ const options = {+ sessions,+ projectAliases: new Map([['device:mac-a:/repo/app', 'Customer Portal']]),+ };+ const home = buildMobileHomePresentation(options);+ expect(home.projects.map((project) => [project.key, project.title])).toEqual([+ ['device:mac-a:/repo/app', 'Customer Portal'],+ ['device:mac-b:/repo/app', 'app'],+ ]);+ expect(buildMobileHomePresentation({ ...options, searchQuery: 'customer' }).projects.map((p) => p.deviceId)).toEqual(['mac-a']);+ expect(buildMobileHomePresentation({ ...options, projectAliases: new Map() }).projects.map((p) => p.title)).toEqual(['app', 'app']);+ });+it('hides Cindy Make creation and merge tasks from the home presentation', () => {const sessions = [session('make-a', { source: 'cindy-make', workingDir: 'C:\\Cindy\\tasks\\random-a' }),diff --git a/packages/maker-shared/src/mobileHome.ts b/packages/maker-shared/src/mobileHome.tsindex 6973cc6c71..8a2c43de34 100644--- a/packages/maker-shared/src/mobileHome.ts+++ b/packages/maker-shared/src/mobileHome.ts@@ -15,6 +15,10 @@ import { stripTrailingPathSeparators } from './pathText.js';import { normalizeProjectOrderPath } from './projectOrderSync.js';import { collapseWorktreeDirForGrouping } from './worktreePaths.js';import { CINDY_MAKE_ENABLED, isCindyMakeSource } from './cindyMakeFeature.js';+import { remoteProjectAlias, type RemoteProjectAliasIndex } from './projectAliases.js';+export { remoteProjectAlias, remoteProjectAliasKey, parseHostProjectAliases,+ PROJECT_ALIASES_LIST_CHANNEL, PROJECT_ALIASES_CHANGED_CHANNEL } from './projectAliases.js';+export type { RemoteProjectAliasIndex } from './projectAliases.js';export const MOBILE_HOME_ALL_DEVICES = 'all';@@ -118,6 +122,7 @@ export interface MobileHomePresentation {}export interface MobileHomeOptions {+ projectAliases?: RemoteProjectAliasIndex;devices?: readonly MobileHomeDeviceLike[];messagePreviewIndex?: ReadonlyMap<string, string>;liveActivityIndex?: ReadonlyMap<string, RemoteSessionLiveActivity>;@@ -137,6 +142,7 @@ export interface MobileHomeOptions {}export function buildMobileHomePresentation({+ projectAliases,devices = [],messagePreviewIndex,liveActivityIndex,@@ -176,6 +182,7 @@ export function buildMobileHomePresentation({pendingInteractionIndex,scheduleIndex,unnamedLabel,+ projectAliases,)).sort(compareSessionsByStatusThenActivityDesc);const items = filteredSessions.map((session) => toRemoteSessionListItem(@@ -214,6 +221,7 @@ export function buildMobileHomePresentation({localizer,),devices,+ projectAliases,);const overview = summarizeHomeOverview(normalizedSessions, projects, pendingInteractionIndex, normalizedSelectedDeviceId);const primaryDevice = pickPrimaryDevice(deviceFilters, normalizedSelectedDeviceId);@@ -334,6 +342,7 @@ function pickPrimaryDevice(function buildProjectGroups(items: readonly RemoteSessionListItem[],devices: readonly MobileHomeDeviceLike[],+ projectAliases?: RemoteProjectAliasIndex,): MobileHomeProjectGroup[] {const deviceNames = new Map(devices.map((device) => [device.deviceId, device.name]));const grouped = new Map<string, RemoteSessionListItem[]>();@@ -369,7 +378,7 @@ function buildProjectGroups(sessionCount: group.reduce((sum, item) => sum + (item.automationGroup?.sessionCount ?? 1), 0),sessions: group,subtitle: [deviceName, workingDir].filter(Boolean).join(' · '),- title: cindyMake ? 'Cindy Make' : projectTitle(workingDir),+ title: cindyMake ? 'Cindy Make' : remoteProjectAlias(projectAliases, deviceId, workingDir) ?? projectTitle(workingDir),workingDir,};})@@ -535,10 +544,12 @@ function matchesSearchQuery(pendingInteractionIndex: ReadonlyMap<string, number> | undefined,scheduleIndex: ReadonlyMap<string, RemoteSessionScheduleInfo> | undefined,unnamedLabel: string | undefined,+ projectAliases?: RemoteProjectAliasIndex,): boolean {if (!query) return true;const scheduleInfo = scheduleIndex?.get(session.id) ?? fallbackScheduleInfo(session);const haystack = [+ remoteProjectAlias(projectAliases, sessionDeviceKey(session), session.workingDir),// 与首页行展示同源到函数级(同 sessionList 的 matchesSearchQuery):行上显示的就是// remoteSessionDisplayTitle 的结果,haystack 直接调同一个函数。放原始哨兵会让// 「搜得到的」与「看得到的」错位 —— 两个方向都错(见 sessionList 那条注释)。diff --git a/packages/maker-shared/src/projectAliases.ts b/packages/maker-shared/src/projectAliases.tsnew file mode 100644index 0000000000..e2891c7d03--- /dev/null+++ b/packages/maker-shared/src/projectAliases.ts@@ -0,0 +1,50 @@+import { normalizeProjectOrderPath } from './projectOrderSync.js';++/** Host-owned display metadata. Never changes filesystem paths or task grouping. */+export const PROJECT_ALIASES_LIST_CHANNEL = 'local-db:project-aliases:list';+export const PROJECT_ALIASES_CHANGED_CHANNEL =+ 'local-db:project-aliases:changed';+export type RemoteProjectAliasIndex = ReadonlyMap<string, string>;++export function remoteProjectAliasKey(+ deviceId: string,+ workingDir: string,+): string {+ return `device:${encodeURIComponent(deviceId)}:${normalizeProjectOrderPath(workingDir)}`;+}++/** Local keys belong to the responding host; SSH/viewer-only aliases must not leak into them. */+export function parseHostProjectAliases(+ deviceId: string,+ value: unknown,+): Map<string, string> {+ if (!Array.isArray(value))+ throw new Error('Invalid project aliases response');+ const aliases = new Map<string, string>();+ for (const entry of value) {+ if (!entry || typeof entry !== 'object') continue;+ const { projectKey, alias } = entry as Record<string, unknown>;+ if (+ typeof projectKey !== 'string' ||+ !projectKey.startsWith('local:') ||+ !projectKey.slice(6).trim() ||+ typeof alias !== 'string' ||+ !alias.trim()+ )+ continue;+ const key = remoteProjectAliasKey(deviceId, projectKey.slice(6));+ // Host lists newest first, including legacy case variants.+ if (!aliases.has(key)) aliases.set(key, alias.trim());+ }+ return aliases;+}++export function remoteProjectAlias(+ aliases: RemoteProjectAliasIndex | undefined,+ deviceId: string | null | undefined,+ workingDir: string | null | undefined,+): string | undefined {+ return deviceId && workingDir+ ? aliases?.get(remoteProjectAliasKey(deviceId, workingDir))+ : undefined;+}