Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(tasks): filter by teammate and retain ownership across devices
zqchris43d07eca1578
diff --git a/apps/desktop/scripts/fixtures/teammate-task-filter/fixture.tsx b/apps/desktop/scripts/fixtures/teammate-task-filter/fixture.tsxnew file mode 100644index 0000000000..a0fbcae7c9--- /dev/null+++ b/apps/desktop/scripts/fixtures/teammate-task-filter/fixture.tsx@@ -0,0 +1,62 @@+import { useMemo, useState } from 'react';+import { mountPage, subscription } from '../../ui-page/harness';+import { SidebarFilterPopover } from '../../../src/renderer/features/cc-agent/sidebar/SidebarFilterPopover';+import { persistCreators } from '../../../src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore';+import { useSidebarFilter } from '../../../src/renderer/features/cc-agent/hooks/useSidebarFilter';+import { BotFollowMark, useSessionFollowers } from '../../../src/renderer/features/bots/BotFollowMark';+import { matchesTaskCreators, useTaskCreatorIndex, useTaskCreatorOptions } from '../../../src/renderer/features/bots/botFollowScopes';+import { setDataOwnerGeneration } from '../../../src/renderer/contexts/dataOwnerGeneration';+import type { Session } from '../../../src/renderer/lib/ccAgent.types';++const snapshot = { dataOwnerId: 'fixture', ownerGeneration: 1, pinnedOrderIsAuthoritative: true,+ pinnedOrder: [], hiddenProjectKeys: [], hiddenMainViewGhostIds: [] };+const tasks = [+ { id: 'owner', title: 'Personal task' },+ { id: 'cindy-local', title: 'Cindy · Local task' },+ { id: 'cindy-remote', title: 'Cindy · Remote task', deviceLinkDeviceId: 'laptop' },+ { id: 'routine', title: 'Cindy · Daily routine', source: 'bot', companion: { id: 'cindy-default', role: 'routine' } },+ { id: 'channel', title: 'Cindy · Feishu conversation', source: 'bot', deviceLinkDeviceId: 'laptop', companion: { id: 'remote-cindy', role: 'channel', channel: 'feishu' } },+ { id: 'local', title: 'Dash · Local task' },+ { id: 'remote', title: 'Lizi · Remote task', status: 'archived', deviceLinkDeviceId: 'laptop' },+].map(row => ({ status: 'active', source: 'desktop', ...row }) as Session);+function TaskRow({ task }: { task: Session }) {+ return <div className="flex items-center gap-2 py-2" data-task={task.id}>+ <BotFollowMark followers={useSessionFollowers(task)} /><span>{task.title}</span>+ </div>;+}+function Fixture() {+ useState(() => { persistCreators(['["laptop","remote-cindy"]'], 'fixture'); return true; });+ const options = useTaskCreatorOptions();+ const hidden = useMemo(() => new Set<string>(), []);+ const filter = useSidebarFilter(hidden, snapshot, options);+ const index = useTaskCreatorIndex();+ const [open, setOpen] = useState(true);+ return <div className="p-4 text-14 text-foreground">+ <SidebarFilterPopover filter={filter} allKnownProjects={[]} open={open} onOpenChange={setOpen} />+ <div className="mt-64" data-testid="tasks">+ {tasks.filter(task => matchesTaskCreators(task, filter.creators, index)).map(task => <TaskRow key={task.id} task={task} />)}+ </div>+ </div>;+}+mountPage({+ host: () => {+ setDataOwnerGeneration('fixture', 1);+ return {+ authHasPersistedSessionHintSync: () => false,+ appearanceSettings: undefined,+ setApplicationMenuLocale: async () => {},+ setUpdateRelaunchTheme: async () => {},+ sidebarSettings: {+ loadSnapshot: () => snapshot,+ claimLegacyRendererOwner: () => ({ ...snapshot, claimed: true, canInitialize: true, pinnedLegacyConsumed: true }),+ onPinnedOrderChanged: subscription('pinned'),+ },+ maker: { onBotWorkbenchChanged: subscription('workbench'), onBotDelegationChanged: subscription('delegation') },+ localDb: { bots: { workbench: { followScopes: async () => [+ { botId: 'cindy-default', delegatedSessionIds: ['cindy-local'] },+ { botId: 'dash', sessionIds: ['local', 'owner'], delegatedSessionIds: ['local'] },+ ] } } },+ };+ },+ render: () => <Fixture />,+});diff --git a/apps/desktop/scripts/fixtures/teammate-task-filter/ui-page.mjs b/apps/desktop/scripts/fixtures/teammate-task-filter/ui-page.mjsnew file mode 100644index 0000000000..77fb0d59fc--- /dev/null+++ b/apps/desktop/scripts/fixtures/teammate-task-filter/ui-page.mjs@@ -0,0 +1,58 @@+import assert from 'node:assert/strict';+export default {+ name: 'teammate-task-filter', entry: './fixture.tsx', viewport: { width: 840, height: 640 },+ real: 'SidebarFilterPopover, useSidebarFilter persistence/reset, task creator matching and BotFollowMark with real themes and translations',+ notCovered: 'Live cross-device transport and host database reads; task/roster snapshots are fixture data. Pinned exemptions remain in the full sidebar.',+ stubs: {+ 'src/renderer/features/bots/botStore': `const bots = [{id:'cindy-default',name:'Cindy',avatar:'',avatarColor:'blue',enabled:true,status:'active'}, { id:'dash',name:'Dash',avatar:'',avatarColor:'blue',enabled:true,status:'active' }]; export const useBotProfiles=()=>bots; export const hasLoadedBotProfiles=()=>true; export const ensureBotProfilesLoaded=async()=>bots;`,+ 'src/renderer/features/bots/useRemoteBots': `const bots = [{id:'remote-cindy',templateId:'cindy',name:'Cindy',avatar:'',avatarColor:'blue',deviceId:'laptop',deviceName:'MacBook Pro',delegatedSessionIds:['cindy-remote']},{id:'lizi',name:'Lizi',avatar:'',avatarColor:'green',deviceId:'laptop',deviceName:'MacBook Pro',followingSessionIds:[],delegatedSessionIds:['remote']}]; export const useRemoteBots=()=>bots;`,+ 'src/renderer/features/device-link/useMachineSwitcher': `export const useEffectiveSelectedMachineId=()=> 'all';`,+ 'src/renderer/features/cc-agent/hooks/useRemoteHostProjectOrders': `export const useLocalHostProjectOrder=()=>({snapshot:undefined}); export const useRemoteHostProjectOrders=()=>({orders:new Map()}); export const projectOrderWriteScopeForSelection=()=>({kind:'viewer'}); export const controllerManualOrderForDevice=()=>[];`,+ },+ cases: { default: { about: 'Legacy choice migration → one Cindy across computers → unrestricted → single/multiple/reset; archived creator avatar' } },+ async check(page, ui) {+ const rows = page.locator('[data-task]');+ assert.equal(await rows.count(), 4);+ const filterHeading = await ui.t('ccAgent.sidebar.filterHeading');+ const creatorsHeading = await ui.t('ccAgent.sidebar.filterCreatorsHeading');+ await page.getByRole('menuitem').filter({ hasText: filterHeading }).last().press('ArrowRight');+ await page.getByRole('menuitem').filter({ hasText: creatorsHeading }).last().press('ArrowRight');+ const cindy = page.getByRole('menuitemcheckbox', { name: 'Cindy', exact: true });+ assert.equal(await cindy.count(), 1);+ assert.equal(await cindy.getAttribute('aria-checked'), 'true');+ await page.getByRole('menuitem', { name: await ui.t('ccAgent.sidebar.filterCreatorsAny'), exact: true }).click();+ await page.waitForFunction(() => document.querySelectorAll('[data-task]').length === 7);+ await page.locator('[data-task="remote"] [data-testid="bot-follow-mark"]').waitFor();+ const local = page.getByRole('menuitemcheckbox', { name: 'Dash', exact: true });+ const remote = page.getByRole('menuitemcheckbox', { name: 'Lizi MacBook Pro', exact: true });+ await local.click();+ await page.waitForFunction(() => document.querySelectorAll('[data-task]').length === 1);+ assert.equal(await page.locator('[data-task]').getAttribute('data-task'), 'local');+ await remote.click();+ await page.waitForFunction(() => document.querySelectorAll('[data-task]').length === 2);+ await local.click();+ await page.waitForFunction(() => document.querySelectorAll('[data-task]').length === 1);+ assert.equal(await page.locator('[data-task]').getAttribute('data-task'), 'remote');+ const all = page.getByRole('menuitem', { name: await ui.t('ccAgent.sidebar.filterCreatorsAny'), exact: true });+ await all.click();+ await page.waitForFunction(() => document.querySelectorAll('[data-task]').length === 7);+ await local.click();+ await local.press('ArrowLeft');+ await page.getByRole('menuitem', { name: await ui.t('ccAgent.sidebar.filterReset'), exact: true }).click();+ await page.waitForFunction(() => document.querySelectorAll('[data-task]').length === 7);+ await page.getByRole('menuitem').filter({ hasText: creatorsHeading }).last().hover();+ await page.getByRole('menuitem').filter({ hasText: creatorsHeading }).last().press('ArrowRight');+ await local.click();+ await remote.click();+ assert.equal(await local.getAttribute('aria-checked'), 'true');+ assert.equal(await remote.getAttribute('aria-checked'), 'true');+ await all.click();+ await cindy.click();+ await page.waitForFunction(() => document.querySelectorAll('[data-task]').length === 4);+ assert.deepEqual(await rows.evaluateAll(rows => rows.map(row => row.dataset.task)), ['cindy-local', 'cindy-remote', 'routine', 'channel']);+ for (const id of ['routine', 'channel']) {+ const mark = page.locator(`[data-task="${id}"] [data-testid="bot-follow-mark"]`);+ assert.equal(await mark.getAttribute('aria-label'), await ui.t('bots.workbench.ownedMark', { names: 'Cindy' }));+ }+ },+};diff --git a/apps/desktop/src/main/companion-cloud/__tests__/control.test.ts b/apps/desktop/src/main/companion-cloud/__tests__/control.test.tsindex a295578b03..1749e905bf 100644--- a/apps/desktop/src/main/companion-cloud/__tests__/control.test.ts+++ b/apps/desktop/src/main/companion-cloud/__tests__/control.test.ts@@ -770,3 +770,13 @@ describe('merging copies of Cindy', () => {expect(await t.runtime.flushHere('cindy-default')).toEqual({ ok: true });});});++// Filtering still needs Cindy's identity after all cloud copies have already been merged.+it('lists a single remaining Cindy by profile identity, without running a merge', async () => {+ const t = setup({ home: 'laptop', handler: (route, method) => {+ if (route === '/preferences' && method === 'GET') return [{ key: 'companion.profile.v1', value: { ...MIA, templateId: 'cindy' }, revision: 1 }];+ throw new Error(`unexpected ${method} ${route}`);+ } });+ expect(await t.runtime.cindyCopies()).toEqual([{ botId: 'bot_mia', name: 'Mia', homeDeviceId: 'laptop' }]);+ expect(t.calls.every(call => call.method === 'GET')).toBe(true);+});diff --git a/apps/desktop/src/main/companion-cloud/runtime.ts b/apps/desktop/src/main/companion-cloud/runtime.tsindex 9fa3661f87..cdbc1bc10b 100644--- a/apps/desktop/src/main/companion-cloud/runtime.ts+++ b/apps/desktop/src/main/companion-cloud/runtime.ts@@ -784,7 +784,7 @@ export function startCompanionCloud(input: {const profile = await profileOf(actor.id).catch(() => null);if (isCindyCompanion(actor.externalId, profile)) copies.push({ botId: actor.externalId, name: actor.name, homeDeviceId: actor.homeDeviceId ?? null });}- return copies.length > 1 ? copies : [];+ return copies;},async mergeCindy(keepBotId, fromBotIds) {diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.tsindex ffa9d9a738..56331c8e66 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheStore.test.ts@@ -282,6 +282,7 @@ describe('coerceCachedSession', () => {attached: true,_count: { messages: 99 },extraDirs: ['/a', '/b'],+ companion: { id: 'owner', role: 'channel', channel: 'feishu', secret: 'omit' },});expect(coerced).not.toBeNull();expect(coerced).not.toHaveProperty('deviceLinkConnectionStatus');@@ -290,6 +291,7 @@ describe('coerceCachedSession', () => {expect(coerced).not.toHaveProperty('_count');expect(coerced).not.toHaveProperty('extraDirs');expect(coerced?.title).toBe('T');+ expect(coerced?.companion).toEqual({ id: 'owner', role: 'channel', channel: 'feishu' });});it('长文本截断到上限', () => {diff --git a/apps/desktop/src/main/device-link/mirrorCacheStore.ts b/apps/desktop/src/main/device-link/mirrorCacheStore.tsindex 43d8ee7028..cde9a37ef1 100644--- a/apps/desktop/src/main/device-link/mirrorCacheStore.ts+++ b/apps/desktop/src/main/device-link/mirrorCacheStore.ts@@ -275,6 +275,11 @@ export function coerceCachedSession(input: unknown): Record<string, unknown> | nout[key] =typeof value === 'string' && TRUNCATED_TEXT_FIELDS.has(key) ? truncateText(value) : value;}+ const companion = input.companion;+ if (isRecord(companion) && typeof companion.id === 'string' && typeof companion.role === 'string') {+ out.companion = { id: companion.id, role: companion.role,+ ...(typeof companion.channel === 'string' ? { channel: companion.channel } : {}) };+ }return out;}diff --git a/apps/desktop/src/main/localDb/__tests__/sessionListPagination.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionListPagination.test.tsindex e8a01a0fe2..b17783516b 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionListPagination.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionListPagination.test.ts@@ -2,15 +2,15 @@ import Database from 'better-sqlite3';import { drizzle } from 'drizzle-orm/better-sqlite3';import { eq, getTableColumns, getTableName } from 'drizzle-orm';import { expect, it } from 'vitest';-import { sessions, messages, taskTags, sessionTaskTags } from '../schema';-import { selectSessionListRows } from '../sessionQueries';+import { sessions, messages, taskTags, sessionTaskTags, botSessionLinks, botProfiles } from '../schema';+import { selectSessionListRows, ordinaryTaskListFilter, flattenSessionReadRow } from '../sessionQueries';import type { DbClient } from '../client/DbClient';it('pages the actual list query across tied timestamps without skipping or repeating rows', async () => {const sqlite = new Database(':memory:');try {// Derive columns from production schema; no account DB or migrations are touched.- for (const table of [sessions, messages, taskTags, sessionTaskTags]) {+ for (const table of [sessions, messages, taskTags, sessionTaskTags, botSessionLinks]) {sqlite.exec(`CREATE TABLE "${getTableName(table)}" (${Object.values(getTableColumns(table)).map((column) => `"${column.name}" ${column.getSQLType()}`)@@ -49,3 +49,33 @@ it('pages the actual list query across tied timestamps without skipping or repeasqlite.close();}});++// Unit: actual list SQL and attribution projection, including previously hidden existing lanes.+it('lists linked teammate routine/channel tasks, keeping private lanes and hidden owners out', async () => {+ const sqlite = new Database(':memory:');+ try {+ for (const table of [sessions, messages, taskTags, sessionTaskTags, botSessionLinks, botProfiles]) {+ sqlite.exec(`CREATE TABLE "${getTableName(table)}" (${Object.values(getTableColumns(table))+ .map(column => `"${column.name}" ${column.getSQLType()}`).join(',')})`);+ }+ sqlite.exec("INSERT INTO bot_profiles(id,status) VALUES ('owner','active'),('removed','deleting');");+ const insert = sqlite.prepare("INSERT INTO sessions(id,source,status,updated_at,list_preview,list_message_count) VALUES (?, ?, ?,1,'',0)");+ const link = sqlite.prepare('INSERT INTO bot_session_links(bot_id,session_id,role,route_key) VALUES (?,?,?,?)');+ for (const role of ['routine', 'channel', 'canonical', 'group', 'thread']) {+ insert.run(role, 'bot', role === 'routine' ? 'archived' : 'active');+ link.run('owner', role, role, role === 'channel' ? 'im:feishu:chat' : null);+ }+ for (const id of ['unlinked', 'removed', 'hidden']) insert.run(id, 'bot', 'active');+ link.run('removed', 'removed', 'routine', null);+ link.run('owner', 'hidden', 'channel', null);+ sqlite.exec("UPDATE sessions SET hidden_at=1 WHERE id='hidden'");+ insert.run('ordinary', 'desktop', 'active');+ const db = drizzle(sqlite) as unknown as DbClient['drizzle'];+ const rows = await selectSessionListRows(db, ordinaryTaskListFilter(), 100);+ expect(rows.map(row => row.session.id).sort()).toEqual(['channel', 'ordinary', 'routine']);+ expect(flattenSessionReadRow(rows.find(row => row.session.id === 'channel')!).companion)+ .toEqual({ id: 'owner', role: 'channel', channel: 'feishu' });+ expect(flattenSessionReadRow(rows.find(row => row.session.id === 'routine')!).companion)+ .toEqual({ id: 'owner', role: 'routine' });+ } finally { sqlite.close(); }+});diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex f04f27a6ad..a88bc6393d 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -1,3 +1,4 @@+import { emitSessionCreated } from '../sessionCreatedBroadcast.js';import { captureAgentRequest } from '../../../maker-ipc/forwardedRequest';import { admitTaskAction, assertTaskActionCurrent, TaskActionAuthorizationError } from '../../../maker-ipc/taskActionAuthorization';import { formatForwardedRequest } from '../../../../shared/forwardedRequest';@@ -56,6 +57,7 @@ import {} from '../../schema';// Host preference storage is outside this database/runtime integration test.+vi.mock('../sessionCreatedBroadcast.js', () => ({ emitSessionCreated: vi.fn(), emitSessionListChangedLocally: vi.fn() }));vi.mock('electron-store', () => ({ default: class {private values = new Map<string, unknown>();get(key: string, fallback?: unknown) { return this.values.get(key) ?? fallback; }@@ -2043,18 +2045,20 @@ describe('Bot canonical Session lifecycle', () => {);});- it('creates one hidden IM channel lane per route key, projects it as `channel` and keeps it out of history search', async () => {+ it('creates one IM channel lane per route key, notifies the task list and keeps it out of private history search', async () => {const created = await invoke('local-db:bots:create-canonical-session', {botId: 'bot-1',expectedCanonicalSessionId: null,expectedProfileVersion: 1,});+ vi.mocked(emitSessionCreated).mockClear();const routeKey = 'im:telegram:777:g:-100123';const first = await ensureBotChannelLaneSession({ botId: 'bot-1', routeKey, title: '[TG·群] 100123' });expect(first).toMatchObject({ ok: true, created: true });if (!first.ok) throw new Error(first.message);await expect(ensureBotChannelLaneSession({ botId: 'bot-1', routeKey, title: 'ignored' })).resolves.toEqual({ ok: true, sessionId: first.sessionId, created: false });+ expect(emitSessionCreated).toHaveBeenCalledExactlyOnceWith(first.sessionId);await expect(findBotChannelLaneSession('bot-1', routeKey)).resolves.toBe(first.sessionId);const canonical = h.sqlite!.prepare('SELECT working_dir AS workingDir, model, permission_mode AS permissionMode FROM sessions WHERE id = ?',diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsHiddenTasks.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsHiddenTasks.test.tsindex 5b474ca8de..eec06ce3e7 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsHiddenTasks.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsHiddenTasks.test.ts@@ -20,6 +20,7 @@ const h = vi.hoisted(() => ({}));vi.mock('electron', () => ({+ app: { once: vi.fn() },ipcMain: {handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => {h.handlers.set(channel, handler);@@ -60,6 +61,8 @@ function createDb(): void {h.sqlite?.close();const sqlite = new Database(':memory:');sqlite.exec(`+ CREATE TABLE bot_session_links(session_id TEXT, bot_id TEXT, role TEXT, route_key TEXT);+ CREATE TABLE bot_profiles(id TEXT, status TEXT, hidden_at INTEGER);CREATE TABLE task_tags(id TEXT PRIMARY KEY,name TEXT,color TEXT,favorite_order INTEGER,sort_order INTEGER,revision INTEGER,name_customized INTEGER NOT NULL DEFAULT 0);CREATE TABLE session_task_tags(session_id TEXT,tag_id TEXT);CREATE TABLE sessions (diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.tsindex f430d34f49..917ef3c212 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsRestoreIfArchived.test.ts@@ -29,6 +29,7 @@ const h = vi.hoisted(() => ({}));vi.mock('electron', () => ({+ app: { once: vi.fn() },ipcMain: {handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => {h.handlers.set(channel, handler);@@ -85,6 +86,8 @@ function createDb(): void {h.sqlite?.close();const sqlite = new Database(':memory:');sqlite.exec(`+ CREATE TABLE bot_session_links(session_id TEXT, bot_id TEXT, role TEXT, route_key TEXT);+ CREATE TABLE bot_profiles(id TEXT, status TEXT, hidden_at INTEGER);CREATE TABLE task_tags(id TEXT PRIMARY KEY,name TEXT,color TEXT,favorite_order INTEGER,sort_order INTEGER,revision INTEGER,name_customized INTEGER NOT NULL DEFAULT 0);CREATE TABLE session_task_tags(session_id TEXT,tag_id TEXT);CREATE TABLE sessions (diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 5ad8cea17c..4832e44887 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -218,6 +218,8 @@ function createDb(): void {const sqlite = new Database(':memory:');// 与 schema.ts 的 sessions/messages 全列对齐(selectSessionWithCount select 全列)。sqlite.exec(`+ CREATE TABLE bot_session_links(session_id TEXT, bot_id TEXT, role TEXT, route_key TEXT);+ CREATE TABLE bot_profiles(id TEXT, status TEXT, hidden_at INTEGER);CREATE TABLE task_tags (id TEXT PRIMARY KEY NOT NULL,name TEXT NOT NULL,diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex bc7a48d807..74f0a4c332 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -1,3 +1,4 @@+import { emitSessionCreated } from './sessionCreatedBroadcast.js';import type { RoutineModel } from '@cindy/maker-scheduler';import { todoAccess } from '../../maker-ipc/botTodoAccess.js';import { botLinkedProjectAccess } from '../../maker-ipc/botLinkedProjects.js';@@ -580,6 +581,7 @@ async function ensureBotOwnedLaneSession(input: { botId: string; routeKey: strinawait syncBotLinkedLanePermissions(result.permissionRepairCanonicalSessionId);owner.assertCurrent();}+ if (result.created) emitSessionCreated(result.sessionId);return { ok: true, sessionId: result.sessionId, created: result.created };}@@ -2801,7 +2803,7 @@ export function registerBotIpc(): void {const bots = await getDbClient().drizzle.select({ id: botProfiles.id }).from(botProfiles)- .where(eq(botProfiles.status, 'active'));+ .where(ne(botProfiles.status, 'deleting'));// Older renderers receive empty directories rather than claiming projects.const scopes = await collectTaskResponsibilityScopes(bots.map((bot) => bot.id),diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 1962819ca7..0bb3d033a8 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -46,6 +46,7 @@ import { sessions, messages } from '../schema';import { clearSessionAttention } from '../../appBadgeService';import {selectSessionListRows,+ ordinaryTaskListFilter,selectSessionWithCount,selectSessionsByIds,flattenSessionReadRow,@@ -84,7 +85,6 @@ import { imAttachmentsRoot, removeImSessionAttachmentDirs } from '../../im/shareimport { upsertRecentWorkdir } from './recentWorkdirs';import { createLogger } from '../../logger';import {- DESKTOP_TASK_LIST_SESSION_SOURCES,DESKTOP_VISIBLE_SESSION_SOURCES,isRetainableProjectSession,} from '../../../shared/sessionSource.js';@@ -1611,10 +1611,7 @@ export function registerSessionIpc(// 只从来源任务的审查卡片打开,不进普通任务列表(用量历史仍包含)。// 插件后台隐藏任务(hidden_at 非空)同样不进任务列表,只在插件详情页「后台任务」// 查看与接手;手机/远控经 device-link 调同一 handler,口径一致。- const sourceFilter = and(- inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES),- isNull(sessions.hiddenAt),- );+ const sourceFilter = ordinaryTaskListFilter();const statusWhere = () =>statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere(), ids ? inArray(sessions.id, ids) : undefined), cap, before);diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex 10ddf0c54c..bc29d7ad7f 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -128,6 +128,7 @@ export function projectSessionRuntimeFields(session: SessionRuntimeFields): Part* preview 落 null,渲染端兜底隐藏。*/export type SessionRowWithCount = SessionRow & {+ companion?: Session['companion'];tags?: import('@cindy/maker-shared').TaskTag[];messageCount: number;latestMessageContent?: string | null;@@ -245,6 +246,7 @@ export function sessionToCamel(row: SessionRowWithCount): Session {row.totalCostUsd + (row.totalCostCurrency === 'USD' ? row.totalCostAmount : 0);const base: Session = {id: row.id,+ ...(row.companion ? { companion: row.companion } : {}),...(row.tags ? { tags: row.tags } : {}),userId: '', // 本地 db 已按 user 隔离,无需冗余存储title: row.title,diff --git a/apps/desktop/src/main/localDb/sessionQueries.ts b/apps/desktop/src/main/localDb/sessionQueries.tsindex fc4f831288..91091a86b8 100644--- a/apps/desktop/src/main/localDb/sessionQueries.ts+++ b/apps/desktop/src/main/localDb/sessionQueries.ts@@ -1,8 +1,10 @@+import { historyCompanionJson, parseHistoryCompanion } from './historyCompanion';import { normalizeTaskTags } from '@cindy/maker-shared';/** Shared database reads for local IPC, remote IPC and internal callers. */-import { and, desc, eq, inArray, sql, type SQL } from 'drizzle-orm';+import { and, desc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm';import type { DbClient } from './client/DbClient';import { sessions } from './schema';+import { DESKTOP_TASK_LIST_SESSION_SOURCES } from '../../shared/sessionSource';import { LIST_PREVIEW_EXTRACT_SQL, LATEST_VISIBLE_PREVIEW_FILTER_SQL } from './sessionListProjection';import { sessionToCamel, type SessionRowWithCount } from './mapper';import { projectSessionContextWindow, type ContextWindowSession } from '../../shared/sessionContextWindow';@@ -14,6 +16,20 @@ import { projectSessionContextWindow, type ContextWindowSession } from '../../shconst OUTER_SESSION_ID_SQL = sql`${sql.identifier('sessions')}.${sql.identifier('id')}`;const OUTER_SESSION_CLEARED_AT_SQL = sql`${sql.identifier('sessions')}.${sql.identifier('cleared_at')}`;+/** Main task list: exact teammate lanes join ordinary sources; private chat lanes keep their own entry. */+export function ordinaryTaskListFilter(): SQL | undefined {+ return and(+ or(inArray(sessions.source, DESKTOP_TASK_LIST_SESSION_SOURCES),+ and(eq(sessions.source, 'bot'), sql`EXISTS (+ SELECT 1 FROM bot_session_links task_link+ JOIN bot_profiles task_bot ON task_bot.id = task_link.bot_id+ WHERE task_link.session_id = ${OUTER_SESSION_ID_SQL} AND task_link.role IN ('routine', 'channel')+ AND task_bot.status <> 'deleting' AND (task_bot.hidden_at IS NULL OR task_bot.hidden_at = 0)+ )`)),+ isNull(sessions.hiddenAt),+ );+}+/*** list / get / update 共用的 messageCount:标量子查询。口径是该会话的全部 messages 行数,* 不过滤 role / rewind_at / cleared_at(口径要动就得连手机端卡片上的「N 条消息」一起想,@@ -79,11 +95,13 @@ export interface SessionListRow {latestMessageExtract: string | null;latestMessageRole: string | null;tagsJson?: string;+ companionJson?: string | null;}function sessionReadSelection() {return {session: sessions,+ companionJson: historyCompanionJson(OUTER_SESSION_ID_SQL).as('companion_json'),tagsJson:sql<string>`(SELECT coalesce(json_group_array(json_object('id',t.id,'name',t.name,'nameCustomized',json(CASE WHEN t.name_customized THEN 'true' ELSE 'false' END),'color',t.color,'favoriteOrder',t.favorite_order,'sortOrder',t.sort_order,'revision',t.revision)), '[]') FROM task_tags t JOIN session_task_tags st ON st.tag_id=t.id WHERE st.session_id=${OUTER_SESSION_ID_SQL})`.as('tags_json',@@ -96,6 +114,7 @@ function sessionReadSelection() {export function flattenSessionReadRow(row: SessionListRow): SessionRowWithCount {return { ...row.session,+ companion: parseHistoryCompanion(row.companionJson),tags: normalizeTaskTags(JSON.parse(row.tagsJson ?? '[]')), messageCount: row.messageCount,latestMessageExtract: row.latestMessageExtract, latestMessageRole: row.latestMessageRole };}diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.tsindex b9f19eb431..70a5d16536 100644--- a/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts+++ b/apps/desktop/src/renderer/__tests__/machineSwitcher.test.ts@@ -107,6 +107,13 @@ describe('selectVisibleSessions', () => {},);+ it('includes local routine and remote channel tasks with exact ownership, excluding private lanes', () => {+ const lane = (role: string, device?: string): Session => ({ ...mkSession(role, device), source: 'bot', companion: { id: 'owner', role } });+ expect(selectVisibleSessions([lane('routine'), lane('canonical')],+ [lane('channel', 'dev-a'), lane('group', 'dev-a'), lane('thread', 'dev-a')], MACHINE_ALL)+ .map(row => row.id)).toEqual(['routine', 'channel']);+ });+it('所有(默认)→ 本机 + 全部远程合并(顺序:本地在前)', () => {expect(selectVisibleSessions(local, remote, MACHINE_ALL).map((s) => s.id)).toEqual(['l1',diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex 51a6747bf7..e492fedb13 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -30,14 +30,17 @@ import {} from '@/features/device-link/remoteSessionActivityStore';const invoke = vi.fn();+const historyInvoke = vi.fn();let n = 0;const did = () => `retry-dev-${n++}`;const noSleep = async () => {};beforeEach(() => {invoke.mockReset();+ historyInvoke.mockReset().mockResolvedValue({ ok: true, sessions: [], hasMore: false });// Existing cases exercise compatibility with hosts predating batch reconciliation.vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: (...args: unknown[]) => {+ if (args[1] === 'local-db:history:query') return historyInvoke(...args);if (args[1] === 'local-db:sessions:get-many') return Promise.reject(new Error('[DEVICE_LINK_CHANNEL_NOT_ALLOWED] old host'));return invoke(...args);} } } });@@ -1222,13 +1225,14 @@ describe('batch reconciliation', () => {const outside = Array.from({ length: 8 }, (_, i) => session(`outside-${i}`));remoteProjectsStore.setDeviceSessions(d, 'Mac', outside);const batchInvoke = vi.fn(async (_device: string, channel: string) => {+ if (channel === 'local-db:history:query') return { ok: true, sessions: [] };if (channel === 'local-db:sessions:list') return recent;if (channel === 'local-db:sessions:get-many') return outside.slice(1).map((s) => ({ ...s, title: 'updated', model: 'new-model', pinnedAt: '2026-09-12T00:00:00.000Z' }));throw new Error('unexpected individual read');});vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: batchInvoke } } });await refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });- expect(batchInvoke).toHaveBeenCalledTimes(2);+ expect(batchInvoke).toHaveBeenCalledTimes(3);expect(batchInvoke).toHaveBeenLastCalledWith(d, 'local-db:sessions:get-many', [outside.map((s) => s.id)]);const result = remoteProjectsStore.getDeviceSessions(d);expect(result.find((s) => s.id === 'outside-0')).toBeUndefined();@@ -1240,13 +1244,14 @@ describe('batch reconciliation', () => {const outside = session('outside');remoteProjectsStore.setDeviceSessions(d, 'Mac', [outside]);const batchInvoke = vi.fn(async (_device: string, channel: string) => {+ if (channel === 'local-db:history:query') return { ok: true, sessions: [] };if (channel === 'local-db:sessions:list') return Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));if (failure === 'malformed') return [{ id: 'not-requested', status: 'active' }];throw new Error(failure === 'timeout' ? '[DEVICE_LINK_TIMEOUT] slow' : '[DEVICE_LINK_ACCESS_REVOKED] revoked');});vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: batchInvoke } } });await refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });- expect(batchInvoke).toHaveBeenCalledTimes(2);+ expect(batchInvoke).toHaveBeenCalledTimes(3);expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside')).toMatchObject({ title: 'outside' });});@@ -1256,6 +1261,7 @@ describe('batch reconciliation', () => {const response = deferred<Session[]>();const started = deferred<void>();const batchInvoke = vi.fn(async (_device: string, channel: string) => {+ if (channel === 'local-db:history:query') return { ok: true, sessions: [] };if (channel === 'local-db:sessions:list') return Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));started.resolve();return response.promise;@@ -1274,12 +1280,45 @@ it('falls back to bounded GETs for oversized batches', async () => {const d = did();remoteProjectsStore.setDeviceSessions(d, 'Mac', [session('outside')]);const calls = vi.fn(async (_device: string, channel: string) => {+ if (channel === 'local-db:history:query') return { ok: true, sessions: [] };if (channel === 'local-db:sessions:list') return Array.from({ length: 200 }, (_, i) => session(`recent-${i}`));if (channel === 'local-db:sessions:get-many') throw new Error('[PRECONDITION_FAILED] REMOTE_SESSION_BATCH_TOO_LARGE');return session('outside', { title: 'updated' });});vi.stubGlobal('window', { electronAPI: { deviceLink: { invoke: calls } } });await refreshRemoteDeviceSessions(d, 'Mac', { maxAttempts: 1, snapshotMode: 'merge' });- expect(calls).toHaveBeenCalledTimes(3);+ expect(calls).toHaveBeenCalledTimes(4);expect(remoteProjectsStore.getDeviceSessions(d).find((s) => s.id === 'outside')?.title).toBe('updated');});++// Released hosts list no bot lanes, but provide owner-scoped history links; unit, real refresh/store path.+it('lists routine and channel tasks from legacy history with ownership, excluding canonical and group chats', async () => {+ const device = did();+ historyInvoke.mockResolvedValueOnce({ ok: true, sessions: [+ { id: 'main', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'canonical' } },+ { id: 'im', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'channel', channel: 'feishu' } },+ ], hasMore: true, nextCursor: 'next' }).mockResolvedValueOnce({ ok: true, sessions: [+ { id: 'routine', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'routine' } },+ { id: 'group', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'group' } },+ ], hasMore: false });+ invoke.mockImplementation(async (_device, channel, args) => channel === 'local-db:sessions:list'+ ? [session('ordinary')] : session(args[0], { source: 'bot' }));+ expect(await refreshRemoteDeviceSessions(device)).toBe('ok');+ const rows = remoteProjectsStore.getDeviceSessions(device);+ expect(rows.map(row => row.id).sort()).toEqual(['im', 'ordinary', 'routine']);+ expect(rows.find(row => row.id === 'im')).toMatchObject({ deviceLinkDeviceId: device, companion: { id: 'cindy', role: 'channel', channel: 'feishu' } });+ expect(historyInvoke).toHaveBeenCalledTimes(2);+});++it('does not resurrect teammate task discovery after its device snapshot is invalidated', async () => {+ const device = did();+ let finish!: (value: unknown) => void;+ invoke.mockResolvedValue([]);+ historyInvoke.mockImplementation(() => new Promise(resolve => { finish = resolve; }));+ const refresh = refreshRemoteDeviceSessions(device);+ await Promise.resolve(); await Promise.resolve();+ remoteProjectsStore.removeDevice(device);+ finish({ ok: true, sessions: [{ id: 'im', source: 'bot', status: 'active', companion: { id: 'cindy', role: 'channel' } }], hasMore: false });+ expect(await refresh).toBe('superseded');+ expect(remoteProjectsStore.getDeviceSessions(device)).toEqual([]);+});diff --git a/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts b/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.tsindex 70b52c5b02..19b5781bde 100644--- a/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts+++ b/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts@@ -15,6 +15,10 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest';import {+ CREATORS_KEY,+ loadCreators,+ persistCreators,+ nextCreatorsAfterToggle,STATUS_KEY,VENDOR_KEY,loadVendor,@@ -884,3 +888,24 @@ describe('Harness filter persistence', () => {expect(loadVendor()).toBe('all');});});++describe('creator filter selection and owner persistence', () => {+ beforeEach(() => installMemoryLocalStorage());+ afterEach(() => uninstallLocalStorage());+ it('starts at all, selects one or several, and returns to all when the last choice is removed', () => {+ expect(loadCreators(OWNER_ID)).toBe('all');+ expect(nextCreatorsAfterToggle('all', 'a')).toEqual(['a']);+ expect(nextCreatorsAfterToggle(['a'], 'b')).toEqual(['a', 'b']);+ expect(nextCreatorsAfterToggle(['a', 'b'], 'a')).toEqual(['b']);+ expect(nextCreatorsAfterToggle(['b'], 'b')).toBe('all');+ persistCreators(['a', 'b'], OWNER_ID);+ expect(loadCreators(OWNER_ID)).toEqual(['a', 'b']);+ expect(loadCreators('owner-b')).toBe('all');+ persistCreators('all', OWNER_ID);+ expect(loadCreators(OWNER_ID)).toBe('all');+ });+ it('recovers from an invalid saved choice', () => {+ localStorage.setItem(ownerKey(CREATORS_KEY), '{');+ expect(loadCreators(OWNER_ID)).toBe('all');+ });+});diff --git a/apps/desktop/src/renderer/features/bots/BotFollowMark.tsx b/apps/desktop/src/renderer/features/bots/BotFollowMark.tsxindex e6f127f22a..0fe5e56204 100644--- a/apps/desktop/src/renderer/features/bots/BotFollowMark.tsx+++ b/apps/desktop/src/renderer/features/bots/BotFollowMark.tsx@@ -1,22 +1,28 @@import { Tip } from '@/components/ui/tooltip';import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';import { BotAvatar } from './BotAvatar';-import type { BotProfile } from './botStore';+import type { TaskBotIdentity } from './botFollowScopes';export { useSessionFollowers } from './botFollowScopes';/**- * 普通任务行上的「<伙伴>在跟进」:这件任务由哪个伙伴创建或明确接手。只显示第一位伙伴的- * 14px 头像(头像底色是伙伴身份,不是状态),悬停说明全部伙伴。没有伙伴跟进时不占位。+ * 普通任务行上的创建者/跟进者:优先显示创建者的 14px 头像,归档后仍保留。+ * 悬停区分创建与跟进关系。没有伙伴归属时不占位。* 行组件用 `useSessionFollowers(session)` 取伙伴列表,自己决定要不要为标记让位。*/-export function BotFollowMark({ followers }: { followers: readonly BotProfile[] }) {+export function BotFollowMark({ followers }: { followers: readonly TaskBotIdentity[] }) {const { t, i18n } = useTranslation();const first = followers[0];if (!first) return null;- const names = new Intl.ListFormat(i18n.language, { style: 'long', type: 'conjunction' })- .format(followers.map((bot) => bot.name));- const label = t('bots.workbench.followingMark', { names });+ const formatter = new Intl.ListFormat(i18n.language, { style: 'long', type: 'conjunction' });+ const creators = followers.filter(bot => bot.taskRelation === 'created');+ const owners = followers.filter(bot => bot.taskRelation === 'owned');+ const responsible = followers.filter(bot => !bot.taskRelation);+ const label = [+ owners.length ? t('bots.workbench.ownedMark', { names: formatter.format(owners.map(bot => bot.name)) }) : '',+ creators.length ? t('bots.workbench.createdMark', { names: formatter.format(creators.map(bot => bot.name)) }) : '',+ responsible.length ? t('bots.workbench.followingMark', { names: formatter.format(responsible.map(bot => bot.name)) }) : '',+ ].filter(Boolean).join('\n');return (<Tip text={label}><span role="img" aria-label={label} className="inline-flex shrink-0" data-testid="bot-follow-mark">diff --git a/apps/desktop/src/renderer/features/bots/CindyMergeSetting.tsx b/apps/desktop/src/renderer/features/bots/CindyMergeSetting.tsxindex 64f84beca1..2286c12b3e 100644--- a/apps/desktop/src/renderer/features/bots/CindyMergeSetting.tsx+++ b/apps/desktop/src/renderer/features/bots/CindyMergeSetting.tsx@@ -44,7 +44,7 @@ export function CindyMergeSetting({ bot, className = 'mt-3' }: { bot: { id: strireturn () => { live = false; };}, [cloud.enabled, actorsKey]);- if (!copies.some((copy) => copy.botId === bot.id)) return null;+ if (copies.length < 2 || !copies.some((copy) => copy.botId === bot.id)) return null;const deviceName = (copy: CompanionCindyCopy) => {const actor = cloud.actors.find((candidate) => candidate.externalId === copy.botId);if (copy.homeDeviceId && copy.homeDeviceId === cloud.selfDeviceId) return t('bots.cloud.thisComputer');diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsxindex baec60a289..e068e4fbae 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botFollowMark.test.tsx@@ -1,12 +1,13 @@// @vitest-environment jsdom-import { act, cleanup, render, screen } from '@testing-library/react';+import { act, cleanup, render, renderHook, screen } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { Session } from '@/lib/ccAgent.types';const h = vi.hoisted(() => ({profiles: [] as Array<Record<string, unknown>>,+ remote: [] as Array<Record<string, unknown>>,}));vi.mock('react-i18next', () => ({@@ -21,8 +22,11 @@ vi.mock('../botStore', () => ({ensureBotProfilesLoaded: vi.fn(async () => h.profiles),}));+vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => h.remote }));+import { BotFollowMark, useSessionFollowers } from '../BotFollowMark';-import { __testing, useSessionDelegatingBot } from '../botFollowScopes';+import { __testing, useSessionDelegatingBot, useTaskCreatorIndex, useTaskCreatorOptions, matchesTaskCreators, taskBotKey } from '../botFollowScopes';+import { resetCompanionCloudStoreForTests } from '../companionCloudStore';import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';function Row({ session: value }: { session: Session }) {@@ -42,6 +46,8 @@ const followScopes = vi.fn(async (): Promise<Array<{ botId: string; sessionIds?:beforeEach(() => {__testing.reset();+ resetCompanionCloudStoreForTests();+ h.remote = [];h.profiles = [bot('bot-1', 'Dash'), bot('bot-2', 'Lizi')];followScopes.mockClear();(window as unknown as { electronAPI: unknown }).electronAPI = {@@ -134,12 +140,13 @@ describe('useSessionDelegatingBot', () => {expect(followScopes).toHaveBeenCalledTimes(1);});- it('keeps naming the Bot for its archived background task, while the follow mark stays active-only', async () => {- followScopes.mockResolvedValueOnce([{ botId: 'bot-1', sessionIds: ['s2'], delegatedSessionIds: ['s2'] }]);+ it('keeps the creator avatar after archiving but does not carry over a mere follow relationship', async () => {+ followScopes.mockResolvedValueOnce([{ botId: 'bot-1', sessionIds: ['s2', 's3'], delegatedSessionIds: ['s2'] }]);const archived = session({ id: 's2', status: 'archived' });- await act(async () => render(<><Owner session={archived} /><Row session={archived} /></>));+ await act(async () => render(<><Owner session={archived} /><Row session={archived} /><Row session={session({id: 's3', status: 'archived'})} /></>));expect(screen.getByTestId('owner').textContent).toBe('Dash');- expect(screen.queryByTestId('bot-follow-mark')).toBeNull();+ expect(screen.getAllByTestId('bot-follow-mark')).toHaveLength(1);+ expect(screen.getByTestId('bot-follow-mark').getAttribute('aria-label')).toBe('bots.workbench.createdMark:Dash');});it('does not guess from an older host that only lists responsibilities', async () => {@@ -171,3 +178,108 @@ it('ignores a late responsibility snapshot after switching owners', async () =>await act(async () => { finish([{ botId: 'bot-1', sessionIds: ['s1'] }]); changed?.(); });expect(screen.queryByTestId('bot-follow-mark')).toBeNull();});++// Regression: Desktop ignored advertised remote following links and excluded remote rows.+it('uses the remote computer identity for marks and never borrows a same-ID local Bot', async () => {+ h.remote = [{ ...bot('bot-1', 'Remote Dash'), deviceId: 'laptop', followingSessionIds: ['s1'] }];+ const view = render(<Row session={session({ deviceLinkDeviceId: 'laptop' })} />);+ await act(async () => {});+ expect(screen.getByTestId('bot-follow-mark').getAttribute('aria-label')).toContain('Remote Dash');+ view.rerender(<Row session={session({ deviceLinkDeviceId: 'other-computer' })} />);+ expect(screen.queryByTestId('bot-follow-mark')).toBeNull();+ h.remote = [];+ view.rerender(<Row session={session({ deviceLinkDeviceId: 'laptop' })} />);+ expect(screen.queryByTestId('bot-follow-mark')).toBeNull();+});++it('shows the remote creator mark when an older host only provides task-card attribution', async () => {+ h.remote = [{ ...bot('bot-1', 'Remote Dash'), deviceId: 'laptop', followingSessionIds: [], delegatedSessionIds: ['s1'] }];+ const view = render(<Row session={session({ deviceLinkDeviceId: 'laptop' })} />);+ await act(async () => {});+ expect(screen.getByTestId('bot-follow-mark').getAttribute('aria-label')).toContain('Remote Dash');+ view.rerender(<Row session={session({ deviceLinkDeviceId: 'laptop', status: 'archived' })} />);+ expect(screen.getByTestId('bot-follow-mark').getAttribute('aria-label')).toBe('bots.workbench.createdMark:Remote Dash');+ view.rerender(<Row session={session({ deviceLinkDeviceId: 'other' })} />);+ expect(screen.queryByTestId('bot-follow-mark')).toBeNull();+});++it('filters single and multiple creators, including archived tasks, independently of follow responsibility', async () => {+ followScopes.mockResolvedValueOnce([+ { botId: 'bot-1', sessionIds: ['s1'], delegatedSessionIds: ['s2'] },+ { botId: 'bot-2', sessionIds: ['s3'], delegatedSessionIds: ['s3'] },+ ]);+ h.remote = [{ ...bot('bot-1', 'Remote Dash'), deviceId: 'laptop', delegatedSessionIds: ['s2'] }];+ const { result } = renderHook(useTaskCreatorIndex);+ await act(async () => {});+ const local = taskBotKey({ id: 'bot-1' });+ const remote = taskBotKey({ id: 'bot-1', deviceId: 'laptop' });+ const tasks = [session(), session({ id: 's2', status: 'archived' }), session({ id: 's3' }),+ session({ id: 's2', deviceLinkDeviceId: 'laptop' }), session({ id: 's2', deviceLinkDeviceId: 'other' })];+ const matching = (selection: 'all' | string[]) => tasks.filter(task => matchesTaskCreators(task, selection, result.current));+ expect(matching('all')).toEqual(tasks);+ expect(matching([local])).toEqual([tasks[1]]);+ expect(matching([remote])).toEqual([tasks[3]]);+ expect(matching([local, remote])).toEqual([tasks[1], tasks[3]]);+});++// User regression: one built-in Cindy must filter local and remote creations together.+it('offers one Cindy across computers without merging a custom namesake or unrelated same-ID bots', async () => {+ h.profiles = [bot('cindy-default', 'Cindy'), bot('custom', 'Cindy')];+ h.remote = [+ { ...bot('remote-cindy', 'Renamed', { templateId: 'cindy' }), deviceId: 'laptop', deviceName: 'Laptop', delegatedSessionIds: ['remote-child'] },+ { ...bot('custom', 'Cindy'), deviceId: 'laptop', delegatedSessionIds: ['custom-child'] },+ ];+ followScopes.mockResolvedValueOnce([{ botId: 'cindy-default', delegatedSessionIds: ['local-child'] }]);+ const { result, rerender } = renderHook(() => ({ options: useTaskCreatorOptions(), index: useTaskCreatorIndex() }));+ await act(async () => {});+ expect(result.current.options).toHaveLength(3);+ const cindy = result.current.options.find(bot => bot.id === 'cindy-default')!;+ expect(cindy.filterMemberKeys).toEqual([taskBotKey({ id: 'cindy-default' }), taskBotKey({ id: 'remote-cindy', deviceId: 'laptop' })]);+ expect(cindy.deviceName).toBeUndefined();+ const { taskCreatorFilterKey } = await import('../cindyDeviceRoster');+ const selected = [taskCreatorFilterKey(cindy)];+ const tasks = [session({ id: 'local-child' }), session({ id: 'remote-child', deviceLinkDeviceId: 'laptop', status: 'archived' }),+ session({ id: 'custom-child', deviceLinkDeviceId: 'laptop' }), session()];+ expect(tasks.filter(task => matchesTaskCreators(task, selected, result.current.index))).toEqual(tasks.slice(0, 2));+ h.remote = [...h.remote, { ...bot('new-cindy', 'Cindy', { templateId: 'cindy' }), deviceId: 'new-host', delegatedSessionIds: ['new-child'] }];+ rerender();+ expect(result.current.options).toHaveLength(3);+ expect(matchesTaskCreators(session({ id: 'new-child', deviceLinkDeviceId: 'new-host' }), selected, result.current.index)).toBe(true);+});++// The filter must reuse the main roster's retired-copy rules, not resurrect a demoted local Cindy.+it('hides retired copies and filters one cloud companion across its old and current computers', async () => {+ h.profiles = [bot('cindy-default', 'Cindy'), bot('cloud-bot', 'Cindy')];+ h.remote = [{ ...bot('cloud-bot', 'Cindy'), deviceId: 'laptop', delegatedSessionIds: ['remote-child'] }];+ resetCompanionCloudStoreForTests({ enabled: true, selfDeviceId: 'desktop', humanActorId: 'human', demotedBotIds: ['cindy-default'],+ actors: [{ id: 'actor', externalId: 'cloud-bot', name: 'Cindy', avatar: null, homeDeviceId: 'laptop', homeDevice: { deviceId: 'laptop', name: 'Mac Studio', online: true, isSelf: false } }] });+ followScopes.mockResolvedValueOnce([{ botId: 'cloud-bot', delegatedSessionIds: ['local-child'] }]);+ const { result } = renderHook(() => ({ options: useTaskCreatorOptions(), index: useTaskCreatorIndex() }));+ await act(async () => {});+ expect(result.current.options).toHaveLength(1);+ const option = result.current.options[0]!;+ expect(option.id).toBe('cloud-bot');+ expect(option.deviceName).toBeUndefined();+ expect(option.filterMemberKeys).toContain(taskBotKey({ id: 'cloud-bot' }));+ const { taskCreatorFilterKey } = await import('../cindyDeviceRoster');+ const selection = [taskCreatorFilterKey(option)];+ expect(matchesTaskCreators(session({ id: 'local-child', status: 'archived' }), selection, result.current.index)).toBe(true);+ expect(matchesTaskCreators(session({ id: 'remote-child', deviceLinkDeviceId: 'laptop' }), selection, result.current.index)).toBe(true);+});++// Unit: the same bot id on another device must not steal ownership; archived lanes retain their avatar.+it.each(['routine', 'channel'])('uses exact local/remote ownership for %s avatars and filtering', async role => {+ h.remote = [bot('bot-1', 'Remote Dash', { deviceId: 'remote', deviceName: 'Mac' })];+ const local = session({ source: 'bot', companion: { id: 'bot-1', role }, status: 'archived' });+ const remote = session({ ...local, deviceLinkDeviceId: 'remote' });+ await act(async () => render(<><Row session={local} /><Row session={remote} /></>));+ expect(screen.getAllByTestId('bot-follow-mark').map(mark => mark.getAttribute('aria-label')))+ .toEqual(['bots.workbench.ownedMark:Dash', 'bots.workbench.ownedMark:Remote Dash']);+ const { result } = renderHook(useTaskCreatorIndex);+ const localKey = taskBotKey({ id: 'bot-1' });+ const remoteKey = taskBotKey({ id: 'bot-1', deviceId: 'remote' });+ expect(matchesTaskCreators(local, [localKey], result.current)).toBe(true);+ expect(matchesTaskCreators(remote, [localKey], result.current)).toBe(false);+ expect(matchesTaskCreators(remote, [remoteKey], result.current)).toBe(true);+ expect(matchesTaskCreators(local, [localKey, remoteKey], result.current)).toBe(true);+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/cindyMergeSetting.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/cindyMergeSetting.test.tsxindex 3c8a71d9de..dc6c2cf0f3 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/cindyMergeSetting.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/cindyMergeSetting.test.tsx@@ -41,7 +41,7 @@ afterEach(() => { cleanup(); });describe('CindyMergeSetting', () => {it('is hidden while there is only one Cindy', async () => {- maker.listCindyCopies.mockResolvedValue([]);+ maker.listCindyCopies.mockResolvedValue([copies[0]]);render(<CindyMergeSetting bot={{ id: 'cindy-default', name: 'Cindy' }} />);await waitFor(() => expect(maker.listCindyCopies).toHaveBeenCalled());expect(screen.queryByTestId('cindy-merge-row')).toBeNull();diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsxindex edac41985d..6f06bd921d 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBots.test.tsx@@ -5,9 +5,15 @@ const h = vi.hoisted(() => ({owner: 'owner-a',devices: [] as any[],invoke: vi.fn(),+ cloudEnabled: false,+ copies: vi.fn(),status: null as any,push: null as any,}));+vi.mock('../companionCloudStore', () => ({+ useCompanionCloud: () => ({ enabled: h.cloudEnabled, actors: [] }),+ companionCloudApi: () => ({ listCindyCopies: h.copies }),+}));vi.mock('@/contexts/AuthContext', () => ({useAuth: () => ({ dataOwnerId: h.owner, isAuthenticated: true }),}));@@ -16,7 +22,7 @@ vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({}));vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ isDeviceLinkRemotePushCurrent: () => true }));import { useRemoteBotSync, useRemoteBots, markRemoteBotRead } from '../useRemoteBots';-import { parseRemoteCollectionListRequest } from '@cindy/device-link';+import { parseRemoteCollectionListRequest, REMOTE_RESOURCE_LIST_CHANNEL, REMOTE_RESOURCE_CHANGED_CHANNEL } from '@cindy/device-link';import { parseRemoteBots, remoteBotKey, isRemoteBotUnread } from '../remoteBotRoster';const host = (deviceId: string, online = true) => ({deviceId,@@ -41,6 +47,8 @@ function useRoster() {return useRemoteBots();}beforeEach(() => {+ h.cloudEnabled = false;+ h.copies.mockReset();h.owner = `owner-${Math.random()}`;h.devices = [host('a'), host('b')];h.invoke.mockReset().mockResolvedValue(collection());@@ -69,7 +77,7 @@ describe('remote teammate roster', () => {const { result, rerender } = renderHook(useRoster);await waitFor(() => expect(result.current).toHaveLength(2));expect(new Set(result.current.map(remoteBotKey)).size).toBe(2);- for (const call of h.invoke.mock.calls)+ for (const call of h.invoke.mock.calls.filter(call => call[1] === REMOTE_RESOURCE_LIST_CHANNEL))expect(parseRemoteCollectionListRequest(call[2][0])).not.toBeNull();h.devices = [host('a', false), host('b')];rerender();@@ -158,9 +166,104 @@ it('does not reinterpret a resource read error as device disconnection', async (expect(result.current[0].online).toBe(true);h.invoke.mockRejectedValue(new Error('model/resource failure'));act(() => h.status({ status: 'online' }));- await waitFor(() => expect(h.invoke).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(h.invoke.mock.calls.filter(call => call[1] === REMOTE_RESOURCE_LIST_CHANNEL)).toHaveLength(2));expect(result.current[0].online).toBe(true);act(() => h.status({ status: 'stopped' }));expect(result.current[0].online).toBe(false);expect(result.current[0].connectionKnown).toBe(true);});++it('parses exact following links without confusing them with the canonical conversation', () => {+ const response = collection();+ response.items[0].links.push(+ { rel: 'following', target: { kind: 'session', sessionId: 'taken-over' } },+ { rel: 'following', target: { kind: 'session', sessionId: 'taken-over' } },+ { rel: 'following', target: { kind: 'resource', sessionId: 'not-a-task' } },+ );+ expect(parseRemoteBots(response, 'a', 'Laptop')[0]).toMatchObject({+ sessionId: 'canonical', followingSessionIds: ['taken-over'],+ });+ expect(parseRemoteBots(collection(), 'a', 'Laptop')[0]).toMatchObject({+ followingSessionIds: [],+ });+});++// Regression: released hosts advertise teammates without any created-task links.+it('hydrates exact creation attribution through the existing task-card API on each computer', async () => {+ h.invoke.mockImplementation(async (device, channel) => channel === REMOTE_RESOURCE_LIST_CHANNEL+ ? collection() : { ok: true, delegations: [+ { requestingBotId: 'same-bot', childSessionId: `${device}-child` },+ { requestingBotId: 'same-bot', childSessionId: `${device}-child` },+ { requestingBotId: 'someone-else', childSessionId: 'not-owned' },+ { requestingBotId: 'same-bot', childSessionId: null },+ ] });+ const { result } = renderHook(useRoster);+ await waitFor(() => expect(result.current.map(bot => bot.delegatedSessionIds)).toEqual([['a-child'], ['b-child']]));+ expect(h.invoke).toHaveBeenCalledWith('a', 'maker:bot-delegations:list', ['canonical']);+ expect(h.invoke).toHaveBeenCalledWith('b', 'maker:bot-delegations:list', ['canonical']);+});++it('refreshes creation attribution on a delegation push, keeps it on failure and clears it on a successful empty read', async () => {+ h.devices = [host('a')];+ let response: unknown = { ok: true, delegations: [{ requestingBotId: 'same-bot', childSessionId: 'child' }] };+ h.invoke.mockImplementation(async (_device, channel) => channel === REMOTE_RESOURCE_LIST_CHANNEL ? collection() : response);+ const { result } = renderHook(useRoster);+ await waitFor(() => expect(result.current[0]?.delegatedSessionIds).toEqual(['child']));+ const taskReads = () => h.invoke.mock.calls.filter(call => call[1] === 'maker:bot-delegations:list').length;+ const beforeStatusPush = taskReads();+ vi.useFakeTimers();+ try {+ act(() => h.push({ deviceId: 'a', channel: REMOTE_RESOURCE_CHANGED_CHANNEL }));+ await act(async () => { await vi.advanceTimersByTimeAsync(500); });+ expect(taskReads()).toBe(beforeStatusPush);+ } finally { vi.useRealTimers(); }+ response = { ok: false, errorCode: 'HOST_NOT_READY' };+ act(() => h.status({ status: 'online' }));+ await act(async () => {});+ expect(result.current[0].delegatedSessionIds).toEqual(['child']);+ response = { ok: true, delegations: [] };+ vi.useFakeTimers();+ try {+ act(() => h.push({ deviceId: 'a', channel: 'maker:bot-delegation:changed' }));+ await act(async () => { await vi.advanceTimersByTimeAsync(500); });+ expect(result.current[0].delegatedSessionIds).toEqual([]);+ } finally { vi.useRealTimers(); }+});++it('cannot restore old attribution when a pending task-card read completes after switching accounts', async () => {+ h.devices = [host('a')];+ let finish!: (value: unknown) => void;+ h.invoke.mockImplementation(async (_device, channel) => channel === REMOTE_RESOURCE_LIST_CHANNEL+ ? collection() : new Promise(resolve => { finish = resolve; }));+ const { result, rerender } = renderHook(useRoster);+ await waitFor(() => expect(finish).toBeDefined());+ h.owner = 'new-owner';+ h.devices = [];+ rerender();+ await act(async () => finish({ ok: true, delegations: [{ requestingBotId: 'same-bot', childSessionId: 'old-child' }] }));+ expect(result.current).toEqual([]);+});++// The compact legacy roster has no templateId; the cloud knows the built-in identity.+it('applies cloud Cindy identity regardless of roster arrival order and rejects a late old-owner reply', async () => {+ h.cloudEnabled = true;+ let finish!: (value: unknown) => void;+ h.copies.mockImplementation(() => new Promise(resolve => { finish = resolve; }));+ const { result, rerender } = renderHook(useRoster);+ await waitFor(() => expect(result.current).toHaveLength(2));+ await act(async () => finish([{ botId: 'same-bot' }]));+ expect(result.current.every(bot => bot.templateId === 'cindy')).toBe(true);+ act(() => h.status({ status: 'online' }));+ await act(async () => {});+ expect(result.current.every(bot => bot.templateId === 'cindy')).toBe(true);+ h.owner = 'another-owner';+ rerender();+ await act(async () => {});+ expect(result.current.every(bot => bot.templateId === undefined)).toBe(true);+ const oldFinish = finish;+ h.owner = 'third-owner';+ h.cloudEnabled = false;+ rerender();+ await act(async () => oldFinish([{ botId: 'same-bot' }]));+ expect(result.current.every(bot => bot.templateId === undefined)).toBe(true);+});diff --git a/apps/desktop/src/renderer/features/bots/botFollowScopes.ts b/apps/desktop/src/renderer/features/bots/botFollowScopes.tsindex 9fa5139e16..695cee2bac 100644--- a/apps/desktop/src/renderer/features/bots/botFollowScopes.ts+++ b/apps/desktop/src/renderer/features/bots/botFollowScopes.ts@@ -7,7 +7,14 @@ import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contextsimport type { Session } from '@/lib/ccAgent.types';import { createLogger } from '@/lib/logger';+import { isTeammateTaskSession } from '../../../shared/sessionSource';import { isWorkbenchTaskSource } from '../../../shared/botWorkbench';+import { useRemoteBots } from './useRemoteBots';+import { useCompanionCloud } from './companionCloudStore';+import { cloudRemoteBots, withoutShadowedBots } from './companionCloudPresentation';+import { taskCreatorFilterKey } from './cindyDeviceRoster';+import { taskBotKey, type RemoteBot } from './remoteBotRoster';+export { taskBotKey } from './remoteBotRoster';import { ensureBotProfilesLoaded, hasLoadedBotProfiles, useBotProfiles, type BotProfile } from './botStore';const log = createLogger('BotFollowScopes');@@ -125,12 +132,97 @@ function isDelegatableSession(session: Session): boolean {return (session.status === 'active' || session.status === 'archived') && isLocalPlainSession(session);}+export function useBotFollowScopes(): readonly BotFollowScope[] {+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+}++/** Display identity only; a remote identity must never become a local action target. */+export type TaskBotIdentity = Pick<BotProfile, 'id' | 'name' | 'avatar' | 'avatarColor'> & {+ deviceId?: string;+ deviceName?: string;+ taskRelation?: 'created' | 'owned';+ templateId?: string;+ filterKey?: string;+ /** Previous per-computer selection keys, used to preserve existing filter choices. */+ filterMemberKeys?: readonly string[];+};++export function useTaskCreatorOptions(): TaskBotIdentity[] {+ const profiles = useBotProfiles();+ const remote = useRemoteBots();+ const cloud = useCompanionCloud();+ return useMemo(() => {+ const grouped = new Map<string, TaskBotIdentity>();+ for (const bot of [...withoutShadowedBots(profiles, cloud).filter(bot => !bot.hiddenAt && bot.status !== 'deleting'), ...cloudRemoteBots(cloud, remote)]) {+ const key = taskCreatorFilterKey(bot, cloud);+ const existing = grouped.get(key);+ if (existing) {+ existing.filterMemberKeys = [...(existing.filterMemberKeys ?? []), taskBotKey(bot)];+ } else {+ // Keep the original device ID for avatar resolution; the merged choice has no device subtitle.+ grouped.set(key, { ...bot, filterKey: key, deviceName: key === taskBotKey(bot) && 'deviceName' in bot ? bot.deviceName : undefined,+ filterMemberKeys: [taskBotKey(bot)] });+ }+ }+ // Old per-computer choices follow the same cloud companion after it moves home.+ for (const bot of [...profiles, ...remote]) {+ const option = grouped.get(taskCreatorFilterKey(bot, cloud));+ const member = taskBotKey(bot);+ if (option && !option.filterMemberKeys?.includes(member)) option.filterMemberKeys = [...(option.filterMemberKeys ?? []), member];+ }+ return [...grouped.values()].sort((a, b) => a.name.localeCompare(b.name));+ }, [profiles, remote, cloud]);+}++/** Indexed once for the sidebar, so selecting multiple creators does not scan every Bot per row. */+export function useTaskCreatorIndex(): ReadonlyMap<string, ReadonlySet<string>> {+ const scopes = useBotFollowScopes();+ const profiles = useBotProfiles();+ const remote = useRemoteBots();+ const cloud = useCompanionCloud();+ return useMemo(() => {+ const index = new Map<string, Set<string>>();+ const add = (bot: Pick<TaskBotIdentity, 'id' | 'deviceId' | 'templateId'>, ids: readonly string[] | undefined) => {+ for (const id of ids ?? []) {+ const key = taskCreatorSessionKey(id, bot.deviceId);+ const creators = index.get(key) ?? new Set<string>();+ creators.add(taskCreatorFilterKey(bot, cloud));+ index.set(key, creators);+ }+ };+ for (const bot of [...profiles, ...remote]) {+ index.set(`creator:${taskBotKey(bot)}`, new Set([taskCreatorFilterKey(bot, cloud)]));+ }+ const localById = new Map(profiles.map(bot => [bot.id, bot]));+ for (const scope of scopes) add(localById.get(scope.botId) ?? { id: scope.botId }, scope.delegatedSessionIds);+ for (const bot of remote) add(bot, bot.delegatedSessionIds);+ return index;+ }, [scopes, profiles, remote, cloud]);+}++function taskCreatorSessionKey(id: string, deviceId?: string): string {+ return JSON.stringify([deviceId ?? null, id]);+}++export function matchesTaskCreators(+ session: Session,+ selected: 'all' | readonly string[],+ index: ReadonlyMap<string, ReadonlySet<string>>,+): boolean {+ if (selected === 'all') return true;+ const creators = isTeammateTaskSession(session) && session.companion+ ? index.get(`creator:${taskBotKey({ id: session.companion.id, deviceId: session.deviceLinkDeviceId })}`)+ : index.get(taskCreatorSessionKey(session.id, session.deviceLinkDeviceId));+ return selected.some(key => creators?.has(key));+}+function useScopedBots(session: Session,eligible: (session: Session) => boolean,ids: (scope: BotFollowScope) => readonly string[] | undefined,+ activeProfilesOnly = true,): BotProfile[] {- const followScopes = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+ const followScopes = useBotFollowScopes();const profiles = useBotProfiles();const followable = eligible(session);const sessionId = session.id;@@ -143,18 +235,43 @@ function useScopedBots();if (matching.size === 0) return [];return profiles- .filter((bot) => matching.has(bot.id) && bot.enabled && !bot.hiddenAt- && (bot.status === undefined || bot.status === 'active'))+ .filter((bot) => matching.has(bot.id) && !bot.hiddenAt && bot.status !== 'deleting'+ && (!activeProfilesOnly || (bot.enabled && (bot.status === undefined || bot.status === 'active')))).sort((a, b) => a.name.localeCompare(b.name));- }, [followable, followScopes, ids, profiles, sessionId]);+ }, [followable, followScopes, ids, profiles, sessionId, activeProfilesOnly]);}const responsibleIds = (scope: BotFollowScope) => scope.sessionIds;const delegatedIds = (scope: BotFollowScope) => scope.delegatedSessionIds;-/** 正在负责这件任务的伙伴(按名字排序;隐藏、停用的伙伴不显示)。 */-export function useSessionFollowers(session: Session): BotProfile[] {- return useScopedBots(session, isFollowableSession, responsibleIds);+/** 创建者归属不随归档消失;额外跟进者只在任务活跃时显示。 */+export function useSessionFollowers(session: Session): TaskBotIdentity[] {+ const local = useScopedBots(session, isFollowableSession, responsibleIds);+ const localCreators = useScopedBots(session, isDelegatableSession, delegatedIds, false);+ const remote = useRemoteBots();+ const profiles = useBotProfiles();+ return useMemo(() => {+ const order = (a: TaskBotIdentity, b: TaskBotIdentity) =>+ Number(b.taskRelation === 'created') - Number(a.taskRelation === 'created') || a.name.localeCompare(b.name);+ if (isTeammateTaskSession(session) && session.companion && session.orcaRole !== 'worker'+ && (session.status === 'active' || session.status === 'archived')) {+ const owner = session.deviceLinkDeviceId+ ? remote.find(bot => bot.deviceId === session.deviceLinkDeviceId && bot.id === session.companion!.id)+ : profiles.find(bot => bot.id === session.companion!.id && !bot.hiddenAt && bot.status !== 'deleting');+ return owner ? [{ ...owner, taskRelation: 'owned' as const }] : [];+ }+ if (!session.deviceLinkDeviceId) {+ const identities = new Map<string, TaskBotIdentity>(local.map(bot => [bot.id, bot]));+ for (const bot of localCreators) identities.set(bot.id, { ...bot, taskRelation: 'created' });+ return [...identities.values()].sort(order);+ }+ if ((session.status !== 'active' && session.status !== 'archived') || session.source === 'bot' || session.orcaRole === 'worker'+ || !isWorkbenchTaskSource(session.source)) return [];+ return remote.filter((bot: RemoteBot) => bot.deviceId === session.deviceLinkDeviceId+ && ((session.status === 'active' && bot.followingSessionIds?.includes(session.id)) || bot.delegatedSessionIds?.includes(session.id)))+ .map((bot): TaskBotIdentity => ({ ...bot, taskRelation: bot.delegatedSessionIds?.includes(session.id) ? 'created' : undefined }))+ .sort(order);+ }, [local, localCreators, remote, profiles, session.companion, session.deviceLinkDeviceId, session.status, session.source, session.orcaRole, session.id]);}/**diff --git a/apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts b/apps/desktop/src/renderer/features/bots/cindyDeviceRoster.tsindex ac52c15ccd..ef918f6c98 100644--- a/apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts+++ b/apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts@@ -1,6 +1,7 @@import { deviceDisplayName } from '@/lib/deviceName';+import type { CompanionCloudSnapshot } from '../../../shared/companionCloud';import type { BotProfile } from './botStore';-import { isRemoteBotUnread, type RemoteBot } from './remoteBotRoster';+import { isRemoteBotUnread, taskBotKey, type RemoteBot } from './remoteBotRoster';export type CindyDeviceBot = BotProfile | RemoteBot;@@ -22,6 +23,17 @@ export function isCindyDeviceBot(bot: { id: string; templateId?: string }): boolreturn bot.templateId === 'cindy' || bot.id === 'cindy-default';}+/** Task filtering follows the built-in teammate across computers, including historical tasks. */+export function taskCreatorFilterKey(+ bot: { id: string; deviceId?: string; templateId?: string; filterKey?: string },+ cloud?: CompanionCloudSnapshot,+): string {+ if (bot.filterKey) return bot.filterKey;+ if (isCindyDeviceBot(bot)) return JSON.stringify(['teammate', 'cindy']);+ if (cloud?.enabled && cloud.actors.some(actor => actor.externalId === bot.id)) return JSON.stringify(['companion', bot.id]);+ return taskBotKey(bot);+}+export function cindyDeviceKey(bot: { id: string; deviceId?: string }): string {return JSON.stringify([bot.deviceId ?? null, bot.id]);}diff --git a/apps/desktop/src/renderer/features/bots/remoteBotRoster.ts b/apps/desktop/src/renderer/features/bots/remoteBotRoster.tsindex 834a6bbba0..5a224f4b6e 100644--- a/apps/desktop/src/renderer/features/bots/remoteBotRoster.ts+++ b/apps/desktop/src/renderer/features/bots/remoteBotRoster.ts@@ -1,5 +1,6 @@import { readWorkingPhase, type WorkingPhase } from '../../../shared/workingStatus';export interface RemoteBot {+ templateId?: string;id: string;deviceId: string;deviceName: string;@@ -15,6 +16,8 @@ export interface RemoteBot {generation?: { phase: WorkingPhase; startedAt: number | null };lastReplyAt?: number;readAt?: number;+ followingSessionIds?: string[];+ delegatedSessionIds?: string[];}function record(value: unknown): Record<string, unknown> {@@ -30,6 +33,29 @@ function text(value: unknown): string {: '';}+/** Unknown relations and malformed targets never establish task ownership. */+export function remoteBotTaskIds(links: unknown, rel: string): string[] {+ if (!Array.isArray(links)) return [];+ return [...new Set(links.flatMap((value: unknown) => {+ const link = record(value);+ const target = record(link.target);+ return link.rel === rel && target.kind === 'session'+ && typeof target.sessionId === 'string' && target.sessionId.length > 0+ ? [target.sessionId] : [];+ }))];+}++/** Existing task-card API: only the requesting teammate owns a created child. */+export function remoteBotCreatedTaskIds(value: unknown, botId: string): string[] | null {+ const response = record(value);+ if (response.ok !== true || !Array.isArray(response.delegations)) return null;+ return [...new Set(response.delegations.flatMap((value: unknown) => {+ const row = record(value);+ return row.requestingBotId === botId && typeof row.childSessionId === 'string' && row.childSessionId+ ? [row.childSessionId] : [];+ }))];+}+/** Only consume the advertised Bot collection, never infer identity from task titles. */export function parseRemoteBots(value: unknown, deviceId: string, deviceName: string): RemoteBot[] {const response = record(value);@@ -69,6 +95,7 @@ export function parseRemoteBots(value: unknown, deviceId: string, deviceName: stactivityAt: typeof display.timestamp === 'number' ? display.timestamp : 0,sessionId: typeof sessionId === 'string' && sessionId ? sessionId : null,lastReplyAt: typeof display.lastReplyAt === 'number' && Number.isFinite(display.lastReplyAt) && display.lastReplyAt >= 0 ? display.lastReplyAt : undefined,+ followingSessionIds: remoteBotTaskIds(item.links, 'following'),online: true,connectionKnown: true,...(typeof record(display.generation).phase === 'string' ? { generation: {@@ -86,3 +113,8 @@ export function remoteBotKey(bot: Pick<RemoteBot, 'deviceId' | 'id'>): string {export function isRemoteBotUnread(bot: RemoteBot): boolean {return bot.lastReplyAt !== undefined && bot.readAt !== undefined && bot.lastReplyAt > bot.readAt;}++/** Computer + Bot ID; names and same-ID Bots on other computers never alias. */+export function taskBotKey(bot: { id: string; deviceId?: string }): string {+ return JSON.stringify([bot.deviceId ?? null, bot.id]);+}diff --git a/apps/desktop/src/renderer/features/bots/useRemoteBots.ts b/apps/desktop/src/renderer/features/bots/useRemoteBots.tsindex 33c6b75ef2..afd4fd896f 100644--- a/apps/desktop/src/renderer/features/bots/useRemoteBots.ts+++ b/apps/desktop/src/renderer/features/bots/useRemoteBots.ts@@ -8,13 +8,16 @@ import { useAuth } from '@/contexts/AuthContext';import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';import { revokedDevicesStore } from '@/features/device-link/revokedDevicesStore';-import { parseRemoteBots, type RemoteBot } from './remoteBotRoster';+import { useCompanionCloud, companionCloudApi } from './companionCloudStore';+import { parseRemoteBots, remoteBotCreatedTaskIds, type RemoteBot } from './remoteBotRoster';const CACHE_PREFIX = 'cindy.remoteBots.v1.';let owner: string | null = null;let snapshot: RemoteBot[] = [];+let cindyIds = new Set<string>();const listeners = new Set<() => void>();const publish = (next: RemoteBot[]) => {+ next = next.map(bot => cindyIds.has(bot.id) ? { ...bot, templateId: 'cindy' } : bot);snapshot = next;if (owner) {try { const value = JSON.stringify(next.map((bot) => ({ ...bot, online: false })));@@ -46,6 +49,8 @@ export function useRemoteBots(): readonly RemoteBot[] {export function useRemoteBotSync(): void {const { dataOwnerId, isAuthenticated } = useAuth();const devices = useDeviceLinkDeviceList();+ const cloud = useCompanionCloud();+ const actorsKey = cloud.actors.map(actor => `${actor.externalId}:${actor.homeDeviceId ?? ''}`).join(',');const revoked = useSyncExternalStore(revokedDevicesStore.subscribe,revokedDevicesStore.getSnapshot,@@ -54,6 +59,7 @@ export function useRemoteBotSync(): void {const nextOwner = isAuthenticated ? (dataOwnerId ?? null) : null;if (owner !== nextOwner) {owner = nextOwner;+ cindyIds = new Set();let cached: RemoteBot[] = [];try {if (!nextOwner) {@@ -64,7 +70,10 @@ export function useRemoteBotSync(): void {const rows = JSON.parse(raw);if (Array.isArray(rows)) cached = rows.slice(0, 200).filter((bot) => bot && ['id', 'deviceId', 'deviceName', 'name', 'avatar', 'avatarColor', 'description', 'preview'].every((key) => typeof bot[key] === 'string') && Number.isFinite(bot.activityAt)).map((bot) => ({id: bot.id, deviceId: bot.deviceId, deviceName: bot.deviceName, name: bot.name,+ templateId: typeof bot.templateId === 'string' ? bot.templateId : undefined,avatar: bot.avatar, avatarColor: bot.avatarColor, description: bot.description, preview: bot.preview,+ followingSessionIds: Array.isArray(bot.followingSessionIds) ? bot.followingSessionIds.filter((id: unknown) => typeof id === 'string') : [],+ delegatedSessionIds: Array.isArray(bot.delegatedSessionIds) ? bot.delegatedSessionIds.filter((id: unknown) => typeof id === 'string') : [],activityAt: bot.activityAt, sessionId: typeof bot.sessionId === 'string' ? bot.sessionId : null,lastReplyAt: Number.isFinite(bot.lastReplyAt) ? bot.lastReplyAt : undefined,readAt: Number.isFinite(bot.readAt) ? bot.readAt : undefined, online: false, connectionKnown: false,@@ -90,10 +99,13 @@ export function useRemoteBotSync(): void {);const generations = new Map<string, number>();const timers = new Map<string, ReturnType<typeof setTimeout>>();+ const taskRefreshes = new Set<string>();const current = () => !disposed && owner === nextOwner;- async function refresh(deviceId: string) {+ async function refresh(deviceId: string, refreshTasks = true) {const host = byId.get(deviceId);if (!host?.online || !relayAvailable || !current()) return;+ if (refreshTasks) taskRefreshes.add(deviceId);+ refreshTasks ||= taskRefreshes.has(deviceId);// Reachability comes from the live device directory + relay, never from a list/API error.publish(snapshot.map(bot => bot.deviceId === deviceId ? { ...bot, online: true, connectionKnown: true } : bot));const epoch = (generations.get(deviceId) ?? 0) + 1;@@ -110,10 +122,33 @@ export function useRemoteBotSync(): void {[request],);if (!current() || generations.get(deviceId) !== epoch) return;+ const previous = new Map(snapshot.filter(bot => bot.deviceId === deviceId).map(bot => [bot.id, bot]));const bots = parseRemoteBots(result, deviceId, host.name).map((bot) => ({- ...bot, readAt: snapshot.find((old) => old.deviceId === deviceId && old.id === bot.id)?.readAt ?? bot.lastReplyAt ?? 0,+ ...bot,+ delegatedSessionIds: previous.get(bot.id)?.delegatedSessionIds,+ templateId: previous.get(bot.id)?.templateId,+ readAt: snapshot.find((old) => old.deviceId === deviceId && old.id === bot.id)?.readAt ?? bot.lastReplyAt ?? 0,}));publish([...snapshot.filter((bot) => bot.deviceId !== deviceId), ...bots]);+ // Older released hosts already expose the task-card list, even when their+ // directory has no task links. Read serially per host; never per task row.+ for (const bot of bots) {+ if (!current() || generations.get(deviceId) !== epoch) return;+ if (!bot.sessionId) continue;+ const old = previous.get(bot.id);+ if (!refreshTasks && old?.delegatedSessionIds !== undefined && old.sessionId === bot.sessionId) continue;+ try {+ const tasks = await window.electronAPI.deviceLink.invoke(+ deviceId, 'maker:bot-delegations:list', [bot.sessionId],+ );+ if (!current() || generations.get(deviceId) !== epoch) return;+ const created = remoteBotCreatedTaskIds(tasks, bot.id);+ if (created === null) continue;+ publish(snapshot.map(row => row.deviceId === deviceId && row.id === bot.id+ ? { ...row, delegatedSessionIds: created } : row));+ } catch { /* Keep this host's last known attribution on a temporary read failure. */ }+ }+ if (current() && generations.get(deviceId) === epoch) taskRefreshes.delete(deviceId);} catch {if (!current() || generations.get(deviceId) !== epoch) return;// Keep connection evidence and cached identity. An unsupported/failed@@ -128,17 +163,19 @@ export function useRemoteBotSync(): void {const offPush = window.electronAPI.deviceLink.onRemotePush((push, stamp) => {if (!current() ||- push.channel !== REMOTE_RESOURCE_CHANGED_CHANNEL ||+ (push.channel !== REMOTE_RESOURCE_CHANGED_CHANNEL && push.channel !== 'maker:bot-delegation:changed') ||!byId.has(push.deviceId) ||!isDeviceLinkRemotePushCurrent(push, stamp))return;+ if (push.channel === 'maker:bot-delegation:changed') taskRefreshes.add(push.deviceId);if (timers.has(push.deviceId)) return;timers.set(push.deviceId,setTimeout(() => {timers.delete(push.deviceId);- void refresh(push.deviceId);+ const refreshTasks = taskRefreshes.has(push.deviceId);+ void refresh(push.deviceId, refreshTasks);}, 500),);});@@ -172,6 +209,19 @@ export function useRemoteBotSync(): void {timers.forEach(clearTimeout);};}, [dataOwnerId, isAuthenticated, devices, revoked]);+ useEffect(() => {+ const api = companionCloudApi();+ const requestOwner = isAuthenticated ? dataOwnerId : null;+ if (!requestOwner || !cloud.enabled || !api?.listCindyCopies) return;+ let live = true;+ void api.listCindyCopies().then(copies => {+ if (!live || owner !== requestOwner) return;+ cindyIds = new Set(copies.map(copy => copy.botId));+ publish(snapshot);+ }).catch(() => { /* Cached template identity remains usable offline. */ });+ return () => { live = false; };+ }, [dataOwnerId, isAuthenticated, cloud.enabled, actorsKey]);+}export function markRemoteBotRead(deviceId: string, botId: string, at: number): void {diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex ea289ccc78..17e1bba537 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -1,3 +1,4 @@+import { matchesTaskCreators, useTaskCreatorIndex, useTaskCreatorOptions } from '@/features/bots/botFollowScopes';import { shouldShowOpenPathError } from '../../../shared/openPathResult';import { ErrorNotice } from '@/components/ui/error-notice';/**@@ -442,7 +443,8 @@ export function CCAgentSidebarUpper() {// F-PJ-10:filter.status 决定后端 fetch 时是否带 ?status=archived|allconst hiddenProjects = useHiddenProjects();const { hiddenProjectKeys, initialSnapshot: sidebarSettingsSnapshot } = hiddenProjects;- const filter = useSidebarFilter(hiddenProjectKeys, sidebarSettingsSnapshot);+ const creatorOptions = useTaskCreatorOptions();+ const filter = useSidebarFilter(hiddenProjectKeys, sidebarSettingsSnapshot, creatorOptions);const includeArchived = filter.status;const sessionsHook = useCCSessions({ includeArchived });const { sessions: allSessionsForAttentionRaw } = useCCSessions({ includeArchived: 'all' });@@ -1580,18 +1582,20 @@ function ExpandedView({[scopedSidebarSessions, hiddenProjectKeys, localPlatform],);+ const taskCreatorIndex = useTaskCreatorIndex();const activityFilteredSessions = useMemo(() => {const cutoff = cutoffForLastActivity(filter.lastActivity);- if (cutoff === null) return sidebarSessions;- return sidebarSessions.filter((s) => sessionActivityMs(s) >= cutoff);- }, [sidebarSessions, filter.lastActivity]);+ if (cutoff === null && filter.creators === 'all') return sidebarSessions;+ return sidebarSessions.filter((s) => (cutoff === null || sessionActivityMs(s) >= cutoff)+ && matchesTaskCreators(s, filter.creators, taskCreatorIndex));+ }, [sidebarSessions, filter.lastActivity, filter.creators, taskCreatorIndex]);const activityFilteredPersistentLocalProjects = useMemo(() =>filterPersistentLocalProjectsByLastActivity(- visiblePersistentLocalProjects,+ filter.creators === 'all' ? visiblePersistentLocalProjects : [],cutoffForLastActivity(filter.lastActivity),),- [filter.lastActivity, visiblePersistentLocalProjects],+ [filter.lastActivity, filter.creators, visiblePersistentLocalProjects],);/* ---- Grouping & collapse ---- */diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.tsindex 5f39f51b04..df029a5bb3 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts@@ -29,6 +29,9 @@ const log = createLogger('SidebarFilterCore');export const STATUS_KEY = 'cc-agent.sidebar.filter.status';export const PROJECTS_KEY = 'cc-agent.sidebar.filter.projects';+export const CREATORS_KEY = 'cc-agent.sidebar.filter.creators';+export type FilterCreators = 'all' | string[];+export const VENDOR_KEY = 'cc-agent.sidebar.filter.vendor';export const GROUP_BY_KEY = 'cc-agent.sidebar.filter.groupBy';export const GROUP_DIALOGUE_KEY = 'cc-agent.sidebar.filter.groupDialogue';@@ -142,6 +145,28 @@ export function loadProjects(ownerId: string | null): FilterProjects {return 'all';}+/** Creator keys contain both the computer and Bot identity, and are scoped to the signed-in owner. */+export function loadCreators(ownerId: string | null): FilterCreators {+ const raw = readSidebarOwnerStorage(CREATORS_KEY, ownerId);+ if (!raw) return 'all';+ try {+ const value: unknown = JSON.parse(raw);+ if (!Array.isArray(value)) return 'all';+ const keys = [...new Set(value.filter((key): key is string => typeof key === 'string' && key.length > 0))];+ return keys.length ? keys : 'all';+ } catch { return 'all'; }+}++export function persistCreators(value: FilterCreators, ownerId: string | null): void {+ writeSidebarOwnerStorage(CREATORS_KEY, ownerId, JSON.stringify(value));+}++export function nextCreatorsAfterToggle(previous: FilterCreators, key: string): FilterCreators {+ if (previous === 'all') return [key];+ const next = previous.includes(key) ? previous.filter(value => value !== key) : [...previous, key];+ return next.length ? next : 'all';+}+/* ============================== persist ============================== */export function persistStatus(s: FilterStatus): void {diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.tsindex a574feecb4..2edd08ea25 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts@@ -45,6 +45,8 @@import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { taskCreatorFilterKey } from '@/features/bots/cindyDeviceRoster';+import type { TaskBotIdentity } from '@/features/bots/botFollowScopes';import { createLogger } from '@/lib/logger';import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';import type { DataOwnerPushStamp } from '../../../../shared/dataOwnerPush';@@ -55,6 +57,10 @@ import {} from '../../../../shared/sidebarSettings';import {+ loadCreators,+ persistCreators,+ nextCreatorsAfterToggle,+ type FilterCreators,loadStatus,loadProjects,loadVendor,@@ -120,6 +126,10 @@ export {export interface UseSidebarFilterReturn {/** Status 维度(默认 'active')。 */status: FilterStatus;+ creators: FilterCreators;+ creatorOptions: readonly TaskBotIdentity[];+ toggleCreator: (key: string) => void;+ setCreatorsAll: () => void;/** Project 维度。'all' = 全部;string[] = 仅显示其中的 normalized workingDir。 */projects: FilterProjects;/** projects === 'all' 时返回 null,方便 render 阶段做"是否在集合内"判定。 */@@ -214,6 +224,7 @@ function isExactOwnerStampCurrent(export function useSidebarFilter(hiddenProjectKeys: ReadonlySet<string>,initialSnapshot: SidebarSettingsSnapshot,+ creatorOptions: readonly TaskBotIdentity[] = [],): UseSidebarFilterReturn {const ownerId = initialSnapshot.dataOwnerId;const ownerStamp = useMemo<DataOwnerPushStamp>(@@ -226,6 +237,31 @@ export function useSidebarFilter(const [loadedPinned] = useState(() => loadManualPinnedOrder(initialSnapshot));const [status, setStatusState] = useState<FilterStatus>(() => loadStatus());const [projects, setProjectsState] = useState<FilterProjects>(() => loadProjects(ownerId));+ const [storedCreators, setCreators] = useState<FilterCreators>(() => loadCreators(ownerId));+ const normalizeCreators = useCallback((selected: FilterCreators): FilterCreators => {+ if (selected === 'all') return selected;+ const aliases = new Map(creatorOptions.flatMap(bot => (bot.filterMemberKeys ?? [])+ .map(member => [member, taskCreatorFilterKey(bot)] as const)));+ const next = [...new Set(selected.map(key => aliases.get(key) ?? key))];+ return next.length === selected.length && next.every((key, i) => key === selected[i]) ? selected : next;+ }, [creatorOptions]);+ const creators = useMemo(() => normalizeCreators(storedCreators), [normalizeCreators, storedCreators]);+ useEffect(() => {+ if (creators === storedCreators) return;+ setCreators(creators);+ persistCreators(creators, ownerId);+ }, [creators, storedCreators, ownerId]);+ const toggleCreator = useCallback((key: string) => {+ setCreators(previous => {+ const next = nextCreatorsAfterToggle(normalizeCreators(previous), key);+ persistCreators(next, ownerId);+ return next;+ });+ }, [ownerId, normalizeCreators]);+ const setCreatorsAll = useCallback(() => {+ setCreators('all');+ persistCreators('all', ownerId);+ }, [ownerId]);const [vendor, setVendorState] = useState<FilterVendor>(() => loadVendor());const [lastActivity, setLastActivityState] = useState<FilterLastActivity>(() =>loadLastActivity(),@@ -524,6 +560,8 @@ export function useSidebarFilter(persistProjects('all', ownerId);return 'all';});+ setCreators('all');+ persistCreators('all', ownerId);setVendorState('all');persistVendor('all');setLastActivityState('all');@@ -602,11 +640,15 @@ export function useSidebarFilter();const isSessionContentFiltered =- status !== 'active' || projects !== 'all' || vendor !== 'all' || lastActivity !== 'all';+ status !== 'active' || projects !== 'all' || vendor !== 'all' || lastActivity !== 'all' || creators !== 'all';const isFilterActive = isSessionContentFiltered || groupBy !== 'project' || sortBy !== 'recency';return {+ creators,+ creatorOptions,+ toggleCreator,+ setCreatorsAll,status,projects,projectsAsSet,diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsxindex 703eae769d..2b875d3a4a 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx@@ -3,7 +3,7 @@* ---------------------------------------------------------------------------* 一级入口:分组 / 任务排序 / 项目排序 / 任务状态 / 筛选 / 显示 / 任务信息。* 每行显示当前设置,具体选项在子菜单中;任务排序直接三选一,优先级在前。- * 分组、排序保持原有语义;筛选只包含项目 / Harness / 最近活跃,不重置任务状态。+ * 分组、排序保持原有语义;筛选只包含项目 / 伙伴 / Harness / 最近活跃,不重置任务状态。** 入口仍复用 sliders-horizontal 图标;内容为行式菜单 + 子菜单。*@@ -48,10 +48,13 @@ import {LayoutList,SlidersHorizontal,Wallet,+ Users,type LucideIcon,} from 'lucide-react';import { useTranslation } from 'react-i18next';+import { BotAvatar } from '@/features/bots/BotAvatar';+import { taskCreatorFilterKey } from '@/features/bots/cindyDeviceRoster';import { cn } from '@/lib/utils';import { Tip } from '@/components/ui/tooltip';import { useSidebarMainViewMode, type SidebarMainViewMode } from '@/hooks/useSidebarCardMode';@@ -232,6 +235,7 @@ function MenuSubRow({valueNode,valueEmphasized = false,Icon,+ contentClassName,children,}: {label: string;@@ -246,13 +250,14 @@ function MenuSubRow({valueNode?: ReactNode;/** 偏离默认值时右侧摘要转正文色,提示筛选生效。 */valueEmphasized?: boolean;+ contentClassName?: string;children: ReactNode;}) {return (<DropdownMenuSub><DropdownMenuSubTrigger className={MENU_ROW_CLASS}><MenuItemIcon Icon={Icon} />- <span className="truncate">{label}</span>+ <span className="truncate" title={label}>{label}</span><spanclassName={cn('ml-auto max-w-[96px] truncate text-right',@@ -260,12 +265,13 @@ function MenuSubRow({)}// 图标摘要下把文字版留给读屏(图标本身 aria-hidden)。aria-label={valueNode ? value : undefined}+ title={valueNode ? undefined : value}>{valueNode ?? value}</span><ChevronRight size={14} className="shrink-0 text-[var(--cmd-palette-item-meta)]" /></DropdownMenuSubTrigger>- <DropdownMenuSubContent sideOffset={8} className="w-[220px]">+ <DropdownMenuSubContent sideOffset={8} className={cn('w-[220px]', contentClassName)}>{children}</DropdownMenuSubContent></DropdownMenuSub>@@ -380,6 +386,10 @@ export function SidebarFilterPopover({status,projects,projectsAsSet,+ creators,+ creatorOptions,+ toggleCreator,+ setCreatorsAll,isFilterActive,vendor,lastActivity,@@ -509,9 +519,15 @@ export function SidebarFilterPopover({? t('ccAgent.sidebar.filterAllText'): t('ccAgent.sidebar.filterSelectedProjects', { count: projects.length });+ const creatorValue = creators === 'all' ? t('ccAgent.sidebar.filterCreatorsAny')+ : creators.length === 1+ ? (creatorOptions.find(bot => taskCreatorFilterKey(bot) === creators[0])?.name+ ?? t('ccAgent.sidebar.filterSelectedCreators', { count: creators.length }))+ : t('ccAgent.sidebar.filterSelectedCreators', { count: creators.length });+// 一级「筛选」行摘要:偏离默认的维度数。const activeFilterCount =- (projects !== 'all' ? 1 : 0) + (vendor !== 'all' ? 1 : 0) + (lastActivity !== 'all' ? 1 : 0);+ (projects !== 'all' ? 1 : 0) + (vendor !== 'all' ? 1 : 0) + (lastActivity !== 'all' ? 1 : 0) + (creators !== 'all' ? 1 : 0);const filterSummary =activeFilterCount > 0? t('ccAgent.sidebar.filterSummaryActive', { count: activeFilterCount })@@ -537,6 +553,7 @@ export function SidebarFilterPopover({groupBy: groupByValue,sortBy: sortByValue,projects: projectValue,+ creators: creatorValue,});return (@@ -692,6 +709,7 @@ export function SidebarFilterPopover({value={filterSummary}valueEmphasized={activeFilterCount > 0}Icon={Filter}+ contentClassName="w-[280px]"><MenuSubRowlabel={t('ccAgent.sidebar.filterProjectsHeading')}@@ -784,6 +802,30 @@ export function SidebarFilterPopover({</div></MenuSubRow>+ <MenuSubRow label={t('ccAgent.sidebar.filterCreatorsHeading')} value={creatorValue} Icon={Users}>+ <SelectMenuItem label={t('ccAgent.sidebar.filterCreatorsAny')} selected={creators === 'all'}+ onSelect={setCreatorsAll} Icon={Users} />+ {creatorOptions.length > 0 && <DropdownMenuSeparator />}+ <div className="max-h-[256px] overflow-y-auto">+ {creatorOptions.map(bot => {+ const key = taskCreatorFilterKey(bot);+ return (+ <DropdownMenuItem key={key} className={cn(MENU_ITEM_CLASS, bot.deviceName && 'h-auto min-h-8 items-start')}+ role="menuitemcheckbox" aria-label={[bot.name, bot.deviceName].filter(Boolean).join(' ')} aria-checked={creators !== 'all' && creators.includes(key)}+ onSelect={event => { event.preventDefault(); toggleCreator(key); }}>+ <BotAvatar bot={bot} size="xs" />+ <span className="min-w-0 flex-1">+ <span className="block truncate" title={bot.name}>{bot.name}</span>+ {bot.deviceName && <span className="block truncate text-xs text-[var(--cmd-palette-item-meta)]" title={bot.deviceName}>{bot.deviceName}</span>}+ </span>+ {creators !== 'all' && creators.includes(key) &&+ <Check size={15} className={cn('shrink-0 text-[var(--msg-assistant-text)]', bot.deviceName && 'mt-0.5')} />}+ </DropdownMenuItem>+ );+ })}+ </div>+ </MenuSubRow>+<MenuSubRowlabel={t('ccAgent.sidebar.filterAgentHeading')}value={vendorValue}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsxindex 7a152da6a6..ec9a7ada91 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SidebarFilterPopover.test.tsx@@ -43,6 +43,10 @@ vi.mock('@cindy/maker-shared/project-order-sync', () => ({function makeFilter(overrides: Partial<UseSidebarFilterReturn> = {}): UseSidebarFilterReturn {return {+ creators: 'all',+ creatorOptions: [],+ toggleCreator: vi.fn(),+ setCreatorsAll: vi.fn(),status: 'active',projects: 'all',projectsAsSet: null,@@ -197,3 +201,19 @@ describe('sidebar display settings menu', () => {expect(filter.groupDevice).toBe(true);});});++it('keeps the creator submenu open for multiple selections and exposes an all reset', async () => {+ const filter = makeFilter({ creators: ['[null,"a"]'], creatorOptions: [+ { id: 'a', name: 'Dash', avatar: '', avatarColor: 'blue' },+ { id: 'a', name: 'Dash', deviceId: 'remote', deviceName: 'Laptop', avatar: '', avatarColor: 'blue' },+ ] });+ render(<Preview filter={filter} />);+ await openSubmenu(/^筛选/);+ const submenu = await openSubmenu(/^伙伴/);+ expect(within(submenu).getByRole('menuitemcheckbox', { name: 'Dash' }).getAttribute('aria-checked')).toBe('true');+ fireEvent.click(within(submenu).getByRole('menuitemcheckbox', { name: 'Dash Laptop' }));+ expect(filter.toggleCreator).toHaveBeenCalledWith('["remote","a"]');+ expect(screen.getAllByRole('menu')).toHaveLength(3);+ fireEvent.click(within(submenu).getByRole('menuitem', { name: '不限来源' }));+ expect(filter.setCreatorsAll).toHaveBeenCalledOnce();+});diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex a0a197a3d6..e94abcb223 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -18,6 +18,7 @@import { projectScheduleSidebarIndex } from '../scheduler/lib/projectScheduleSidebarIndex';import { parseScheduleBindings } from '../scheduler/lib/scheduleBindingIndex';import type { ScheduleSidebarIndexSnapshot } from '../scheduler/lib/scheduleSidebarIndexRuns';+import { isTeammateTaskSession } from '../../../shared/sessionSource';import type { Session } from '@/lib/ccAgent.types';import { createLogger } from '@/lib/logger';import { extractIpcError } from '@/utils/ipcError';@@ -114,6 +115,41 @@ function parseRemoteSessionList(value: unknown, expectedStatus: RemoteSessionStareturn value as unknown as Session[];}+/** Old hosts omit teammate lanes from sessions:list; their owner-authorized history API already exposes exact links. */+async function readRemoteTeammateTasks(+ deviceId: string, status: RemoteSessionStatus, limit: number, current: () => boolean,+): Promise<Session[]> {+ const links = new Map<string, NonNullable<Session['companion']>>();+ const cursors = new Set<string>();+ let cursor: string | undefined;+ try {+ do {+ if (!current()) return [];+ const response = await window.electronAPI.deviceLink.invoke(deviceId, 'local-db:history:query', [{+ tool: 'list_sessions', args: { source: 'bot', time_field: 'activity', limit: 200, ...(cursor ? { cursor } : {}) },+ }]) as { ok?: boolean; sessions?: Array<{ id?: unknown; status?: unknown; source?: unknown; companion?: Session['companion'] }>; hasMore?: boolean; nextCursor?: string };+ if (!current() || response?.ok !== true || !Array.isArray(response.sessions)) return [];+ for (const row of response.sessions) {+ if (typeof row.id === 'string' && row.status === status && isTeammateTaskSession(row)+ && typeof row.companion?.id === 'string') links.set(row.id, row.companion);+ }+ if (!response.hasMore || links.size >= limit) break;+ if (!response.nextCursor || cursors.has(response.nextCursor)) return [];+ cursor = response.nextCursor;+ cursors.add(cursor);+ } while (current());+ if (!current() || links.size === 0) return [];+ const rows = await readSessionBatch([...links.keys()].slice(0, limit), deviceId);+ if (!current()) return [];+ return rows.flatMap(({ sessionId, value }) => value && value.source === 'bot' && value.status === status+ ? [{ ...value, companion: links.get(sessionId)! }] : []);+ } catch (error) {+ if (String(error).includes(ACCESS_REVOKED_MARKER)) throw error;+ // Unsupported/offline history must not replace ordinary tasks or cached companion rows.+ return [];+ }+}+/** 退避:250ms 起指数增长,封顶 3000ms。 */function backoffMs(attempt: number): number {return Math.min(250 * 2 ** attempt, 3000);@@ -370,7 +406,11 @@ async function runRefreshRemoteDeviceSessions(// 乱序保护:本次拉取已不是最新一次 → 丢弃,别覆盖更新的结果。if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status))return 'superseded';- const sessions = parseRemoteSessionList(value, status);+ const ordinary = parseRemoteSessionList(value, status);+ const teammateTasks = await readRemoteTeammateTasks(deviceId, status, listLimit,+ () => remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status));+ if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status)) return 'superseded';+ const sessions = [...new Map([...teammateTasks, ...ordinary].map(session => [session.id, session])).values()];// Companions are fetched by resource:get + sessions:get, not by the// ordinary task list. Keep their live state and reconcile them by id,// even when the ordinary list is empty or is a full replacement.diff --git a/apps/desktop/src/renderer/features/device-link/selectedMachineStore.ts b/apps/desktop/src/renderer/features/device-link/selectedMachineStore.tsindex 083669324d..07b9dc1dc2 100644--- a/apps/desktop/src/renderer/features/device-link/selectedMachineStore.ts+++ b/apps/desktop/src/renderer/features/device-link/selectedMachineStore.ts@@ -1,3 +1,4 @@+import { isOrdinaryTaskListSession } from '../../../shared/sessionSource';/*** selectedMachineStore —— 控制端「机器切换栏」当前选择态(device-link 远程机器切换)。* ---------------------------------------------------------------------------@@ -206,7 +207,7 @@ export function selectVisibleSessions(selection: MachineSelection,): Session[] {// Attached task metadata remains readable in the mirror but has its own entry.- const isOrdinaryTask = (session: Session) => session.source !== 'bot' && session.source !== 'side-chat';+ const isOrdinaryTask = isOrdinaryTaskListSession;const visibleLocal = localSessions.filter(isOrdinaryTask);const visibleRemote = remoteSessions.filter(isOrdinaryTask);if (selection === MACHINE_ALL) return [...visibleLocal, ...visibleRemote];diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 46e29467ea..320fecafae 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9228,6 +9228,8 @@},"bots": {"workbench": {+ "ownedMark": "Belongs to {{names}}",+ "createdMark": "Created by {{names}}","followingMark": "This task is looked after by {{names}}"},"glance": {@@ -13043,7 +13045,7 @@"selectFolderFailed": "Could not select folder. Try again.","projectsToggleExpand": "Expand all project sessions","projectsToggleCollapse": "Collapse all project sessions",- "filterAria": "Sidebar settings (Status: {{status}}, Harness: {{vendor}}, Last activity: {{lastActivity}}, Group by: {{groupBy}}, Sort by: {{sortBy}}, Projects: {{projects}})",+ "filterAria": "Sidebar settings (Status: {{status}}, Harness: {{vendor}}, Last activity: {{lastActivity}}, Group by: {{groupBy}}, Sort by: {{sortBy}}, Projects: {{projects}}, Teammates: {{creators}})","organizeSidebar": "Sidebar settings","filterAllText": "all","filterSelectedProjects": "{{count}} selected",@@ -13108,6 +13110,9 @@"filterProjectOrderTip": {"custom": "Drag project rows with the mouse to reorder. Sessions inside still follow the sort above."},+ "filterCreatorsHeading": "Teammates",+ "filterCreatorsAny": "Any source",+ "filterSelectedCreators": "{{count}} selected","filterProjectsHeading": "Projects","filterAllProjects": "All projects","filterHeading": "Filters",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 33a1a4a002..b7d6dff080 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9196,6 +9196,8 @@},"bots": {"workbench": {+ "ownedMark": "担当:{{names}}",+ "createdMark": "{{names}} が作成","followingMark": "このセッションの担当: {{names}}"},"glance": {@@ -12989,7 +12991,7 @@"selectFolderFailed": "フォルダーを選択できませんでした。もう一度お試しください。","projectsToggleExpand": "すべてのプロジェクトセッションを展開","projectsToggleCollapse": "すべてのプロジェクトセッションを折りたたむ",- "filterAria": "サイドバー表示設定(ステータス:{{status}}、Harness:{{vendor}}、最終アクティビティ:{{lastActivity}}、グループ:{{groupBy}}、並び替え:{{sortBy}}、プロジェクト:{{projects}})",+ "filterAria": "サイドバー表示設定(ステータス:{{status}}、Harness:{{vendor}}、最終アクティビティ:{{lastActivity}}、グループ:{{groupBy}}、並び替え:{{sortBy}}、プロジェクト:{{projects}}、チームメイト:{{creators}})","organizeSidebar": "サイドバー表示設定","filterAllText": "すべて","filterSelectedProjects": "{{count}} 件選択",@@ -13054,6 +13056,9 @@"filterProjectOrderTip": {"custom": "マウスでプロジェクト行をドラッグして並び替え。中のセッションは上の並び替えに従う"},+ "filterCreatorsHeading": "チームメイト",+ "filterCreatorsAny": "作成元を問わない",+ "filterSelectedCreators": "{{count}} 人を選択","filterProjectsHeading": "プロジェクト","filterAllProjects": "すべてのプロジェクト","filterHeading": "フィルター",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex d79b3ed3d2..cb9988d8c2 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9196,6 +9196,8 @@},"bots": {"workbench": {+ "ownedMark": "담당: {{names}}",+ "createdMark": "{{names}} 님이 생성","followingMark": "이 세션 담당: {{names}}"},"glance": {@@ -12989,7 +12991,7 @@"selectFolderFailed": "폴더를 선택하지 못했습니다. 다시 시도해 주세요.","projectsToggleExpand": "모든 프로젝트 세션 펼치기","projectsToggleCollapse": "모든 프로젝트 세션 접기",- "filterAria": "사이드바 표시 설정(상태: {{status}}, Harness: {{vendor}}, 최근 활동: {{lastActivity}}, 그룹: {{groupBy}}, 정렬: {{sortBy}}, 프로젝트: {{projects}})",+ "filterAria": "사이드바 표시 설정(상태: {{status}}, Harness: {{vendor}}, 최근 활동: {{lastActivity}}, 그룹: {{groupBy}}, 정렬: {{sortBy}}, 프로젝트: {{projects}}, 팀원: {{creators}})","organizeSidebar": "사이드바 표시 설정","filterAllText": "전체","filterSelectedProjects": "{{count}}개 선택됨",@@ -13054,6 +13056,9 @@"filterProjectOrderTip": {"custom": "마우스로 프로젝트 행을 끌어 순서를 바꿉니다. 안의 세션은 위 정렬을 따릅니다."},+ "filterCreatorsHeading": "팀원",+ "filterCreatorsAny": "생성자 제한 없음",+ "filterSelectedCreators": "{{count}}명 선택","filterProjectsHeading": "프로젝트","filterAllProjects": "모든 프로젝트","filterHeading": "필터",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 88fd2309e8..5ee9f935cb 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9196,6 +9196,8 @@},"bots": {"workbench": {+ "ownedMark": "归属 {{names}}",+ "createdMark": "由 {{names}} 创建","followingMark": "{{names}}在跟进这个任务"},"glance": {@@ -12989,7 +12991,7 @@"selectFolderFailed": "选择目录失败,请重试","projectsToggleExpand": "展开所有项目任务","projectsToggleCollapse": "收起所有项目任务",- "filterAria": "侧边栏显示设置(状态:{{status}},Harness:{{vendor}},最近活跃:{{lastActivity}},分组:{{groupBy}},排序:{{sortBy}},项目:{{projects}})",+ "filterAria": "侧边栏显示设置(状态:{{status}},Harness:{{vendor}},最近活跃:{{lastActivity}},分组:{{groupBy}},排序:{{sortBy}},项目:{{projects}},伙伴:{{creators}})","organizeSidebar": "侧边栏显示设置","filterAllText": "全部","filterSelectedProjects": "已选 {{count}} 个",@@ -13054,6 +13056,9 @@"filterProjectOrderTip": {"custom": "用鼠标拖动项目行调整顺序,组内任务仍按上面的排序"},+ "filterCreatorsHeading": "伙伴",+ "filterCreatorsAny": "不限来源",+ "filterSelectedCreators": "已选 {{count}} 位","filterProjectsHeading": "项目","filterAllProjects": "所有项目","filterHeading": "筛选",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 2d119bbbea..eef31a761e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9196,6 +9196,8 @@},"bots": {"workbench": {+ "ownedMark": "所屬夥伴:{{names}}",+ "createdMark": "由 {{names}} 建立","followingMark": "{{names}}在跟進這個任務"},"glance": {@@ -12989,7 +12991,7 @@"selectFolderFailed": "選擇目錄失敗,請重試","projectsToggleExpand": "展開所有專案任務","projectsToggleCollapse": "收起所有專案任務",- "filterAria": "側邊欄顯示設定(狀態:{{status}},Harness:{{vendor}},最近活躍:{{lastActivity}},分組:{{groupBy}},排序:{{sortBy}},專案:{{projects}})",+ "filterAria": "側邊欄顯示設定(狀態:{{status}},Harness:{{vendor}},最近活躍:{{lastActivity}},分組:{{groupBy}},排序:{{sortBy}},專案:{{projects}},夥伴:{{creators}})","organizeSidebar": "側邊欄顯示設定","filterAllText": "全部","filterSelectedProjects": "已選 {{count}} 個",@@ -13054,6 +13056,9 @@"filterProjectOrderTip": {"custom": "用滑鼠拖動專案列調整順序,組內任務仍按上面的排序"},+ "filterCreatorsHeading": "夥伴",+ "filterCreatorsAny": "不限來源",+ "filterSelectedCreators": "已選 {{count}} 位","filterProjectsHeading": "專案","filterAllProjects": "所有專案","filterHeading": "篩選",diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex a62d3cf3f4..24d7480579 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -393,6 +393,8 @@ export interface Session {agentKind: AgentKind;/** 会话来源。scheduler 表示由自动化任务创建;缺失时按 desktop 兼容旧 payload。 */source?: SessionSource;+ /** Host-owned teammate link, also used by the existing history API. Display only. */+ companion?: { id: string; role: string; channel?: string } | null;/** Orca split-session role marker. null/undefined means a regular Maker session. */orcaRole?: OrcaRole | null;/** fork-session:派生来源会话 id(self-FK,源被删 → SET NULL)。null = 顶层会话。 */diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.tsindex f15c3eba95..291f8ba181 100644--- a/apps/desktop/src/renderer/lib/sessionsStore.ts+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts@@ -1,3 +1,4 @@+import { isOrdinaryTaskListSession } from '../../shared/sessionSource';import { emitTaskTagCatalog } from '@/features/task-tags/taskTagEvents';import { normalizeTaskTags, reconcileTaskTags } from '@cindy/maker-shared';/**@@ -1126,12 +1127,9 @@ export const sessionsStore = {*/prependCreated(session: Session): void {if (!session?.id) return;- // Bot canonical sessions have their own sidebar/history projection. They must- // never leak into the regular desktop Session cache through the optimistic- // prepend path (the IPC list already excludes source='bot').- if (session.source === 'bot') return;- // /review 审查任务同样不进普通任务列表,只从来源任务的审查卡片打开。- if (session.source === 'review') return;+ // Canonical/private companion chats keep their own entry; linked routine and+ // channel tasks share the ordinary list, matching the host projection.+ if (!isOrdinaryTaskListSession(session)) return;// 已转入后台的任务不经本地插入回到列表。if (hiddenSessionIds.has(session.id)) return;// 插入前叠乐观预览:createSession 往往先于 sessions:created 刷新返回,但预览diff --git a/apps/desktop/src/shared/botTemplatePreset.ts b/apps/desktop/src/shared/botTemplatePreset.tsindex dd3d2c3685..a368500679 100644--- a/apps/desktop/src/shared/botTemplatePreset.ts+++ b/apps/desktop/src/shared/botTemplatePreset.ts@@ -1,55 +1,2 @@-export const BOT_TEMPLATE_PRESET_IDS = ['cindy'] as const;--export type BotTemplatePresetId = (typeof BOT_TEMPLATE_PRESET_IDS)[number];--export const BOT_TEMPLATE_PRESET_AVATARS: Record<BotTemplatePresetId, string> = {- cindy: 'cindy://avatar/preset/cindy',-};--/**- * 仅保留旧 Cindy 的精确身份指纹,以识别默认伙伴而不重复创建。用户改过- * SOUL 后不再根据姓名或头像猜测身份;已建立的其它伙伴不依赖模板运行。- */-export const BOT_TEMPLATE_PRESET_IDENTITIES: Record<BotTemplatePresetId, string> = {- cindy: [- '# 身份\n你是 Cindy 助理,负责处理用户日常工作与生活中的大部分 AI 需求。',- '# 主要职责\n写作、整理、分析、计划、资料制作和事务推进;遇到更适合由专业伙伴处理的工作时,主动请对方接手并带回结果。',- '# 擅长处理\n邮件与文案、资料归纳、方案梳理、日程与行动计划、跨事项协调,以及把零散输入整理成可继续使用的文档。',- '# 做事方式\n先理解用户真正要得到的结果;简单工作直接完成,复杂工作拆清楚后推进。对外只用自然语言描述协作,不暴露内部技术名词。',- '# 判断标准\n结果是否准确、完整、容易继续使用;是否在需要时找到了更合适的伙伴,而没有把协调负担留给用户。',- '# 输出格式\n先给结论或成品,再补必要说明。需要留档、分享或继续编辑时,形成正式文档。',- '# 需要确认的情况\n涉及不可逆操作、对外发送、费用、权限或会显著改变目标的取舍时先确认。',- '# 不应该做的事\n不虚构事实,不把不确定判断说成结论,不用 Bot、Session、Worker、MCP、harness 等内部词汇向用户解释工作。',- ].join('\n\n'),-};--/** Previous default: recognition only; never rewrite an existing SOUL. */-const PREVIOUS_CINDY_DEFAULT_IDENTITY = [- '# 身份\n你是 Cindy,Cindy 客户端里的默认伙伴。你帮助用户使用客户端和已连接的工具完成工作;你不是整个客户端,也不代替用户拥有账号和权限。',- '# 工作\n处理写作、整理、分析、计划和日常事务。简单工作直接完成;编码实施和中大型工作使用独立任务,跟进结果并核对后交付。伙伴间消息用于必要沟通,不代替独立任务。',- '# 方式\n先理解用户想得到的结果,再用实际可用的工具行动。需要外部服务时先查已安装插件并复用已有连接;按宿主提供的授权卡完成缺失的连接。',- '# 相处\n表达自然、简洁、具体。保留用户已给出的要求和授权;不编造背景、能力或完成状态,不反复询问已经明确的事情。',-].join('\n\n');--/** New installations; the legacy identity above remains an exact migration fingerprint. */-export const CINDY_DEFAULT_IDENTITY = [- '# 身份\n你是 Cindy,Cindy 客户端里的默认伙伴。你帮助用户使用客户端和已连接的工具完成工作;你不是整个客户端,也不代替用户拥有账号和权限。',- '# 工作\n处理写作、整理、分析、计划和日常事务。优先在当前对话完成工作;需要独立执行时按当前工具指引开任务,跟进并核对结果。',- '# 方式\n先理解用户想得到的结果,再用实际可用的工具行动。需要外部服务时先查已安装插件并复用已有连接;按宿主提供的授权卡完成缺失的连接。',- '# 相处\n表达自然、简洁、具体。保留用户已给出的要求和授权;不编造背景、能力或完成状态,不反复询问已经明确的事情。',-].join('\n\n');--export function inferBotTemplatePresetId(identitySource: string): BotTemplatePresetId | null {- if (identitySource === CINDY_DEFAULT_IDENTITY || identitySource === PREVIOUS_CINDY_DEFAULT_IDENTITY) return 'cindy';- return (- BOT_TEMPLATE_PRESET_IDS.find(- (templateId) => BOT_TEMPLATE_PRESET_IDENTITIES[templateId] === identitySource,- ) ?? null- );-}--export function isBotTemplatePresetId(value: unknown): value is BotTemplatePresetId {- return (- typeof value === 'string' && (BOT_TEMPLATE_PRESET_IDS as readonly string[]).includes(value)- );-}+// Shared exact identity fingerprints; Desktop keeps this import path for existing callers.+export * from '@cindy/maker-shared/bot-template-preset';diff --git a/apps/desktop/src/shared/sessionSource.ts b/apps/desktop/src/shared/sessionSource.tsindex 25680ef8d1..eac43b4b4c 100644--- a/apps/desktop/src/shared/sessionSource.ts+++ b/apps/desktop/src/shared/sessionSource.ts@@ -69,8 +69,8 @@ export function isReviewSessionSource(source: unknown): source is 'review' {// shared: .xdtshare 导入的分享会话,按 workingDir 归组。// plugin: 插件经 workspace 槽创建的工作区会话入口(空 draft,用户确认后建;// projectGrouping 对零消息的 plugin 会话豁免草稿判定,直接落项目分组)。-// bot: 伙伴的任务(主对话 / 渠道 / 历史)。由 Bots 面板投影,不散进普通任务列表;-// 任务本身仍是 Cindy 的真实 Session,隐藏的是普通列表投影,不是运行时能力。+// bot: 伙伴任务通过 bot_session_links 区分:routine/channel 进普通任务列表并标归属;+// canonical/thread/group 保留伙伴入口。不能仅按 source 把所有伙伴任务放入列表。// cindy-make: /cindy-make 弹窗选择制作个人版后创建的代码任务,工作目录是 Cindy 受管// 源码。Main 据此注入 cindy_make 工具与任务说明;按 workingDir 归到源码项目分组。export const DESKTOP_VISIBLE_SESSION_SOURCES: SessionSource[] = [@@ -121,3 +121,13 @@ export function normalizeSessionSource(source: unknown): SessionSource {? source: 'desktop';}++/** Standalone teammate work requested in the task list; main chats and private/group threads keep their own entries. */+export function isTeammateTaskSession(session: { source?: unknown; companion?: { role?: unknown } | null }): boolean {+ return session.source === 'bot' && (session.companion?.role === 'routine' || session.companion?.role === 'channel');+}++export function isOrdinaryTaskListSession(session: { source?: unknown; companion?: { role?: unknown } | null }): boolean {+ return session.source !== 'side-chat' && session.source !== 'review'+ && (session.source !== 'bot' || isTeammateTaskSession(session));+}diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsxindex 1f32dbf15e..eb738f095f 100644--- a/apps/mobile/app/devices/[deviceId].tsx+++ b/apps/mobile/app/devices/[deviceId].tsx@@ -1,3 +1,5 @@+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';+import { readTeammateTasks } from '@/session/readTeammateTasks';import { deviceDisplayName } from '@/device-link/deviceName';import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';import { withNewSessionCreationRemoval } from '@/session/newSessionCreation';@@ -327,7 +329,8 @@ function DeviceDetailScreenContent() {const syncSessions = useCallback(async () => {if (!deviceId) return;- const isCurrentQuery = () => listQueryScopeRef.current === listQueryScope;+ const owner = getMobileAuthOwner();+ const isCurrentQuery = () => listQueryScopeRef.current === listQueryScope && isMobileAuthOwnerCurrent(owner);if (!isCurrentQuery()) return;setLoading(true);setError(null);@@ -335,7 +338,7 @@ function DeviceDetailScreenContent() {const mutationEpoch = remoteSessionStore.captureDeviceSessionListMutationEpoch(deviceId);const list = await withTransientRemoteRetry(async () => {await subscribe(`device:${deviceId}`, deviceId, ['sessions']);- return invoke<RemoteSession[]>(deviceId, 'local-db:sessions:list', [+ const sessions = await invoke<RemoteSession[]>(deviceId, 'local-db:sessions:list', [LIST_LIMIT,// 自动化任务作用域页承诺展示"该任务的全部 N 次运行",归档的 run 也算,// 必须拉全量;其余模式仍按当前筛选拉取。@@ -343,6 +346,10 @@ function DeviceDetailScreenContent() {// 首拉 / reseed / 筛选重拉都是权威快照,不并入被控端写前查询。{ includePinned: true, fresh: true },]);+ return readTeammateTasks({ invoke, deviceId, deviceName, scope: JSON.stringify([owner, deviceId, listQueryScope]),+ sessions: Array.isArray(sessions) ? sessions : [], previous: remoteSessionStore.getHomeSessions(),+ status: requestedListFilter, limit: LIST_LIMIT, current: isCurrentQuery,+ });});if (!isCurrentQuery()) return;if (!remoteSessionStore.isDeviceSessionListMutationEpochCurrent(deviceId, mutationEpoch)) {diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.tsindex c176fe5ad4..f1caf9e17d 100644--- a/apps/mobile/src/__tests__/chatServerClient.test.ts+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts@@ -489,3 +489,17 @@ it('projects waiting and stopping executions without inventing task IDs or losin[id(30), 'needs_input', null], [id(31), 'stopping', null],]);});++// Unit: cross-device Cindy filters use profile identity, including exact legacy presets.+it('reads Cindy preset identity without inferring from names and retains known IDs on transient failure', async () => {+ const { CINDY_DEFAULT_IDENTITY } = await import('@cindy/maker-shared/bot-template-preset');+ const request = vi.fn(async (_path: string, _method?: string, _body?: unknown, actorId?: string) => {+ if (actorId === id(4)) throw new Error('offline');+ return [{ key: 'companion.profile.v1', value: actorId === id(1) ? { templateId: 'cindy' }+ : actorId === id(2) ? { soul: CINDY_DEFAULT_IDENTITY } : { name: 'Cindy', soul: 'custom' } }];+ });+ const actors = [1, 2, 3, 4].map(n => ({ id: id(n), externalId: `bot-${n}`, kind: 'bot', name: 'Cindy', avatar: null, homeDeviceId: 'mac' }));+ const ids = await createChatServerClient(request as any).cindyCompanionIds(actors, ['bot-4']);+ expect(ids).toEqual(['bot-1', 'bot-2', 'bot-4']);+ expect(request.mock.calls.every(call => call[0] === '/preferences' && call[1] === 'GET')).toBe(true);+});diff --git a/apps/mobile/src/__tests__/homeChromeMenus.test.ts b/apps/mobile/src/__tests__/homeChromeMenus.test.tsindex c1deb80fa0..dbe13ec916 100644--- a/apps/mobile/src/__tests__/homeChromeMenus.test.ts+++ b/apps/mobile/src/__tests__/homeChromeMenus.test.ts@@ -222,6 +222,21 @@ describe("home chrome menus", () => {expect(find(build({ taskInfoFields: [] }), "taskInfo")?.subtitle).toBe("devices.list.menu.summaryNone");});+ it("selects multiple teammates and explicitly returns to any source", () => {+ const options = [{ key: "cindy", title: "Cindy" }, { key: "filo", title: "Filo" }];+ let state = { ...displayState };+ for (const key of ["cindy", "filo"]) state = { ...state, ...homeDisplayActionPatch(`filter.teammate:${key}`, state) };+ const actions = buildHomeDisplayPullDownActions({ state, teammates: options, projects: [], dialogueCount: 0, t });+ expect(state.teammateFilter).toEqual(["cindy", "filo"]);+ expect(find(actions, "filter.teammates.all")?.state).toBe("off");+ expect(find(actions, "filter.teammate:cindy")).toMatchObject({ state: "on", keepPresented: true });+ expect(find(actions, "filter.teammate:filo")?.state).toBe("on");+ state = { ...state, ...homeDisplayActionPatch("filter.teammate:cindy", state) };+ state = { ...state, ...homeDisplayActionPatch("filter.teammate:filo", state) };+ expect(state.teammateFilter).toBe("all");+ expect(homeDisplayActionPatch("filter.teammates.all", { ...state, teammateFilter: ["cindy"] })).toEqual({ teammateFilter: "all" });+ });+it("maps menu actions to preference patches", () => {expect(homeDisplayActionPatch("group.dialogue", displayState)).toEqual({ groupDialogue: true });expect(homeDisplayActionPatch("group.project", displayState)).toEqual({ groupByProject: false });@@ -238,6 +253,7 @@ describe("home chrome menus", () => {expect(homeDisplayActionPatch("filter.reset", displayState)).toEqual({lastActivityFilter: "all",projectFilter: "all",+ teammateFilter: "all",vendorFilter: "all",});expect(homeDisplayActionPatch("view.text", displayState)).toEqual({ viewMode: "text" });diff --git a/apps/mobile/src/__tests__/homeDisplaySettings.test.ts b/apps/mobile/src/__tests__/homeDisplaySettings.test.tsindex 8bdaf6fbf0..455190207d 100644--- a/apps/mobile/src/__tests__/homeDisplaySettings.test.ts+++ b/apps/mobile/src/__tests__/homeDisplaySettings.test.ts@@ -79,6 +79,17 @@ describe('home content filters (desktop 筛选 parity)', () => {],});+ it('filters by multiple teammate identities, preserves pinned rows and excludes unknown shared owners', () => {+ const filters: HomeContentFilters = { ...NO_FILTERS, teammates: ['cindy', 'filo'],+ teammateKey: row => row.session.id === 'chat-cc' ? 'cindy' : row.session.id === 'p2-pi' ? 'filo' : undefined };+ const result = applyHomeContentFilters(fixture, filters, NOW);+ expect(result.chats.map(row => row.session.id)).toEqual(['chat-cc']);+ expect(result.projects.map(row => row.key)).toEqual(['p2']);+ expect(result.pinned).toBe(fixture.pinned);+ expect(activeContentFilterCount(filters)).toBe(1);+ expect(filterSharedHomeRows([{ id: 'unknown' }, { id: 'known', item: item('chat-cc') }], filters, NOW).map(row => row.id)).toEqual(['known']);+ });+it('returns the same presentation when nothing is filtered', () => {expect(applyHomeContentFilters(fixture, NO_FILTERS, NOW)).toBe(fixture);expect(activeContentFilterCount(NO_FILTERS)).toBe(0);@@ -212,7 +223,7 @@ describe('task info and retained Home behavior', () => {it('counts each dialogue automation run in the actual display-menu input', () => {const projectFilterUniverse = { chats: [item('normal'), { ...item('automation'), automationGroup: { sessionCount: 4 } }], projects: [] };const options = surfaceValue('homeDisplayPullDownActions', { useMemo, projectFilterUniverse,- selectedDeviceId: null, displayMenuState: {}, t: (key: string) => key,+ selectedDeviceId: null, teammateOptions: [], displayMenuState: {}, t: (key: string) => key,buildHomeDisplayPullDownActions: (value: unknown) => value });expect(options.dialogueCount).toBe(5);});diff --git a/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts b/apps/mobile/src/__tests__/homeViewPreferenceStore.test.tsindex 50e28441a1..8811338421 100644--- a/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts+++ b/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts@@ -26,6 +26,8 @@ const defaultPrefs = {manualProjectOrder: [],projectFilter: 'all',projectFilterOwner: '',+ teammateFilter: 'all',+ teammateFilterOwner: '',vendorFilter: 'all',lastActivityFilter: 'all',viewMode: 'list',@@ -33,6 +35,14 @@ const defaultPrefs = {} as const;describe('homeViewPreferenceStore', () => {+ it('persists teammate multi-selection for its owner and resets without changing project choices', async () => {+ const { saveHomeViewPreferences, readHomeViewPreferences } = await import('@/session/homeViewPreferenceStore');+ await saveHomeViewPreferences({ teammateFilter: { owner: OWNER, value: ['cindy', 'filo'] }, projectFilter: { owner: OWNER, value: ['project'] } });+ expect((await readHomeViewPreferences(OWNER)).teammateFilter).toEqual(['cindy', 'filo']);+ expect((await readHomeViewPreferences('another-owner')).teammateFilter).toBe('all');+ await saveHomeViewPreferences({ teammateFilter: { owner: OWNER, value: 'all' } });+ expect(await readHomeViewPreferences(OWNER)).toMatchObject({ teammateFilter: 'all', projectFilter: ['project'] });+ });it('does not overwrite saved grouping when the merge read fails', async () => {const { saveHomeViewPreferences, readHomeViewPreferences } = await import('@/session/homeViewPreferenceStore');await saveHomeViewPreferences({ groupByProject: false, groupDialogue: true });@@ -117,6 +127,8 @@ describe('homeViewPreferenceStore', () => {};await expect(readHomeViewPreferences(OWNER)).resolves.toEqual({...expected,+ teammateFilter: 'all',+ teammateFilterOwner: '',selectedDevice: { deviceId: 'devA', name: 'Mac A' },});expect(JSON.parse(store.get(__testing.storageKey) ?? '{}')).toEqual({diff --git a/apps/mobile/src/__tests__/mobileHomeListCache.test.ts b/apps/mobile/src/__tests__/mobileHomeListCache.test.tsindex 3c9991e78c..e587965ffc 100644--- a/apps/mobile/src/__tests__/mobileHomeListCache.test.ts+++ b/apps/mobile/src/__tests__/mobileHomeListCache.test.ts@@ -61,6 +61,15 @@ describe('mobileHomeListCache', () => {vi.useRealTimers();});+ it('retains lane ownership and creator avatars across cold starts', async () => {+ const { getCachedHomeListSnapshot, cacheHomeListSnapshot } = await import('@/session/mobileHomeListCache');+ const companion = { id: 'cindy-default', role: 'routine' };+ const taskTeammate = { id: 'cindy-default', name: 'Cindy', avatar: { kind: 'asset', value: 'cindy://avatar/preset/cindy', fallbackText: 'C' } };+ await cacheHomeListSnapshot(USER_ID, [makeSession('routine', 'mac', { source: 'bot', companion, taskTeammate })]);+ const [cached] = await getCachedHomeListSnapshot(USER_ID);+ expect(cached.sessions[0]).toMatchObject({ companion, taskTeammate });+ });+it('round-trips a grouped device snapshot from a flat stamped session list', async () => {const { cacheHomeListSnapshot, getCachedHomeListSnapshot } = await import('@/session/mobileHomeListCache');diff --git a/apps/mobile/src/__tests__/readTeammateTasks.test.ts b/apps/mobile/src/__tests__/readTeammateTasks.test.tsnew file mode 100644index 0000000000..f1322f7894--- /dev/null+++ b/apps/mobile/src/__tests__/readTeammateTasks.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it, vi } from 'vitest';+import { REMOTE_RESOURCE_LIST_CHANNEL } from '@cindy/device-link';+import type { RemoteInvoke } from '@/device-link/mobileMakerTransport';+import { readTeammateTasks } from '@/session/readTeammateTasks';+import { normalizeTaskTeammateSelection, taskTeammateKey, taskTeammateOptions } from '@/session/teammateTaskSource';+import type { RemoteSession } from '@/session/types';+import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';++// Unit: missing mobile attribution/old-host lanes. Exercise the real reader and batch+// transport with one ordinary task, canonical chat, routine and channel; no timers.+const task = (id: string, patch: Partial<RemoteSession> = {}) => ({ id, title: id, status: 'active', source: 'cc', ...patch } as RemoteSession);+const bot = (id = 'cindy-default') => ({ ref: { collectionId: 'teammates', kind: 'bot', id },+ revision: '1', display: { title: 'Cindy', avatar: { kind: 'asset', value: 'cindy://avatar/preset/cindy', fallbackText: 'C' } },+ links: [{ rel: 'conversation', target: { kind: 'session', sessionId: 'canonical' } },+ { rel: 'following', target: { kind: 'session', sessionId: 'followed' } }] });+const input = { deviceId: 'mac', deviceName: 'Mac', scope: 'owner/mac', status: 'all', limit: 200, current: () => true };++describe('mobile teammate task list', () => {+ it('loads old-host lanes across pages, keeps exact ownership and marks archived delegated tasks', async () => {+ const routine = task('routine', { source: 'bot', companion: { id: 'cindy-default', role: 'routine' } });+ const channel = task('channel', { source: 'bot', companion: { id: 'cindy-default', role: 'channel' } });+ const invoke = vi.fn(async (_device: string, api: string, args: any[]) => {+ if (api === 'local-db:history:query') return args[0].args.cursor+ ? { ok: true, sessions: [channel] }+ : { ok: true, sessions: [routine, task('canonical', { source: 'bot', companion: { id: 'cindy-default', role: 'canonical' } })], hasMore: true, nextCursor: 'page2' };+ if (api === 'local-db:sessions:get-many') return args[0].map((id: string) => task(id, { source: 'bot' }));+ if (api === REMOTE_RESOURCE_LIST_CHANNEL) return { collectionId: 'teammates', items: [bot()] };+ if (api === 'maker:bot-delegations:list') return { ok: true, delegations: [+ { requestingBotId: 'cindy-default', childSessionId: 'created' },+ { requestingBotId: 'other', childSessionId: 'followed' },+ ] };+ throw new Error(api);+ });+ const rows = await readTeammateTasks({ ...input, invoke: invoke as RemoteInvoke,+ sessions: [task('created', { status: 'archived' }), task('followed')] });+ expect(rows.map(row => row.id)).toEqual(['created', 'followed', 'routine', 'channel']);+ expect(rows.filter(row => row.taskTeammate).map(row => row.id)).toEqual(['created', 'routine', 'channel']);+ expect(rows[0].taskTeammate?.avatar?.value).toBe('cindy://avatar/preset/cindy');+ expect(invoke.mock.calls.filter(call => call[1] === 'local-db:sessions:get-many')).toHaveLength(1);+ expect(invoke.mock.calls.find(call => call[1] === 'maker:bot-delegations:list')?.[2]).toEqual(['canonical']);+ });++ it('preserves cached host attribution on optional failure, but clears successful removal', async () => {+ const previous = [task('created', { deviceLinkDeviceId: 'mac', taskTeammate: { id: 'cindy-default', name: 'Cindy' } }),+ task('lane', { deviceLinkDeviceId: 'mac', source: 'bot', companion: { id: 'cindy-default', role: 'channel' } })];+ const failed = vi.fn(async () => { throw new Error('CHANNEL_NOT_ALLOWED'); });+ const retained = await readTeammateTasks({ ...input, invoke: failed as RemoteInvoke, sessions: [task('created')], previous });+ expect(retained.map(row => row.id)).toEqual(['created', 'lane']);+ expect(retained[0].taskTeammate?.id).toBe('cindy-default');+ const empty = vi.fn(async (_device: string, api: string) => api === 'local-db:history:query'+ ? { ok: true, sessions: [] } : { collectionId: 'teammates', items: [] });+ const cleared = await readTeammateTasks({ ...input, invoke: empty as RemoteInvoke, sessions: [task('created')], previous });+ expect(cleared).toHaveLength(1);+ expect(cleared[0].taskTeammate).toBeNull();+ });++ it('stops after account/query invalidation and propagates access revocation', async () => {+ let current = true;+ const stale = vi.fn(async () => { current = false; return { ok: true, sessions: [] }; });+ expect(await readTeammateTasks({ ...input, invoke: stale as RemoteInvoke, sessions: [task('normal')], current: () => current })).toEqual([]);+ expect(stale).toHaveBeenCalledTimes(1);+ const revoked = vi.fn(async () => { throw new Error('[DEVICE_LINK_ACCESS_REVOKED] revoked'); });+ await expect(readTeammateTasks({ ...input, invoke: revoked as RemoteInvoke, sessions: [] })).rejects.toThrow('REVOKED');+ });++ it('merges cloud and preset Cindy devices without conflating unrelated names', () => {+ const rows = ['mac', 'mbp'].map(deviceId => ({ key: deviceId, host: { deviceId, deviceName: deviceId }, item: bot('cloud-cindy') } as HostedRemoteCollectionItem));+ const cloud = new Set(['cloud-cindy']);+ const options = taskTeammateOptions(rows, cloud, 'en');+ expect(options).toEqual([{ key: taskTeammateKey('cloud-cindy', 'mac', cloud), title: 'Cindy' }]);+ expect(taskTeammateKey('cloud-cindy', 'mac', cloud)).toBe(taskTeammateKey('cloud-cindy', 'mbp', cloud));+ expect(taskTeammateKey('cindy-default', 'mac', cloud)).toBe(taskTeammateKey('cindy-default', 'mbp', cloud));+ expect(taskTeammateOptions(rows, new Set(), 'en')).toHaveLength(2);+ const selections = rows.map(row => taskTeammateKey(row.item.ref.id, row.host.deviceId, new Set()));+ expect(normalizeTaskTeammateSelection(selections, cloud)).toEqual([options[0].key]);+ const cindyIds = new Set(['cloud-cindy', 'other-cindy']);+ expect(normalizeTaskTeammateSelection([...selections, taskTeammateKey('other-cindy', 'other', cloud)], cloud, cindyIds))+ .toEqual([JSON.stringify(['teammate', 'cindy'])]);+ expect(taskTeammateOptions(rows, cloud, 'en', cindyIds)[0].key).toBe(JSON.stringify(['teammate', 'cindy']));+ });+});diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex b9e9883643..4ad46cce75 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -237,6 +237,21 @@ function pending(kind: string, requestId?: string, persistId?: string): PendingIdescribe('remoteSessionStore', () => {beforeEach(() => remoteSessionStore.clear());+ it('lists independent teammate lanes, excludes canonical chat and retains attribution after legacy detail reads', () => {+ const taskTeammate = { id: 'cindy-default', name: 'Cindy' };+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('routine', { source: 'bot', companion: { id: 'cindy-default', role: 'routine' }, taskTeammate }),+ session('channel', { source: 'bot', companion: { id: 'cindy-default', role: 'channel' }, taskTeammate }),+ session('canonical', { source: 'bot', companion: { id: 'cindy-default', role: 'canonical' } }),+ session('thread', { source: 'bot' }),+ ]);+ expect(remoteSessionStore.getHomeSessions().map(row => row.id).sort()).toEqual(['channel', 'routine']);+ remoteSessionStore.upsertDeviceSession('dev-1', 'Mac', session('routine', { source: 'bot', status: 'archived' }));+ expect(remoteSessionStore.getHomeSessions().find(row => row.id === 'routine')).toMatchObject({+ status: 'archived', companion: { id: 'cindy-default', role: 'routine' }, taskTeammate,+ });+ });+it('keeps an edited async question across disconnection but removes it on explicit history clearing', () => {remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);const item: PendingInteraction = { persistId: 'p1',diff --git a/apps/mobile/src/__tests__/useCloudCompanion.test.tsx b/apps/mobile/src/__tests__/useCloudCompanion.test.tsxindex cfa26e4674..78dbe623be 100644--- a/apps/mobile/src/__tests__/useCloudCompanion.test.tsx+++ b/apps/mobile/src/__tests__/useCloudCompanion.test.tsx@@ -5,7 +5,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';const h = vi.hoisted(() => ({owner: 'owner:1:global', current: true, readDeviceList: vi.fn(),- capabilities: vi.fn(), actors: vi.fn(),+ capabilities: vi.fn(), actors: vi.fn(), cindyCompanionIds: vi.fn(),disk: new Map<string, string>(),}));vi.mock('@react-native-async-storage/async-storage', () => ({ default: {@@ -24,7 +24,7 @@ vi.mock('@/chat/useChatServer', async () => {const { useMemo } = await import('react');return { useChatClient: () => useMemo(() => ({ owner: h.owner, enabled: true,userId: h.owner.split(':')[0], realm: h.owner.split(':')[2],- current: () => h.current, client: { capabilities: h.capabilities, actors: h.actors } }), [h.owner]) };+ current: () => h.current, client: { capabilities: h.capabilities, actors: h.actors, cindyCompanionIds: h.cindyCompanionIds } }), [h.owner]) };});vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ readDeviceList: h.readDeviceList }) }));import { useCloudCompanionHome } from '@/chat/useCloudCompanion';@@ -39,6 +39,7 @@ const actor = { id: 'actor', kind: 'bot', externalId: 'writer', name: 'Writer',beforeEach(async () => {await clearRemoteResourceCache();vi.resetAllMocks(); h.owner = 'owner:1:global'; h.current = true;+ h.cindyCompanionIds.mockResolvedValue([]);h.capabilities.mockResolvedValue({ companionHome: true }); h.actors.mockResolvedValue([actor]);h.readDeviceList.mockResolvedValue({ devices: [{ deviceId: 'studio', name: 'Mac Studio' }] });root = createRoot(document.createElement('div'));@@ -93,3 +94,19 @@ it('ignores a late directory result after a newer refresh wins', async () => {await act(async () => { complete({ devices: [{ deviceId: 'studio', name: 'Old name' }] }); await pending; });expect(result.deviceNames.get('studio')).toBe('New name');});++// Unit: delayed cloud identity must enrich without replacing independently read names.+it('retains preset identities alongside computer labels and drops them across accounts', async () => {+ let finish: (ids: string[]) => void = () => {};+ h.cindyCompanionIds.mockImplementation(() => new Promise(resolve => { finish = resolve; }));+ await render();+ expect(result.actors).toEqual([actor]);+ expect(result.deviceNames.get('studio')).toBe('Mac Studio');+ await act(async () => finish(['writer']));+ expect(result.cindyIds).toEqual(['writer']);+ expect(result.deviceNames.get('studio')).toBe('Mac Studio');+ h.owner = 'another:2:global';+ h.capabilities.mockImplementation(() => new Promise(() => {}));+ await render();+ expect(result.cindyIds).toEqual([]);+});diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex 0f5cf701d3..1c257dfec6 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -1,3 +1,4 @@+import { inferBotTemplatePresetId } from '@cindy/maker-shared/bot-template-preset';import { createConversationListState } from '@cindy/maker-shared/chatConversationList';import type { ChatHistory } from '@cindy/maker-shared/chat-history';/** The existing Chat Server HTTP contract; no device-link or executor registration. */@@ -388,6 +389,21 @@ export function createChatServerClient(request: ChatRequest, personalList = creaavatar: typeof row.avatar === 'string' ? row.avatar : null, homeDeviceId: typeof row.homeDeviceId === 'string' && row.homeDeviceId ? row.homeDeviceId : null }];});},+ /** Same preset identity as Desktop. Read profile metadata only; never infer from a name/avatar. */+ async cindyCompanionIds(actors: readonly ChatActor[], previous: readonly string[] = [], current = () => true): Promise<string[]> {+ const ids: string[] = [];+ for (const actor of actors) {+ if (!current()) break;+ if (actor.kind !== 'bot') continue;+ if (actor.externalId === 'cindy-default') { ids.push(actor.externalId); continue; }+ try {+ const rows = await request<Array<{ key?: unknown; value?: unknown }>>('/preferences', 'GET', undefined, chatId(actor.id));+ const profile = rows?.find(row => row.key === 'companion.profile.v1')?.value as { templateId?: unknown; soul?: unknown } | undefined;+ if (profile?.templateId === 'cindy' || (typeof profile?.soul === 'string' && inferBotTemplatePresetId(profile.soul) === 'cindy')) ids.push(actor.externalId);+ } catch { if (previous.includes(actor.externalId)) ids.push(actor.externalId); }+ }+ return ids;+ },/** The main computer has uploaded the profile snapshot another computer builds the companion from. */async hasProfileSnapshot(actorId: string): Promise<boolean> {const rows = await request<Array<{ key?: unknown; value?: unknown }>>('/preferences', 'GET', undefined, chatId(actorId));diff --git a/apps/mobile/src/chat/useCloudCompanion.ts b/apps/mobile/src/chat/useCloudCompanion.tsindex 225d9225d9..4c5543b9f1 100644--- a/apps/mobile/src/chat/useCloudCompanion.ts+++ b/apps/mobile/src/chat/useCloudCompanion.ts@@ -4,12 +4,13 @@ import { useFocusEffect } from 'expo-router';import type { ChatActor, ChatSetHomeResult } from './chatServerClient';import { useChatClient } from './useChatServer';import { useDeviceLink } from '@/device-link/DeviceLinkContext';-import { cacheCloudHome, peekCachedCloudHome, readCachedCloudHome,+import { cacheCloudHome, patchCachedCloudHome, peekCachedCloudHome, readCachedCloudHome,remoteResourceCacheRevision, subscribeRemoteResourceCache } from '@/device-link/remoteResourceCache';import { mobileDebugLog } from '@/debug/mobileDebugLog';import { forgetCloudConversation } from './cloudConversationCache';const NO_ACTORS: ChatActor[] = [];+const NO_CINDY_IDS: string[] = [];const NO_NAMES: ReadonlyMap<string, string> = new Map();/**@@ -43,13 +44,18 @@ export function useCloudCompanionHome(enabled: boolean) {await Promise.all((previous?.actors ?? []).filter(actor => !ids.has(actor.id)).map(actor => forgetCloudConversation(actor.id)));if (!current()) return;}- await cacheCloudHome(api.userId, api.realm, { supported: companionHome, actors, deviceNames: previousNames }, current);+ const cindyIds = (previous?.cindyIds ?? []).filter(id => actors.some(actor => actor.externalId === id));+ await cacheCloudHome(api.userId, api.realm, { supported: companionHome, actors, cindyIds, deviceNames: previousNames }, current);if (!current()) return;setFailure(null);- // Optional computer labels never delay the companion roster itself.+ // Neither optional metadata read delays the roster or the other's publication.if (companionHome && actors.length) {- const names = await readDeviceList().then(({ devices }) => devices.map(device => [device.deviceId, device.name] as [string, string]), () => null);- if (names && current()) await cacheCloudHome(api.userId, api.realm, { supported: companionHome, actors, deviceNames: names }, current);+ const enrich = (patch: { deviceNames?: Array<[string, string]>; cindyIds?: string[] }) =>+ patchCachedCloudHome(api.userId, api.realm, patch, current);+ await Promise.all([+ readDeviceList().then(({ devices }) => enrich({ deviceNames: devices.map(device => [device.deviceId, device.name]) }), () => undefined),+ api.client.cindyCompanionIds(actors, cindyIds, current).then(ids => enrich({ cindyIds: ids })),+ ]);}} catch (error) {if (!current()) return;@@ -72,5 +78,5 @@ export function useCloudCompanionHome(enabled: boolean) {return api.client.setHome(actorId, homeDeviceId, expected);}, [api]);return { supported: cached?.supported === true, actors: cached?.actors ?? NO_ACTORS,- deviceNames, error: failure?.owner === api.owner ? failure.error : null, refresh, setHome };+ cindyIds: cached?.cindyIds ?? NO_CINDY_IDS, deviceNames, error: failure?.owner === api.owner ? failure.error : null, refresh, setHome };}diff --git a/apps/mobile/src/debug/teammateVisualFixture.ts b/apps/mobile/src/debug/teammateVisualFixture.tsindex 293398697d..ef905e4ef4 100644--- a/apps/mobile/src/debug/teammateVisualFixture.ts+++ b/apps/mobile/src/debug/teammateVisualFixture.ts@@ -19,7 +19,7 @@ const TEAMMATES = 'teammates';export const VISUAL_TEAMMATE_SESSION_ID = 'visual-teammate-session';const MINUTE = 60_000;const teammates: ReadonlyArray<{ id: string; name: string; preview: string; minutesAgo: number; avatar: RemoteCollectionItem['display']['avatar']; working?: boolean; following?: string[] }> = [- { id: 'visual-bot-cindy', name: 'Cindy', preview: '登录页窄窗口的错位已经修好,截图放在任务里了。', minutesAgo: 2,+ { id: 'cindy-default', name: 'Cindy', preview: '登录页窄窗口的错位已经修好,截图放在任务里了。', minutesAgo: 2,avatar: { kind: 'asset', value: 'cindy://avatar/preset/cindy', fallbackText: 'C' }, working: true,// Task rows show the follow mark (`ui-mock` tasks): one shared with LiZi, so the mark picks by name.following: ['visual-running', `${UI_MOCK_ID_PREFIX}rich-answer`] },@@ -40,6 +40,12 @@ const teammates: ReadonlyArray<{ id: string; name: string; preview: string; minuconst FIXTURE_NOW = Date.now();export function teammateVisualFixture(channel: string, args: unknown[], now = FIXTURE_NOW): unknown {+ if (channel === 'maker:bot-delegations:list') {+ const bot = teammates.find(item => args[0] === `${VISUAL_TEAMMATE_SESSION_ID}:${item.id}`);+ const ids = bot?.id === 'cindy-default' ? ['visual-running', `${UI_MOCK_ID_PREFIX}rich-answer`]+ : bot?.id === 'visual-bot-lizi' ? [`${UI_MOCK_ID_PREFIX}english`, `${UI_MOCK_ID_PREFIX}archived`] : [];+ return { ok: true, delegations: ids.map(childSessionId => ({ requestingBotId: bot!.id, childSessionId })) };+ }if (channel === REMOTE_RESOURCE_MANIFEST_CHANNEL) return {protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION,collections: [{ id: TEAMMATES, resourceKind: 'bot', title: 'Teammates', placement: 'home-scope',@@ -65,9 +71,9 @@ export function teammateVisualFixture(channel: string, args: unknown[], now = FIref: { collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, kind: BOT_GROUP_REMOTE_RESOURCE_KIND, id: request.ref.id },revision: 'visual-1', display: { title: '任务入口演示群' }, actions: [], links: [],blocks: [{ id: 'chat', primitive: BOT_GROUP_CHAT_PRIMITIVE, fallbackMarkdown: 'Cindy 正在工作', data: {- id: request.ref.id, name: '任务入口演示群', members: [{ botId: 'visual-bot-cindy', name: 'Cindy', status: 'active' }],+ id: request.ref.id, name: '任务入口演示群', members: [{ botId: 'cindy-default', name: 'Cindy', status: 'active' }],messages: [], plans: [], createdAt: now, updatedAt: now,- round: { status: 'running', canContinue: false, speakers: [{ botId: 'visual-bot-cindy', activity: 'reply', sessionId: VISUAL_TEAMMATE_SESSION_ID }] },+ round: { status: 'running', canContinue: false, speakers: [{ botId: 'cindy-default', activity: 'reply', sessionId: VISUAL_TEAMMATE_SESSION_ID }] },} }],};// Existing connection/session records for exercising both native settings entries.@@ -105,7 +111,10 @@ export function teammateVisualFixture(channel: string, args: unknown[], now = FIavatar: bot.avatar,...(bot.working ? { generation: { phase: 'replying', startedAt: now - MINUTE } } : {}),},- links: (bot.following ?? []).map((sessionId) => ({ rel: 'following', target: { kind: 'session' as const, sessionId } })),+ links: [+ { rel: 'conversation', target: { kind: 'session' as const, sessionId: `${VISUAL_TEAMMATE_SESSION_ID}:${bot.id}` } },+ ...(bot.following ?? []).map((sessionId) => ({ rel: 'following', target: { kind: 'session' as const, sessionId } })),+ ],revision: 'visual-1',})),} satisfies RemoteCollectionListResponse;diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.tsindex a3235615c1..c57253ca7d 100644--- a/apps/mobile/src/debug/visualMock.ts+++ b/apps/mobile/src/debug/visualMock.ts@@ -297,7 +297,11 @@ async function visualMockInvoke<T = unknown>(return { prompt: (args[0] as { sessionId?: string } | undefined)?.sessionId === 'visual-prompt-recommendation'? '继续跟进 PR #4670' : null } as T;case 'local-db:sessions:list':- return visualMockSessions(args[0] as string | undefined) as T;+ return visualMockSessions((typeof args[0] === 'string' ? args[0] : args[1]) as string | undefined) as T;+ case 'local-db:history:query':+ return { ok: true, sessions: visualMockSessions('all').filter(row => row.source === 'bot'), hasMore: false } as T;+ case 'local-db:sessions:get-many':+ return (args[0] as string[]).map(visualMockSession) as T;case 'local-db:sessions:get':return visualMockSession(String(args[0] ?? VISUAL_MOCK_SESSION_ID)) as T;case 'local-db:messages:list':@@ -524,6 +528,10 @@ function catalogSession(row: UiMockSessionRow): RemoteSession {status: row.status,agentKind: row.agentKind,source: row.source,+ // Overlay existing catalog tasks with exact ownership, just as the mock host's+ // runtime overlays running/queued state. No extra task titles or private data.+ ...(row.id === 'visual-automation-running' ? { source: 'bot', companion: { id: 'cindy-default', role: 'routine' } } : {}),+ ...(row.id === 'ui-mock-long-title' ? { source: 'bot', companion: { id: 'visual-bot-lizi', role: 'channel', channel: 'telegram' } } : {}),pinnedAt: row.pinnedAt === null ? null : iso(row.pinnedAt),userSendAt: iso(row.userSendAt),createdAt: iso(row.createdAt),diff --git a/apps/mobile/src/device-link/remoteResourceCache.ts b/apps/mobile/src/device-link/remoteResourceCache.tsindex 76e7f45d93..d3b5f95d11 100644--- a/apps/mobile/src/device-link/remoteResourceCache.ts+++ b/apps/mobile/src/device-link/remoteResourceCache.ts@@ -6,7 +6,7 @@ import { isMobileRemoteCollectionSupported, normalizeRemoteCollectionItems, parsconst PREFIX = 'cindy.remoteResources.v1.';const MAX_CHARS = 256 * 1024;type ChatRoster = { items: HostedRemoteCollectionItem[]; ids: string[] };-export type CachedCloudHome = { supported: boolean; actors: ChatActor[]; deviceNames: Array<[string, string]> };+export type CachedCloudHome = { cindyIds?: string[]; supported: boolean; actors: ChatActor[]; deviceNames: Array<[string, string]> };type Snapshot = { home: RemoteHomeCollection[]; items: Record<string, HostedRemoteCollectionItem[]>; read: Record<string, number>; readSequences?: Record<string, string>; chatRosters?: Record<string, ChatRoster>; cloudHomes?: Record<string, CachedCloudHome> };const empty = (): Snapshot => ({ home: [], items: {}, read: {}, readSequences: {} });const validSequence = (value: unknown): value is string => typeof value === 'string' && /^\d{1,30}$/.test(value);@@ -30,6 +30,7 @@ function normalize(raw: unknown): Snapshot {const home = value.cloudHomes[realm];if (!home || typeof home.supported !== 'boolean' || !Array.isArray(home.actors) || !Array.isArray(home.deviceNames)) continue;(out.cloudHomes ??= {})[realm] = { supported: home.supported,+ ...(Array.isArray(home.cindyIds) ? { cindyIds: home.cindyIds.filter(id => typeof id === 'string' && home.actors.some(actor => actor?.externalId === id)) } : {}),actors: home.actors.filter(actor => actor && typeof actor.id === 'string' && typeof actor.name === 'string'&& typeof actor.kind === 'string' && typeof actor.externalId === 'string'&& (actor.homeDeviceId === null || typeof actor.homeDeviceId === 'string')@@ -111,6 +112,15 @@ export const cacheCloudHome = (userId: string, realm: string, value: CachedCloudif (current()) (s.cloudHomes ??= {})[realm] = value;});+/** Independent metadata reads merge inside the serialized cache update. */+export const patchCachedCloudHome = (userId: string, realm: string,+ patch: Pick<CachedCloudHome, 'cindyIds'> & Partial<Pick<CachedCloudHome, 'deviceNames'>>,+ current: () => boolean,+) => update(userId, s => {+ const home = s.cloudHomes?.[realm];+ if (current() && home) s.cloudHomes![realm] = { ...home, ...patch };+});+/** Trim only the disposable disk mirror; live rows and read positions stay intact. */function diskSnapshot(raw: string): string {if (raw.length <= MAX_CHARS) return raw;diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.jsonindex d4f9beaead..f75d1536c0 100644--- a/apps/mobile/src/i18n/locales/en/devices.json+++ b/apps/mobile/src/i18n/locales/en/devices.json@@ -338,7 +338,9 @@"doneUnread": "Completed, unread","running": "Running","close": "Close",- "cancelRename": "Cancel rename"+ "cancelRename": "Cancel rename",+ "createdBy": "Created by {{name}}",+ "ownedBy": "Belongs to {{name}}"},"accounts": {"title": "Switch account",@@ -415,7 +417,10 @@},"summaryNone": "None","summarySeparator": ", ",- "filterEmptyCopy": "Adjust or reset Filters in Display settings."+ "filterEmptyCopy": "Adjust or reset Filters in Display settings.",+ "filterTeammatesHeading": "Teammates",+ "filterAnySource": "Any source",+ "filterSelectedTeammates": "{{count}} selected"},"search": {"placeholder": "Search titles or content…",diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.jsonindex 715af42725..12797e9a6f 100644--- a/apps/mobile/src/i18n/locales/ja/devices.json+++ b/apps/mobile/src/i18n/locales/ja/devices.json@@ -338,7 +338,9 @@"doneUnread": "完了・未読","running": "実行中","close": "閉じる",- "cancelRename": "名前の変更をキャンセル"+ "cancelRename": "名前の変更をキャンセル",+ "createdBy": "{{name}} が作成",+ "ownedBy": "{{name}} に所属"},"accounts": {"title": "アカウントを切り替え",@@ -415,7 +417,10 @@},"summaryNone": "なし","summarySeparator": "、",- "filterEmptyCopy": "表示設定の「フィルター」で調整またはリセットできます。"+ "filterEmptyCopy": "表示設定の「フィルター」で調整またはリセットできます。",+ "filterTeammatesHeading": "パートナー",+ "filterAnySource": "すべての作成元",+ "filterSelectedTeammates": "{{count}} 人を選択"},"search": {"placeholder": "タイトルまたは内容を検索…",diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.jsonindex 768b5082d7..0249e683af 100644--- a/apps/mobile/src/i18n/locales/ko/devices.json+++ b/apps/mobile/src/i18n/locales/ko/devices.json@@ -338,7 +338,9 @@"doneUnread": "완료·읽지 않음","running": "실행 중","close": "닫기",- "cancelRename": "이름 변경 취소"+ "cancelRename": "이름 변경 취소",+ "createdBy": "{{name}}이(가) 생성",+ "ownedBy": "{{name}} 소속"},"accounts": {"title": "계정 전환",@@ -415,7 +417,10 @@},"summaryNone": "없음","summarySeparator": ", ",- "filterEmptyCopy": "표시 설정의 필터에서 조정하거나 재설정할 수 있습니다."+ "filterEmptyCopy": "표시 설정의 필터에서 조정하거나 재설정할 수 있습니다.",+ "filterTeammatesHeading": "파트너",+ "filterAnySource": "모든 출처",+ "filterSelectedTeammates": "{{count}}명 선택"},"search": {"placeholder": "제목 또는 내용 검색…",diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.jsonindex 452347be93..a08fd2cc05 100644--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json@@ -338,7 +338,9 @@"doneUnread": "已完成未读","running": "运行中","close": "关闭",- "cancelRename": "取消重命名"+ "cancelRename": "取消重命名",+ "createdBy": "由 {{name}} 创建",+ "ownedBy": "归属 {{name}}"},"accounts": {"title": "切换账号",@@ -415,7 +417,10 @@},"summaryNone": "无","summarySeparator": "、",- "filterEmptyCopy": "可在显示设置的「筛选」中调整或重置。"+ "filterEmptyCopy": "可在显示设置的「筛选」中调整或重置。",+ "filterTeammatesHeading": "伙伴",+ "filterAnySource": "不限来源",+ "filterSelectedTeammates": "已选 {{count}} 位"},"search": {"placeholder": "搜索标题或内容…",diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.jsonindex 370e8763b5..38739dab84 100644--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json@@ -338,7 +338,9 @@"doneUnread": "已完成未讀","running": "執行中","close": "關閉",- "cancelRename": "取消重新命名"+ "cancelRename": "取消重新命名",+ "createdBy": "由 {{name}} 建立",+ "ownedBy": "歸屬 {{name}}"},"accounts": {"title": "切換帳號",@@ -415,7 +417,10 @@},"summaryNone": "無","summarySeparator": "、",- "filterEmptyCopy": "可在顯示設定的「篩選」中調整或重設。"+ "filterEmptyCopy": "可在顯示設定的「篩選」中調整或重設。",+ "filterTeammatesHeading": "夥伴",+ "filterAnySource": "不限來源",+ "filterSelectedTeammates": "已選 {{count}} 位"},"search": {"placeholder": "搜尋標題或內容…",diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsxindex a491d0b62d..ec12a542a1 100644--- a/apps/mobile/src/session/HomeSurface.tsx+++ b/apps/mobile/src/session/HomeSurface.tsx@@ -1,3 +1,7 @@+import { useCloudCompanionHome } from '@/chat/useCloudCompanion';+import { cloudCompanionRows } from '@/chat/cloudCompanion';+import { normalizeTaskTeammateSelection, taskTeammateKey, taskTeammateOptions } from './teammateTaskSource';+import { readTeammateTasks } from './readTeammateTasks';import { deviceDisplayName } from '@/device-link/deviceName';import { MountOnFirstOpen } from './MountOnFirstOpen';import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';@@ -294,7 +298,7 @@ import { AutomationTimerIcon } from '@/session/AutomationTimerIcon';import { RenameSessionModal } from '@/session/RenameSessionModal';import { SessionOptionsPresenter } from '@/session/SessionOptionsExpoSheet';import { SwipeableSessionRow, type SessionSwipeControls } from '@/session/SwipeableSessionRow';-import { TaskFollowMark, taskFollowerNames, useTaskFollowers } from '@/session/TaskFollowMark';+import { TaskCreatorMark, TaskFollowMark, taskFollowerNames, useTaskFollowers } from '@/session/TaskFollowMark';import { createSwipeRowRegistry } from '@/session/swipeRowRegistry';import { useSessionListActions } from '@/session/useSessionListActions';import { useModalFadeLifecycle } from '@/session/useModalFadeLifecycle';@@ -500,13 +504,14 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falseconst preferenceOwnerRef = useRef(preferenceOwner);preferenceOwnerRef.current = preferenceOwner;const saveHomeViewPreferences = useCallback((- patch: Omit<HomeViewPreferencePatch, 'projectFilter'> & { projectFilter?: HomeProjectFilter },+ patch: Omit<HomeViewPreferencePatch, 'projectFilter' | 'teammateFilter'> & { projectFilter?: HomeProjectFilter; teammateFilter?: HomeProjectFilter },) => {const owner = getMobileAuthOwner();- const { projectFilter, ...rest } = patch;- const stored: HomeViewPreferencePatch = projectFilter === undefined- ? rest- : { ...rest, projectFilter: { owner: preferenceOwnerRef.current, value: projectFilter } };+ const { projectFilter, teammateFilter, ...rest } = patch;+ const stored: HomeViewPreferencePatch = { ...rest,+ ...(projectFilter === undefined ? {} : { projectFilter: { owner: preferenceOwnerRef.current, value: projectFilter } }),+ ...(teammateFilter === undefined ? {} : { teammateFilter: { owner: preferenceOwnerRef.current, value: teammateFilter } }),+ };return persistHomeViewPreferences(stored).catch(() => {if (isMobileAuthOwnerCurrent(owner)) {Alert.alert(t('devices.list.alert.actionFailed'), t('models.unified.saveFailed'));@@ -677,6 +682,7 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falseconst [sortBy, setSortBy] = useRetainedHomeState<HomeListSortBy>(viewSession, 'sortBy', 'recency');const [projectOrder, setProjectOrder] = useRetainedHomeState<HomeProjectOrder>(viewSession, 'projectOrder', 'activity');const [manualProjectOrder, setManualProjectOrder] = useRetainedHomeState<string[]>(viewSession, 'manualProjectOrder', []);+ const [teammateFilter, setTeammateFilter] = useRetainedHomeState<HomeProjectFilter>(viewSession, 'teammateFilter', 'all');const [projectFilter, setProjectFilter] = useRetainedHomeState<HomeProjectFilter>(viewSession, 'projectFilter', 'all');const [vendorFilter, setVendorFilter] = useRetainedHomeState<HomeVendorFilter>(viewSession, 'vendorFilter', 'all');const [lastActivityFilter, setLastActivityFilter] = useRetainedHomeState<HomeLastActivityFilter>(viewSession, 'lastActivityFilter', 'all');@@ -974,7 +980,15 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falserequestedListFilter,{ includePinned: true, fresh: true },]);- return [list, epoch] as const;+ const enriched = await readTeammateTasks({ invoke, deviceId: device.deviceId, deviceName: device.name,+ scope: JSON.stringify([expectedAccountGeneration, expectedHomeSyncGeneration, device.deviceId]),+ sessions: Array.isArray(list) ? list : [], previous: remoteSessionStore.getHomeSessions(),+ status: requestedListFilter, limit: LIST_LIMIT,+ current: () => homeAccountGenerationRef.current === expectedAccountGeneration+ && isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration),+ });+ assertCurrentScope();+ return [enriched, epoch] as const;},async () => {assertCurrentScope();@@ -1425,6 +1439,7 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falsesetProjectOrder(preferences.projectOrder);setManualProjectOrder(preferences.manualProjectOrder);setProjectFilter(preferences.projectFilter);+ setTeammateFilter(preferences.teammateFilter);setVendorFilter(preferences.vendorFilter);setLastActivityFilter(preferences.lastActivityFilter);setViewMode(preferences.viewMode);@@ -2121,11 +2136,25 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falseconst sharedGroup = useMemo(() => splitSharedHomeGroup(home, ownedSharedTasks, {sessions: homeSessions, searchQuery, statusFilter,}), [home, ownedSharedTasks, homeSessions, searchQuery, statusFilter]);+ const cloudTeammates = useCloudCompanionHome(false);+ const cloudTeammateIds = useMemo(() => new Set(cloudTeammates.actors.filter(actor => actor.kind === 'bot').map(actor => actor.externalId)), [cloudTeammates.actors]);+ const cindyTeammateIds = useMemo(() => new Set(cloudTeammates.cindyIds), [cloudTeammates.cindyIds]);+ const effectiveTeammateFilter = useMemo(() => normalizeTaskTeammateSelection(teammateFilter, cloudTeammateIds, cindyTeammateIds), [teammateFilter, cloudTeammateIds, cindyTeammateIds]);+ const teammateOptions = useMemo(() => taskTeammateOptions(+ cloudCompanionRows(teammatesSectionContext.shared?.roster.items ?? [], cloudTeammates.actors, cloudTeammates.deviceNames),+ cloudTeammateIds, i18nInstance.language, cindyTeammateIds,+ ), [teammatesSectionContext.shared?.roster.items, cloudTeammates.actors, cloudTeammates.deviceNames, cloudTeammateIds, i18nInstance.language, cindyTeammateIds]);const contentFilters = useMemo<HomeContentFilters>(() => ({lastActivity: lastActivityFilter,projects: projectFilter,+ teammates: effectiveTeammateFilter,+ teammateKey: item => {+ const session = item.session as RemoteSession;+ const id = session.taskTeammate?.id ?? session.companion?.id;+ return id ? taskTeammateKey(id, session.deviceLinkDeviceId ?? '', cloudTeammateIds, cindyTeammateIds) : undefined;+ },vendor: vendorFilter,- }), [lastActivityFilter, projectFilter, vendorFilter]);+ }), [lastActivityFilter, projectFilter, effectiveTeammateFilter, cloudTeammateIds, cindyTeammateIds, vendorFilter]);// 「最近活跃」按当前时间截断:列表没有新数据时也要让越过截止线的任务按时移出。const filterTick = useHomeFilterClock(lastActivityFilter !== 'all' && screenFocused);const filteredSharedRows = useMemo(@@ -2476,6 +2505,7 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falseif (nextPatch.groupDialogue !== undefined) setGroupDialogue(nextPatch.groupDialogue);if (nextPatch.sortBy !== undefined) setSortBy(nextPatch.sortBy);if (nextPatch.statusFilter !== undefined) setStatusFilter(nextPatch.statusFilter);+ if (nextPatch.teammateFilter !== undefined) setTeammateFilter(nextPatch.teammateFilter);if (nextPatch.projectFilter !== undefined) setProjectFilter(nextPatch.projectFilter);if (nextPatch.vendorFilter !== undefined) setVendorFilter(nextPatch.vendorFilter);if (nextPatch.lastActivityFilter !== undefined) setLastActivityFilter(nextPatch.lastActivityFilter);@@ -2898,13 +2928,14 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falsegroupDialogue,lastActivityFilter,projectFilter,+ teammateFilter: effectiveTeammateFilter,projectOrder: displayedProjectOrder,sortBy,statusFilter,taskInfoFields,vendorFilter,viewMode,- }), [displayedProjectOrder, groupByProject, groupDialogue, lastActivityFilter, projectFilter, sortBy, statusFilter, taskInfoFields, vendorFilter, viewMode]);+ }), [displayedProjectOrder, groupByProject, groupDialogue, lastActivityFilter, projectFilter, effectiveTeammateFilter, sortBy, statusFilter, taskInfoFields, vendorFilter, viewMode]);// 在看已归档任务时,顶栏「⋯」带提醒点(iOS 系统顶栏 / 自绘按钮两条路径共用这一个判据),// 同时把状态写进无障碍名称,读屏用户不用打开菜单也知道列表不是平常的进行中任务。const archivedReminder = statusFilter === 'archived';@@ -2922,10 +2953,11 @@ function HomeScreenContent({ active = true, width, newSessionInSystemBar = falsesubtitle: selectedDeviceId ? undefined : project.deviceName || undefined,title: project.title,})),+ teammates: teammateOptions,state: displayMenuState,t,}),- [displayMenuState, projectFilterUniverse.chats, projectFilterUniverse.projects, selectedDeviceId, t],+ [displayMenuState, teammateOptions, projectFilterUniverse.chats, projectFilterUniverse.projects, selectedDeviceId, t],);const handleDisplayAction = useCallback((id: string) => {const patch = homeDisplayActionPatch(id, displayMenuState);@@ -4408,6 +4440,7 @@ function HomeSessionRowInner({const latestItem = latestMobileSessionRow(item);// 伙伴开的或接手的任务:标题后带第一位伙伴的头像(与桌面侧栏「在跟进」同口径)。const followers = useTaskFollowers(latestItem.session);+ const taskTeammate = (latestItem.session as RemoteSession).taskTeammate;const sessionIsRunning = useSessionRunning(latestItem.session.id);// 已加载消息的预览按 session 订阅。普通流式 token 只让对应的可见行更新,首页根层、// sections 和其它任务行都保持原引用。@@ -4462,14 +4495,16 @@ function HomeSessionRowInner({};const groupRowOpensPrimary = !!group && (attention || rightStatus === 'error') && !groupExpanded;const accessibilityTitle = sharedRole === 'owned' ? item.title + ', ' + t('sharedTask.roleHost') : item.title;- const followedBy = !group && followers.length+ const attributedTo = !group && taskTeammate+ ? ', ' + t((latestItem.session as RemoteSession).companion ? 'devices.list.a11y.ownedBy' : 'devices.list.a11y.createdBy', { name: taskTeammate.name }) : '';+ const followedBy = !attributedTo && !group && followers.length? t('devices.list.a11y.followedBy', { names: taskFollowerNames(followers, i18n.language) }): '';const accessibilityLabel = group? groupRowOpensPrimary? t('devices.list.a11y.openAutomationLatest', { title: accessibilityTitle }): t('devices.list.a11y.automationTask', { title: accessibilityTitle })- : t('devices.list.a11y.openConversation', { title: accessibilityTitle }) + followedBy;+ : t('devices.list.a11y.openConversation', { title: accessibilityTitle }) + attributedTo + followedBy;const handlePress = selectionMode && onPressSelection? onPressSelection: group@@ -4605,7 +4640,10 @@ function HomeSessionRowInner({{showPinned ? <Pin color={colors.textTertiary} size={iconSize.md} strokeWidth={iconStroke.thin} /> : null}</View>) : null}- {!group && followers[0] ? (+ {!group && taskTeammate ? (+ <TaskCreatorMark teammate={taskTeammate} deviceId={item.session.deviceLinkDeviceId ?? ''}+ testID={`home.sessionCreatorMark.${item.session.id}`} />+ ) : !group && followers[0] ? (<TaskFollowMark follower={followers[0]} testID={`home.sessionFollowMark.${item.session.id}`} />) : null}{rightStatus === 'time' ? (diff --git a/apps/mobile/src/session/TaskFollowMark.tsx b/apps/mobile/src/session/TaskFollowMark.tsxindex 494e9f7374..12b0cecc4e 100644--- a/apps/mobile/src/session/TaskFollowMark.tsx+++ b/apps/mobile/src/session/TaskFollowMark.tsx@@ -43,3 +43,14 @@ export function TaskFollowMark({ follower, testID }: { follower: HostedRemoteCol</View>);}++/** Creation/ownership persists when the task is archived or no longer followed. */+export function TaskCreatorMark({ teammate, deviceId, testID }: {+ teammate: import('./teammateTaskSource').TaskTeammate; deviceId: string; testID: string;+}) {+ const { status, getPresenceAvailability } = useDeviceLink();+ return <View accessible={false} importantForAccessibility="no-hide-descendants" testID={testID}>+ <RemoteCompanionAvatar avatar={teammate.avatar} deviceId={deviceId} name={teammate.name}+ framed size={iconSize.md} online={status === 'online' && getPresenceAvailability(deviceId) !== false} />+ </View>;+}diff --git a/apps/mobile/src/session/homeChromeMenus.ts b/apps/mobile/src/session/homeChromeMenus.tsindex c49c1f9830..a82e235520 100644--- a/apps/mobile/src/session/homeChromeMenus.ts+++ b/apps/mobile/src/session/homeChromeMenus.ts@@ -144,6 +144,7 @@ export interface HomeDisplayMenuState {projectOrder: HomeProjectOrder;statusFilter: HomeStatusFilter;projectFilter: HomeProjectFilter;+ teammateFilter?: HomeProjectFilter;vendorFilter: HomeVendorFilter;lastActivityFilter: HomeLastActivityFilter;viewMode: HomeListViewMode;@@ -210,6 +211,7 @@ export function buildHomeDisplayPullDownActions(input: {state: HomeDisplayMenuState;/** 项目筛选的候选:完整项目集,不受最近活跃等筛选收窄。 */projects: readonly HomeDisplayMenuProject[];+ teammates?: readonly { key: string; title: string; subtitle?: string }[];dialogueCount: number;t: Translate;}): NativePullDownAction[] {@@ -220,6 +222,7 @@ export function buildHomeDisplayPullDownActions(input: {].filter(Boolean).join(t(`${MENU}.summarySeparator`)) || t(`${MENU}.summaryNone`);const filterCount = activeContentFilterCount({projects: state.projectFilter,+ teammates: state.teammateFilter,vendor: state.vendorFilter,lastActivity: state.lastActivityFilter,});@@ -278,6 +281,16 @@ export function buildHomeDisplayPullDownActions(input: {]),section("filter.projects.list", projectRows),]),+ submenu("filter.teammates", t(`${MENU}.filterTeammatesHeading`),+ !state.teammateFilter || state.teammateFilter === "all" ? t(`${MENU}.filterAnySource`)+ : t(`${MENU}.filterSelectedTeammates`, { count: state.teammateFilter.length }), "person.2", [+ checkable("filter.teammates.all", t(`${MENU}.filterAnySource`), !state.teammateFilter || state.teammateFilter === "all"),+ ...(input.teammates ?? []).map(teammate => ({+ ...checkable(`filter.teammate:${teammate.key}`, teammate.title,+ projectExplicitlySelected(state.teammateFilter ?? "all", teammate.key), true),+ ...(teammate.subtitle ? { subtitle: teammate.subtitle } : {}),+ })),+ ]),submenu("filter.vendor", t(`${MENU}.filterVendorHeading`), t(`${MENU}.filterVendor.${state.vendorFilter}`), "cpu",HOME_VENDOR_FILTERS.map((vendor) =>checkable(`filter.vendor.${vendor}`, t(`${MENU}.filterVendor.${vendor}`), state.vendorFilter === vendor))),@@ -322,7 +335,12 @@ export function homeDisplayActionPatch(): HomeDisplayPatch | null {if (id === "group.project") return { groupByProject: !state.groupByProject };if (id === "group.dialogue") return { groupDialogue: !state.groupDialogue };- if (id === "filter.reset") return { lastActivityFilter: "all", projectFilter: "all", vendorFilter: "all" };+ if (id === "filter.reset") return { lastActivityFilter: "all", projectFilter: "all", teammateFilter: "all", vendorFilter: "all" };+ if (id === "filter.teammates.all") return { teammateFilter: "all" };+ if (id.startsWith("filter.teammate:")) {+ const key = id.slice("filter.teammate:".length);+ return key ? { teammateFilter: toggleProjectFilter(state.teammateFilter ?? "all", key) } : null;+ }if (id === "filter.projects.all") return { projectFilter: "all" };if (id.startsWith(PROJECT_FILTER_PREFIX)) {const key = id.slice(PROJECT_FILTER_PREFIX.length);diff --git a/apps/mobile/src/session/homeContentFilters.ts b/apps/mobile/src/session/homeContentFilters.tsindex 7acddc057e..62f29ef689 100644--- a/apps/mobile/src/session/homeContentFilters.ts+++ b/apps/mobile/src/session/homeContentFilters.ts@@ -17,7 +17,7 @@ import {type RemoteSessionListItem,} from './sessionList';-// 首页「筛选」(项目 / Harness / 最近活跃)作用到展示模型。与 homeDisplaySettings 分开:+// 首页「筛选」(项目 / 伙伴 / Harness / 最近活跃)作用到展示模型。与 homeDisplaySettings 分开:// 自动化组部分命中时要重新折叠并本地化,依赖 i18n;设置本身的纯逻辑不应带上这条依赖。/**@@ -29,11 +29,13 @@ export function createHomeContentFilter(filters: HomeContentFilters,nowMs: number,): ((item: RemoteSessionListItem) => RemoteSessionListItem | null) | null {- if (filters.vendor === 'all' && filters.lastActivity === 'all') return null;+ if (filters.vendor === 'all' && filters.lastActivity === 'all' && (!filters.teammates || filters.teammates === 'all')) return null;const cutoff = filters.lastActivity === 'all'? null: nowMs - LAST_ACTIVITY_DAYS[filters.lastActivity] * DAY_MS;const keep = (item: RemoteSessionListItem): boolean => {+ if (filters.teammates && filters.teammates !== 'all'+ && !filters.teammates.includes(filters.teammateKey?.(item) ?? '')) return false;if (filters.vendor !== 'all' && sessionVendor(item) !== filters.vendor) return false;if (cutoff !== null && activityMsFromIso(item.lastActivityAt) < cutoff) return false;return true;@@ -75,7 +77,7 @@ function filterItems(/*** 按筛选收窄首页展示模型。与桌面侧栏一致(设计文档 §3.3,2026-08-12 用户重申):* **筛选一律不作用于置顶区**——置顶是「我要一直看见它」,被筛掉会让人以为置顶丢了。- * 项目筛选作用于项目组与对话;Harness / 最近活跃作用于项目组与对话里的任务。+ * 项目筛选作用于项目组与对话;伙伴 / Harness / 最近活跃作用于项目组与对话里的任务。* 筛完为空的项目组整组隐藏。共享任务分组见 filterSharedHomeRows。*/export function applyHomeContentFilters(@@ -116,7 +118,7 @@ export function filterSharedHomeRows<Row extends { item?: RemoteSessionListItemconst filter = createHomeContentFilter(filters, nowMs);if (!filter) return rows;return rows.flatMap((row) => {- if (!row.item) return [row];+ if (!row.item) return filters.teammates && filters.teammates !== 'all' ? [] : [row];const item = filter(row.item);if (!item) return [];return [item === row.item ? row : { ...row, item }];diff --git a/apps/mobile/src/session/homeDisplaySettings.ts b/apps/mobile/src/session/homeDisplaySettings.tsindex 0ab6f9ec81..3fff3eb307 100644--- a/apps/mobile/src/session/homeDisplaySettings.ts+++ b/apps/mobile/src/session/homeDisplaySettings.ts@@ -5,7 +5,7 @@ import { formatRemoteMoney, resolveSessionTotalMoney } from './remoteMoney';/*** 首页「显示」菜单里与桌面侧栏对齐的设置(筛选 / 显示 / 任务信息)。* 语义逐项照搬桌面 SidebarFilterPopover:- * - 筛选只含项目 / Harness / 最近活跃,不动任务状态;+ * - 筛选包含项目 / 伙伴 / Harness / 最近活跃,不动任务状态;* - 显示 = 文字(单行)/ 列表(带预览行);* - 任务信息复选,行内渲染顺序 = 勾选先后。*/@@ -40,6 +40,8 @@ export const DAY_MS = 24 * 60 * 60 * 1000;export interface HomeContentFilters {projects: HomeProjectFilter;+ teammates?: HomeProjectFilter;+ teammateKey?: (item: RemoteSessionListItem) => string | undefined;vendor: HomeVendorFilter;lastActivity: HomeLastActivityFilter;}@@ -95,6 +97,7 @@ export function projectFilterIncludes(filter: HomeProjectFilter, key: string): bexport function activeContentFilterCount(filters: HomeContentFilters): number {return (filters.projects !== 'all' ? 1 : 0)+ + (filters.teammates && filters.teammates !== 'all' ? 1 : 0)+ (filters.vendor !== 'all' ? 1 : 0)+ (filters.lastActivity !== 'all' ? 1 : 0);}diff --git a/apps/mobile/src/session/homeViewPreferenceStore.ts b/apps/mobile/src/session/homeViewPreferenceStore.tsindex 866d10369e..03c6977d91 100644--- a/apps/mobile/src/session/homeViewPreferenceStore.ts+++ b/apps/mobile/src/session/homeViewPreferenceStore.ts@@ -30,6 +30,8 @@ export interface HomeViewPreferences {manualProjectOrder: string[];/** 项目 key 带设备与路径,只对保存它的账号身份有效(见 projectFilterOwner)。 */projectFilter: HomeProjectFilter;+ teammateFilter: HomeProjectFilter;+ teammateFilterOwner: string;/** 保存项目筛选时的账号身份(homeNavigationOwner);读取时与当前身份不符则视为不筛选。 */projectFilterOwner: string;vendorFilter: HomeVendorFilter;@@ -51,6 +53,7 @@ export interface HomeViewPreferencePatch {manualProjectOrder?: string[];/** 写项目筛选必须同时给 owner,否则无法判断它属于哪个账号。 */projectFilter?: { owner: string; value: HomeProjectFilter };+ teammateFilter?: { owner: string; value: HomeProjectFilter };vendorFilter?: HomeVendorFilter;lastActivityFilter?: HomeLastActivityFilter;viewMode?: HomeListViewMode;@@ -71,9 +74,10 @@ export async function readHomeViewPreferences(owner: string): Promise<HomeViewPr} catch {return emptyPreferences();}- return owner && preferences.projectFilterOwner === owner- ? preferences- : { ...preferences, projectFilter: 'all', projectFilterOwner: '' };+ return { ...preferences,+ ...(!owner || preferences.projectFilterOwner !== owner ? { projectFilter: 'all' as const, projectFilterOwner: '' } : {}),+ ...(!owner || preferences.teammateFilterOwner !== owner ? { teammateFilter: 'all' as const, teammateFilterOwner: '' } : {}),+ };}// save 是 read-modify-write:并发调用会拿到同一份旧快照互相覆盖(后落盘者丢掉先落盘的 patch),@@ -90,7 +94,7 @@ export function saveHomeViewPreferences(patch: HomeViewPreferencePatch): Promise/*** 只持久化用户 override(docs/dev-rules/configuration-and-overrides.md §2):把 patch 合并进已存的* 稀疏记录,未写过的字段不落盘,读取时按当下默认值补齐,默认值演进时未自定义的用户自动跟随。- * 三个筛选的 'all' 即「不筛选」= 默认,写入时删除字段(「重置筛选」由此恢复跟随默认);+ * 筛选的 'all' 即「不筛选」= 默认,写入时删除字段(「重置筛选」由此恢复跟随默认);* 其余字段一经用户显式选择就保留为 override,即使恰好等于当前默认值。* 旧版本写下的完整记录无法区分是否自定义,按规则不猜测,原样当作 override。*/@@ -111,13 +115,15 @@ async function writeHomeViewPreferences(patch: HomeViewPreferencePatch): Promiseassign('manualProjectOrder', patch.manualProjectOrder ? [...patch.manualProjectOrder] : undefined);assign('viewMode', patch.viewMode);assign('taskInfoFields', patch.taskInfoFields ? [...patch.taskInfoFields] : undefined);- if (patch.projectFilter) {- if (patch.projectFilter.value === 'all') {- delete record.projectFilter;- delete record.projectFilterOwner;+ for (const field of ['projectFilter', 'teammateFilter'] as const) {+ const filter = patch[field];+ if (!filter) continue;+ if (filter.value === 'all') {+ delete record[field];+ delete record[`${field}Owner`];} else {- record.projectFilter = [...patch.projectFilter.value];- record.projectFilterOwner = patch.projectFilter.owner;+ record[field] = [...filter.value];+ record[`${field}Owner`] = filter.owner;}}for (const field of ['vendorFilter', 'lastActivityFilter'] as const) {@@ -163,6 +169,8 @@ function emptyPreferences(): HomeViewPreferences {projectOrder: 'activity',manualProjectOrder: [],projectFilter: 'all',+ teammateFilter: 'all',+ teammateFilterOwner: '',projectFilterOwner: '',vendorFilter: 'all',lastActivityFilter: 'all',@@ -191,6 +199,8 @@ function normalizeStoredPreferences(value: unknown): HomeViewPreferences {projectOrder: record.projectOrder === 'custom' ? 'custom' : 'activity',manualProjectOrder: readStringList(record.manualProjectOrder),projectFilter: normalizeProjectFilter(record.projectFilter),+ teammateFilter: normalizeProjectFilter(record.teammateFilter),+ teammateFilterOwner: readString(record.teammateFilterOwner) ?? '',projectFilterOwner: readString(record.projectFilterOwner) ?? '',vendorFilter: normalizeVendorFilter(record.vendorFilter),lastActivityFilter: normalizeLastActivityFilter(record.lastActivityFilter),diff --git a/apps/mobile/src/session/mobileHomeListCache.ts b/apps/mobile/src/session/mobileHomeListCache.tsindex f4454fb085..57f54f2df7 100644--- a/apps/mobile/src/session/mobileHomeListCache.ts+++ b/apps/mobile/src/session/mobileHomeListCache.ts@@ -1,3 +1,4 @@+import { parseTaskCompanion, parseTaskTeammate } from './teammateTaskSource';import { getSessionListActivityAt } from '@cindy/maker-shared/session-activity';import { normalizeTaskTags } from '@cindy/maker-shared';import AsyncStorage from '@react-native-async-storage/async-storage';@@ -232,6 +233,8 @@ function coerceCachedSession(item: unknown): RemoteSession | null {// Keep that identity in the cold-start list too; otherwise an SSH row can borrow a local alias.if (typeof item.remoteHostId === 'string') session.remoteHostId = item.remoteHostId;if (typeof item.source === 'string') session.source = item.source;+ session.companion = parseTaskCompanion(item.companion);+ session.taskTeammate = parseTaskTeammate(item.taskTeammate);if (orcaRole) session.orcaRole = orcaRole;if (typeof item.pinnedAt === 'string') session.pinnedAt = item.pinnedAt;if (typeof item.preview === 'string') session.preview = truncateText(item.preview);diff --git a/apps/mobile/src/session/readTeammateTasks.ts b/apps/mobile/src/session/readTeammateTasks.tsnew file mode 100644index 0000000000..59f05b334b--- /dev/null+++ b/apps/mobile/src/session/readTeammateTasks.ts@@ -0,0 +1,91 @@+import { resolveRemoteText } from '@cindy/device-link';+import { isAccessRevokedRemoteError as isAccessRevokedError } from '@cindy/maker-shared/device-link-contract';+import type { RemoteInvoke } from '@/device-link/mobileMakerTransport';+import { listRemoteCollection, normalizeRemoteCollectionItems } from '@/device-link/remoteResources';+import { readCompanionTask } from './companionTaskReads';+import { isTeammateTask, parseTaskCompanion, type TaskTeammate } from './teammateTaskSource';+import type { RemoteSession } from './types';++/** Released hosts expose these read APIs even when sessions:list omits bot lanes.+ * Caller supplies its account/query fence; no process-global results or per-row reads. */+export async function readTeammateTasks(input: {+ invoke: RemoteInvoke; deviceId: string; deviceName: string; scope: string;+ sessions: readonly RemoteSession[]; previous?: readonly RemoteSession[];+ status: string; limit: number; current(): boolean;+}): Promise<RemoteSession[]> {+ const { invoke, deviceId, current, status, limit } = input;+ const matches = (s: RemoteSession) => s.status !== 'deleted' && (status === 'all' || s.status === status || !!s.pinnedAt);+ const rows = new Map(input.sessions.map(row => [row.id, row]));+ const previous = new Map((input.previous ?? []).filter(row => row.deviceLinkDeviceId === deviceId).map(row => [row.id, row]));+ // Independent from roster support: old hosts' history carries the exact lane owner.+ try {+ const links = new Map<string, NonNullable<RemoteSession['companion']>>();+ const cursors = new Set<string>();+ let cursor: string | undefined;+ do {+ if (!current()) return [];+ const reply = await invoke<{ ok: boolean; sessions: Array<RemoteSession>; hasMore?: boolean; nextCursor?: string }>(+ deviceId, 'local-db:history:query', [{ tool: 'list_sessions', args: {+ source: 'bot', time_field: 'activity', limit: 200, ...(cursor ? { cursor } : {}),+ } }]);+ if (!current()) return [];+ if (!reply?.ok || !Array.isArray(reply.sessions)) throw new Error('Invalid task history');+ for (const row of reply.sessions) {+ const companion = parseTaskCompanion(row.companion);+ if (typeof row.id === 'string' && isTeammateTask({ ...row, companion }) && matches(row)) links.set(row.id, companion!);+ }+ if (!reply.hasMore || links.size >= limit) break;+ if (!reply.nextCursor || cursors.has(reply.nextCursor)) throw new Error('Invalid task history cursor');+ cursor = reply.nextCursor;+ cursors.add(cursor);+ } while (current());+ const ids = [...links.keys()].slice(0, limit);+ // Existing reader batches eight requests, with serial fallback only for old hosts.+ const values = await Promise.all(ids.map(id => rows.get(id) ?? readCompanionTask(input.scope, deviceId, id, invoke, current)));+ if (!current()) return [];+ values.forEach((value, index) => {+ const row = value as RemoteSession | null;+ if (row && row.id === ids[index] && row.source === 'bot' && matches(row)) rows.set(row.id, { ...row, companion: links.get(row.id)! });+ });+ } catch (error) {+ if (isAccessRevokedError(error)) throw error;+ // Optional/temporarily unavailable history must not remove last known lanes.+ for (const row of previous.values()) if (isTeammateTask(row) && matches(row) && !rows.has(row.id)) rows.set(row.id, row);+ }+ const creators = new Map<string, TaskTeammate>();+ const owners = new Map<string, TaskTeammate>();+ const checked = new Set<string>();+ let rosterRead = false;+ try {+ if (!current()) return [];+ const response = await listRemoteCollection(invoke, { deviceId, deviceName: input.deviceName }, 'teammates');+ if (!current()) return [];+ if (response.collectionId !== 'teammates' || !Array.isArray(response.items)) throw new Error('Invalid teammates');+ const items = normalizeRemoteCollectionItems(response, 'teammates').filter(item => item.ref.kind === 'bot');+ rosterRead = true;+ for (const item of items) {+ const bot: TaskTeammate = { id: item.ref.id, name: resolveRemoteText(item.display.title), avatar: item.display.avatar };+ owners.set(bot.id, bot);+ const session = item.links?.find(link => link.rel === 'conversation' && link.target.kind === 'session')?.target;+ if (session?.kind !== 'session') continue;+ if (!current()) return [];+ try {+ const reply = await invoke<{ ok: boolean; delegations: Array<{ requestingBotId: string; childSessionId: string }> }>(+ deviceId, 'maker:bot-delegations:list', [session.sessionId]);+ if (!current()) return [];+ if (!reply?.ok || !Array.isArray(reply.delegations)) continue;+ checked.add(bot.id);+ for (const task of reply.delegations) if (task.requestingBotId === bot.id && typeof task.childSessionId === 'string') creators.set(task.childSessionId, bot);+ } catch (error) { if (isAccessRevokedError(error)) throw error; }+ }+ } catch (error) { if (isAccessRevokedError(error)) throw error; }+ if (!current()) return [];+ return [...rows.values()].filter(row => row.source !== 'bot' || isTeammateTask(row)).map(row => {+ const old = previous.get(row.id)?.taskTeammate;+ const ownerId = isTeammateTask(row) ? row.companion!.id : undefined;+ const found = ownerId ? owners.get(ownerId) : creators.get(row.id);+ // Successful absence clears attribution; transient failure retains it on the same host.+ const retained = old && (!rosterRead || (owners.has(old.id) && !checked.has(old.id))) ? old : undefined;+ return { ...row, taskTeammate: found ?? retained ?? null };+ });+}diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex 1b93e86f84..4aef340f87 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -1,3 +1,4 @@+import { isTeammateTask } from './teammateTaskSource';import { readTokenSpeedSnapshot, type TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';import { historyTurnEnded, nextHistoryCacheReceipt } from '@cindy/maker-shared/message-window';import { normalizeTaskTags, reconcileTaskTags } from '@cindy/maker-shared';@@ -1784,6 +1785,7 @@ function sameElementRefs<T>(a: readonly T[], b: readonly T[]): boolean {function reconcileVisibleSessions(): void {const next = mergedSessions.filter((session) => session.source !== 'side-chat'+ && (session.source !== 'bot' || isTeammateTask(session))&& sessionListRemovalPreviews.pendingFields(session.id).length === 0&& (CINDY_MAKE_ENABLED || !isCindyMakeSource(session.source)));if (!sameElementRefs(visibleSessions, next)) visibleSessions = next;@@ -1827,6 +1829,8 @@ function preserveSessionRuntimeFields(if (!local) return fresh;let next = fresh;for (const key of [+ 'companion',+ 'taskTeammate','agentSwitchIntent','runtimeGeneration','runtimeBaseline',diff --git a/apps/mobile/src/session/teammateTaskSource.ts b/apps/mobile/src/session/teammateTaskSource.tsnew file mode 100644index 0000000000..63fd51d9fd--- /dev/null+++ b/apps/mobile/src/session/teammateTaskSource.ts@@ -0,0 +1,64 @@+import type { RemoteResourceAvatar } from '@cindy/device-link';+import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';+import { resolveRemoteText } from '@cindy/device-link';+import type { RemoteSession } from './types';++/** Display attribution only; never used as authorization for a task. */+export interface TaskTeammate {+ id: string;+ name: string;+ avatar?: RemoteResourceAvatar;+}+export type TaskCompanion = { id: string; role: string; channel?: string };++export function taskTeammateKey(id: string, deviceId: string, cloudIds: ReadonlySet<string>, cindyIds: ReadonlySet<string> = new Set()): string {+ if (id === 'cindy-default' || cindyIds.has(id)) return JSON.stringify(['teammate', 'cindy']);+ return cloudIds.has(id) ? JSON.stringify(['companion', id]) : JSON.stringify([deviceId, id]);+}++export function taskTeammateOptions(rows: readonly HostedRemoteCollectionItem[], cloudIds: ReadonlySet<string>, locale: string, cindyIds: ReadonlySet<string> = new Set()) {+ const options = new Map<string, { key: string; title: string; subtitle?: string }>();+ for (const row of rows) {+ if (row.item.ref.kind !== 'bot') continue;+ const id = row.item.ref.id;+ const key = taskTeammateKey(id, row.host.deviceId, cloudIds, cindyIds);+ if (!options.has(key)) options.set(key, { key, title: resolveRemoteText(row.item.display.title, locale),+ ...(cloudIds.has(id) || cindyIds.has(id) || id === 'cindy-default' ? {} : { subtitle: row.host.deviceName }) });+ }+ return [...options.values()];+}++export function isTeammateTask(session: Pick<RemoteSession, 'source' | 'companion'>): boolean {+ return session.source === 'bot' && !!session.companion?.id+ && (session.companion.role === 'routine' || session.companion.role === 'channel');+}++export function parseTaskCompanion(value: unknown): TaskCompanion | undefined {+ if (!value || typeof value !== 'object') return;+ const row = value as Record<string, unknown>;+ if (typeof row.id !== 'string' || !row.id || typeof row.role !== 'string') return;+ return { id: row.id, role: row.role, ...(typeof row.channel === 'string' ? { channel: row.channel } : {}) };+}++export function parseTaskTeammate(value: unknown): TaskTeammate | undefined {+ if (!value || typeof value !== 'object') return;+ const row = value as Record<string, unknown>;+ if (typeof row.id !== 'string' || !row.id || typeof row.name !== 'string') return;+ const avatar = row.avatar as Record<string, unknown> | undefined;+ return { id: row.id, name: row.name, ...(avatar && typeof avatar.kind === 'string'+ && typeof avatar.value === 'string' && typeof avatar.fallbackText === 'string'+ ? { avatar: { kind: avatar.kind, value: avatar.value, fallbackText: avatar.fallbackText } } : {}) };+}++/** Cached device-specific selections keep matching when cloud/preset identity arrives later. */+export function normalizeTaskTeammateSelection(selection: 'all' | readonly string[], cloudIds: ReadonlySet<string>, cindyIds: ReadonlySet<string> = new Set()): 'all' | string[] {+ if (selection === 'all') return selection;+ return [...new Set(selection.map(key => {+ try {+ const parts: unknown = JSON.parse(key);+ if (!Array.isArray(parts) || parts.length !== 2 || !parts.every(part => typeof part === 'string')) return key;+ if (parts[0] === 'teammate') return key;+ return taskTeammateKey(parts[1], parts[0], cloudIds, cindyIds);+ } catch { return key; }+ }))];+}diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex f1bafbfcf7..5aa881d56e 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -83,6 +83,8 @@ export interface RemoteSession {/** main 进程内的下一条消息跨 Agent 切换意图;null = 已确认没有。 */agentSwitchIntent?: RemoteSessionAgentSwitchIntent | null;source?: string;+ companion?: import("./teammateTaskSource").TaskCompanion;+ taskTeammate?: import("./teammateTaskSource").TaskTeammate | null;orcaRole?: 'lead' | 'worker' | string | null;/** 运行设备上的远端 Worker 身份;团队在 Lead 电脑上,不作为本机 orcaRole 使用。旧端缺省。 */orcaRemoteLead?: {diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex d1f2dcbf86..8e75a89892 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -719,6 +719,36 @@ Decision: [#6796, maintainer confirmation](https://github.com/makecindy/cindy/isThe expanded teammate section previews five chats (local teammates, remote teammates, groups and the merged Cindy device row share this limit). Keep the current chat visible within those five rows. Use the task list’s “Show all N” footer style, with “Show less” after expansion. Collapsing the section to its existing avatar strip resets the preview; the strip’s +N button opens the full list. This limit applies to the Desktop sidebar; the Mobile task home section below previews three.+### Desktop and Mobile task creator filters (2026-10-27)++The sidebar's existing Filter submenu adds Teammates. Any source (不限来源) is the default and includes personal tasks and all teammates' tasks;+choosing one teammate selects only its created tasks, then further choices add or remove teammates.+Removing the last choice restores Any source. Reset Filters also clears this dimension, preserving task status,+grouping and sorting. Pinned entries retain their existing exemption from content filters.+Use the existing menu rows, avatar component and check marks; keep the menu open for multiple choices.+Show a remote computer name only for device-scoped identities, to distinguish same-name teammates.+Cindy and cloud companions use a single name row without a computer subtitle: their filters span computers. Persist selections+per viewer account. Built-in Cindy is one choice across computers; choosing it includes every copy’s+created tasks, including archived history. Identify it from preset/cloud identity, never its name; custom+namesakes remain separate. Existing per-computer Cindy selections migrate to the unified choice.+Cloud companions use their account identity across old and current computers; retired copies stay out+of the choices, as in the teammate roster. Unlinked teammates remain keyed by computer and teammate ID.+Creation attribution is distinct from following. Existing teammate routine and IM channel tasks also+appear in the desktop task list and share this filter. Their exact linked owner supplies the avatar;+the tooltip says “Belongs to” to distinguish ownership from delegation or following. Active/archived+filters still apply; main chats, private threads and internal group lanes retain their dedicated entries.+Task rows retain their creator avatar after archiving, on both local and remote computers. Prefer the+creator's avatar when others follow the same task; the tooltip distinguishes creation from following.+Two-line teammate rows grow with their content; align the avatar and check mark with the name line,+keeping the computer name in the same text column and preserving vertical padding.+Verify the menu in all five UI locales and both themes; long names retain the existing menu width.+Mobile uses the same multi-selection semantics in the existing iOS native / Android display menus.+The home (including the task drawer) and device task lists retain creation/ownership avatars after+archiving and cold start. Read the existing teammate delegation and history APIs on older hosts;+keep main chats and internal lanes out of these lists. Cache only portable ownership/avatar metadata+in the account-scoped home snapshot. Late cloud/preset discovery canonicalizes existing selections+without clearing the list or splitting Cindy by computer.+### Mobile task home teammate section (owner-approved “A+B”, 2026-10-24)The task home opens with a “Teammates” section above shared tasks, Pinned and projects. Its header uses the project/Pinned header geometry (56pt, 22 chevron + 20 icon + 16/28 title + 13 count) and a trailing 20pt “+” whose 44pt target ends on the 16pt right edge. Expanded, it shows 78pt teammate rows (teammates and groups mixed by activity), previewing three; the “Show all N” / “Show less” row is 48pt, 15/20 secondary text aligned to the rows’ text column (72pt). Collapsed, it becomes a horizontally scrolling strip: 56pt avatars in 64pt cells, 8pt gap, 16pt side insets, 12/18 names (primary + medium when unread), the row’s 10pt unread dot in a 2pt surface ring, the presence ring while replying, and a dashed 56pt create cell last. Phones scroll instead of the Desktop +N. Both states swap with the list’s 225ms disclosure; reduced motion switches instantly. Every language must fit the header and names without widening; long names truncate to one line within the cell.diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex eef02efd74..f91cc334e2 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -3604,3 +3604,42 @@ worker 的任务,按最近更新取前 200 条;伙伴行 `revision` 追加旧控制端按未知 rel 忽略,`conversation` 仍是第一条链接,打开聊天不变;新控制端连接旧 Host时没有该链接,任务行不显示标记。Mobile 读取的链接上限由 64 放宽到 256 以容纳这组链接。不增加 IPC channel、请求参数、数据库字段、push 类型或 Mobile 原生配置。++## 桌面伙伴来源筛选++桌面在读取 `teammates` 名册后,用每个伙伴的 `conversation` 任务 ID 调用既有的+`maker:bot-delegations:list`。只将 `requestingBotId` 匹配、`childSessionId` 非空的记录+作为创建来源;不把接手关系当创建,也不要求远端支持新增的 `created` link。+包含活跃和归档任务,实际展示仍由任务列表状态筛选决定;旧版远端也能直接使用。+已有 `following` 链接继续提供跟进标记,任务创建关系同时用于远程创建者头像。++按电脑 ID + 伙伴 ID 区分筛选,按电脑 ID + 任务 ID 匹配任务;远程头像使用原电脑媒体地址。+同一 Host 串行读取伙伴任务记录,关系缓存保留 ID、不保存任务卡正文。委派变更推送与+名册变更沿原刷新合并窗口更新;读取失败保留已有归属,成功空结果清空。+切账号、撤权、断线后的旧响应仍受原请求代次隔离。只读关系请求失败不重启 relay、+不影响其它设备、不重放任何任务操作。不增加 IPC、权限、服务端字段或数据库迁移。++Task creator filtering resolves built-in Cindy identity through the existing local `listCindyCopies` read,+which now returns even a single remaining cloud Cindy. The merge settings entry still requires two copies.+This allows old remote hosts without template metadata to participate in the unified filter without+changing their wire protocol or triggering any companion merge. Identity is cached with the owner-scoped roster.++### 伙伴独立任务的列表归属(2026-10-27)++`sessions:list/get/get-many` 可选投影 `companion: { id, role, channel? }`,从现有+`bot_session_links` 读取,不新增数据库列或改运行身份。普通列表仅纳入 `routine/channel`,+仍过滤隐藏任务与删除中的伙伴;`canonical/thread/group` 保留伙伴入口。+旧远端的普通列表未包含这些任务时,桌面经原有同账号 `history:query/list_sessions`+分页读取 `source=bot` 的归属,再用原有批量/单条读取补齐 Session。无权限或接口失败不能+清空普通任务;撤权沿原处理路径上报。设备/状态代次失效时丢弃迟到回复,保留其它设备的+镜像,不重启链路或重新授权。离线镜像仅保存归属的 id/role/channel,恢复时仍可筛选和显示头像。+++Mobile follows the same read-only compatibility path for teammate task attribution and independent+routine/channel Sessions. `taskTeammate` is a client-local display projection (ID/name/avatar), not a+new wire field or permission. Its slim home cache keeps it with `companion`; optional read failure+retains that host's previous attribution and successful absence clears it. Account/query invalidation+and list mutation epochs fence all late results. Home and device list refreshes share this reader.+Cloud Cindy identities come from the existing owner-scoped `/preferences` profile snapshots, using+the same exact preset identity helper as Desktop. Only their IDs enter the cloud-home display cache;+profile bodies are not persisted. This adds no endpoint, database migration or native configuration.diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.mdindex 79dcc2f27e..3930de18f1 100644--- a/docs/product-rules/bot-routines.md+++ b/docs/product-rules/bot-routines.md@@ -6,7 +6,7 @@一条例行任务属于一个伙伴,包含名称、常驻指令、启用状态和多个触发条件。条件之间是 OR:同一事件命中多个条件只入队一次。时间条件与事件条件可以共存,适合「PR 更新时检查,每小时兜底」。条件编辑不授予模型额外权限。-桌面入口在伙伴设置「例行任务」及伙伴任务的标准右侧栏。列表里的普通规则和内置规则都用右侧开关直接启停,文字明确显示启用/暂停,排队/运行中单独显示,不以时钟或暂停图标代替状态。点普通规则名称进入详情,仍可修改指令、立即运行、增删触发条件、删除规则和查看历史;历史的失败/中断结果在展开前可读。立即运行先保存当前编辑,再运行,避免执行屏幕上看不到的旧指令。+桌面入口在伙伴设置「例行任务」及伙伴任务的标准右侧栏。已创建的例行任务 Session 也进入桌面和手机任务列表,按真实伙伴归属显示头像、参与伙伴来源筛选;仅有自动化规则、尚未创建 Session 时不凭空生成列表任务。列表里的普通规则和内置规则都用右侧开关直接启停,文字明确显示启用/暂停,排队/运行中单独显示,不以时钟或暂停图标代替状态。点普通规则名称进入详情,仍可修改指令、立即运行、增删触发条件、删除规则和查看历史;历史的失败/中断结果在展开前可读。立即运行先保存当前编辑,再运行,避免执行屏幕上看不到的旧指令。时间描述跟随界面语言,复用调度器的 Cron 解析规则,保留全部小时、分钟、日期与 IANA 时区;复杂条件可展开,多个条件明确为满足任一项即运行。不依据前端时钟推测下次执行,也不把配置更新时间当作最近结果。定时菜单提供每小时、每天、工作日、每周、每月、间隔和高级 Cron。事件菜单来自实际插件声明,不显示未接入平台的假入口。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 3b3d02a17e..4d99bc877d 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -276,7 +276,7 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭侧边栏全文搜索覆盖普通任务及伙伴个人主聊天、历史线程,本机还包含伙伴消息平台的渠道专线,默认包含归档历史。搜索结果带伙伴姓名,点击后保持命中的线程与消息位置;不依赖伙伴在侧栏是否展开或已加载。历史线程和本机渠道专线打开原 ID 的普通任务页面,沿用该任务的权限、消息定位与归档状态;不切回当前主任务,-不因打开页面恢复发送队列。伙伴群聊内部专线不进入搜索;渠道专线仍不进入普通任务列表,不因搜索恢复或归档任务。远程搜索继续排除渠道专线;伙伴委派的普通后台任务保持普通任务入口。+不因打开页面恢复发送队列。伙伴群聊内部专线不进入搜索;渠道专线与自动化任务(`bot_session_links.role=channel/routine`)进入桌面和手机普通任务列表,显示所属伙伴头像,并参与单选/多选伙伴来源筛选;已有记录同样展示,归档状态遵从任务筛选,不因展示而恢复或运行任务。伙伴主聊天、私聊话题和内部群聊专线保留各自入口。远程搜索继续排除渠道专线;伙伴委派的普通后台任务保持普通任务入口。手机首页、设备页与任务抽屉采用同一结果归属与消息定位。远程仍遵守既有伙伴可见性:整体隐藏或归档的伙伴只在所属电脑本地恢复,不能因新增搜索入口扩大远程权限。实现见 `localDb/conversationSearch.ts`、`ConversationSearchBox.tsx` 与 Mobilediff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex 94716bc268..e768c24cd4 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -13,6 +13,7 @@"./agent-input-projection": "./src/agentInputProjection.ts","./auto-review-intent": "./src/autoReviewIntent.ts","./agent-task": "./src/agentTask.ts",+ "./bot-template-preset": "./src/botTemplatePreset.ts","./branding": "./src/branding.ts","./brand-identity": "./src/brandIdentity.ts","./chat-quotes": "./src/chatQuotes.ts",diff --git a/packages/maker-shared/src/botTemplatePreset.ts b/packages/maker-shared/src/botTemplatePreset.tsnew file mode 100644index 0000000000..dd3d2c3685--- /dev/null+++ b/packages/maker-shared/src/botTemplatePreset.ts@@ -0,0 +1,55 @@+export const BOT_TEMPLATE_PRESET_IDS = ['cindy'] as const;++export type BotTemplatePresetId = (typeof BOT_TEMPLATE_PRESET_IDS)[number];++export const BOT_TEMPLATE_PRESET_AVATARS: Record<BotTemplatePresetId, string> = {+ cindy: 'cindy://avatar/preset/cindy',+};++/**+ * 仅保留旧 Cindy 的精确身份指纹,以识别默认伙伴而不重复创建。用户改过+ * SOUL 后不再根据姓名或头像猜测身份;已建立的其它伙伴不依赖模板运行。+ */+export const BOT_TEMPLATE_PRESET_IDENTITIES: Record<BotTemplatePresetId, string> = {+ cindy: [+ '# 身份\n你是 Cindy 助理,负责处理用户日常工作与生活中的大部分 AI 需求。',+ '# 主要职责\n写作、整理、分析、计划、资料制作和事务推进;遇到更适合由专业伙伴处理的工作时,主动请对方接手并带回结果。',+ '# 擅长处理\n邮件与文案、资料归纳、方案梳理、日程与行动计划、跨事项协调,以及把零散输入整理成可继续使用的文档。',+ '# 做事方式\n先理解用户真正要得到的结果;简单工作直接完成,复杂工作拆清楚后推进。对外只用自然语言描述协作,不暴露内部技术名词。',+ '# 判断标准\n结果是否准确、完整、容易继续使用;是否在需要时找到了更合适的伙伴,而没有把协调负担留给用户。',+ '# 输出格式\n先给结论或成品,再补必要说明。需要留档、分享或继续编辑时,形成正式文档。',+ '# 需要确认的情况\n涉及不可逆操作、对外发送、费用、权限或会显著改变目标的取舍时先确认。',+ '# 不应该做的事\n不虚构事实,不把不确定判断说成结论,不用 Bot、Session、Worker、MCP、harness 等内部词汇向用户解释工作。',+ ].join('\n\n'),+};++/** Previous default: recognition only; never rewrite an existing SOUL. */+const PREVIOUS_CINDY_DEFAULT_IDENTITY = [+ '# 身份\n你是 Cindy,Cindy 客户端里的默认伙伴。你帮助用户使用客户端和已连接的工具完成工作;你不是整个客户端,也不代替用户拥有账号和权限。',+ '# 工作\n处理写作、整理、分析、计划和日常事务。简单工作直接完成;编码实施和中大型工作使用独立任务,跟进结果并核对后交付。伙伴间消息用于必要沟通,不代替独立任务。',+ '# 方式\n先理解用户想得到的结果,再用实际可用的工具行动。需要外部服务时先查已安装插件并复用已有连接;按宿主提供的授权卡完成缺失的连接。',+ '# 相处\n表达自然、简洁、具体。保留用户已给出的要求和授权;不编造背景、能力或完成状态,不反复询问已经明确的事情。',+].join('\n\n');++/** New installations; the legacy identity above remains an exact migration fingerprint. */+export const CINDY_DEFAULT_IDENTITY = [+ '# 身份\n你是 Cindy,Cindy 客户端里的默认伙伴。你帮助用户使用客户端和已连接的工具完成工作;你不是整个客户端,也不代替用户拥有账号和权限。',+ '# 工作\n处理写作、整理、分析、计划和日常事务。优先在当前对话完成工作;需要独立执行时按当前工具指引开任务,跟进并核对结果。',+ '# 方式\n先理解用户想得到的结果,再用实际可用的工具行动。需要外部服务时先查已安装插件并复用已有连接;按宿主提供的授权卡完成缺失的连接。',+ '# 相处\n表达自然、简洁、具体。保留用户已给出的要求和授权;不编造背景、能力或完成状态,不反复询问已经明确的事情。',+].join('\n\n');++export function inferBotTemplatePresetId(identitySource: string): BotTemplatePresetId | null {+ if (identitySource === CINDY_DEFAULT_IDENTITY || identitySource === PREVIOUS_CINDY_DEFAULT_IDENTITY) return 'cindy';+ return (+ BOT_TEMPLATE_PRESET_IDS.find(+ (templateId) => BOT_TEMPLATE_PRESET_IDENTITIES[templateId] === identitySource,+ ) ?? null+ );+}++export function isBotTemplatePresetId(value: unknown): value is BotTemplatePresetId {+ return (+ typeof value === 'string' && (BOT_TEMPLATE_PRESET_IDS as readonly string[]).includes(value)+ );+}