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。

Merge main and reconcile project alias contracts

xuzini-xzn1fcfcc4d508e
diff --cc apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts
index 9aaf09f99a,d70eabfd1a..0a29a2410d
--- a/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts
@@@ -16,15 -24,6 +24,10 @@@ vi.mock('electron', () => (
handle: vi.fn(),
},
}));
- vi.mock('../../device-link/broadcast-tap.js', () => ({
- captureDataOwnerBroadcastScope: () => ({}),
- isDataOwnerBroadcastScopeCurrent: () => true,
- tapWindowBroadcast: vi.fn(),
- }));
+vi.mock('../../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: vi.fn(),
+ isTrustedAppRendererWindow: () => true,
+}));
describe('projectAliases localDb helpers', () => {
let currentClient: DbClient | null = null;
@@@ -62,6 -65,10 +69,10 @@@
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 },
++ { channel: 'local-db:project-aliases:changed', payload: {} },
++ { channel: 'local-db:project-aliases:changed', payload: {} },
+ ]);
});
it('atomically replaces every Unicode Windows casing variant', async () => {
diff --cc apps/desktop/src/main/localDb/ipc/__tests__/projectAliasesBroadcast.test.ts
index fb1ba9268d,0000000000..37032be9b5
mode 100644,000000..100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/projectAliasesBroadcast.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/projectAliasesBroadcast.test.ts
@@@ -1,126 -1,0 +1,140 @@@
+/**
+ * Test value: real snapshot/mutation handlers expose only host-owned names and scoped invalidations.
+ * Regression: project renames never reached device-link; existing SQLite tests did not exercise
+ * IPC authorization or broadcasts. Minimal input is one local/SSH alias plus a device override,
+ * or an owner change during the awaited read/write. Unit tier with injected DB/renderer boundaries.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ trusted: { webContents: { send: vi.fn() } },
+ untrusted: { webContents: { send: vi.fn() } },
+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 2 },
+ scopeCurrent: true,
+ read: vi.fn(),
+ tx: vi.fn(),
+ tap: vi.fn(),
+ handle: vi.fn(),
+ assertTrusted: vi.fn(),
+ remoteInvoke: false,
+}));
+vi.mock('electron', () => ({
+ BrowserWindow: { getAllWindows: () => [h.trusted, h.untrusted] },
+ ipcMain: { handle: h.handle },
+}));
+vi.mock('../../client/current', () => ({
+ getDbClient: () => ({
+ drizzle: { select: () => ({ from: () => ({ orderBy: h.read }) }) },
+ tx: h.tx,
+ }),
+}));
+vi.mock('../../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({ ownerScopeKey: 'owner-a:2', ownerStamp: h.ownerStamp }),
+ isDataOwnerBroadcastScopeCurrent: () => h.scopeCurrent,
+ tapWindowBroadcast: h.tap,
+}));
+vi.mock('../../../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: h.assertTrusted,
+ isTrustedAppRendererWindow: (window: unknown) => window === h.trusted,
+}));
+vi.mock('../../../device-link/invoke-context.js', () => ({
+ isDeviceLinkInvoke: () => h.remoteInvoke,
+}));
+
+import {
+ readHostProjectAliasesSnapshot,
+ registerProjectAliasesIpc,
+ upsertProjectAlias,
+} from '../projectAliases';
+
+describe('project alias remote snapshot and owner boundary', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ h.scopeCurrent = true;
+ h.remoteInvoke = false;
+ h.assertTrusted.mockReset();
+ h.read.mockResolvedValue([]);
+ h.tx.mockResolvedValue(null);
+ });
+
+ it('requires a trusted local sender while permitting already-authorized device-link invocations', async () => {
+ registerProjectAliasesIpc();
+ const handler = h.handle.mock.calls.find(([channel]) => channel === 'sidebar-settings:get-project-aliases')![1];
+ h.assertTrusted.mockImplementationOnce(() => { throw new Error('UNAUTHORIZED'); });
+ await expect(handler({})).rejects.toThrow('UNAUTHORIZED');
+ expect(h.read).not.toHaveBeenCalled();
+ h.remoteInvoke = true;
+ await expect(handler({})).resolves.toMatchObject({ aliases: [] });
+ expect(h.assertTrusted).toHaveBeenCalledTimes(1);
+ });
+
+ it('registers a separate snapshot and excludes controller-local device overrides', async () => {
+ h.read.mockResolvedValue([
+ { projectKey: 'local:C:/Repo', alias: 'Local project', updatedAt: 1 },
+ { projectKey: 'remote:ssh-a:/repo', alias: 'SSH project', updatedAt: 2 },
+ { projectKey: 'device:other:/repo', alias: 'Private override', updatedAt: 3 },
+ ]);
+ registerProjectAliasesIpc();
+ expect(h.handle).toHaveBeenCalledWith('sidebar-settings:get-project-aliases', expect.any(Function));
+ expect(await readHostProjectAliasesSnapshot()).toEqual({
+ aliases: [
+ { projectKey: 'local:C:/Repo', alias: 'Local project' },
+ { projectKey: 'remote:ssh-a:/repo', alias: 'SSH project' },
+ ],
+ platform: process.platform,
+ ownerStamp: h.ownerStamp,
+ });
+ });
+
++ it.each([false, true])('keeps the legacy list contract while filtering remote viewer overrides (remote=%s)', async (remote) => {
++ const rows = [
++ { projectKey: 'local:/repo', alias: 'Local', updatedAt: 1 },
++ { projectKey: 'remote:ssh:/repo', alias: 'SSH', updatedAt: 2 },
++ { projectKey: 'device:viewer:/repo', alias: 'Private', updatedAt: 3 },
++ ];
++ h.read.mockResolvedValue(rows);
++ h.remoteInvoke = remote;
++ registerProjectAliasesIpc();
++ const handler = h.handle.mock.calls.find(([channel]) => channel === 'local-db:project-aliases:list')![1];
++ expect(await handler({})).toEqual((remote ? rows.slice(0, 2) : rows)
++ .map(row => ({ ...row, updatedAt: new Date(row.updatedAt).toISOString() })));
++ });
++
+ it('broadcasts persisted rename and deletion invalidations with the captured owner stamp', async () => {
+ await upsertProjectAlias('local:/repo', 'New name');
+ await upsertProjectAlias('local:/repo', '');
+ expect(h.tap).toHaveBeenCalledTimes(2);
+ expect(h.tap).toHaveBeenLastCalledWith('local-db:project-aliases:changed', {}, h.ownerStamp);
+ expect(h.trusted.webContents.send).toHaveBeenLastCalledWith(
+ 'local-db:project-aliases:changed', {}, h.ownerStamp,
+ );
+ expect(h.untrusted.webContents.send).not.toHaveBeenCalled();
+ });
+
+ it('does not emit an old owner write after an account switch', async () => {
+ let complete!: (value: null) => void;
+ h.tx.mockImplementationOnce(() => new Promise((resolve) => { complete = resolve; }));
+ const pending = upsertProjectAlias('local:/repo', 'Old account name');
+ h.scopeCurrent = false;
+ complete(null);
+ await pending;
+ expect(h.tap).not.toHaveBeenCalled();
+ expect(h.trusted.webContents.send).not.toHaveBeenCalled();
+ });
+
+ it('rejects a snapshot that finishes after its owner becomes stale', async () => {
+ h.read.mockImplementationOnce(async () => {
+ h.scopeCurrent = false;
+ return [{ projectKey: 'local:/repo', alias: 'Old account name', updatedAt: 1 }];
+ });
+ await expect(readHostProjectAliasesSnapshot()).rejects.toThrow('PRECONDITION_FAILED');
+ });
+
+ it('does not broadcast a failed mutation or hide a failed snapshot read', async () => {
+ h.tx.mockRejectedValueOnce(new Error('write failed'));
+ await expect(upsertProjectAlias('local:/repo', 'Name')).rejects.toThrow('write failed');
+ expect(h.tap).not.toHaveBeenCalled();
+ h.read.mockRejectedValueOnce(new Error('read failed'));
+ await expect(readHostProjectAliasesSnapshot()).rejects.toThrow('read failed');
+ });
+});
diff --cc apps/desktop/src/main/localDb/ipc/projectAliases.ts
index acf718500d,a2b42c9795..f8cc8b334a
--- a/apps/desktop/src/main/localDb/ipc/projectAliases.ts
+++ b/apps/desktop/src/main/localDb/ipc/projectAliases.ts
@@@ -71,22 -64,6 +73,27 @@@ export async function listProjectAliase
return rows.map(aliasToCamel);
}
+/** Read-only host projection; controller-local overrides never propagate to a third device. */
+export async function readHostProjectAliasesSnapshot(): Promise<HostProjectAliasesSnapshot> {
+ const scope = captureDataOwnerBroadcastScope();
- const rows = await listProjectAliases();
++ const rows = await listProjectAliases().catch((error: unknown) => {
++ if (!isDataOwnerBroadcastScopeCurrent(scope)) {
++ throwIpcError('PRECONDITION_FAILED', 'active account changed during project alias read');
++ }
++ throw error;
++ });
+ if (!isDataOwnerBroadcastScopeCurrent(scope)) {
+ throwIpcError('PRECONDITION_FAILED', 'active account changed during project alias read');
+ }
+ return {
+ aliases: rows
+ .filter((row) => row.projectKey.startsWith('local:') || row.projectKey.startsWith('remote:'))
+ .map(({ projectKey, alias }) => ({ projectKey, alias })),
+ platform: process.platform,
+ ...(scope.ownerStamp ? { ownerStamp: scope.ownerStamp } : {}),
+ };
+}
+
export async function upsertProjectAlias(
projectKeyRaw: unknown,
aliasRaw: unknown,
@@@ -130,11 -107,7 +137,16 @@@ export async function deleteProjectAlia
}
export function registerProjectAliasesIpc(): void {
- ipcMain.handle('local-db:project-aliases:list', async () => listProjectAliases());
+ ipcMain.handle(PROJECT_ALIASES_GET_CHANNEL, async (event) => {
+ if (!isDeviceLinkInvoke()) assertTrustedAppRendererEvent(event);
+ return readHostProjectAliasesSnapshot();
+ });
- ipcMain.handle('local-db:project-aliases:list', async () => listProjectAliases());
++ ipcMain.handle('local-db:project-aliases:list', async () => {
++ const rows = await listProjectAliases();
++ return isDeviceLinkInvoke()
++ ? rows.filter(row => row.projectKey.startsWith('local:') || row.projectKey.startsWith('remote:'))
++ : rows;
++ });
ipcMain.handle('local-db:project-aliases:set', async (_event, input: unknown) => {
const body = requireObject(input, 'input');
diff --cc apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts
index bd9f6c0d11,8fc5e08f1b..8b4bf8962c
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts
@@@ -6,8 -6,9 +6,9 @@@
* Row-only patches reuse membership and ordering, keeping unrelated nodes stable.
*/
-import { useMemo } from 'react';
+import { useMemo, useSyncExternalStore } from 'react';
import { createProjectGroupsSelector } from '../lib/projectGroupsSelector';
+ import { useProvisionalDraftProjectTaskId } from './useProvisionalDraftProjectTaskId';
import type { Session } from '@/lib/ccAgent.types';
import { useRemoteSshHosts } from '@/hooks/useRemoteSshHosts';
@@@ -34,8 -34,8 +35,9 @@@ export function useProjectGroups
equivalentResult?: ProjectGroupsResult,
): ProjectGroupsResult {
const sshHosts = useRemoteSshHosts();
+ const hostProjectAliases = useSyncExternalStore(remoteProjectAliases.subscribe, remoteProjectAliases.getSnapshot);
const selectGroups = useMemo(() => createProjectGroupsSelector(), []);
+ const provisionalDraftTaskId = useProvisionalDraftProjectTaskId();
/*
伙伴归属表。会话行本身不带 botId,归属只有伙伴档案知道 —— 档案还没加载完的
那一瞬间这张表是空的,伙伴任务就走原来的分组落到别处,**不会消失**。
diff --cc apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.ts
index 664ba4460e,cd42856bdc..7938781370
--- a/apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/projectGroupsSelector.ts
@@@ -58,9 -58,9 +58,10 @@@ function samePersistentProjects
function sameOptions(a: GroupSessionsOptions, b: GroupSessionsOptions): boolean {
return (
a.projectAliases === b.projectAliases &&
+ a.remoteProjectAliases === b.remoteProjectAliases &&
a.includePinnedInProjects === b.includePinnedInProjects &&
a.includeDraftsInProjects === b.includeDraftsInProjects &&
+ a.provisionalDraftTaskId === b.provisionalDraftTaskId &&
a.localPlatform === b.localPlatform &&
a.botOwnerBySessionId === b.botOwnerBySessionId &&
samePersistentProjects(a.persistentLocalProjects, b.persistentLocalProjects)
diff --cc apps/mobile/app/devices/[deviceId].tsx
index f859c14ab2,04c92aae84..687fb53323
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@@ -239,9 -230,10 +239,9 @@@ function DeviceDetailScreenContent()
deviceName,
reachable: !deviceUnresponsive,
}] : []), [deviceId, deviceName, deviceUnresponsive]);
- const projectAliases = useRemoteProjectAliases(deviceId ? [deviceId] : []);
const searchProjects = useMemo(
() => listConversationSearchProjects(sessions, deviceId ? new Set([deviceId]) : undefined, projectAliases),
- [deviceId, projectAliases, sessions],
+ [deviceId, sessions, projectAliases],
);
const indexedSearch = useConversationSearch({
enabled: !automationScopeKey && !!deviceId,
diff --cc apps/mobile/src/__tests__/homeDisplaySettings.test.ts
index 89d93905a8,d32c9f1028..8bdaf6fbf0
--- a/apps/mobile/src/__tests__/homeDisplaySettings.test.ts
+++ b/apps/mobile/src/__tests__/homeDisplaySettings.test.ts
@@@ -225,11 -225,15 +225,16 @@@ describe('task info and retained Home b
it('keeps real project candidates available despite nonmatching search and status', () => {
const sessions = ['A', 'B'].map((name) => ({ ...item(name).session, title: name, workingDir: '/' + name,
workspaceKind: 'project', status: 'active', deviceLinkDeviceId: 'd', deviceLinkDeviceName: 'Computer' }));
+ // Keep the existing production-expression fixture complete when aliases become an optional Home input.
const result = surfaceValue('projectFilterUniverse', { useMemo, buildMobileHomePresentation,
- projectAliases: new Map(), deviceModels: [], scheduleIndex: new Map(), selectedDeviceId: null, homeSessions: sessions,
+ deviceModels: [], scheduleIndex: new Map(), selectedDeviceId: null, homeSessions: sessions,
+ projectAliases: new Map([['device:d:/A', 'Customer Portal']]),
t: (key: string) => key, searchQuery: 'no match', statusFilter: 'running' });
expect(result.projects.map((project: { workingDir: string }) => project.workingDir).sort()).toEqual(['/A', '/B']);
+ // #7026: the production initializer consumes host aliases; keep that input
+ // in this unit fixture and verify its visible title without filtering candidates.
+ expect(result.projects.find((project: { workingDir: string }) => project.workingDir === '/A')?.title)
+ .toBe('Customer Portal');
});
it('expires active-time rows using the actual clock input while Home stays open', () => {
diff --cc apps/mobile/src/__tests__/newSession.test.ts
index 3bc6625e96,cb1dd0efbe..e81631a580
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@@ -1795,6 -1810,19 +1810,29 @@@ 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');
+ });
+
++ it('keeps mixed local/SSH recent-workspace names independent of row order', () => {
++ const aliases = new Map([['device:mac-a:/repo/app', 'Local name']]);
++ const local = remoteSession('local', { workingDir: '/repo/app', deviceLinkDeviceId: 'mac-a' });
++ const ssh = remoteSession('ssh', { workingDir: '/repo/app', deviceLinkDeviceId: 'mac-a', remoteHostId: 'ssh-a' });
++ for (const rows of [[local, ssh], [ssh, local]]) {
++ expect(buildRecentWorkspaceOptions(rows, 'mac-a', 6, aliases)[0]).toMatchObject({ title: 'app', sessionCount: 2 });
++ }
++ expect(buildRecentWorkspaceOptions([ssh], 'mac-a', 6, aliases)[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 --cc apps/mobile/src/device-link/DeviceLinkContext.tsx
index 92b2d4aa3d,ae6ec13172..5bc015ec99
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@@ -1785,8 -1736,9 +1790,9 @@@ export function routeFrame(env: Envelop
for (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.
+ if (push.channel === PROJECT_ALIASES_CHANGED_CHANNEL) {
+ handlers.onProjectAliasesChanged?.(env.src, push.ownerStamp);
+ for (const listener of remoteProjectAliasesChangedListeners) listener(env.src);
return;
}
if (push.channel === 'maker:provider:changed') {
diff --cc apps/mobile/src/session/conversationSearch.ts
index 9ebbfcd695,c8a2392249..5d7c699aa9
--- a/apps/mobile/src/session/conversationSearch.ts
+++ b/apps/mobile/src/session/conversationSearch.ts
@@@ -20,7 -21,7 +21,7 @@@ import
type ConversationSearchStatusFilter,
} from '@cindy/maker-shared/conversation-search';
import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';
- import { resolveProjectAliasForSessions, type ProjectAliasesByDevice } from '@cindy/maker-shared/project-alias-sync';
-import { remoteProjectAlias, type RemoteProjectAliasIndex } from '@cindy/maker-shared/mobile-home';
++import { resolveProjectAliasForSessions, type ProjectAliasDisplayIndex } from '@cindy/maker-shared/project-alias-sync';
import {
remoteSessionDisplayTitle,
sessionRowMessagePreview,
@@@ -83,6 -84,7 +84,7 @@@ export function conversationSearchOrigi
}
export interface SearchConversationsAcrossDevicesDeps {
- projectAliases?: RemoteProjectAliasIndex;
++ projectAliases?: ProjectAliasDisplayIndex;
invoke: ConversationSearchInvoke;
getCachedSessions: () => readonly RemoteSession[];
isDeviceUnresponsive?: (deviceId: string) => boolean;
@@@ -124,6 -126,21 +126,20 @@@ export async function searchConversatio
origins.map((origin) => searchOneDevice(origin, keywordRequest, deps)),
);
const present = pages.filter((page): page is ConversationSearchResponse => page != null);
+ // Updated hosts match aliases before limiting indexed results. Supplement the
+ // cache for older/offline hosts, retaining the same visible device/project scope.
+ if (deps.projectAliases?.size) {
+ // Cache ranks are not comparable to host ranks. Never replace an existing
+ // hit (and its message location/metadata) with an alias-only cache projection.
+ const existingKeys = new Set(present.flatMap((page) => page.results.map(conversationSearchResultKey)));
+ const aliasMatches = deps.getCachedSessions().filter((session) =>
+ !existingKeys.has(conversationSearchSessionCacheKey(session)) &&
- session.workspaceKind === 'project' && remoteProjectAlias(deps.projectAliases,
- session.canonicalDeviceId ?? session.deviceLinkDeviceId, session.workingDir)
++ session.workspaceKind === 'project' && resolveProjectAliasForSessions([session], deps.projectAliases)
+ ?.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(
@@@ -178,6 -195,7 +194,7 @@@ export function searchCachedDeviceSessi
origin: ConversationSearchDeviceOrigin,
request: ConversationSearchRequest,
sessions: readonly RemoteSession[],
- projectAliases?: RemoteProjectAliasIndex,
++ projectAliases?: ProjectAliasDisplayIndex,
): ConversationSearchResponse {
const query = request.query.trim().toLowerCase();
if (!query) return emptyConversationSearchResponse('');
@@@ -186,7 -204,9 +203,9 @@@
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);
++ ? resolveProjectAliasForSessions([session], projectAliases, origin.deviceId ?? undefined) : undefined;
++ const match = cachedConversationSearchMatch(session, query, request.unnamedLabel, alias ?? undefined);
if (!match) return;
hits.push({
session: sessionToSearchSummary(session, origin),
@@@ -455,12 -477,11 +476,12 @@@ export function scopedConversationSearc
}
export function listConversationSearchProjects(
- sessions: readonly Pick<RemoteSession, 'canonicalDeviceId' | 'deviceLinkDeviceId' | 'deviceLinkDeviceName' | 'orcaRole' | 'workingDir' | 'workspaceKind'>[],
+ sessions: readonly Pick<RemoteSession, 'canonicalDeviceId' | 'deviceLinkDeviceId' | 'deviceLinkDeviceName' | 'orcaRole' | 'workingDir' | 'workspaceKind' | 'remoteHostId'>[],
deviceIds?: ReadonlySet<string>,
- projectAliases?: ProjectAliasesByDevice,
- projectAliases?: RemoteProjectAliasIndex,
++ projectAliases?: ProjectAliasDisplayIndex,
): ConversationSearchProjectOption[] {
const byKey = new Map<string, ConversationSearchProjectOption>();
+ const groupedSessions = new Map<string, typeof sessions[number][]>();
for (const session of sessions) {
if (session.orcaRole === 'worker') continue;
if (deviceIds && !sessionBelongsToSelectedDevice(session, deviceIds)) continue;
diff --cc apps/mobile/src/session/newSession.ts
index 4d86347933,8b20e5137a..121c546b5a
--- a/apps/mobile/src/session/newSession.ts
+++ b/apps/mobile/src/session/newSession.ts
@@@ -2,6 -2,7 +2,7 @@@ import { modelNeedsReselection } from '
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 { resolveProjectAliasForSessions, type ProjectAliasDisplayIndex } from '@cindy/maker-shared/project-alias-sync';
import {
DEFAULT_DRAFT_SESSION_TITLE,
deriveOptimisticSessionTitle,
@@@ -366,8 -367,9 +367,10 @@@ export function buildRecentWorkspaceOpt
sessions: readonly RemoteSession[],
deviceId?: string,
limit = 6,
- projectAliases?: RemoteProjectAliasIndex,
++ projectAliases?: ProjectAliasDisplayIndex,
): RecentWorkspaceOption[] {
const byPath = new Map<string, RecentWorkspaceOption>();
++ const membersByPath = new Map<string, RemoteSession[]>();
for (const session of sessions) {
if (deviceId && session.deviceLinkDeviceId && session.deviceLinkDeviceId !== deviceId) continue;
if (session.status === 'deleted') continue;
@@@ -378,6 -380,6 +381,9 @@@
const workingDir = collapseWorktreeDirForGrouping(rawWorkingDir);
// Match home project grouping; keep the original path for display and remote actions.
const pathKey = normalizeProjectOrderPath(workingDir);
++ const members = membersByPath.get(pathKey) ?? [];
++ members.push(session);
++ membersByPath.set(pathKey, members);
const lastActivityAt = session.userSendAt ?? session.updatedAt ?? session.createdAt;
const current = byPath.get(pathKey);
if (!current) {
@@@ -395,6 -397,6 +401,10 @@@
}
}
++ for (const [key, workspace] of byPath) {
++ workspace.title = resolveProjectAliasForSessions(membersByPath.get(key) ?? [], projectAliases, deviceId)
++ ?? workspace.title;
++ }
return [...byPath.values()]
.sort((a, b) => b.lastActivityAt.localeCompare(a.lastActivityAt) || a.workingDir.localeCompare(b.workingDir))
.slice(0, Math.max(0, limit));
diff --cc apps/mobile/src/session/useConversationSearch.ts
index 2580df4e51,f0f659d179..020560f8e8
--- a/apps/mobile/src/session/useConversationSearch.ts
+++ b/apps/mobile/src/session/useConversationSearch.ts
@@@ -20,6 -20,7 +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 { ProjectAliasDisplayIndex } from '@cindy/maker-shared/project-alias-sync';
import type {
ConversationSearchAgentFilter,
ConversationSearchLastActivityFilter,
@@@ -43,6 -45,7 +45,7 @@@ export function useConversationSearch(
retainedState?: HomeViewSession;
lockedWorkingDirs?: string[] | null;
projects?: readonly ConversationSearchProjectOption[];
- projectAliases?: RemoteProjectAliasIndex;
++ projectAliases?: ProjectAliasDisplayIndex;
}): {
query: string;
setQuery: (value: string) => void;
diff --cc docs/dev-rules/protocol-compatibility.md
index 7e9f54dcfa,6d88c7ca5f..8667b826bf
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@@ -1,5 -1,26 +1,31 @@@
# 跨端协议兼容
+ ## 手机读取项目别名(#6916)
+
+ 同账号 device-link 只读白名单增加 `local-db:project-aliases:list`,返回宿主现有的
-`{ projectKey, alias, updatedAt }[]`。`local-db:project-aliases:changed` 作为无数据的失效通知
++`{ projectKey, alias, updatedAt }[]`;远程响应只包含宿主 `local:` / `remote:` 项,
++控制端 `device:` 覆盖名保留在本机。本机 Renderer 的列表结构和范围不变。
++`local-db:project-aliases:changed` 作为无数据的失效通知
+ 加入 `sessions` topic;写入完成后带捕获的账号代次转发,手机收到后重读宿主。
+ 不开放远程 `set/delete`,不改变路径、项目分组键或任务归属,不涉及服务端及数据库迁移。
+
+ 手机只采用响应中 `local:` 项,并用来源 deviceId 和规范化路径隔离;不把宿主的 SSH/
-另一台电脑的查看端别名套到本机项目。首页、项目筛选、别名搜索及最近工作区共用该投影。
++另一台电脑的查看端别名套到本机项目。该平面投影继续兼容既有最近工作区入口;
++首页、详情和项目筛选采用文末的主机平台/账号快照,同时保留此处的别名搜索能力。
++共享展示函数兼容两种只读投影;完整项目成员含不同本地/SSH 身份时保持目录名,
++不能因搜索、状态或置顶筛选借用剩余一条的别名。
+ 订阅完成、前台恢复、链路重连及设备恢复可达时重读;旧账号/旧连接的迟到回复丢弃。
+ 恢复只影响单台设备的元数据读请求,不重置共享连接、不重放写操作;瞬时失败保留本次
+ 挂载内的快照并最多重试两次。清除别名回到目录名。
+
+ 远程任务搜索在宿主的完整可见候选集合中匹配本机项目别名,再排序和截断结果,避免
+ 手机首页 200 条缓存漏掉旧任务。沿用既有搜索请求与响应,项目/状态等筛选不变;
+ 别名命中不生成任务标题高亮,不将本机别名套到 SSH 项目。旧宿主/离线仍可补充缓存命中,
+ 但完整别名搜索需要宿主升级;不要求手机加载全量任务。
+
+ 新手机连接旧宿主遇到通道不支持时显示目录名;旧手机忽略新增通知,仍可读取既有结构的搜索结果。
+ 完整同步需要两端都有此改动。没有 Mobile 原生依赖/配置变更。
+
## Device Link 局域网优先直连
可靠链路的 `link-open/link-accept` 增加可选能力 `direct-link-v1`。双方均支持且已完成
diff --cc packages/device-link/src/__tests__/allowlist.test.ts
index 29a67c72ae,75e30e4faf..cee8123f10
--- a/packages/device-link/src/__tests__/allowlist.test.ts
+++ b/packages/device-link/src/__tests__/allowlist.test.ts
@@@ -215,14 -220,6 +220,14 @@@ describe('REMOTE_INVOKE_ALLOWLIST', ()
expect(REMOTE_INVOKE_ALLOWLIST.has('sidebar-settings:set-project-order')).toBe(false);
});
+ it('exposes host project aliases as a read-only snapshot and forwards invalidations', () => {
+ expect(REMOTE_INVOKE_ALLOWLIST.has('sidebar-settings:get-project-aliases')).toBe(true);
- expect(REMOTE_INVOKE_ALLOWLIST.has('local-db:project-aliases:list')).toBe(false);
++ 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(PUSH_FORWARD_ALLOWLIST.has('local-db:project-aliases:changed')).toBe(true);
+ });
+
it('放行 Git safety 只读查询(远程 Codex Rewind 按被控端 snapshot 设置 gate)', () => {
expect(REMOTE_INVOKE_ALLOWLIST.has('maker:git-safety:get')).toBe(true);
expect(REMOTE_INVOKE_ALLOWLIST.has('maker:git-safety:set')).toBe(false);
diff --cc packages/device-link/src/__tests__/topics.test.ts
index e001979354,a8ef7c9ddd..ebecd9874b
--- a/packages/device-link/src/__tests__/topics.test.ts
+++ b/packages/device-link/src/__tests__/topics.test.ts
@@@ -51,9 -51,9 +51,10 @@@ describe('topicForPush', () =>
});
it('账号 / 全局级 channel → sessions(随列表订阅走)', () => {
+ expect(topicForPush('local-db:project-aliases:changed', {})).toBe('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 --cc packages/maker-shared/src/__tests__/projectAliasPresentation.test.ts
index db271161f7,0000000000..2351200658
mode 100644,000000..100644
--- a/packages/maker-shared/src/__tests__/projectAliasPresentation.test.ts
+++ b/packages/maker-shared/src/__tests__/projectAliasPresentation.test.ts
@@@ -1,128 -1,0 +1,142 @@@
+import { describe, expect, it } from 'vitest';
+// Regression: mobile home/detail built directory titles even when the host had a project alias.
+// Production entries: buildMobileHomePresentation/buildRemoteSessionSections. Existing list tests
+// cover grouping but not alias updates. Minimal failure: rename one /repo/Slack对话 snapshot;
+// both titles must change while task titles, source paths and group keys stay unchanged (unit).
+import { buildMobileHomePresentation, type MobileHomeSessionLike } from '../mobileHome.js';
+import { buildRemoteSessionSections } from '../sessionList.js';
+import { createProjectAliasMirror, type HostProjectAliasesSnapshot } from '../projectAliasSync.js';
+
+function session(id: string, patch: Partial<MobileHomeSessionLike> = {}): MobileHomeSessionLike {
+ return {
+ id,
+ title: `Task ${id}`,
+ workingDir: '/repo/Slack对话',
+ workspaceKind: 'project',
+ deviceLinkDeviceId: 'computer-a',
+ model: 'model',
+ agentKind: 'cc',
+ status: 'active',
+ createdAt: '2026-10-23T00:00:00.000Z',
+ updatedAt: '2026-10-23T00:00:00.000Z',
+ ...patch,
+ };
+}
+
+function snapshot(alias: string | null, projectKey = 'local:/repo/Slack对话'): HostProjectAliasesSnapshot {
+ return { platform: 'darwin', aliases: alias === null ? [] : [{ projectKey, alias }] };
+}
+
+describe('project aliases in controller presentations', () => {
+ it('renames and clears project titles on home and detail without changing task titles, paths, or group keys', async () => {
+ const mirror = createProjectAliasMirror();
+ const sessions = [session('one'), session('two')];
+ let host = snapshot(null);
+ const read = async () => host;
+ await mirror.refresh('computer-a', read);
+ const home = () => buildMobileHomePresentation({ sessions, projectAliases: mirror.getSnapshot() });
+ const detail = () => buildRemoteSessionSections(sessions, 0, { projectAliases: mirror.getSnapshot() });
+ const originalKey = home().projects[0].key;
+ expect(home().projects[0].title).toBe('Slack对话');
+ expect(detail()[0].title).toBe('Slack对话');
+
+ host = snapshot('Slack同步测试');
+ await mirror.invalidate('computer-a', read);
+ expect(home().projects[0]).toMatchObject({ key: originalKey, title: 'Slack同步测试', workingDir: '/repo/Slack对话' });
+ expect(detail()[0].title).toBe('Slack同步测试');
+ expect(sessions.map((row) => row.title)).toEqual(['Task one', 'Task two']);
+
+ host = snapshot(null);
+ await mirror.invalidate('computer-a', read);
+ expect(home().projects[0]).toMatchObject({ key: originalKey, title: 'Slack对话' });
+ expect(detail()[0].title).toBe('Slack对话');
+ });
+
+ it('keeps different computers with the same path independent', () => {
+ const projectAliases = new Map([
+ ['computer-a', snapshot('First')],
+ ['computer-b', snapshot('Second')],
+ ]);
+ const home = buildMobileHomePresentation({
+ sessions: [session('one'), session('two', { deviceLinkDeviceId: 'computer-b' })],
+ projectAliases,
+ });
+ expect(new Map(home.projects.map((group) => [group.deviceId, group.title])))
+ .toEqual(new Map([['computer-a', 'First'], ['computer-b', 'Second']]));
+ });
+
+ it('applies a host base-project alias to its worktree and supports detail rows without source metadata', () => {
+ const projectAliases = new Map([['computer-a', snapshot('Project')]]);
+ const row = session('worktree', { workingDir: '/repo/Slack对话/.cindy-worktrees/example' });
+ expect(buildMobileHomePresentation({ sessions: [row], projectAliases }).projects[0].title).toBe('Project');
+ expect(buildRemoteSessionSections([{ ...row, deviceLinkDeviceId: undefined }], 0, {
+ projectAliases, projectAliasDeviceId: 'computer-a',
+ })[0].title).toBe('Project');
+ });
+
++ it('accepts the existing local-name projection without borrowing it for SSH members', () => {
++ const projectAliases = new Map([['device:computer-a:/repo/Slack对话', 'Local']]);
++ const local = session('one');
++ const ssh = session('two', { remoteHostId: 'ssh-a' });
++ expect(buildMobileHomePresentation({ sessions: [local], projectAliases }).projects[0].title).toBe('Local');
++ expect(buildRemoteSessionSections([local], 0, { projectAliases })[0].title).toBe('Local');
++ for (const sessions of [[local, ssh], [ssh, local]]) {
++ expect(buildMobileHomePresentation({ sessions, projectAliases, searchQuery: 'Task one' }).projects[0].title)
++ .toBe('Slack对话');
++ expect(buildRemoteSessionSections(sessions, 0, { projectAliases })[0].title).toBe('Slack对话');
++ }
++ expect(buildMobileHomePresentation({ sessions: [ssh], projectAliases }).projects[0].title).toBe('Slack对话');
++ });
++
+ it('keeps a single-identity alias when a deleted foreign member remains in the source', () => {
+ const projectAliases = new Map([['computer-a', snapshot('Local')]]);
+ const sessions = [session('one'), session('gone', { remoteHostId: 'ssh-a', status: 'deleted' })];
+ expect(buildMobileHomePresentation({ sessions, projectAliases, searchQuery: 'Task one' }).projects[0].title)
+ .toBe('Local');
+ expect(buildRemoteSessionSections(sessions, 0, { projectAliases, searchQuery: 'Task one' })[0].title)
+ .toBe('Local');
+ });
+
+ // A project's identity comes from every member, before search/status/pinning hide rows.
+ it.each(['search', 'status', 'pinned', 'worktree'] as const)(
+ 'keeps a mixed local/SSH project title stable when %s hides its other member',
+ (filter) => {
+ const projectAliases = new Map([['computer-a', {
+ platform: 'darwin', aliases: [
+ { projectKey: 'local:/repo/Slack对话', alias: 'Local' },
+ { projectKey: 'remote:ssh-a:/repo/Slack对话', alias: 'Remote' },
+ ],
+ }]]);
+ const sessions = [session('one'), session('two', {
+ remoteHostId: 'ssh-a',
+ ...(filter === 'status' ? { status: 'archived' } : {}),
+ ...(filter === 'pinned' ? { pinnedAt: '2026-10-23T00:00:00.000Z' } : {}),
+ ...(filter === 'worktree' ? { workingDir: '/repo/Slack对话/.cindy-worktrees/example' } : {}),
+ })];
+ const options = filter === 'status' ? { statusFilter: 'active' as const }
+ : filter === 'pinned' ? {} : { searchQuery: 'Task one' };
+ const home = buildMobileHomePresentation({ sessions, projectAliases, ...options });
+ const detail = buildRemoteSessionSections(sessions, 0, { projectAliases, ...options })
+ .find(section => section.key.startsWith('project:'))!;
+ expect(home.projects[0].title).toBe('Slack对话');
+ expect(detail.title).toBe('Slack对话');
+ expect(home.projects[0].sessions.map(item => item.session.id)).toEqual(['one']);
+ expect(detail.data.map(item => item.session.id)).toEqual(['one']);
+ },
+ );
+
+ it.each([false, true])('never assigns a local name to an existing mixed local/SSH group (reversed=%s)', (reverse) => {
+ const projectAliases = new Map([['computer-a', {
+ platform: 'darwin', aliases: [
+ { projectKey: 'local:/repo/Slack对话', alias: 'Local' },
+ { projectKey: 'remote:ssh-a:/repo/Slack对话', alias: 'Remote' },
+ ],
+ }]]);
+ const sessions = [session('one'), session('two', { remoteHostId: 'ssh-a' })];
+ if (reverse) sessions.reverse();
+ expect(buildMobileHomePresentation({ sessions, projectAliases }).projects[0].title).toBe('Slack对话');
+ expect(buildRemoteSessionSections(sessions, 0, { projectAliases })[0].title).toBe('Slack对话');
+ expect(buildMobileHomePresentation({ sessions: [session('ssh', { remoteHostId: 'ssh-a' })], projectAliases }).projects[0].title)
+ .toBe('Remote');
+ });
+});
diff --cc packages/maker-shared/src/mobileHome.ts
index 35104d52ec,8a2c43de34..15d5c943e4
--- a/packages/maker-shared/src/mobileHome.ts
+++ b/packages/maker-shared/src/mobileHome.ts
@@@ -15,7 -15,10 +15,10 @@@ import { stripTrailingPathSeparators }
import { normalizeProjectOrderPath } from './projectOrderSync.js';
import { collapseWorktreeDirForGrouping } from './worktreePaths.js';
import { CINDY_MAKE_ENABLED, isCindyMakeSource } from './cindyMakeFeature.js';
- import { resolveProjectAliasForSessions, type ProjectAliasesByDevice } from './projectAliasSync.js';
-import { remoteProjectAlias, type RemoteProjectAliasIndex } from './projectAliases.js';
++import { resolveProjectAliasForSessions, type ProjectAliasDisplayIndex } from './projectAliasSync.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';
@@@ -119,7 -122,7 +122,7 @@@ export interface MobileHomePresentatio
}
export interface MobileHomeOptions {
- projectAliases?: ProjectAliasesByDevice;
- projectAliases?: RemoteProjectAliasIndex;
++ projectAliases?: ProjectAliasDisplayIndex;
devices?: readonly MobileHomeDeviceLike[];
messagePreviewIndex?: ReadonlyMap<string, string>;
liveActivityIndex?: ReadonlyMap<string, RemoteSessionLiveActivity>;
@@@ -339,21 -342,8 +343,21 @@@ function pickPrimaryDevice
function buildProjectGroups(
items: readonly RemoteSessionListItem[],
devices: readonly MobileHomeDeviceLike[],
- projectAliases?: RemoteProjectAliasIndex,
+ allSessions: readonly MobileHomeSessionLike[],
- projectAliases?: ProjectAliasesByDevice,
++ projectAliases?: ProjectAliasDisplayIndex,
): MobileHomeProjectGroup[] {
+ // Hidden and pinned members still define the project's identity. Filtering only
+ // changes the displayed rows, never which host/local-or-SSH name belongs to it.
+ const projectMembers = new Map<string, MobileHomeSessionLike[]>();
+ if (projectAliases) {
+ for (const session of allSessions) {
+ if (session.status === 'deleted' || isDialogueSession(session)) continue;
+ const key = projectGroupKey(session);
+ const members = projectMembers.get(key) ?? [];
+ members.push(session);
+ projectMembers.set(key, members);
+ }
+ }
const deviceNames = new Map(devices.map((device) => [device.deviceId, device.name]));
const grouped = new Map<string, RemoteSessionListItem[]>();
for (const item of items) {
@@@ -557,10 -544,12 +561,12 @@@ function matchesSearchQuery
pendingInteractionIndex: ReadonlyMap<string, number> | undefined,
scheduleIndex: ReadonlyMap<string, RemoteSessionScheduleInfo> | undefined,
unnamedLabel: string | undefined,
- projectAliases?: RemoteProjectAliasIndex,
++ projectAliases?: ProjectAliasDisplayIndex,
): boolean {
if (!query) return true;
const scheduleInfo = scheduleIndex?.get(session.id) ?? fallbackScheduleInfo(session);
const haystack = [
- remoteProjectAlias(projectAliases, sessionDeviceKey(session), session.workingDir),
++ resolveProjectAliasForSessions([session], projectAliases),
// 与首页行展示同源到函数级(同 sessionList 的 matchesSearchQuery):行上显示的就是
// remoteSessionDisplayTitle 的结果,haystack 直接调同一个函数。放原始哨兵会让
// 「搜得到的」与「看得到的」错位 —— 两个方向都错(见 sessionList 那条注释)。
diff --cc packages/maker-shared/src/projectAliasSync.ts
index f3b7242788,0000000000..68ba2b3fc2
mode 100644,000000..100644
--- a/packages/maker-shared/src/projectAliasSync.ts
+++ b/packages/maker-shared/src/projectAliasSync.ts
@@@ -1,248 -1,0 +1,261 @@@
+import { collapseWorktreeDirForGrouping } from './worktreePaths.js';
+import {
++ normalizeProjectOrderPath,
+ parseSyncedProjectOrderOwnerStamp,
+ type SyncedProjectOrderOwnerStamp,
+} from './projectOrderSync.js';
+
+export const PROJECT_ALIASES_GET_CHANNEL = 'sidebar-settings:get-project-aliases';
+export const PROJECT_ALIASES_CHANGED_CHANNEL = 'local-db:project-aliases:changed';
+
+export interface HostProjectAliasesSnapshot {
+ /** Host identities only: a controller's device: overrides stay on that controller. */
+ aliases: readonly { projectKey: string; alias: string }[];
+ platform: string;
+ ownerStamp?: SyncedProjectOrderOwnerStamp;
+}
+
+export type ProjectAliasesByDevice = ReadonlyMap<string, HostProjectAliasesSnapshot>;
++/** Supports the host snapshots and main's already-shipped local-name projection. */
++export type ProjectAliasDisplayIndex = ProjectAliasesByDevice | ReadonlyMap<string, string>;
+
+export interface ProjectAliasSessionLike {
+ workingDir: string | null;
+ remoteHostId?: string | null;
+ /** Physical source, never canonicalDeviceId (which is only a display identity). */
+ deviceLinkDeviceId?: string | null;
+}
+
+function normalizeAliasPath(raw: string): string | null {
+ if (!raw.trim()) return null;
+ let value = raw;
+ if (value.startsWith('\\\\?\\UNC\\')) value = `\\\\${value.slice(8)}`;
+ else if (value.startsWith('\\\\?\\')) value = value.slice(4);
+ if (/^[A-Za-z]:[\\/]/.test(value) || value.startsWith('\\\\') || value.startsWith('//')) {
+ value = value.replaceAll('\\', '/');
+ }
+ while (value.length > 1 && value.endsWith('/') && !/^[A-Za-z]:\/$/.test(value)) {
+ value = value.slice(0, -1);
+ }
+ return collapseWorktreeDirForGrouping(value);
+}
+
+/** Comparison only; never use this value as an IO path or a controller grouping key. */
+export function projectAliasComparisonKey(raw: string, platform: string): string | null {
+ if (raw.startsWith('local:')) {
+ const path = normalizeAliasPath(raw.slice(6));
+ if (path === null) return null;
+ const windows = /^[A-Za-z]:\//.test(path) || path.startsWith('//');
+ return `local:${platform === 'win32' && windows ? path.toLowerCase() : path}`;
+ }
+ if (!raw.startsWith('remote:')) return null;
+ const separator = raw.indexOf(':', 7);
+ if (separator < 0) return null;
+ try {
+ const host = decodeURIComponent(raw.slice(7, separator));
+ const path = normalizeAliasPath(raw.slice(separator + 1));
+ return host && path !== null ? `remote:${encodeURIComponent(host)}:${path}` : null;
+ } catch {
+ return null;
+ }
+}
+
+export function parseHostProjectAliasesSnapshot(raw: unknown): HostProjectAliasesSnapshot | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const value = raw as Record<string, unknown>;
+ if (!Array.isArray(value.aliases) || typeof value.platform !== 'string') return null;
+ const ownerStamp = parseSyncedProjectOrderOwnerStamp(value.ownerStamp);
+ if (Object.prototype.hasOwnProperty.call(value, 'ownerStamp') && !ownerStamp) return null;
+ const aliases: { projectKey: string; alias: string }[] = [];
+ const seen = new Set<string>();
+ for (const row of value.aliases) {
+ if (!row || typeof row !== 'object') continue;
+ const { projectKey, alias } = row as Record<string, unknown>;
+ if (typeof projectKey !== 'string' || typeof alias !== 'string') continue;
+ const comparison = projectAliasComparisonKey(projectKey, value.platform);
+ const trimmed = alias.trim();
+ if (!comparison || !trimmed || trimmed.length > 80 || seen.has(comparison)) continue;
+ // Host rows are newest-first, matching the desktop's legacy duplicate handling.
+ seen.add(comparison);
+ aliases.push({ projectKey, alias: trimmed });
+ }
+ return { aliases, platform: value.platform, ...(ownerStamp ? { ownerStamp } : {}) };
+}
+
+const aliasIndexes = new WeakMap<HostProjectAliasesSnapshot, ReadonlyMap<string, string>>();
+
+function aliasIndex(snapshot: HostProjectAliasesSnapshot): ReadonlyMap<string, string> {
+ const existing = aliasIndexes.get(snapshot);
+ if (existing) return existing;
+ const next = new Map<string, string>();
+ for (const row of snapshot.aliases) {
+ const key = projectAliasComparisonKey(row.projectKey, snapshot.platform);
+ if (key && !next.has(key)) next.set(key, row.alias);
+ }
+ aliasIndexes.set(snapshot, next);
+ return next;
+}
+
+/** Existing mixed-identity groups keep their path title, rather than borrowing one member's alias. */
+export function resolveProjectAliasForSessions(
+ sessions: readonly ProjectAliasSessionLike[],
- snapshots: ProjectAliasesByDevice | undefined,
++ snapshots: ProjectAliasDisplayIndex | undefined,
+ defaultDeviceId?: string,
+): string | null {
+ if (!snapshots || sessions.length === 0) return null;
+ let identity: string | undefined;
+ let alias: string | null = null;
+ for (const session of sessions) {
+ const deviceId = session.deviceLinkDeviceId || defaultDeviceId;
+ if (!deviceId || !session.workingDir) return null;
+ const snapshot = snapshots.get(deviceId);
- if (!snapshot) return null;
++ if (!snapshot || typeof snapshot === 'string') {
++ // The legacy projection carries only local aliases, never SSH identity.
++ if (session.remoteHostId) return null;
++ const key = `device:${encodeURIComponent(deviceId)}:${normalizeProjectOrderPath(session.workingDir)}`;
++ const value = snapshots.get(key);
++ const current = JSON.stringify([deviceId, key]);
++ if (identity !== undefined && identity !== current) return null;
++ identity = current;
++ alias = typeof value === 'string' ? value : null;
++ continue;
++ }
+ const key = projectAliasComparisonKey(
+ session.remoteHostId
+ ? `remote:${encodeURIComponent(session.remoteHostId)}:${session.workingDir}`
+ : `local:${session.workingDir}`,
+ snapshot.platform,
+ );
+ if (!key) return null;
+ const current = JSON.stringify([deviceId, key]);
+ if (identity !== undefined && identity !== current) return null;
+ identity = current;
+ alias = aliasIndex(snapshot).get(key) ?? null;
+ }
+ return alias;
+}
+
+type ReadAliases = () => Promise<unknown>;
+type IsCurrent = (snapshot?: HostProjectAliasesSnapshot) => boolean;
+interface AliasRead {
+ read: ReadAliases;
+ isCurrent: IsCurrent;
+ revision: number;
+ pending?: Promise<void>;
+}
+
+function missingChannel(error: unknown): boolean {
+ const record = error && typeof error === 'object' ? error as Record<string, unknown> : null;
+ const code = typeof record?.code === 'string' ? record.code : undefined;
+ const message = typeof error === 'string' ? error : record?.message;
+ const resolved = code ?? (typeof message === 'string' ? message.match(/\[([A-Z0-9_]+)\]/)?.[1] : undefined);
+ return resolved === 'CHANNEL_NOT_ALLOWED' || resolved === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED';
+}
+
+function snapshotsEqual(a: HostProjectAliasesSnapshot | undefined, b: HostProjectAliasesSnapshot): boolean {
+ return !!a && a.platform === b.platform
+ && a.ownerStamp?.dataOwnerId === b.ownerStamp?.dataOwnerId
+ && a.ownerStamp?.ownerGeneration === b.ownerStamp?.ownerGeneration
+ && a.aliases.length === b.aliases.length
+ && a.aliases.every((row, index) => row.projectKey === b.aliases[index].projectKey && row.alias === b.aliases[index].alias);
+}
+
+/** In-memory read model. Hosts own persistence; adapters own authorization and connection recovery. */
+export function createProjectAliasMirror() {
+ let snapshots: ProjectAliasesByDevice = new Map();
+ const reads = new Map<string, AliasRead>();
+ const listeners = new Set<() => void>();
+ const notify = () => { for (const listener of listeners) listener(); };
+ // Display metadata has its own small budget; it never holds up session-list recovery.
+ let activeReads = 0;
+ const waitingReads: (() => void)[] = [];
+ async function acquireReadSlot(): Promise<() => void> {
+ if (activeReads >= 6) await new Promise<void>((resolve) => { waitingReads.push(resolve); });
+ else activeReads += 1;
+ return () => {
+ const next = waitingReads.shift();
+ if (next) next(); // Transfer the occupied slot directly to the next waiting reader.
+ else activeReads -= 1;
+ };
+ }
+
+ function apply(deviceId: string, snapshot: HostProjectAliasesSnapshot): void {
+ if (snapshotsEqual(snapshots.get(deviceId), snapshot)) return;
+ const next = new Map(snapshots);
+ next.set(deviceId, snapshot);
+ snapshots = next;
+ notify();
+ }
+
+ function request(deviceId: string, read: ReadAliases, isCurrent: IsCurrent = () => true, invalidate = false): Promise<void> {
+ let state = reads.get(deviceId);
+ if (!state) {
+ state = { read, isCurrent, revision: 0 };
+ reads.set(deviceId, state);
+ }
+ state.read = read;
+ state.isCurrent = isCurrent;
+ if (invalidate) state.revision += 1;
+ if (state.pending) return state.pending;
+ const active = state;
+ // Defer execution until pending is assigned, including synchronous reader throws.
+ const pending = Promise.resolve().then(async () => {
+ while (reads.get(deviceId) === active) {
+ const release = await acquireReadSlot();
+ if (reads.get(deviceId) !== active || !active.isCurrent()) {
+ release();
+ return;
+ }
+ const revision = active.revision;
+ const guard = active.isCurrent;
+ const loader = active.read;
+ try {
+ const snapshot = parseHostProjectAliasesSnapshot(await loader());
+ if (reads.get(deviceId) !== active) return;
+ if (revision !== active.revision) continue;
+ if (snapshot && guard(snapshot)) apply(deviceId, snapshot);
+ } catch (error) {
+ if (reads.get(deviceId) !== active) return;
+ if (revision !== active.revision) continue;
+ // A transient failure must not erase a known name. An old host has no aliases to mirror.
+ if (missingChannel(error) && guard()) apply(deviceId, { aliases: [], platform: '' });
+ } finally {
+ release();
+ }
+ // A synchronous subscriber can invalidate while apply() publishes the snapshot.
+ if (revision !== active.revision) continue;
+ active.pending = undefined;
+ return;
+ }
+ }).finally(() => {
+ if (reads.get(deviceId) === active && active.pending === pending) active.pending = undefined;
+ });
+ active.pending = pending;
+ return pending;
+ }
+
+ return {
+ getSnapshot: (): ProjectAliasesByDevice => snapshots,
+ subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+ },
+ refresh: (deviceId: string, read: ReadAliases, isCurrent?: IsCurrent) => request(deviceId, read, isCurrent),
+ invalidate: (deviceId: string, read: ReadAliases, isCurrent?: IsCurrent) => request(deviceId, read, isCurrent, true),
+ suspend(deviceId: string): void { reads.delete(deviceId); },
+ remove(deviceId: string): void {
+ reads.delete(deviceId);
+ if (!snapshots.has(deviceId)) return;
+ const next = new Map(snapshots);
+ next.delete(deviceId);
+ snapshots = next;
+ notify();
+ },
+ clear(): void {
+ reads.clear();
+ if (snapshots.size === 0) return;
+ snapshots = new Map();
+ notify();
+ },
+ };
+}
diff --cc packages/maker-shared/src/projectAliases.ts
index 0000000000,e2891c7d03..7e1a91662a
mode 000000,100644..100644
--- a/packages/maker-shared/src/projectAliases.ts
+++ b/packages/maker-shared/src/projectAliases.ts
@@@ -1,0 -1,50 +1,50 @@@
+ import { normalizeProjectOrderPath } from './projectOrderSync.js';
++import { resolveProjectAliasForSessions, type ProjectAliasDisplayIndex } from './projectAliasSync.js';
++export { PROJECT_ALIASES_CHANGED_CHANNEL } from './projectAliasSync.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,
++ aliases: ProjectAliasDisplayIndex | undefined,
+ deviceId: string | null | undefined,
+ workingDir: string | null | undefined,
+ ): string | undefined {
+ return deviceId && workingDir
- ? aliases?.get(remoteProjectAliasKey(deviceId, workingDir))
++ ? resolveProjectAliasForSessions([{ deviceLinkDeviceId: deviceId, workingDir }], aliases) ?? undefined
+ : undefined;
+ }
diff --cc packages/maker-shared/src/sessionList.ts
index 4fc97ae76a,148992a391..387b2e2c3e
--- a/packages/maker-shared/src/sessionList.ts
+++ b/packages/maker-shared/src/sessionList.ts
@@@ -9,7 -9,6 +9,7 @@@ import { sessionCollaborationLabel, ses
import { isDefaultDraftSessionTitle } from './sessionTitle.js';
import { getSessionListCollapseView } from './sessionListCollapse.js';
import { collapseWorktreeDirForGrouping } from './worktreePaths.js';
- import { resolveProjectAliasForSessions, type ProjectAliasesByDevice } from './projectAliasSync.js';
++import { resolveProjectAliasForSessions, type ProjectAliasDisplayIndex } from './projectAliasSync.js';
let sessionListCollator: Intl.Collator | undefined;
/** Call when the host resumes after system locale/region preferences may change. */
@@@ -173,9 -170,6 +173,9 @@@ export interface RemoteSessionListConte
export type RemoteSessionStatusFilter = 'active' | 'waiting' | 'automation' | 'archived' | 'all';
export interface RemoteSessionListOptions {
- projectAliases?: ProjectAliasesByDevice;
++ projectAliases?: ProjectAliasDisplayIndex;
+ /** A single-device detail view may have rows without controller-local device metadata. */
+ projectAliasDeviceId?: string;
statusFilter?: RemoteSessionStatusFilter;
messagePreviewIndex?: ReadonlyMap<string, string>;
liveActivityIndex?: ReadonlyMap<string, RemoteSessionLiveActivity>;