Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 记住伙伴工作台的关闭选择 (#5852)

Chris Zhang4b401b3d722f
diff --git a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts
index 9d70c707ea..e7c3d69489 100644
--- a/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/right-sidebar-window/__tests__/ipc.test.ts
@@ -70,6 +70,18 @@ beforeEach(() => {
});
describe('right-sidebar-window IPC', () => {
+ it('preserves workbench click intent, keeps legacy commands passive, and rejects invalid intent', async () => {
+ const controller = makeController();
+ const { handler, mainWebContents } = registerController(controller);
+ const command = { type: 'open-bot-workbench-tab', sessionId: 's1', botId: 'bot-1' };
+ await handler({ sender: mainWebContents }, { command, allowOpen: false });
+ expect(controller.routeCommand).toHaveBeenLastCalledWith({ command, allowOpen: false });
+ await handler({ sender: mainWebContents }, { command: { ...command, focusTab: true }, allowOpen: true });
+ expect(controller.routeCommand).toHaveBeenLastCalledWith({ command: { ...command, focusTab: true }, allowOpen: true });
+ await expect(handler({ sender: mainWebContents }, { command: { ...command, focusTab: 'true' }, allowOpen: true }))
+ .rejects.toThrow(/command.focusTab/);
+ });
+
it('forwards the optional device-link origin and Pi-only Subagents eligibility', () => {
const controller = makeController();
const { mainWebContents } = registerController(controller);
diff --git a/apps/desktop/src/main/right-sidebar-window/ipc.ts b/apps/desktop/src/main/right-sidebar-window/ipc.ts
index 0ffc093ee4..135678d187 100644
--- a/apps/desktop/src/main/right-sidebar-window/ipc.ts
+++ b/apps/desktop/src/main/right-sidebar-window/ipc.ts
@@ -141,7 +141,11 @@ function parseCommand(raw: unknown): RsbWindowCommand {
}
if (r.type === 'open-bot-workbench-tab') {
if (typeof r.botId !== 'string' || !r.botId || r.botId.length > 128) throwIpcError('INVALID_PARAMS', 'Invalid teammate');
- return { type: 'open-bot-workbench-tab', sessionId: r.sessionId, botId: r.botId };
+ if (r.focusTab !== undefined && typeof r.focusTab !== 'boolean') throwIpcError('INVALID_PARAMS', 'command.focusTab must be boolean');
+ return {
+ type: 'open-bot-workbench-tab', sessionId: r.sessionId, botId: r.botId,
+ ...(r.focusTab === undefined ? {} : { focusTab: r.focusTab }),
+ };
}
if (r.type === 'open-background-tasks-tab') {
const hasFocusTaskId =
diff --git a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
index 427843e796..b7106909ce 100644
--- a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
@@ -191,7 +191,9 @@ function BotSessionGateView() {
const workbenchSessionId = gate.kind === 'ready' && gate.isCanonical ? sessionId : undefined;
useEffect(() => {
if (!botId || !workbenchSessionId) return;
- void ensureBotWorkbenchTab(workbenchSessionId, botId).catch(() => undefined);
+ const controller = new AbortController();
+ void ensureBotWorkbenchTab(workbenchSessionId, botId, controller.signal).catch(() => undefined);
+ return () => controller.abort();
}, [botId, workbenchSessionId]);
const onReadThrough = useCallback((at: number) => {
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchLifecycle.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchLifecycle.test.tsx
new file mode 100644
index 0000000000..afa2a28c48
--- /dev/null
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchLifecycle.test.tsx
@@ -0,0 +1,72 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { _resetStore, closeTab, getBucket } from '@/features/right-sidebar/store';
+import { openBotWorkbenchTab } from '@/features/right-sidebar/lib/openBotWorkbenchTab';
+import { _resetSidebarCommandsForTests, onRequestRightSidebarVisibility } from '@/features/right-sidebar/lib/sidebarCommands';
+import { readPanelCollapsedRecord, writePanelCollapsed } from '@/layout/collapsePrefs';
+import { BotSessionView } from '../BotSessionView';
+
+// Keep the real Bot route gate, workbench initializer, tab store and preferences.
+// The model/chat surface and host database are isolated; no Electron app is started.
+vi.mock('react-router-dom', () => ({
+ useParams: () => ({ botId: 'bot', sessionId: 'chat' }),
+ useNavigate: () => vi.fn(), Navigate: () => null,
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('../useBotIslandVisibleSession', () => ({ useBotIslandVisibleSession: () => {} }));
+vi.mock('../botStore', () => ({ useBotProfiles: () => [] }));
+vi.mock('@/features/cc-agent/CCAgentSessionView', () => ({ CCAgentSessionView: () => <div>chat</div> }));
+vi.mock('@/features/right-sidebar/lib/detachedSidebarRouting', () => ({ routeSidebarCommand: async () => 'attached' }));
+
+const visibility = vi.fn();
+const listTabs = vi.fn(async () => ({ tabs: [], activeTabId: null, persistable: false }));
+beforeEach(() => {
+ _resetStore(); _resetSidebarCommandsForTests(); localStorage.clear(); visibility.mockClear(); listTabs.mockClear();
+ onRequestRightSidebarVisibility(visibility);
+ window.electronAPI = {
+ localDb: {
+ bots: { list: async () => [], get: async () => ({ id: 'bot', name: 'Cindy', status: 'active', sessions: [
+ { id: 'chat', kind: 'chat', status: 'active', role: 'canonical' },
+ ] }) },
+ rightSidebarTabs: { list: listTabs },
+ },
+ } as unknown as Window['electronAPI'];
+});
+afterEach(() => { cleanup(); _resetStore(); _resetSidebarCommandsForTests(); });
+
+it('the actual Bot view respects a closed workbench through remount and a fresh store, until explicitly reopened', async () => {
+ const first = render(<BotSessionView />);
+ await waitFor(() => expect(getBucket('chat').tabs).toHaveLength(1));
+ await act(async () => { await closeTab('chat', getBucket('chat').tabs[0]!.id); });
+ writePanelCollapsed('right-tabs', { sessionId: 'chat' }, true);
+ visibility.mockClear(); first.unmount();
+ const second = render(<BotSessionView />);
+ await waitFor(() => expect(second.getByText('chat')).toBeTruthy());
+ expect(getBucket('chat').tabs).toEqual([]);
+ expect(visibility).not.toHaveBeenCalled();
+ second.unmount(); _resetStore();
+ const third = render(<BotSessionView />);
+ await waitFor(() => expect(third.getByText('chat')).toBeTruthy());
+ expect(visibility).not.toHaveBeenCalled();
+ expect(readPanelCollapsedRecord('right-tabs', { sessionId: 'chat' })).toBe(true);
+ await act(async () => { await openBotWorkbenchTab('chat', 'bot'); });
+ expect(getBucket('chat').tabs[0]?.kind).toBe('bot-workbench');
+ expect(visibility).toHaveBeenCalledOnce();
+});
+
+it('unmounting the actual Bot view cancels late first-visit hydration', async () => {
+ let release!: () => void;
+ listTabs.mockImplementationOnce(async () => {
+ await new Promise<void>((resolve) => { release = resolve; });
+ return { tabs: [], activeTabId: null, persistable: false };
+ });
+ const view = render(<BotSessionView />);
+ await waitFor(() => expect(listTabs).toHaveBeenCalledOnce());
+ view.unmount();
+ await act(async () => { release(); });
+ expect(getBucket('chat').tabs).toEqual([]);
+ expect(visibility).not.toHaveBeenCalled();
+ expect(readPanelCollapsedRecord('right-tabs', { sessionId: 'chat' })).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts
index fb77c77f43..d4492804f6 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/executeSidebarCommand.test.ts
@@ -22,6 +22,10 @@ vi.mock('../openInSidebarFileBrowser', () => ({
vi.mock('../openSubagentsTab', () => ({
openSubagentsTab: vi.fn(async () => undefined),
}));
+vi.mock('../openBotWorkbenchTab', () => ({
+ ensureBotWorkbenchTab: vi.fn(async () => undefined),
+ openBotWorkbenchTab: vi.fn(async () => undefined),
+}));
vi.mock('../../plugins/orca-workers/actions', () => ({
ensureOrcaWorkersTab: vi.fn(async () => undefined),
closeOrcaWorkersTabAfterTeamEnd: vi.fn(async () => undefined),
@@ -40,10 +44,20 @@ import {
} from '../openInSidebarFileBrowser';
import { openUrlInSidebarBrowser } from '../openInSidebarBrowser';
import { openSubagentsTab } from '../openSubagentsTab';
+import { ensureBotWorkbenchTab, openBotWorkbenchTab } from '../openBotWorkbenchTab';
describe('executeSidebarCommand', () => {
beforeEach(() => vi.clearAllMocks());
+ it('distinguishes a detached passive restore from an explicit workbench click', async () => {
+ await executeSidebarCommand({ type: 'open-bot-workbench-tab', sessionId: 's1', botId: 'bot-1' });
+ expect(ensureBotWorkbenchTab).toHaveBeenCalledWith('s1', 'bot-1');
+ expect(openBotWorkbenchTab).not.toHaveBeenCalled();
+ await executeSidebarCommand({ type: 'open-bot-workbench-tab', sessionId: 's1', botId: 'bot-1', focusTab: true });
+ expect(openBotWorkbenchTab).toHaveBeenCalledWith('s1', 'bot-1');
+ expect(ensureBotWorkbenchTab).toHaveBeenCalledOnce();
+ });
+
it('dispatches every command kind to the current renderer host implementation', async () => {
const searchJump = {
kind: 'conversation-search' as const,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openBotWorkbenchTab.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openBotWorkbenchTab.test.ts
index d337bc86d2..d142072896 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openBotWorkbenchTab.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/openBotWorkbenchTab.test.ts
@@ -1,71 +1,193 @@
// @vitest-environment jsdom
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { readPanelCollapsedRecord, writePanelCollapsed } from '@/layout/collapsePrefs';
+import { setDataOwnerGeneration, __testing as ownerTesting } from '@/contexts/dataOwnerGeneration';
+import { _resetStore, addTab, closeTab, ensureHydrated, getBucket, invalidateSessionCaches } from '../../store';
+import { routeSidebarCommand } from '../detachedSidebarRouting';
+import { ensureBotWorkbenchTab, openBotWorkbenchTab } from '../openBotWorkbenchTab';
+import { _resetSidebarCommandsForTests, onRequestRightSidebarVisibility } from '../sidebarCommands';
-const mocks = vi.hoisted(() => ({
- bucket: {
- tabs: [] as Array<{ id: string; kind: string; state: unknown }>,
- activeTabId: null as string | null,
- },
-}));
+vi.mock('../detachedSidebarRouting', () => ({ routeSidebarCommand: vi.fn(async () => 'attached') }));
-vi.mock('../../store', () => ({
- ensureHydrated: vi.fn(async () => undefined),
- getBucket: vi.fn(() => mocks.bucket),
- addTab: vi.fn(async (_sessionId: string, kind: string, state: unknown) => {
- const tab = { id: 'workbench-new', kind, state };
- mocks.bucket.tabs = [...mocks.bucket.tabs, tab];
- mocks.bucket.activeTabId = tab.id;
- return tab;
+type Row = { id: string; sessionId: string; kind: string; position: number; state: unknown };
+// An isolated persistence adapter: exercise the real store, close queue and layout
+// storage without reading the installed app's SQLite or localStorage profile.
+const rows = new Map<string, Row>();
+const active = new Map<string, string | null>();
+const ipc = {
+ list: vi.fn(async ({ sessionId }: { sessionId: string }) => ({
+ tabs: [...rows.values()].filter((row) => row.sessionId === sessionId).sort((a, b) => a.position - b.position),
+ activeTabId: active.get(sessionId) ?? null,
+ })),
+ upsert: vi.fn(async (row: Row) => { rows.set(row.id, row); }),
+ close: vi.fn(async ({ id }: { id: string }) => { rows.delete(id); }),
+ setActive: vi.fn(async ({ sessionId, id }: { sessionId: string; id: string | null }) => { active.set(sessionId, id); }),
+ reorder: vi.fn(async ({ orderedIds }: { orderedIds: string[] }) => {
+ orderedIds.forEach((id, position) => { const row = rows.get(id); if (row) rows.set(id, { ...row, position }); });
}),
- reorderTabs: vi.fn(async () => undefined),
-}));
-vi.mock('../detachedSidebarRouting', () => ({
- routeSidebarCommand: vi.fn(async () => 'attached'),
-}));
-vi.mock('../sidebarCommands', () => ({
- requestRightSidebarVisibility: vi.fn(),
-}));
+};
+const visibility = vi.fn();
-import { addTab, reorderTabs } from '../../store';
-import { routeSidebarCommand } from '../detachedSidebarRouting';
-import { ensureBotWorkbenchTab } from '../openBotWorkbenchTab';
-import { requestRightSidebarVisibility } from '../sidebarCommands';
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+beforeEach(() => {
+ _resetStore(); _resetSidebarCommandsForTests(); ownerTesting.reset();
+ rows.clear(); active.clear(); localStorage.clear(); vi.clearAllMocks();
+ vi.mocked(routeSidebarCommand).mockResolvedValue('attached');
+ window.electronAPI = { localDb: { rightSidebarTabs: ipc }, platform: 'darwin' } as unknown as Window['electronAPI'];
+ onRequestRightSidebarVisibility(visibility);
+});
+afterEach(() => { _resetStore(); _resetSidebarCommandsForTests(); ownerTesting.reset(); });
+
+function workbenchId() {
+ return getBucket('bot-main').tabs.find((tab) => tab.kind === 'bot-workbench')!.id;
+}
-describe('ensureBotWorkbenchTab', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mocks.bucket.tabs = [];
- mocks.bucket.activeTabId = null;
- vi.mocked(routeSidebarCommand).mockResolvedValue('attached');
+describe('bot workbench layout preference', () => {
+ it('creates the workbench first and opens only on the first visit', async () => {
+ await ensureHydrated('bot-main');
+ const files = await addTab('bot-main', 'file-browser');
+ await Promise.all([ensureBotWorkbenchTab('bot-main', 'bot-1'), ensureBotWorkbenchTab('bot-main', 'bot-1')]);
+ expect(getBucket('bot-main').tabs.map((tab) => tab.kind)).toEqual(['bot-workbench', 'file-browser']);
+ expect(ipc.reorder).toHaveBeenCalledWith({ sessionId: 'bot-main', orderedIds: [workbenchId(), files.id] });
+ expect(visibility).toHaveBeenCalledOnce();
+ expect(visibility).toHaveBeenCalledWith('open', { sessionId: 'bot-main', userInitiated: false });
+ expect(readPanelCollapsedRecord('right-tabs', { sessionId: 'bot-main' })).toBe(false);
});
- it('creates the workbench first and opens the sidebar on the first visit', async () => {
- mocks.bucket.tabs = [{ id: 'files', kind: 'file-browser', state: null }];
+ it('keeps a closed tab closed while other tabs remain, across cache resets; the header restores it', async () => {
await ensureBotWorkbenchTab('bot-main', 'bot-1');
- expect(routeSidebarCommand).toHaveBeenCalledWith(
- { type: 'open-bot-workbench-tab', sessionId: 'bot-main', botId: 'bot-1' },
- { allowOpen: false, userInitiated: false },
- );
- expect(addTab).toHaveBeenCalledWith('bot-main', 'bot-workbench', { botId: 'bot-1' });
- expect(reorderTabs).toHaveBeenCalledWith('bot-main', ['workbench-new', 'files']);
- expect(requestRightSidebarVisibility).toHaveBeenCalledWith('open', {
- sessionId: 'bot-main',
- userInitiated: false,
- });
+ const files = await addTab('bot-main', 'file-browser');
+ await closeTab('bot-main', workbenchId());
+ visibility.mockClear();
+ invalidateSessionCaches();
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ await ensureHydrated('bot-main');
+ expect(getBucket('bot-main').tabs.map((tab) => tab.id)).toEqual([files.id]);
+ expect(visibility).not.toHaveBeenCalled();
+ // Model a fresh renderer after restart, retaining only durable rows/preferences.
+ _resetStore();
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ await ensureHydrated('bot-main');
+ expect(getBucket('bot-main').tabs.map((tab) => tab.id)).toEqual([files.id]);
+ await openBotWorkbenchTab('bot-main', 'bot-1');
+ expect(getBucket('bot-main').tabs.map((tab) => tab.kind)).toEqual(['bot-workbench', 'file-browser']);
+ expect(getBucket('bot-main').activeTabId).toBe(workbenchId());
+ expect(visibility).toHaveBeenCalledOnce();
+ });
+
+ it('preserves panel/button/shortcut collapse through re-entry and restart, then explicitly reopens', async () => {
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ const id = workbenchId();
+ // All MainLayout close/toggle and detached-close paths use this layout writer.
+ writePanelCollapsed('right-tabs', { sessionId: 'bot-main' }, true);
+ visibility.mockClear(); _resetStore();
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ await ensureHydrated('bot-main');
+ expect(workbenchId()).toBe(id);
+ expect(readPanelCollapsedRecord('right-tabs', { sessionId: 'bot-main' })).toBe(true);
+ expect(visibility).not.toHaveBeenCalled();
+ await closeTab('bot-main', id);
+ _resetStore();
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ await ensureHydrated('bot-main');
+ expect(getBucket('bot-main').tabs).toEqual([]);
+ await openBotWorkbenchTab('bot-main', 'bot-1');
+ expect(readPanelCollapsedRecord('right-tabs', { sessionId: 'bot-main' })).toBe(false);
+ expect(getBucket('bot-main').activeTabId).toBe(workbenchId());
});
- it('leaves an existing workbench and the user sidebar choice alone', async () => {
- mocks.bucket.tabs = [{ id: 'wb', kind: 'bot-workbench', state: { botId: 'bot-1' } }];
+ it.each([true, false])('preserves existing ordinary sidebar preferences (%s) without adding or focusing a tab', async (collapsed) => {
+ await ensureHydrated('bot-main');
+ const files = await addTab('bot-main', 'file-browser');
+ writePanelCollapsed('right-tabs', { sessionId: 'bot-main' }, collapsed);
await ensureBotWorkbenchTab('bot-main', 'bot-1');
- expect(addTab).not.toHaveBeenCalled();
- expect(requestRightSidebarVisibility).not.toHaveBeenCalled();
+ expect(getBucket('bot-main').activeTabId).toBe(files.id);
+ expect(getBucket('bot-main').tabs).toHaveLength(1);
+ expect(visibility).not.toHaveBeenCalled();
+ await ensureBotWorkbenchTab('other-bot-main', 'bot-2');
+ expect(getBucket('other-bot-main').tabs[0]?.kind).toBe('bot-workbench');
});
- it('lets a detached sidebar window handle it without popping the window open', async () => {
- vi.mocked(routeSidebarCommand).mockResolvedValue('routed');
+ it('restores old tabs without focus or reveal, and remembers them when subsequently closed', async () => {
+ await ensureHydrated('bot-main');
+ const wb = await addTab('bot-main', 'bot-workbench', { botId: 'bot-1' });
+ const files = await addTab('bot-main', 'file-browser');
+ invalidateSessionCaches();
await ensureBotWorkbenchTab('bot-main', 'bot-1');
- expect(addTab).not.toHaveBeenCalled();
- expect(requestRightSidebarVisibility).not.toHaveBeenCalled();
+ expect(getBucket('bot-main').activeTabId).toBe(files.id);
+ expect(visibility).not.toHaveBeenCalled();
+ await closeTab('bot-main', wb.id);
+ _resetStore();
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ await ensureHydrated('bot-main');
+ expect(getBucket('bot-main').tabs.map((tab) => tab.id)).toEqual([files.id]);
+ });
+
+ it.each(['close', 'owner-switch', 'unmount'] as const)('does not overwrite %s while hydration is in flight', async (action) => {
+ const wait = deferred();
+ ipc.list.mockImplementationOnce(async () => { await wait.promise; return { tabs: [], activeTabId: null }; });
+ const controller = new AbortController();
+ const init = ensureBotWorkbenchTab('bot-main', 'bot-1', controller.signal);
+ await vi.waitFor(() => expect(ipc.list).toHaveBeenCalled());
+ if (action === 'close') writePanelCollapsed('right-tabs', { sessionId: 'bot-main' }, true);
+ if (action === 'owner-switch') { setDataOwnerGeneration('another-owner'); _resetStore(); }
+ if (action === 'unmount') controller.abort();
+ wait.resolve(); await init;
+ expect(ipc.upsert).not.toHaveBeenCalled();
+ expect(visibility).not.toHaveBeenCalled();
+ });
+
+ it('a close during tab INSERT wins; late completion neither resurrects the tab nor reveals the panel', async () => {
+ const wait = deferred();
+ ipc.upsert.mockImplementationOnce(async (row) => { await wait.promise; rows.set(row.id, row); });
+ const init = ensureBotWorkbenchTab('bot-main', 'bot-1');
+ await vi.waitFor(() => expect(ipc.upsert).toHaveBeenCalled());
+ const closing = closeTab('bot-main', workbenchId());
+ writePanelCollapsed('right-tabs', { sessionId: 'bot-main' }, true);
+ visibility.mockClear();
+ wait.resolve(); await Promise.all([init, closing]);
+ expect(visibility).not.toHaveBeenCalled();
+ expect(rows.size).toBe(0);
+ _resetStore(); await ensureBotWorkbenchTab('bot-main', 'bot-1'); await ensureHydrated('bot-main');
+ expect(getBucket('bot-main').tabs).toEqual([]);
+ });
+
+ it.each(['none', 'closed', 'opened'] as const)('failed default creation retries only without a newer user choice (%s)', async (choice) => {
+ const wait = deferred();
+ ipc.upsert.mockImplementationOnce(async () => { await wait.promise; throw new Error('temporary storage failure'); });
+ const init = ensureBotWorkbenchTab('bot-main', 'bot-1');
+ const rejected = expect(init).rejects.toThrow('temporary storage failure');
+ await vi.waitFor(() => expect(ipc.upsert).toHaveBeenCalled());
+ if (choice !== 'none') writePanelCollapsed('right-tabs', { sessionId: 'bot-main' }, choice === 'closed');
+ wait.resolve(); await rejected;
+ expect(readPanelCollapsedRecord('right-tabs', { sessionId: 'bot-main' })).toBe(choice === 'none' ? null : choice === 'closed');
+ expect(visibility).not.toHaveBeenCalled();
+ _resetStore(); await ensureBotWorkbenchTab('bot-main', 'bot-1'); await ensureHydrated('bot-main');
+ expect(getBucket('bot-main').tabs).toHaveLength(choice === 'none' ? 1 : 0);
+ expect(visibility).toHaveBeenCalledTimes(choice === 'none' ? 1 : 0);
+ });
+
+ it('routes passive detached first visits without reopening, and skips them after a recorded close', async () => {
+ vi.mocked(routeSidebarCommand).mockResolvedValue('queued');
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ expect(routeSidebarCommand).toHaveBeenCalledWith(
+ { type: 'open-bot-workbench-tab', sessionId: 'bot-main', botId: 'bot-1' },
+ { allowOpen: false, userInitiated: false },
+ );
+ expect(ipc.upsert).not.toHaveBeenCalled(); expect(visibility).not.toHaveBeenCalled();
+ writePanelCollapsed('right-tabs', { sessionId: 'bot-main' }, true);
+ vi.mocked(routeSidebarCommand).mockClear();
+ await ensureBotWorkbenchTab('bot-main', 'bot-1');
+ expect(routeSidebarCommand).not.toHaveBeenCalled();
+ vi.mocked(routeSidebarCommand).mockResolvedValue('routed');
+ await openBotWorkbenchTab('bot-main', 'bot-1');
+ expect(routeSidebarCommand).toHaveBeenCalledWith({ type: 'open-bot-workbench-tab', sessionId: 'bot-main', botId: 'bot-1', focusTab: true });
+ expect(visibility).toHaveBeenCalledWith('open', { sessionId: 'bot-main' });
});
});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts
index 31169ed9be..aa192a27b6 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts
@@ -1,5 +1,5 @@
import { openRoutinesTab } from './openRoutinesTab';
-import { ensureBotWorkbenchTab } from './openBotWorkbenchTab';
+import { ensureBotWorkbenchTab, openBotWorkbenchTab } from './openBotWorkbenchTab';
/** 执行 main 已裁决并推给当前 renderer host 的 RSB command。 */
import type { RsbWindowCommand } from '../../../../shared/rightSidebarWindow';
@@ -25,7 +25,8 @@ export async function executeSidebarCommand(command: RsbWindowCommand): Promise<
return;
}
if (command.type === 'open-bot-workbench-tab') {
- await ensureBotWorkbenchTab(command.sessionId, command.botId);
+ if (command.focusTab === true) await openBotWorkbenchTab(command.sessionId, command.botId);
+ else await ensureBotWorkbenchTab(command.sessionId, command.botId);
return;
}
if (command.type === 'open-web-browser') {
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts
index acac21aa8e..0eda82a154 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts
@@ -1,6 +1,8 @@
import { addOrFocusSingletonTab, addTab, ensureHydrated, getBucket, reorderTabs } from '../store';
import { routeSidebarCommand } from './detachedSidebarRouting';
import { requestRightSidebarVisibility } from './sidebarCommands';
+import { clearPanelCollapsedRecord, readPanelCollapsed, readPanelCollapsedRecord, writePanelCollapsed } from '@/layout/collapsePrefs';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
/** 工作台排在最前(工作台 / 文件 / 浏览器),其余标签保持原顺序。 */
async function moveWorkbenchToFront(sessionId: string, tabId: string): Promise<void> {
@@ -9,23 +11,55 @@ async function moveWorkbenchToFront(sessionId: string, tabId: string): Promise<v
}
/**
- * 伙伴主任务页进入时确保右侧栏里有「工作台」标签。
+ * 伙伴主任务页首次进入时提供默认的「工作台」标签。
*
- * 只在标签还不存在时创建并展开右侧栏(首次进入默认打开);已存在时什么也不动,
+ * 只在标签和布局记录都不存在时创建并展开(首次进入默认打开);已有记录或标签时不动,
* 用户之后收起右侧栏或切到文件 / 浏览器的选择都保留。这是程序自发的动作:
* detached 形态下只把命令交给已打开的子窗口,不因此弹出窗口或抢前台。
*/
-export async function ensureBotWorkbenchTab(sessionId: string, botId: string): Promise<void> {
+export async function ensureBotWorkbenchTab(
+ sessionId: string,
+ botId: string,
+ signal?: AbortSignal,
+): Promise<void> {
+ const owner = getDataOwnerGeneration();
+ const isCurrent = () => !signal?.aborted && isDataOwnerGenerationCurrent(owner);
+ if (!isCurrent() || readPanelCollapsedRecord('right-tabs', { sessionId }) !== null) return;
const route = await routeSidebarCommand(
{ type: 'open-bot-workbench-tab', sessionId, botId },
{ allowOpen: false, userInitiated: false },
);
- if (route !== 'attached') return;
+ if (route !== 'attached' || !isCurrent()) return;
await ensureHydrated(sessionId);
- if (getBucket(sessionId).tabs.some((tab) => tab.kind === 'bot-workbench')) return;
- const tab = await addTab(sessionId, 'bot-workbench', { botId });
+ // Hydration / routing may finish after a close, route change or owner switch.
+ if (!isCurrent() || readPanelCollapsedRecord('right-tabs', { sessionId }) !== null) return;
+ if (getBucket(sessionId).tabs.some((tab) => tab.kind === 'bot-workbench')) {
+ // Older layouts can contain the tab without a visibility record. Preserve
+ // their effective visibility and remember that this is no longer a first visit.
+ writePanelCollapsed('right-tabs', { sessionId }, readPanelCollapsed('right-tabs', { sessionId }, true));
+ return;
+ }
+ // Use the existing per-session layout record as the first-visit marker. Commit
+ // the default before async tab creation so a later user close wins permanently.
+ const defaultRevision = writePanelCollapsed('right-tabs', { sessionId }, false);
+ let tab;
+ try {
+ tab = await addTab(sessionId, 'bot-workbench', { botId });
+ } catch (error) {
+ // A failed default is not a user choice. Do not erase a later close or a
+ // successful manual reopen while this INSERT was waiting.
+ if (defaultRevision !== undefined && isDataOwnerGenerationCurrent(owner) && getBucket(sessionId).hydrated
+ && !getBucket(sessionId).tabs.some((candidate) => candidate.kind === 'bot-workbench')) {
+ clearPanelCollapsedRecord('right-tabs', { sessionId }, false, defaultRevision);
+ }
+ throw error;
+ }
+ if (!isCurrent() || !getBucket(sessionId).tabs.some((candidate) => candidate.id === tab.id)) return;
await moveWorkbenchToFront(sessionId, tab.id);
- requestRightSidebarVisibility('open', { sessionId, userInitiated: false });
+ if (isCurrent() && readPanelCollapsedRecord('right-tabs', { sessionId }) !== true
+ && getBucket(sessionId).tabs.some((candidate) => candidate.id === tab.id)) {
+ requestRightSidebarVisibility('open', { sessionId, userInitiated: false });
+ }
}
/**
@@ -34,12 +68,24 @@ export async function ensureBotWorkbenchTab(sessionId: string, botId: string): P
* 与 `openRoutinesTab` 同一套路,保留用户已有的 attached / detached 选择。
*/
export async function openBotWorkbenchTab(sessionId: string, botId: string): Promise<void> {
- const route = await routeSidebarCommand({ type: 'open-bot-workbench-tab', sessionId, botId });
+ const owner = getDataOwnerGeneration();
+ const route = await routeSidebarCommand({ type: 'open-bot-workbench-tab', sessionId, botId, focusTab: true });
+ if (!isDataOwnerGenerationCurrent(owner)) return;
+ // The detached receiver activates the tab but its visibility listener is a
+ // no-op for open. The main window must also bring an already open host forward.
+ if (route === 'routed') requestRightSidebarVisibility('open', { sessionId });
if (route === 'attached') {
await ensureHydrated(sessionId);
+ if (!isDataOwnerGenerationCurrent(owner)) return;
const existed = getBucket(sessionId).tabs.some((tab) => tab.kind === 'bot-workbench');
+ writePanelCollapsed('right-tabs', { sessionId }, false);
const tab = await addOrFocusSingletonTab(sessionId, 'bot-workbench', { botId });
- if (!existed) await moveWorkbenchToFront(sessionId, tab.id);
+ if (!existed && isDataOwnerGenerationCurrent(owner) && getBucket(sessionId).tabs.some((candidate) => candidate.id === tab.id)) {
+ await moveWorkbenchToFront(sessionId, tab.id);
+ }
+ if (isDataOwnerGenerationCurrent(owner) && readPanelCollapsedRecord('right-tabs', { sessionId }) !== true
+ && getBucket(sessionId).tabs.some((candidate) => candidate.id === tab.id)) {
+ requestRightSidebarVisibility('open', { sessionId });
+ }
}
- if (route === 'attached' || route === 'routed') requestRightSidebarVisibility('open', { sessionId });
}
diff --git a/apps/desktop/src/renderer/layout/__tests__/collapsePrefs.test.ts b/apps/desktop/src/renderer/layout/__tests__/collapsePrefs.test.ts
index cfea5ec43c..562f80e286 100644
--- a/apps/desktop/src/renderer/layout/__tests__/collapsePrefs.test.ts
+++ b/apps/desktop/src/renderer/layout/__tests__/collapsePrefs.test.ts
@@ -14,6 +14,7 @@ import { __resetBuiltinPanelsForTest } from '../../panels/builtinPanels';
import { __resetPanelRegistryForTest } from '../../panels/registry';
import {
__resetCollapsePrefsForTests,
+ clearPanelCollapsedRecord,
migrateLegacySidebarCollapsed,
readPanelCollapsed,
readPanelCollapsedRecord,
@@ -111,6 +112,17 @@ describe('global 作用域(session-list → 布局树)', () => {
});
describe('per-session 作用域(right-tabs → 会话桶)', () => {
+ it('withdraws only the failed default write, preserving a later same-value choice', () => {
+ const ctx = { sessionId: 'failed-default' };
+ const first = writePanelCollapsed('right-tabs', ctx, false)!;
+ writePanelCollapsed('right-tabs', ctx, false);
+ clearPanelCollapsedRecord('right-tabs', ctx, false, first);
+ expect(readPanelCollapsedRecord('right-tabs', ctx)).toBe(false);
+ const retry = writePanelCollapsed('right-tabs', ctx, false)!;
+ clearPanelCollapsedRecord('right-tabs', ctx, false, retry);
+ expect(readPanelCollapsedRecord('right-tabs', ctx)).toBeNull();
+ });
+
it('record 读法保留无记录 / false / true 三态', () => {
expect(readPanelCollapsedRecord('right-tabs', { sessionId: 'fresh' })).toBeNull();
diff --git a/apps/desktop/src/renderer/layout/collapsePrefs.ts b/apps/desktop/src/renderer/layout/collapsePrefs.ts
index 52f0d18911..d32f52618c 100644
--- a/apps/desktop/src/renderer/layout/collapsePrefs.ts
+++ b/apps/desktop/src/renderer/layout/collapsePrefs.ts
@@ -122,8 +122,13 @@ export function readPanelCollapsedRecord(kind: PanelKind, ctx: CollapseCtx): boo
return null;
}
-/** 写面板折叠态(按声明分发;none / 未注册 kind 为 no-op)。 */
-export function writePanelCollapsed(kind: PanelKind, ctx: CollapseCtx, collapsed: boolean): void {
+// In-memory write identity only, never a second preference store. A newer user
+// write must supersede a provisional default even when it writes the same value.
+let nextSessionWriteRevision = 0;
+const sessionWriteRevisions = new Map<string, number>();
+
+/** 写面板折叠态;per-session 返回写代次,供失败默认值的精确撤回使用。 */
+export function writePanelCollapsed(kind: PanelKind, ctx: CollapseCtx, collapsed: boolean): number | undefined {
const scope = scopeOf(kind);
if (scope === 'global') {
writeGlobalToTree(kind, collapsed);
@@ -133,13 +138,37 @@ export function writePanelCollapsed(kind: PanelKind, ctx: CollapseCtx, collapsed
const sessionId = ctx.sessionId ?? null;
if (!sessionId) return;
try {
- localStorage.setItem(sessionKeyFor(kind, sessionId), String(collapsed));
+ const key = sessionKeyFor(kind, sessionId);
+ localStorage.setItem(key, String(collapsed));
+ const revision = ++nextSessionWriteRevision;
+ sessionWriteRevisions.set(key, revision);
+ return revision;
} catch {
// storage 不可用 —— 静默
}
}
}
+/** Withdraw a failed per-session default only if the record still has that value. */
+export function clearPanelCollapsedRecord(
+ kind: PanelKind,
+ ctx: CollapseCtx,
+ expected: boolean,
+ revision: number,
+): void {
+ if (scopeOf(kind) !== 'per-session' || !ctx.sessionId) return;
+ try {
+ const key = sessionKeyFor(kind, ctx.sessionId);
+ if (sessionWriteRevisions.get(key) !== revision) return;
+ if (localStorage.getItem(key) === String(expected)) {
+ localStorage.removeItem(key);
+ sessionWriteRevisions.delete(key);
+ }
+ } catch {
+ // Keep the same best-effort storage semantics as the read/write helpers.
+ }
+}
+
/**
* 一次性迁移:旧左栏全局键 `sidebar-collapsed` → 布局树 sidebar pane 的 collapsed。
* 有旧值则异步写树并**同步返回该值**给首帧渲染(树的异步写完成前界面已是迁移后
diff --git a/apps/desktop/src/shared/rightSidebarWindow.ts b/apps/desktop/src/shared/rightSidebarWindow.ts
index ea2770c435..64e6e0dd85 100644
--- a/apps/desktop/src/shared/rightSidebarWindow.ts
+++ b/apps/desktop/src/shared/rightSidebarWindow.ts
@@ -40,8 +40,14 @@ export interface RsbWindowContext {
/** main → 子窗口的命令推送(如主窗终端快捷键转发 / detached RSB 内定位文件)。 */
export type RsbWindowCommand =
| { type: 'open-routines-tab'; sessionId: string; botId: string }
- /** 伙伴主任务页:确保「工作台」标签存在(不存在时创建并展开右侧栏)。 */
- | { type: 'open-bot-workbench-tab'; sessionId: string; botId: string }
+ /** 伙伴主任务页的工作台初始化或用户显式打开。 */
+ | {
+ type: 'open-bot-workbench-tab';
+ sessionId: string;
+ botId: string;
+ /** True is an explicit header click; absent keeps passive first-visit behavior. */
+ focusTab?: boolean;
+ }
| { type: 'open-terminal'; sessionId: string }
| { type: 'toggle-review-tab'; sessionId: string }
| { type: 'open-web-browser'; sessionId: string; url: string }
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 90def88396..e28b76087c 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -595,7 +595,8 @@ Todo 是伙伴维护的事务清单:既包含用户交办,也允许从已授
数据经 `local-db:bots:workbench:follow-scopes` 一次取回各伙伴的项目路径(只给路径,不带判断与会话内容),
整个窗口共享一份,工作台变化或换账号时重读。
- 界面:工作台是本机伙伴主任务全局右侧栏里的一个标签(与文件、浏览器并列),首次进入时自动创建
- 并展开右侧栏;伙伴聊天头部常驻「工作台」入口,标签被关掉后可重新打开;伙伴页保留全局右侧栏的其它能力。
+ 并展开右侧栏;已有侧栏布局选择时不自动创建或展开。关闭标签或收起侧栏后,返回伙伴、切换页面和重启
+ 都保留选择;伙伴聊天头部常驻「工作台」入口,用户点击后重新创建或激活标签并展开。伙伴页保留全局右侧栏的其它能力。
Mobile 与远程伙伴暂不提供。
### 6.4 伙伴与普通 Agent 共用能力声明和权限