Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(bots): 支持消息平台对话列表归档与折叠
xd0da257bbef0e
diff --git a/apps/desktop/scripts/fixtures/wechat-companion/ui-page.mjs b/apps/desktop/scripts/fixtures/wechat-companion/ui-page.mjsindex 3c2bd89600..5bb10a5bbe 100644--- a/apps/desktop/scripts/fixtures/wechat-companion/ui-page.mjs+++ b/apps/desktop/scripts/fixtures/wechat-companion/ui-page.mjs@@ -85,6 +85,14 @@ export default {assert.notEqual(focused.boxShadow, 'none', 'focus ring must survive the global outline suppression');assert.equal(focused.outlineStyle, 'none');await row.evaluate((el) => el.blur());+ const platform = await ui.t('bots.channels.platform.feishu');+ const collapse = page.getByRole('button', { name: await ui.t('bots.channels.lanes.collapse', { platform }), exact: true });+ await ui.capture('tasks-expanded');+ await collapse.click();+ assert.equal(await row.isVisible(), false, 'task records collapse without invoking a write');+ await ui.capture('tasks-collapsed');+ await page.getByRole('button', { name: await ui.t('bots.channels.lanes.expand', { platform }), exact: true }).click();+ assert.equal(await row.isVisible(), true, 'task records return after expanding');return;}const trigger = page.locator('#companion-im-wechat-trigger');diff --git a/apps/desktop/scripts/fixtures/wechat-companion/wechat-companion-fixture.tsx b/apps/desktop/scripts/fixtures/wechat-companion/wechat-companion-fixture.tsxindex a9c25265ec..33b747076c 100644--- a/apps/desktop/scripts/fixtures/wechat-companion/wechat-companion-fixture.tsx+++ b/apps/desktop/scripts/fixtures/wechat-companion/wechat-companion-fixture.tsx@@ -41,6 +41,7 @@ mountPage({state: 'running', lastActivityAt: Date.now() - 300000, contextMessageCount: 11 },] }),resetLane: forbid('botImConnection.resetLane'),+ archiveLane: forbid('botImConnection.archiveLane'),onChanged: subscription('connections'),},maker: {diff --git a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.tsindex c82a936976..b459fe0837 100644--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts@@ -12,6 +12,7 @@ import type { BotImConnectionRecord } from '../../../../shared/botImConnection';const h = vi.hoisted(() => ({root: '',+ ipcHandlers: new Map<string, (event: unknown, payload: unknown) => unknown>(),secrets: new Map<string, string>(),botStatus: 'active' as string | null,archived: [] as string[],@@ -25,7 +26,7 @@ const h = vi.hoisted(() => ({vi.mock('electron', () => ({app: { getPath: () => h.root },- ipcMain: { handle: vi.fn() },+ ipcMain: { handle: vi.fn((name: string, handler: (event: unknown, payload: unknown) => unknown) => h.ipcHandlers.set(name, handler)) },BrowserWindow: {getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: (channel: string, payload: unknown) => h.sent.push({ channel, payload }) } },@@ -83,6 +84,7 @@ vi.mock('../../../security/trustedAppRenderer', () => ({ assertTrustedAppRendereimport {addBotImConnection,configureBotImConnectionRuntime,+ registerBotImConnectionIpc,setWechatCompanionBinding,getBotFeishuTransport,listBotImConnectionGroups,@@ -283,6 +285,17 @@ let connectOutcome = true;let telegramConflictAfterConnect = false;describe('bot im connection runtime', () => {+ // Electron IPC 安全规则 §5:新增归档入口不能绕过 sender/payload 校验;旧测试只覆盖连接生命周期。+ // unit:注册真实 handler,以非法 sessionId 作为最小输入,拒绝后无归档写入。+ it('validates archive IPC payload before entering the lane runtime', async () => {+ registerBotImConnectionIpc();+ const handler = h.ipcHandlers.get('botImConnection:archive-lane')!;+ expect(handler).toBeTypeOf('function');+ expect(() => handler({}, { id: 'a1b2c3d4e5f6', sessionId: '../outside' })).toThrow(/INVALID_PARAMS/);+ expect(() => handler({}, { id: 'invalid', sessionId: 'session' })).toThrow(/INVALID_PARAMS/);+ expect(h.archiveCalls).toEqual([]);+ });+beforeEach(() => {h.root = fs.mkdtempSync(path.join(os.tmpdir(), 'bot-im-runtime-'));h.secrets.clear();diff --git a/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.tsindex 5642d98365..4e97d69adc 100644--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionStore.test.ts@@ -13,10 +13,11 @@ vi.mock('../../../maker-host/logger-adapter.js', () => ({vi.mock('../../ownerScopedStorage.js', () => ({ownerScopedImUserDataPath: (...parts: string[]) => path.join(h.root, 'owners', h.owner, ...parts),}));-vi.mock('../../../appSessionState.js', () => ({ activeOwnerScopeKey: () => h.owner }));+vi.mock('../../../appSessionState.js', () => ({ activeOwnerScopeKey: () => h.owner, isAppSessionBoundaryPending: () => false }));import {addBotImConnectionRecord,+ archiveBotImTaskRow,listBotImConnections,listBotImConnectionsForBot,readBotImConnection,@@ -127,6 +128,21 @@ describe('bot im connection store', () => {expect(readBotImConnection('222222222222')?.groupActivation).toEqual({ '-1': 'always' });});+ // 用户明确要求只归档列表、不归档 session。既有存储测试没有行级显示偏好。+ // 最小输入一条连接、两个任务行;unit 走真实文件入口验证并发合并、持久化与账号隔离。+ it('persists row archives atomically per connection without changing its binding', async () => {+ const record = await addBotImConnectionRecord({ botId: 'bot-a', channel: 'feishu' }, { id: () => 'aaaaaaaaaaaa' });+ await Promise.all([archiveBotImTaskRow(record, 'session-main'), archiveBotImTaskRow(record, 'session-topic')]);+ expect(readBotImConnection(record.id)).toMatchObject({+ botId: 'bot-a', channel: 'feishu', botContextId: null,+ archivedTaskRows: { 'session-main': expect.any(Number), 'session-topic': expect.any(Number) },+ });+ expect(JSON.parse(fs.readFileSync(file(), 'utf8')).connections[record.id].archivedTaskRows)+ .toEqual(readBotImConnection(record.id)?.archivedTaskRows);+ h.owner = 'owner-b';+ expect(readBotImConnection(record.id)).toBeNull();+ });+it('is scoped per data owner', async () => {await addBotImConnectionRecord({ botId: 'bot-a', channel: 'telegram' }, { id: () => 'ffffffffffff' });h.owner = 'owner-b';diff --git a/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.tsindex 13687a9660..27f6918ee6 100644--- a/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/botImLaneRuntime.test.ts@@ -10,8 +10,11 @@ import type { BotImConnectionRecord } from '../../../../shared/botImConnection';const h = vi.hoisted(() => ({records: new Map<string, unknown>(),+ archived: new Set<string>(),+ owner: 'owner-a',}));+vi.mock('../../../appSessionState.js', () => ({ activeOwnerScopeKey: () => h.owner, isAppSessionBoundaryPending: () => false }));vi.mock('../../../logger', () => ({createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),}));@@ -19,10 +22,17 @@ vi.mock('../../../localDb/client/current', () => ({ getDbClient: vi.fn() }));vi.mock('../../../localDb/schema', () => ({ botSessionLinks: {}, messages: {}, sessions: {} }));vi.mock('../botImConnectionStore', () => ({readBotImConnection: (id: string) => h.records.get(id) ?? null,+ archiveBotImTaskRow: async (record: BotImConnectionRecord, sessionId: string) => {+ const next = { ...record, archivedTaskRows: { ...record.archivedTaskRows, [sessionId]: Date.now() } };+ h.records.set(record.id, next);+ h.archived.add(sessionId);+ return next;+ },}));import {__testing,+ archiveBotImConnectionLane,configureBotImLaneRuntime,listBotImConnectionLanes,resetBotImConnectionLane,@@ -73,12 +83,46 @@ const knownGroups = vi.fn(async () => [{ chatId: '-1001', chatName: 'Launch crewbeforeEach(() => {vi.clearAllMocks();h.records.clear();+ h.archived.clear();+ h.owner = 'owner-a';h.records.set(TELEGRAM.id, TELEGRAM);__testing.setStore({ listLinks, readActivity });configureBotImLaneRuntime({ isTurnRunning: (id) => id === 's-guest', restartSession });});describe('botImLaneRuntime', () => {+ // 用户确认的专线归档:既有覆盖只有重启;unit 注入存储验证列表移除与越权拒绝。+ it('archives only the selected connection row and preserves all session links', async () => {+ const payload = await archiveBotImConnectionLane(TELEGRAM.id, 's-topic');+ expect(payload.lanes.map((lane) => lane.sessionId)).toEqual(['s-main', 's-group', 's-guest']);+ expect(h.archived).toEqual(new Set(['s-topic']));+ await expect(archiveBotImConnectionLane(TELEGRAM.id, 's-feishu')).rejects.toThrow(/LANE_NOT_FOUND/);+ await expect(archiveBotImConnectionLane(TELEGRAM.id, 's-other-bot')).rejects.toThrow(/LANE_NOT_FOUND/);+ expect(h.archived).toEqual(new Set(['s-topic']));+ expect(await listLinks(TELEGRAM.botId)).toEqual(LINKS);+ const afterOwnerArchive = await archiveBotImConnectionLane(TELEGRAM.id, 's-main');+ expect(afterOwnerArchive.lanes.map((lane) => lane.sessionId)).toEqual(['s-group', 's-guest']);+ expect(restartSession).not.toHaveBeenCalled();+ });++ // 列表归档不改变 session:后续消息仍在原任务上,既有用例不覆盖归档后的活动。+ it('shows the same session again after new activity without creating or restarting it', async () => {+ await archiveBotImConnectionLane(TELEGRAM.id, 's-topic');+ readActivity.mockImplementationOnce(async () => ACTIVITY['s-main']);+ readActivity.mockImplementationOnce(async () => ACTIVITY['s-group']);+ readActivity.mockImplementationOnce(async () => activity({ lastActivityAt: Date.now() + 1 }));+ const payload = await listBotImConnectionLanes(TELEGRAM.id);+ expect(payload.lanes.some((lane) => lane.sessionId === 's-topic')).toBe(true);+ expect(await listLinks(TELEGRAM.botId)).toEqual(LINKS);+ expect(restartSession).not.toHaveBeenCalled();+ });++ it('does not archive after an account change during the ownership lookup', async () => {+ listLinks.mockImplementationOnce(async () => { h.owner = 'owner-b'; return LINKS; });+ await expect(archiveBotImConnectionLane(TELEGRAM.id, 's-topic')).rejects.toThrow(/OWNER_CHANGED/);+ expect(h.archived.size).toBe(0);+ });+it('lists only the lanes of this connection, with names, state and order from existing data', async () => {const payload = await listBotImConnectionLanes(TELEGRAM.id, { knownGroups });diff --git a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts b/apps/desktop/src/main/im/shared/botImConnectionRuntime.tsindex fe9c5b19e9..4d22caccff 100644--- a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts+++ b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts@@ -53,7 +53,7 @@ import {updateBotImConnectionRecord,} from './botImConnectionStore';import { companionConnectionRouteKeyPrefix } from './imBotBindingRoute';-import { listBotImConnectionLanes, resetBotImConnectionLane } from './botImLaneRuntime';+import { archiveBotImConnectionLane, listBotImConnectionLanes, resetBotImConnectionLane } from './botImLaneRuntime';import type { ImOrchestrator } from './orchestrator';const log = createLogger('im:bot-connections');@@ -784,6 +784,15 @@ export function registerBotImConnectionIpc(): void {}return resetBotImConnectionLane(p.id, p.sessionId, laneOptions);});+ ipcMain.handle('botImConnection:archive-lane', (e, payload) => {+ assertTrustedAppRendererEvent(e);+ const p = (payload ?? {}) as { id?: unknown; sessionId?: unknown };+ if (!isBotImConnectionId(p.id)) throwIpcError('INVALID_PARAMS', 'id is invalid');+ if (typeof p.sessionId !== 'string' || !/^[A-Za-z0-9_.:-]{1,200}$/.test(p.sessionId)) {+ throwIpcError('INVALID_PARAMS', 'sessionId is invalid');+ }+ return archiveBotImConnectionLane(p.id, p.sessionId, laneOptions);+ });}export const __testing = { instances, purgeSecrets, toView };diff --git a/apps/desktop/src/main/im/shared/botImConnectionStore.ts b/apps/desktop/src/main/im/shared/botImConnectionStore.tsindex 511246d82f..ace094556a 100644--- a/apps/desktop/src/main/im/shared/botImConnectionStore.ts+++ b/apps/desktop/src/main/im/shared/botImConnectionStore.ts@@ -10,7 +10,7 @@import { randomBytes } from 'node:crypto';-import { activeOwnerScopeKey } from '../../appSessionState.js';+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../appSessionState.js';import { desktopMakerLogger } from '../../maker-host/logger-adapter.js';import { createOverrideSettingsFile } from '../../maker-host/override-settings-file.js';import { ownerScopedImUserDataPath } from '../ownerScopedStorage.js';@@ -60,6 +60,7 @@ function normalizeRecord(id: string, raw: unknown): Omit<BotImConnectionRecord,? r.botContextId: null;const groupActivation = normalizeGroupActivation(r.groupActivation);+ const archivedTaskRows = normalizeArchivedTaskRows(r.archivedTaskRows);return {botId: r.botId,channel: r.channel,@@ -67,9 +68,19 @@ function normalizeRecord(id: string, raw: unknown): Omit<BotImConnectionRecord,...(service ? { service } : {}),botContextId,...(groupActivation ? { groupActivation } : {}),+ ...(archivedTaskRows ? { archivedTaskRows } : {}),};}+/** Presentation state only: malformed cutoffs cannot hide a row. */+function normalizeArchivedTaskRows(raw: unknown): Record<string, number> | undefined {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;+ const rows = Object.fromEntries(Object.entries(raw).filter(([id, at]) =>+ /^[A-Za-z0-9_.:-]{1,200}$/.test(id) && typeof at === 'number' && Number.isFinite(at) && at >= 0,+ )) as Record<string, number>;+ return Object.keys(rows).length ? rows : undefined;+}+/** 只认 chatId → 'always'; 'mention' 是缺省, 不落盘。未知值整条丢弃。 */function normalizeGroupActivation(raw: unknown): Record<string, 'always'> | undefined {if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;@@ -165,6 +176,28 @@ export async function updateBotImConnectionRecord(return next;}+/** Archive a row in one connection, without touching its session or route link. */+export async function archiveBotImTaskRow(+ expected: BotImConnectionRecord,+ sessionId: string,+): Promise<BotImConnectionRecord | null> {+ const owner = activeOwnerScopeKey();+ let next: BotImConnectionRecord | null = null;+ await file.updateAtomic((current) => {+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner) throw new Error('OWNER_CHANGED');+ const existing = current.value.connections[expected.id];+ if (!existing || existing.botId !== expected.botId || existing.channel !== expected.channel || existing.botContextId !== expected.botContextId) return current.value;+ const merged = {+ ...existing,+ archivedTaskRows: { ...existing.archivedTaskRows, [sessionId]: Date.now() },+ };+ next = { id: expected.id, ...merged };+ return { connections: { ...current.value.connections, [expected.id]: merged } };+ }, { preserveDefaults: true });+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner) throw new Error('OWNER_CHANGED');+ return next;+}+/** 单个群的参与模式(always 写入, mention 回缺省并从表中清除)。 */export async function setBotImConnectionGroupActivation(id: string,diff --git a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts b/apps/desktop/src/main/im/shared/botImLaneRuntime.tsindex e1e3d2b112..51ed6a9756 100644--- a/apps/desktop/src/main/im/shared/botImLaneRuntime.ts+++ b/apps/desktop/src/main/im/shared/botImLaneRuntime.ts@@ -18,6 +18,7 @@import { and, count, desc, eq, gt, inArray, isNull, sql } from 'drizzle-orm';+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../appSessionState.js';import { createLogger } from '../../logger';import { getDbClient } from '../../localDb/client/current';import { botSessionLinks, messages, sessions } from '../../localDb/schema';@@ -28,7 +29,7 @@ import type {BotImConnectionRecord,BotImLaneKind,} from '../../../shared/botImConnection';-import { readBotImConnection } from './botImConnectionStore';+import { archiveBotImTaskRow, readBotImConnection } from './botImConnectionStore';import { companionConnectionRouteKeyPrefix } from './imBotBindingRoute';const log = createLogger('im:bot-lanes');@@ -245,7 +246,10 @@ export async function listBotImConnectionLanes(if (a.kind === 'owner-dm' || b.kind === 'owner-dm') return a.kind === 'owner-dm' ? -1 : 1;return (b.lastActivityAt ?? 0) - (a.lastActivityAt ?? 0);});- return { connectionId: id, lanes };+ return { connectionId: id, lanes: lanes.filter((lane) => {+ const archivedAt = record.archivedTaskRows?.[lane.sessionId];+ return typeof archivedAt !== 'number' || (lane.lastActivityAt !== null && lane.lastActivityAt > archivedAt);+ }) };}/**@@ -272,6 +276,34 @@ export async function resetBotImConnectionLane(return listBotImConnectionLanes(id, options);}+/** Archive only a connection list row. The underlying session keeps running unchanged. */+export async function archiveBotImConnectionLane(+ id: string,+ sessionId: string,+ options: BotImLaneListOptions = {},+): Promise<BotImConnectionLanesPayload> {+ const owner = activeOwnerScopeKey();+ const assertCurrent = () => {+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner) {+ throwIpcError('PRECONDITION_FAILED', 'OWNER_CHANGED');+ }+ };+ assertCurrent();+ const record = requireRecord(id);+ const link = (await listScopedLinks(record)).find((item) => item.sessionId === sessionId);+ assertCurrent();+ const current = requireRecord(id);+ if (current.botId !== record.botId || current.botContextId !== record.botContextId || current.channel !== record.channel) {+ throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');+ }+ if (!link) throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');+ if (!await archiveBotImTaskRow(record, sessionId)) throwIpcError('NOT_FOUND', 'LANE_NOT_FOUND');+ assertCurrent();+ const payload = await listBotImConnectionLanes(id, options);+ assertCurrent();+ return payload;+}+export const __testing = {setStore(next: BotImLaneStore | null): void {store = next ?? dbLaneStore;diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 9bb6cc9b3b..cf73eb3095 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -2477,6 +2477,11 @@ contextBridge.exposeInMainWorld('electronAPI', {sessionId: string;}): Promise<import('../shared/botImConnection').BotImConnectionLanesPayload> =>ipcRenderer.invoke('botImConnection:reset-lane', payload),+ archiveLane: (payload: {+ id: string;+ sessionId: string;+ }): Promise<import('../shared/botImConnection').BotImConnectionLanesPayload> =>+ ipcRenderer.invoke('botImConnection:archive-lane', payload),listAdoptable: (): Promise<import('../shared/botImConnection').BotImAdoptablePersonalBotsPayload> =>ipcRenderer.invoke('botImConnection:list-adoptable'),adopt: (diff --git a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsxindex 9118c0c455..af7989b76b 100644--- a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx+++ b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx@@ -9,11 +9,12 @@*/import { HookConnectionsSection } from '@/components/settings/HookConnectionsSection';-import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react';+import { useCallback, useEffect, useId, useRef, useState, type FormEvent } from 'react';import * as Dialog from '@radix-ui/react-dialog';-import { Briefcase, Gamepad2, MessageSquare, Plus, Send, Zap, type LucideIcon } from 'lucide-react';+import { Archive, Briefcase, ChevronRight, ChevronUp, Gamepad2, MessageSquare, Plus, Send, Zap, type LucideIcon } from 'lucide-react';import { useNavigate } from 'react-router-dom';+import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';import { AttentionDot } from '@/components/sidebar/AttentionDot';import { Button } from '@/components/ui/button';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';@@ -41,6 +42,8 @@ import { useBotTranslation } from './botPronounContext';import type { BotProfile } from './botStore';import {addBotImConnection,+ archiveBotImConnectionLane,+ botImConnectionLaneArchiveSupported,adoptPersonalBot,botImConnectionGroupsSupported,botImConnectionLanesSupported,@@ -215,7 +218,7 @@ export function BotChannelsPage({ bot }: { bot: BotProfile }) {<ConnectionGroups connectionId={view.id} botName={bot.name} />) : null}{view.botContextId && botImConnectionLanesSupported() ? (- <ConnectionLanes connectionId={view.id} botId={bot.id} botName={bot.name} />+ <ConnectionLanes connectionId={view.id} botId={bot.id} botName={bot.name} platform={platformName(view)} />) : null}</li>);@@ -358,35 +361,40 @@ const LANE_KIND_KEY: Record<BotImConnectionLane['kind'], string> = {* 显示状态、最近活动和当前上下文里的消息数; 卡住时可以让某一条重新开始(同一条任务,* 记录保留, 下一条消息换干净的上下文)。点击记录复用主界面的只读历史页, 不取消隐藏。*/-function ConnectionLanes({ connectionId, botId, botName }: { connectionId: string; botId: string; botName: string }) {+function ConnectionLanes({ connectionId, botId, botName, platform }: { connectionId: string; botId: string; botName: string; platform: string }) {const { t } = useBotTranslation();const navigate = useNavigate();const { confirm } = useConfirmDialog();+ const [expanded, setExpanded] = useState(true);+ const contentId = useId();const [lanes, setLanes] = useState<BotImConnectionLane[] | null>(null);const [loadFailed, setLoadFailed] = useState(false);const [resettingId, setResettingId] = useState<string | null>(null);+ const [archivingId, setArchivingId] = useState<string | null>(null);const [notice, setNotice] = useState<{ tone: 'done' | 'failed'; text: string } | null>(null);const [reloadToken, setReloadToken] = useState(0);const [now, setNow] = useState(() => Date.now());- const resettingRef = useRef(false);+ const mutatingRef = useRef(false);+ const loadGeneration = useRef(0);useEffect(() => {let cancelled = false;const load = () => {+ const generation = loadGeneration.current;void listBotImConnectionLanes(connectionId).then((payload) => {- if (cancelled) return;+ if (cancelled || generation !== loadGeneration.current || mutatingRef.current) return;setLanes(payload.lanes);setLoadFailed(false);setNow(Date.now());}).catch(() => {- if (!cancelled) setLoadFailed(true);+ if (!cancelled && generation === loadGeneration.current && !mutatingRef.current) setLoadFailed(true);});};load();const timer = setInterval(() => {- if (!document.hidden && !resettingRef.current) load();+ if (!document.hidden && !mutatingRef.current) load();}, LANES_REFRESH_MS);return () => {cancelled = true;@@ -397,35 +405,38 @@ function ConnectionLanes({ connectionId, botId, botName }: { connectionId: strinconst laneName = (lane: BotImConnectionLane) =>lane.kind === 'owner-dm' ? t('bots.channels.lanes.ownerName') : lane.name || lane.chatId || '';- const reset = async (lane: BotImConnectionLane) => {- if (resettingRef.current) return;+ const mutate = async (lane: BotImConnectionLane, action: 'reset' | 'archive') => {+ if (mutatingRef.current) return;+ mutatingRef.current = true;+ loadGeneration.current += 1;const name = laneName(lane);- const ok = await confirm({- title: t('bots.channels.lanes.resetConfirm.title', { lane: name }),- description: t(- lane.kind === 'owner-dm'- ? 'bots.channels.lanes.resetConfirm.ownerDescription'- : 'bots.channels.lanes.resetConfirm.description',- { name: botName },- ),- confirmText: t('bots.channels.lanes.resetConfirm.confirm'),- cancelText: t('bots.channels.lanes.resetConfirm.cancel'),- });- if (!ok) return;- resettingRef.current = true;- setResettingId(lane.sessionId);- setNotice(null);try {- const payload = await resetBotImConnectionLane(connectionId, lane.sessionId);+ const ok = await confirm({+ title: t(`bots.channels.lanes.${action}Confirm.title`, { lane: name }),+ description: t(+ action === 'reset' && lane.kind === 'owner-dm'+ ? 'bots.channels.lanes.resetConfirm.ownerDescription'+ : `bots.channels.lanes.${action}Confirm.description`,+ { name: botName },+ ),+ confirmText: t(`bots.channels.lanes.${action}Confirm.confirm`),+ cancelText: t('bots.channels.lanes.resetConfirm.cancel'),+ });+ if (!ok) return;+ if (action === 'reset') setResettingId(lane.sessionId);+ else setArchivingId(lane.sessionId);+ setNotice(null);+ const payload = await (action === 'reset' ? resetBotImConnectionLane : archiveBotImConnectionLane)(connectionId, lane.sessionId);setLanes(payload.lanes);setNow(Date.now());- setNotice({ tone: 'done', text: t('bots.channels.lanes.resetDone', { lane: name }) });+ setNotice({ tone: 'done', text: t(`bots.channels.lanes.${action}Done`, { lane: name }) });} catch {- setNotice({ tone: 'failed', text: t('bots.channels.lanes.resetFailed') });+ setNotice({ tone: 'failed', text: t(`bots.channels.lanes.${action}Failed`) });setReloadToken((value) => value + 1);} finally {- resettingRef.current = false;+ mutatingRef.current = false;setResettingId(null);+ setArchivingId(null);}};@@ -433,7 +444,19 @@ function ConnectionLanes({ connectionId, botId, botName }: { connectionId: strinconst others = (lanes ?? []).filter((lane) => lane.kind !== 'owner-dm');return (<div className="mt-3 flex flex-col gap-2 border-t border-[var(--border-default)] pt-3">- <div className="text-12 font-medium text-[var(--text-primary)]">{t('bots.channels.lanes.title')}</div>+ <div className="flex items-center justify-between text-12 font-medium text-[var(--text-primary)]">+ <span>{t('bots.channels.lanes.title', { platform })}</span>+ <ChromeIconButton+ className="-my-[5px] shrink-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ aria-label={t(expanded ? 'bots.channels.lanes.collapse' : 'bots.channels.lanes.expand', { platform })}+ aria-expanded={expanded}+ aria-controls={contentId}+ onClick={() => setExpanded((value) => !value)}+ >+ {expanded ? <ChevronUp size={14} aria-hidden /> : <ChevronRight size={14} aria-hidden />}+ </ChromeIconButton>+ </div>+ <div id={contentId} hidden={!expanded} className={expanded ? 'flex flex-col gap-2' : 'hidden'}><p className="text-11 leading-[1.5] text-[var(--text-tertiary)]">{t('bots.channels.lanes.hint', { name: botName })}</p>@@ -487,18 +510,31 @@ function ConnectionLanes({ connectionId, botId, botName }: { connectionId: strin</span><span className="block text-11 leading-[1.5] text-[var(--text-tertiary)]">{meta.join(' · ')}</span></button>+ <div className="flex shrink-0 items-center gap-1">+ {botImConnectionLaneArchiveSupported() ? (+ <ChromeIconButton+ className="shrink-0 text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ aria-label={t('bots.channels.lanes.archiveAria', { lane: name })}+ tooltip={t('bots.channels.lanes.archive')}+ disabled={archivingId !== null || resettingId !== null}+ onClick={() => void mutate(lane, 'archive')}+ >+ {archivingId === lane.sessionId ? <Spinner size={14} /> : <Archive size={14} strokeWidth={2} aria-hidden />}+ </ChromeIconButton>+ ) : null}<Buttontype="button"variant="secondary"size="md"compactloading={resettingId === lane.sessionId}- disabled={resettingId !== null && resettingId !== lane.sessionId}+ disabled={archivingId !== null || (resettingId !== null && resettingId !== lane.sessionId)}aria-label={t('bots.channels.lanes.resetAria', { lane: name })}- onClick={() => void reset(lane)}+ onClick={() => void mutate(lane, 'reset')}>{t('bots.channels.lanes.reset')}</Button>+ </div></div>);})}@@ -518,6 +554,7 @@ function ConnectionLanes({ connectionId, botId, botName }: { connectionId: strin{notice.text}</p>) : null}+ </div></div>);}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsxindex 12afe65dbd..784c908c86 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type {@@ -87,6 +87,7 @@ let groupsApi: {let lanesApi: {listLanes?: ReturnType<typeof vi.fn>;resetLane?: ReturnType<typeof vi.fn>;+ archiveLane?: ReturnType<typeof vi.fn>;} = {};beforeEach(() => {@@ -99,6 +100,29 @@ beforeEach(() => {afterEach(cleanup);describe('BotChannelsPage', () => {+ // 用户确认的飞书任务折叠合同;既有测试只覆盖打开与重启。+ // 最小输入:一条连接和一条专线。unit:真实组件点击后列表隐藏,展开保留原记录,无业务写入。+ it('collapses only this connection task list and restores it without changing sessions', async () => {+ lanesApi = {+ listLanes: vi.fn(async () => ({ connectionId: 'a1b2c3d4e5f6', lanes: [+ { sessionId: 'lane', kind: 'topic', chatId: 'group', threadId: 'topic', name: 'Release room', state: 'idle', lastActivityAt: null, contextMessageCount: 0 },+ ] })),+ resetLane: vi.fn(),+ };+ installApi({ connections: [connection({ channel: 'feishu' })] });+ render(<BotChannelsPage bot={mia} />);+ const label = { platform: 'bots.channels.platform.feishu' };+ expect(await screen.findByText(`bots.channels.lanes.title:${JSON.stringify(label)}`)).toBeTruthy();+ expect(screen.getByRole('button', { name: /^Release room/ })).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: `bots.channels.lanes.collapse:${JSON.stringify(label)}` }));+ expect(screen.queryByRole('button', { name: /^Release room/ })).toBeNull();+ expect(screen.getByText('bots.channels.platform.feishu')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: `bots.channels.lanes.expand:${JSON.stringify(label)}` }));+ expect(screen.getByRole('button', { name: /^Release room/ })).toBeTruthy();+ expect(lanesApi.resetLane).not.toHaveBeenCalled();+ expect(mocks.navigate).not.toHaveBeenCalled();+ });+// 测试价值: 真实列表点击应打开主界面只读详情, 旧覆盖只有重启; 最小输入为一条渠道记录。// unit: 校验路由与副作用, 不需真实飞书连接。it('opens each IM record in the existing history page without restarting it', async () => {@@ -155,6 +179,65 @@ describe('BotChannelsPage', () => {);});+ // 已确认的归档功能:真实列表按钮应调用本连接的归档 IPC,成功移出、失败与取消保留。+ // 现有测试只有 reset;最小输入一条专线。unit:可观察列表结果和错误提示。+ it.each(['done', 'cancel', 'failed'] as const)('archives a channel task with %s outcome', async (outcome) => {+ const lanes = [{ sessionId: 's-topic', kind: 'topic', chatId: 'group', threadId: 'topic', name: 'Release room', state: 'idle', lastActivityAt: null, contextMessageCount: 0 }];+ mocks.confirm.mockResolvedValue(outcome !== 'cancel');+ lanesApi = {+ listLanes: vi.fn(async () => ({ connectionId: 'a1b2c3d4e5f6', lanes })),+ resetLane: vi.fn(),+ archiveLane: vi.fn(async () => {+ if (outcome === 'failed') throw new Error('unavailable');+ return { connectionId: 'a1b2c3d4e5f6', lanes: [] };+ }),+ };+ installApi({ connections: [connection({ channel: 'feishu' })] });+ render(<BotChannelsPage bot={mia} />);+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.lanes.archiveAria:{"lane":"Release room"}' }));+ if (outcome === 'cancel') {+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalled());+ expect(lanesApi.archiveLane).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: /^Release room/ })).toBeTruthy();+ } else {+ await waitFor(() => expect(lanesApi.archiveLane).toHaveBeenCalledWith({ id: 'a1b2c3d4e5f6', sessionId: 's-topic' }));+ if (outcome === 'done') await waitFor(() => expect(screen.queryByRole('button', { name: /^Release room/ })).toBeNull());+ else {+ expect(await screen.findByText('bots.channels.lanes.archiveFailed')).toBeTruthy();+ expect(screen.getByRole('button', { name: /^Release room/ })).toBeTruthy();+ }+ }+ expect(lanesApi.resetLane).not.toHaveBeenCalled();+ expect(mocks.navigate).not.toHaveBeenCalled();+ });++ // 归档与既有 20 秒轮询竞态;最小输入为归档期间迟到的旧列表,旧测试没有在途读取。+ it('does not restore an archived task when an older list request arrives late', async () => {+ const lanes = [{ sessionId: 's-topic', kind: 'topic', chatId: 'group', threadId: 'topic', name: 'Release room', state: 'idle', lastActivityAt: null, contextMessageCount: 0 }];+ let finishOldRead!: (value: { connectionId: string; lanes: typeof lanes }) => void;+ lanesApi = {+ listLanes: vi.fn().mockResolvedValueOnce({ connectionId: 'a1b2c3d4e5f6', lanes })+ .mockImplementationOnce(() => new Promise((resolve) => { finishOldRead = resolve; })),+ resetLane: vi.fn(),+ archiveLane: vi.fn(async () => ({ connectionId: 'a1b2c3d4e5f6', lanes: [] })),+ };+ installApi({ connections: [connection({ channel: 'feishu' })] });+ const visibility = vi.spyOn(document, 'hidden', 'get').mockReturnValue(false);+ vi.useFakeTimers();+ try {+ await act(async () => { render(<BotChannelsPage bot={mia} />); });+ const archive = screen.getByRole('button', { name: 'bots.channels.lanes.archiveAria:{"lane":"Release room"}' });+ await act(async () => { vi.advanceTimersByTime(20_000); });+ await act(async () => { fireEvent.click(archive); });+ expect(screen.queryByRole('button', { name: /^Release room/ })).toBeNull();+ await act(async () => { finishOldRead({ connectionId: 'a1b2c3d4e5f6', lanes }); });+ expect(screen.queryByRole('button', { name: /^Release room/ })).toBeNull();+ } finally {+ vi.useRealTimers();+ visibility.mockRestore();+ }+ });+it('starts one hidden task over through the connection it belongs to', async () => {const lanes = [{ sessionId: 's-main', kind: 'owner-dm', chatId: null, threadId: null, name: null, state: 'idle', lastActivityAt: null, contextMessageCount: 0 },diff --git a/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts b/apps/desktop/src/renderer/features/bots/botImConnectionClient.tsindex 49e8bb055f..f8a62a79e4 100644--- a/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts+++ b/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts@@ -117,6 +117,17 @@ export function resetBotImConnectionLane(id: string, sessionId: string): Promisereturn api.resetLane({ id, sessionId });}+/** Old preload keeps viewing/restart available without advertising archive. */+export function botImConnectionLaneArchiveSupported(): boolean {+ return typeof botImConnectionApi()?.archiveLane === 'function';+}++export function archiveBotImConnectionLane(id: string, sessionId: string): Promise<BotImConnectionLanesPayload> {+ const api = botImConnectionApi();+ if (!api?.archiveLane) return Promise.reject(new Error('botImConnection IPC unavailable'));+ return api.archiveLane({ id, sessionId });+}+/** 设置 → IM 机器人 里可以移给伙伴的个人 bot; 旧 preload 没有这个接口时当作没有。 */export function listAdoptablePersonalBots(): Promise<BotImAdoptablePersonalBotsPayload> {const api = botImConnectionApi();diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 374c9835b6..5e9c1c850c 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -10130,8 +10130,10 @@}},"lanes": {- "title": "Hidden tasks",- "hint": "Each group, topic, and DM from someone else has its own hidden task. If one gets stuck or goes off track, start it over. Its history is kept.",+ "title": "{{platform}} tasks",+ "expand": "Expand {{platform}} tasks",+ "collapse": "Collapse {{platform}} tasks",+ "hint": "Each group, topic, and DM from someone else has its own task. If one gets stuck or goes off track, start it over. Its history is kept.","ownerName": "Your DM","kind": {"ownerDm": "Main task",@@ -10150,15 +10152,24 @@"resetAria": "Start “{{lane}}” over","resetConfirm": {"title": "Start “{{lane}}” over?",- "description": "The next message starts with a clean context, and any reply in progress stops. The full history stays in this hidden task, and {{name}}’s memory is unchanged.",+ "description": "The next message starts with a clean context, and any reply in progress stops. The full history stays in this task, and {{name}}’s memory is unchanged.","ownerDescription": "This is {{name}}’s main task, shared by your desktop conversation and this DM. The next message starts with a clean context, and any reply in progress stops. History, memory, and files are kept.","confirm": "Start over","cancel": "Cancel"},"resetDone": "“{{lane}}” started over. The next message begins with a clean context.","resetFailed": "Couldn’t start it over. Try again later.",- "loadFailed": "Couldn’t load hidden tasks",- "empty": "No groups or DMs from others yet. They show up here once someone talks to {{name}} in a group or a DM."+ "loadFailed": "Couldn’t load tasks",+ "empty": "No groups or DMs from others yet. They show up here once someone talks to {{name}} in a group or a DM.",+ "archive": "Archive task",+ "archiveAria": "Archive “{{lane}}”",+ "archiveConfirm": {+ "title": "Archive “{{lane}}”?",+ "description": "Hide this conversation from this list. Its task, context, history and current reply stay unchanged. New messages bring it back to the list.",+ "confirm": "Archive"+ },+ "archiveDone": "“{{lane}}” archived from the list. Its task and history are kept.",+ "archiveFailed": "Could not archive the task"},"add": {"button": "Add platform",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 301bf3f133..dc3980ea6e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -10096,8 +10096,10 @@}},"lanes": {- "title": "非表示のタスク",- "hint": "グループ、トピック、ほかの人からの DM ごとに非表示のタスクがあります。止まったり話がかみ合わなくなったりしたら、やり直せます。履歴は残ります。",+ "title": "{{platform}}のタスク",+ "expand": "{{platform}}のタスクを展開",+ "collapse": "{{platform}}のタスクを折りたたむ",+ "hint": "グループ、トピック、ほかの人からの DM ごとにタスクがあります。止まったり話がかみ合わなくなったりしたら、やり直せます。履歴は残ります。","ownerName": "あなたとの DM","kind": {"ownerDm": "メインタスク",@@ -10115,15 +10117,24 @@"resetAria": "「{{lane}}」をやり直す","resetConfirm": {"title": "「{{lane}}」をやり直しますか?",- "description": "次のメッセージはまっさらなコンテキストから始まり、進行中の返信は停止します。履歴はこの非表示のタスクにすべて残り、{{name}} の記憶は変わりません。",+ "description": "次のメッセージはまっさらなコンテキストから始まり、進行中の返信は停止します。履歴はこのタスクにすべて残り、{{name}} の記憶は変わりません。","ownerDescription": "これは {{name}} のメインタスクで、デスクトップでの会話とこの DM で共有しています。次のメッセージはまっさらなコンテキストから始まり、進行中の返信は停止します。履歴、記憶、ファイルはすべて残ります。","confirm": "やり直す","cancel": "キャンセル"},"resetDone": "「{{lane}}」をやり直しました。次のメッセージはまっさらなコンテキストから始まります。","resetFailed": "やり直せませんでした。しばらくしてからもう一度お試しください",- "loadFailed": "非表示のタスクを読み込めませんでした",- "empty": "グループやほかの人からの DM はまだありません。グループや DM で誰かが {{name}} に話しかけると、ここに表示されます。"+ "loadFailed": "タスクを読み込めませんでした",+ "empty": "グループやほかの人からの DM はまだありません。グループや DM で誰かが {{name}} に話しかけると、ここに表示されます。",+ "archive": "タスクをアーカイブ",+ "archiveAria": "「{{lane}}」をアーカイブ",+ "archiveConfirm": {+ "title": "「{{lane}}」をアーカイブしますか?",+ "description": "この一覧からのみ非表示にします。元のタスク、コンテキスト、履歴、進行中の返信は変わりません。新しいメッセージがあると再び表示されます。",+ "confirm": "アーカイブ"+ },+ "archiveDone": "「{{lane}}」を一覧からアーカイブしました。元のタスクと履歴は保持されています。",+ "archiveFailed": "タスクをアーカイブできませんでした"},"add": {"button": "プラットフォームを追加",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 4abdb5395e..9792a7c3a4 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -10096,8 +10096,10 @@}},"lanes": {- "title": "숨겨진 작업",- "hint": "그룹, 토픽, 다른 사람이 보낸 DM마다 숨겨진 작업이 하나씩 있습니다. 멈추거나 엉뚱한 답을 하면 다시 시작할 수 있으며, 기록은 유지됩니다.",+ "title": "{{platform}} 작업",+ "expand": "{{platform}} 작업 펼치기",+ "collapse": "{{platform}} 작업 접기",+ "hint": "그룹, 토픽, 다른 사람이 보낸 DM마다 작업이 하나씩 있습니다. 멈추거나 엉뚱한 답을 하면 다시 시작할 수 있으며, 기록은 유지됩니다.","ownerName": "나와의 DM","kind": {"ownerDm": "기본 작업",@@ -10115,15 +10117,24 @@"resetAria": "「{{lane}}」 다시 시작","resetConfirm": {"title": "「{{lane}}」을(를) 다시 시작할까요?",- "description": "다음 메시지부터 깨끗한 컨텍스트로 시작하고, 진행 중인 답장은 멈춥니다. 전체 기록은 이 숨겨진 작업에 그대로 남고 {{name}}의 기억은 바뀌지 않습니다.",+ "description": "다음 메시지부터 깨끗한 컨텍스트로 시작하고, 진행 중인 답장은 멈춥니다. 전체 기록은 이 작업에 그대로 남고 {{name}}의 기억은 바뀌지 않습니다.","ownerDescription": "{{name}}의 기본 작업으로, 데스크톱 대화와 이 DM이 함께 사용합니다. 다음 메시지부터 깨끗한 컨텍스트로 시작하고, 진행 중인 답장은 멈춥니다. 기록, 기억, 파일은 모두 유지됩니다.","confirm": "다시 시작","cancel": "취소"},"resetDone": "「{{lane}}」을(를) 다시 시작했습니다. 다음 메시지부터 깨끗한 컨텍스트로 시작합니다.","resetFailed": "다시 시작하지 못했어요. 잠시 후 다시 시도해 주세요",- "loadFailed": "숨겨진 작업을 불러오지 못했습니다",- "empty": "아직 그룹이나 다른 사람이 보낸 DM이 없습니다. 그룹이나 DM에서 누군가 {{name}}에게 말을 걸면 여기에 표시됩니다."+ "loadFailed": "작업을 불러오지 못했습니다",+ "empty": "아직 그룹이나 다른 사람이 보낸 DM이 없습니다. 그룹이나 DM에서 누군가 {{name}}에게 말을 걸면 여기에 표시됩니다.",+ "archive": "작업 보관",+ "archiveAria": "「{{lane}}」 보관",+ "archiveConfirm": {+ "title": "「{{lane}}」을(를) 보관할까요?",+ "description": "이 목록에서만 숨깁니다. 원래 작업, 컨텍스트, 기록 및 진행 중인 답장은 그대로 유지됩니다. 새 메시지가 있으면 목록에 다시 표시됩니다.",+ "confirm": "보관"+ },+ "archiveDone": "「{{lane}}」을(를) 목록에서 보관했습니다. 원래 작업과 기록은 유지됩니다.",+ "archiveFailed": "작업을 보관하지 못했습니다"},"add": {"button": "플랫폼 추가",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 3ac53e0a20..2609f28230 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -10096,8 +10096,10 @@}},"lanes": {- "title": "隐藏任务",- "hint": "每个群、话题和其他人的私聊各有一条隐藏任务。哪条卡住或答非所问,可以让它重新开始,记录会保留。",+ "title": "{{platform}}任务",+ "expand": "展开{{platform}}任务",+ "collapse": "收起{{platform}}任务",+ "hint": "每个群、话题和其他人的私聊各有一条任务。卡住或答非所问,可以让它重新开始,记录会保留。","ownerName": "你的私聊","kind": {"ownerDm": "主任务",@@ -10115,15 +10117,24 @@"resetAria": "让「{{lane}}」重新开始","resetConfirm": {"title": "让「{{lane}}」重新开始?",- "description": "下一条消息会从干净的上下文开始,正在进行的回复会停下。完整记录仍留在这条隐藏任务里,{{name}} 的记忆不变。",+ "description": "下一条消息会从干净的上下文开始,正在进行的回复会停下。完整记录仍留在这条任务里,{{name}} 的记忆不变。","ownerDescription": "这是 {{name}} 的主任务,桌面上的对话和这里的私聊共用它。下一条消息会从干净的上下文开始,正在进行的回复会停下;记录、记忆和文件都保留。","confirm": "重新开始","cancel": "取消"},"resetDone": "「{{lane}}」已重新开始,下一条消息从干净的上下文开始。","resetFailed": "没能重新开始,请稍后再试",- "loadFailed": "未能读取隐藏任务",- "empty": "还没有群或其他人的私聊。有人在群里或私聊里和 {{name}} 说话后,会出现在这里。"+ "loadFailed": "未能读取任务",+ "empty": "还没有群或其他人的私聊。有人在群里或私聊里和 {{name}} 说话后,会出现在这里。",+ "archive": "归档任务",+ "archiveAria": "归档「{{lane}}」",+ "archiveConfirm": {+ "title": "归档「{{lane}}」?",+ "description": "只从这份列表中收起,记录会保留,原任务、上下文和正在进行的回复不变。有新消息时会重新出现在列表中。",+ "confirm": "归档"+ },+ "archiveDone": "「{{lane}}」已从列表归档,原任务和记录保留。",+ "archiveFailed": "未能归档任务"},"add": {"button": "添加平台",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 98dea0f174..72ff28fd81 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -10096,8 +10096,10 @@}},"lanes": {- "title": "隱藏任務",- "hint": "每個群組、話題和其他人的私聊各有一條隱藏任務。哪條卡住或答非所問,可以讓它重新開始,記錄會保留。",+ "title": "{{platform}}任務",+ "expand": "展開{{platform}}任務",+ "collapse": "收起{{platform}}任務",+ "hint": "每個群組、話題和其他人的私聊各有一條任務。哪條卡住或答非所問,可以讓它重新開始,記錄會保留。","ownerName": "你的私聊","kind": {"ownerDm": "主任務",@@ -10115,15 +10117,24 @@"resetAria": "讓「{{lane}}」重新開始","resetConfirm": {"title": "讓「{{lane}}」重新開始?",- "description": "下一則訊息會從乾淨的上下文開始,進行中的回覆會停下。完整記錄仍留在這條隱藏任務裡,{{name}} 的記憶不變。",+ "description": "下一則訊息會從乾淨的上下文開始,進行中的回覆會停下。完整記錄仍留在這條任務裡,{{name}} 的記憶不變。","ownerDescription": "這是 {{name}} 的主任務,桌面上的對話和這裡的私聊共用它。下一則訊息會從乾淨的上下文開始,進行中的回覆會停下;記錄、記憶和檔案都會保留。","confirm": "重新開始","cancel": "取消"},"resetDone": "「{{lane}}」已重新開始,下一則訊息從乾淨的上下文開始。","resetFailed": "未能重新開始,請稍後再試",- "loadFailed": "無法讀取隱藏任務",- "empty": "還沒有群組或其他人的私聊。有人在群組或私聊裡和 {{name}} 說話後,會出現在這裡。"+ "loadFailed": "無法讀取任務",+ "empty": "還沒有群組或其他人的私聊。有人在群組或私聊裡和 {{name}} 說話後,會出現在這裡。",+ "archive": "歸檔任務",+ "archiveAria": "歸檔「{{lane}}」",+ "archiveConfirm": {+ "title": "歸檔「{{lane}}」?",+ "description": "只從這份清單收起,記錄會保留,原任務、上下文和進行中的回覆不變。有新訊息時會重新出現在清單中。",+ "confirm": "歸檔"+ },+ "archiveDone": "「{{lane}}」已從清單歸檔,原任務和記錄保留。",+ "archiveFailed": "無法歸檔任務"},"add": {"button": "新增平台",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 82673297cf..39e4c1b4d3 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2396,6 +2396,10 @@ interface ElectronAPI {id: string;sessionId: string;}) => Promise<import('../shared/botImConnection').BotImConnectionLanesPayload>;+ archiveLane: (payload: {+ id: string;+ sessionId: string;+ }) => Promise<import('../shared/botImConnection').BotImConnectionLanesPayload>;/** 设置 → IM 机器人 里已配好、可以移给伙伴的个人 bot(只给身份, 不含凭证)。 */listAdoptable: () => Promise<import('../shared/botImConnection').BotImAdoptablePersonalBotsPayload>;/**diff --git a/apps/desktop/src/shared/botImConnection.ts b/apps/desktop/src/shared/botImConnection.tsindex 30510be6da..c25af1ca71 100644--- a/apps/desktop/src/shared/botImConnection.ts+++ b/apps/desktop/src/shared/botImConnection.ts@@ -76,6 +76,8 @@ export interface BotImConnectionRecord {* 个人 bot 的同名配置互不相干 —— 每条连接自己一份。*/groupActivation?: Record<string, 'always'>;+ /** List-only archive cutoffs. Never changes the referenced session or its routing. */+ archivedTaskRows?: Record<string, number>;}export type BotImGroupActivationMode = 'mention' | 'always';diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex 72c923dc49..2b5857dd3d 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -652,6 +652,15 @@ history page does not assign a pill frame or change task state. The separate resaction remains the registered compact secondary Button and is outside this exemption.This records the accepted quiet list, not a general exemption for settings actions.+The section title uses the connection platform (for example, “飞书任务”). A 28px+shared quiet icon action at the right toggles only the hint and task list; its 14px+chevron and localized Tip name the next action. Each listed conversation, including the owner DM, adds a 28px+quiet archive action immediately before the unchanged restart Button, with a 4px+action gap. Reuse the sidebar task archive glyph (`Archive`, 14px, stroke width 2).+Both new actions keep the ordinary pill frame, semantic colors and keyboard focus;+existing record typography, card, spacing and restart treatment stay unchanged.++Keyboard focus uses the theme-invariant `--focus-ring` as a `focus-visible` box-shadowring. Non-input `outline` is suppressed globally, so an outline class is not a visiblefocus treatment here. The ring appears only for keyboard focus and does not create andiff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex fc6a2ca52d..55c8b308bb 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -1,5 +1,15 @@# 跨端协议兼容+## 伙伴消息平台任务归档++Desktop 本机伙伴「消息平台」页新增 `botImConnection:archive-lane({ id, sessionId })`,+响应复用 `BotImConnectionLanesPayload`。Main 校验可信顶层 Renderer、连接归属与具体任务,+仅在账号隔离的连接记录中保存可选 `archivedTaskRows` 显示状态;不改变 session 状态或路由链接。+新 Renderer 配旧 preload 时仅不展示归档按钮,列表读取与重新开始照常;旧 Renderer 不调用新入口。+旧版本忽略新的可选记录字段,若旧版本重写连接记录,列表归档状态可重置,但任务和消息不受影响。+该页原本只对本机伙伴开放,新入口不加入 device-link allowlist,不扩大远程 / 手机的渠道可见性。+无服务端、数据库 schema、历史 migration 或 Mobile 原生改动。+## 灵动岛完成卡操作`local-db:sessions:activity` 追加可选的 `completionToken`,由任务所属进程按完成卡代次签发。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 14cdebd478..edfcca319e 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -155,9 +155,14 @@ Discord 传输层只放行主人,钉钉群里被 @ 时成员也能触发(成别人说的不冒充主人:专线里主人与群成员 / 外部用户的消息落在同一条任务,每条消息的 `imSource.origin` 存谁、在哪说的(与发给模型的 `[渠道说明]` / `[发言人]` 同源),任务面板的卡头对非主人消息写出发言人与群名,主人消息沿用「Cindy · 来自 X」;外部用户私聊的渠道说明写明发言人并点出「不是主人」,不再按 speaker 有无把私聊误判成群。-「消息平台」页每条连接下有「隐藏任务」小节:列出这条连接名下的主人私聊(伙伴主任务)与各群 / 话题 / 外部用户私聊+「消息平台」页每条连接下的小节以平台命名(如「飞书任务」),标题右侧可展开 / 收起说明与列表,+不改变连接和任务状态。列出这条连接名下的主人私聊(伙伴主任务)与各群 / 话题 / 外部用户私聊专线,每条可「重新开始」——复用伙伴已有的 `restartBotCanonicalRuntime` 交接(同一条任务、记录与记忆不删,下一条消息换干净的原生会话),不另写换会话逻辑,见 `im/shared/botImLaneRuntime.ts`。+每条记录(包括「你的私聊」)可从当前连接的任务列表归档。这里的归档只保存连接名下的列表显示状态,+不修改 `sessions.status` 或 `bot_session_links`,不停止回复、不换任务、不重建上下文;历史、记忆与文件保留。+有新消息时,原任务重新出现在列表中并继续使用同一个 session。主人私聊和桌面伙伴仍共用长期主任务,+从飞书列表归档不会归档或停用这个主任务。旧 preload 没有归档接口时保留查看与重新开始能力。点击小节里的记录或灵动岛上的渠道任务,在主界面复用归档历史的只读详情页(`/bots/:id/history/:sid`),不另开窗口,不恢复或归档任务,也不让渠道专线进入左侧普通任务列表。打开前按伙伴的持久归属投影校验;仍在运行的专线继续显示消息更新。「重新开始」与打开详情是独立操作,