Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): merge main and preserve archive target routing
xdab52f0401973
diff --cc apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.tsindex b459fe0837,c076812910..ff71dc6fc6--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts@@@ -83,8 -82,8 +83,9 @@@ vi.mock('../../../security/trustedAppReimport {addBotImConnection,+ buildBotImConnectionListPayload,configureBotImConnectionRuntime,+ registerBotImConnectionIpc,setWechatCompanionBinding,getBotFeishuTransport,listBotImConnectionGroups,diff --cc apps/desktop/src/main/im/shared/botImConnectionRuntime.tsindex 4d22caccff,bd54473662..4153691c78--- a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts+++ b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts@@@ -782,17 -788,8 +788,17 @@@ export function registerBotImConnectionif (typeof p.sessionId !== 'string' || !/^[A-Za-z0-9_.:-]{1,200}$/.test(p.sessionId)) {throwIpcError('INVALID_PARAMS', 'sessionId is invalid');}- return resetBotImConnectionLane(p.id, p.sessionId, laneOptions);+ return resetBotImConnectionLaneForSettings(p.id, p.sessionId);});+ 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);++ return archiveBotImConnectionLane(p.id, p.sessionId, laneOptions());+ });}export const __testing = { instances, purgeSecrets, toView };diff --cc apps/desktop/src/renderer/features/bots/BotChannelsPage.tsxindex 8b10cff143,02b0039072..847879e6b5--- a/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx+++ b/apps/desktop/src/renderer/features/bots/BotChannelsPage.tsx@@@ -216,11 -221,12 +226,12 @@@ export function BotChannelsPage({ bot }{t('bots.channels.remove')}</Button></div>- {view.channel === 'telegram' && view.botContextId && botImConnectionGroupsSupported() ? (- <ConnectionGroups connectionId={view.id} botName={bot.name} />+ {view.channel === 'telegram' && view.botContextId && botImConnectionGroupsSupported(im) ? (+ <ConnectionGroups api={im} connectionId={view.id} botName={bot.name} />) : null}- {view.botContextId && botImConnectionLanesSupported() ? (- <ConnectionLanes connectionId={view.id} botId={bot.id} botName={bot.name} platform={platformName(view)} />+ {view.botContextId && botImConnectionLanesSupported(im) ? (+ <ConnectionLanes api={im} connectionId={view.id} botId={bot.id} botName={bot.name}- canOpenHistory={target.kind === 'local'} />++ platform={platformName(view)} canOpenHistory={target.kind === 'local'} />) : null}</li>);@@@ -363,7 -375,11 +380,11 @@@ const LANE_KIND_KEY: Record<BotImConnec* 显示状态、最近活动和当前上下文里的消息数; 卡住时可以让某一条重新开始(同一条任务,* 记录保留, 下一条消息换干净的上下文)。点击记录复用主界面的只读历史页, 不取消隐藏。*/- function ConnectionLanes({ connectionId, botId, botName, platform }: { connectionId: string; botId: string; botName: string; platform: string }) {-function ConnectionLanes({ api, connectionId, botId, botName, canOpenHistory }: {- api: BotImConnectionApi | null; connectionId: string; botId: string; botName: string;++function ConnectionLanes({ api, connectionId, botId, botName, platform, canOpenHistory }: {++ api: BotImConnectionApi | null; connectionId: string; botId: string; botName: string; platform: string;+ /** The read-only history page lives on the teammate's computer; a remote teammate's lanes only list. */+ canOpenHistory: boolean;+ }) {const { t } = useBotTranslation();const navigate = useNavigate();const { confirm } = useConfirmDialog();@@@ -378,16 -389,16 +399,18 @@@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);+ const apiRef = useRef(api);+ apiRef.current = api;useEffect(() => {let cancelled = false;const load = () => {+ const generation = loadGeneration.current;- void listBotImConnectionLanes(connectionId)+ void listBotImConnectionLanes(apiRef.current, connectionId).then((payload) => {- if (cancelled) return;+ if (cancelled || generation !== loadGeneration.current || mutatingRef.current) return;setLanes(payload.lanes);setLoadFailed(false);setNow(Date.now());@@@ -429,48 -420,35 +452,48 @@@const 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);+ const previousLanes = lanes;try {- const payload = await resetBotImConnectionLane(apiRef.current, connectionId, lane.sessionId);+ if (action === 'reset') {+ 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;+ }+ if (action === 'reset') setResettingId(lane.sessionId);+ else {+ setArchivePendingId(null);+ setArchivingId(lane.sessionId);+ setLanes((current) => current?.filter((row) => row.sessionId !== lane.sessionId) ?? null);+ }+ setNotice(null);- const payload = await (action === 'reset' ? resetBotImConnectionLane : archiveBotImConnectionLane)(connectionId, lane.sessionId);++ const payload = await (action === 'reset' ? resetBotImConnectionLane : archiveBotImConnectionLane)(apiRef.current, connectionId, lane.sessionId);setLanes(payload.lanes);setNow(Date.now());- setNotice({ tone: 'done', text: t('bots.channels.lanes.resetDone', { lane: name }) });+ if (action === 'reset') setNotice({ tone: 'done', text: t('bots.channels.lanes.resetDone', { lane: name }) });} catch {- setNotice({ tone: 'failed', text: t('bots.channels.lanes.resetFailed') });+ if (action === 'archive') {+ setLanes(previousLanes);+ toast.error(t('bots.channels.lanes.archiveFailed'));+ } else setNotice({ tone: 'failed', text: t('bots.channels.lanes.resetFailed') });setReloadToken((value) => value + 1);} finally {- resettingRef.current = false;+ mutatingRef.current = false;setResettingId(null);+ setArchivingId(null);}};@@@ -544,37 -511,6 +568,37 @@@</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() ? (++ {botImConnectionLaneArchiveSupported(api) ? (+ <div className="relative flex h-7 w-7 shrink-0 items-center justify-end">+ {archivePendingId === lane.sessionId ? (+ <Button+ ref={archiveConfirmRef}+ type="button"+ variant="secondary"+ tone="danger-surface"+ size="xs"+ compact+ className="absolute right-0 top-1/2 w-max min-w-14 -translate-y-1/2 whitespace-nowrap"+ aria-label={t('ccAgent.sidebar.sessionMenu.archived')}+ disabled={archivingId !== null || resettingId !== null}+ onClick={() => void mutate(lane, 'archive')}+ >+ {t('ccAgent.sidebar.sessionMenu.archived')}+ </Button>+ ) : (+ <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('ccAgent.sidebar.sessionMenu.archived')}+ disabled={archivingId !== null || resettingId !== null}+ onClick={() => setArchivePendingId(lane.sessionId)}+ >+ <Archive size={14} strokeWidth={2} aria-hidden />+ </ChromeIconButton>+ )}+ </div>+ ) : null}<Buttontype="button"variant="secondary"diff --cc apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsxindex 65a369e5ce,31ae30ddc3..e368128e54--- a/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botChannelsPage.test.tsx@@@ -517,3 -389,104 +519,130 @@@ describe('BotChannelsPage', () =>);});});++ describe('BotChannelsPage with a window API that is not identity-stable', () => {+ it('reads the connection list once, however often it renders', async () => {+ const list = vi.fn(async () => ({ connections: [connection()] }));+ Object.assign(window, { electronAPI: {+ // A harness or proxying bridge hands out a fresh object per access.+ get botImConnection() { return { list, onChanged: () => () => undefined }; },+ } });+ render(<BotChannelsPage bot={mia} />);+ expect(await screen.findByText('bots.channels.platform.telegram')).toBeTruthy();+ await new Promise((resolve) => setTimeout(resolve, 20)); // real-wait: let a would-be render loop show itself+ expect(list).toHaveBeenCalledTimes(1);+ });+ });++ describe('BotChannelsPage for a teammate on another computer', () => {+ /** The page talks to the other computer's API only; this window's own API must stay untouched. */+ function renderRemote(api: Record<string, unknown>, channels: Partial<BotSettingsTarget['channels']> = {}) {+ const own = installApi({ connections: [] });+ const target = {+ ...localBotSettingsTarget,+ kind: 'remote',+ deviceId: 'mac',+ deviceName: 'Studio',+ channels: { im: api, canEnterCredentials: false, wechat: null, x: null, ...channels },+ } as unknown as BotSettingsTarget;+ render(+ <BotSettingsTargetContext.Provider value={target}>+ <BotChannelsPage bot={mia} />+ </BotSettingsTargetContext.Provider>,+ );+ return own;+ }+ const remoteApi = (extra: Record<string, unknown> = {}) => ({+ list: vi.fn(async () => ({ connections: [connection()] })),+ add: vi.fn(async () => { throw new Error('credentials never travel'); }),+ remove: vi.fn(async () => ({ connections: [], archivedSessionIds: [] })),+ listAdoptable: vi.fn(async () => ({ bots: [] })),+ adopt: vi.fn(),+ onChanged: vi.fn(() => () => undefined),+ ...extra,+ });++ it('lists and removes connections through the other computer, never this window', async () => {+ const api = remoteApi();+ const own = renderRemote(api);+ expect(await screen.findByText('bots.channels.platform.telegram')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /bots\.channels\.removeAria/ }));+ await waitFor(() => expect(api.remove).toHaveBeenCalledWith({ id: 'a1b2c3d4e5f6' }));+ expect(own.list).not.toHaveBeenCalled();+ expect(own.remove).not.toHaveBeenCalled();+ });+++ // The merge combines archive with target-specific APIs. A remote target must++ // never borrow this computer's archive capability or write to its connections.++ it.each([false, true])('uses only the target archive capability (supported=%s)', async (supported) => {++ const lane = { sessionId: 'remote-lane', kind: 'group', chatId: 'remote-group', name: 'Remote room',++ state: 'idle', lastActivityAt: null, contextMessageCount: 0 };++ lanesApi = { listLanes: vi.fn(), resetLane: vi.fn(), archiveLane: vi.fn() };++ const archiveLane = vi.fn(async () => ({ connectionId: 'a1b2c3d4e5f6', lanes: [] }));++ const api = remoteApi({++ listLanes: vi.fn(async () => ({ connectionId: 'a1b2c3d4e5f6', lanes: [lane] })),++ resetLane: vi.fn(),++ ...(supported ? { archiveLane } : {}),++ });++ const own = renderRemote(api);++ await expandTaskList();++ expect((await screen.findByRole('button', { name: /^Remote room/ }) as HTMLButtonElement).disabled).toBe(true);++ const archive = screen.queryByRole('button', { name: 'bots.channels.lanes.archiveAria:{"lane":"Remote room"}' });++ if (supported) {++ expect(archive).toBeTruthy();++ fireEvent.click(archive!);++ fireEvent.click(screen.getByRole('button', { name: 'ccAgent.sidebar.sessionMenu.archived' }));++ await waitFor(() => expect(archiveLane).toHaveBeenCalledWith({ id: 'a1b2c3d4e5f6', sessionId: 'remote-lane' }));++ } else expect(archive).toBeNull();++ expect(own.listLanes).not.toHaveBeenCalled();++ expect(own.archiveLane).not.toHaveBeenCalled();++ expect(mocks.navigate).not.toHaveBeenCalled();++ });+++ it('asks for credentials only on the other computer', async () => {+ const api = remoteApi();+ renderRemote(api);+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.add.button' }));+ const dialog = await screen.findByRole('dialog');+ expect(within(dialog).queryByLabelText('bots.channels.add.telegram.tokenLabel')).toBeNull();+ expect(within(dialog).getByText(/bots\.remoteSettings\.finishOnHost:.*Studio/)).toBeTruthy();+ expect((within(dialog).getByRole('button', { name: 'bots.channels.add.confirm' }) as HTMLButtonElement).disabled).toBe(true);+ expect(api.add).not.toHaveBeenCalled();+ });++ it('still moves the personal bot that is already set up there, without any credential', async () => {+ const api = remoteApi({+ listAdoptable: vi.fn(async () => ({ bots: [{ channel: 'telegram', identity: '@mia_bot' }] })),+ adopt: vi.fn(async () => ({ connections: [connection()], connection: connection() })),+ });+ renderRemote(api);+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.add.button' }));+ const dialog = await screen.findByRole('dialog');+ await within(dialog).findByRole('radio', { name: /bots\.channels\.add\.source\.existing/ });+ expect(within(dialog).queryByRole('radio', { name: 'bots.channels.add.source.manual' })).toBeNull();+ fireEvent.click(within(dialog).getByRole('button', { name: 'bots.channels.add.confirm' }));+ await waitFor(() => expect(api.adopt).toHaveBeenCalledWith({ botId: 'bot-1', channel: 'telegram' }));+ expect(api.add).not.toHaveBeenCalled();+ });++ it('shows the official X assignment of the other computer and changes it there, with sign-in left to that computer', async () => {+ const x = {+ get: vi.fn(async () => ({ available: true, enabled: true, connected: true, companionBotId: null as string | null })),+ setCompanion: vi.fn(async () => ({ companionBotId: 'bot-1' })),+ };+ renderRemote(remoteApi(), { x });+ fireEvent.click(await screen.findByRole('button', { name: 'bots.channels.officialX.bind' }));+ await waitFor(() => expect(x.setCompanion).toHaveBeenCalledWith(true, null));+ expect(await screen.findByRole('button', { name: 'bots.channels.officialX.remove' })).toBeTruthy();+ });++ it('asks to connect X on the other computer when its account is not signed in there', async () => {+ const x = {+ get: vi.fn(async () => ({ available: true, enabled: false, connected: false, companionBotId: null })),+ setCompanion: vi.fn(),+ };+ renderRemote(remoteApi(), { x });+ expect(await screen.findByText(/bots\.remoteSettings\.finishOnHost:.*Studio/)).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'bots.channels.officialX.bind' })).toBeNull();+ });+ });-diff --cc apps/desktop/src/renderer/features/bots/botImConnectionClient.tsindex f8a62a79e4,d454cc18e8..1fa7789860--- a/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts+++ b/apps/desktop/src/renderer/features/bots/botImConnectionClient.ts@@@ -117,20 -117,8 +117,18 @@@ export function resetBotImConnectionLanreturn api.resetLane({ id, sessionId });}+/** Old preload keeps viewing/restart available without advertising archive. */- export function botImConnectionLaneArchiveSupported(): boolean {- return typeof botImConnectionApi()?.archiveLane === 'function';++export function botImConnectionLaneArchiveSupported(api: BotImConnectionApi | null = botImConnectionApi()): boolean {++ return typeof api?.archiveLane === 'function';+}+- export function archiveBotImConnectionLane(id: string, sessionId: string): Promise<BotImConnectionLanesPayload> {- const api = botImConnectionApi();++export function archiveBotImConnectionLane(api: BotImConnectionApi | null, id: string, sessionId: string): Promise<BotImConnectionLanesPayload> {+ 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();+ export function listAdoptablePersonalBots(api: BotImConnectionApi | null): Promise<BotImAdoptablePersonalBotsPayload> {if (!api?.listAdoptable) return Promise.resolve({ bots: [] });return api.listAdoptable();}diff --cc apps/desktop/src/renderer/vite-env.d.tsindex 7a0bb776fc,fc6ca27d88..651166d7a2--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@@ -2396,10 -2402,6 +2402,10 @@@ interface ElectronAPIid: string;sessionId: string;}) => Promise<import('../shared/botImConnection').BotImConnectionLanesPayload>;- archiveLane: (payload: {++ archiveLane?: (payload: {+ id: string;+ sessionId: string;+ }) => Promise<import('../shared/botImConnection').BotImConnectionLanesPayload>;/** 设置 → IM 机器人 里已配好、可以移给伙伴的个人 bot(只给身份, 不含凭证)。 */listAdoptable: () => Promise<import('../shared/botImConnection').BotImAdoptablePersonalBotsPayload>;/**