Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Keep agent connection ordering stable (#4840)

sarahf17499c1a089
diff --git a/.changeset/lucky-lions-share.md b/.changeset/lucky-lions-share.md
new file mode 100644
index 000000000..889bae963
--- /dev/null
+++ b/.changeset/lucky-lions-share.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-app": patch
+---
+
+Keep Agent connections ordering stable while toggling, and keep newly enabled agents visible when clearing search or collapsing the list.
diff --git a/packages/app/src/components/settings/AgentConnectionsSection.dom.test.tsx b/packages/app/src/components/settings/AgentConnectionsSection.dom.test.tsx
index 3672ca6ea..d3c115503 100644
--- a/packages/app/src/components/settings/AgentConnectionsSection.dom.test.tsx
+++ b/packages/app/src/components/settings/AgentConnectionsSection.dom.test.tsx
@@ -239,6 +239,7 @@ function renderSection(
</TooltipProvider>
</QueryClientProvider>,
);
+ return client;
}
beforeEach(() => {
@@ -376,6 +377,259 @@ describe('AgentConnectionsSection', () => {
expect(tail).toContain('Cline');
});
+ test('keeps the expanded agent order stable after enabling and resorts on remount', async () => {
+ const user = userEvent.setup();
+ renderSection();
+ await screen.findByText('Claude Agent');
+ await expandInApp();
+ const sectionSelector = 'section[aria-labelledby="settings-configure-agents-in-app"]';
+ const names = (): string[] =>
+ within(document.querySelector<HTMLElement>(sectionSelector) as HTMLElement)
+ .getAllByText(/^(Claude Agent|Gemini|Cursor|OpenCode|Cline)$/)
+ .map((node) => node.textContent ?? '');
+ const before = names();
+ expect(before.indexOf('Cline')).toBeLessThan(before.indexOf('Cursor'));
+
+ const cursor = screen.getByTestId('configure-agents-in-app-registry:cursor');
+ await user.click(cursor);
+
+ expect(cursor.getAttribute('aria-checked')).toBe('true');
+ expect(document.activeElement).toBe(cursor);
+ expect(names()).toEqual(before);
+
+ cleanup();
+ renderSection();
+ await screen.findByText('ACP wrapper for Cursor');
+ await expandInApp();
+ const after = names();
+ expect(after.indexOf('Cursor')).toBeLessThan(after.indexOf('Cline'));
+ });
+
+ test('keeps the expanded agent order stable when catalog detection refreshes', async () => {
+ let refreshedCatalog = structuredClone(catalog);
+ fetchCatalog = () => Promise.resolve(refreshedCatalog);
+ const client = renderSection();
+ await screen.findByText('Claude Agent');
+ await expandInApp();
+ const sectionSelector = 'section[aria-labelledby="settings-configure-agents-in-app"]';
+ const names = (): string[] =>
+ within(document.querySelector<HTMLElement>(sectionSelector) as HTMLElement)
+ .getAllByText(/^(Claude Agent|Gemini|Cursor|OpenCode|Cline)$/)
+ .map((node) => node.textContent ?? '');
+ const before = names();
+ const cursor = screen.getByTestId('configure-agents-in-app-registry:cursor');
+
+ refreshedCatalog = {
+ ...refreshedCatalog,
+ agents: refreshedCatalog.agents.map((agent) =>
+ agent.id === 'cursor'
+ ? {
+ ...agent,
+ harness: { cli: 'cursor', availability: 'present', credentials: 'unknown' },
+ }
+ : agent,
+ ),
+ };
+ await client.invalidateQueries({ queryKey: ['acp-catalog'] });
+ await waitFor(() => expect(cursor.getAttribute('aria-checked')).toBe('true'));
+
+ expect(names()).toEqual(before);
+ });
+
+ test('adds a newly detected catalog agent after the existing primary rows', async () => {
+ let refreshedCatalog = structuredClone(catalog);
+ fetchCatalog = () => Promise.resolve(refreshedCatalog);
+ const client = renderSection();
+ await screen.findByText('Claude Agent');
+
+ refreshedCatalog = {
+ ...refreshedCatalog,
+ agents: [
+ ...refreshedCatalog.agents,
+ {
+ id: 'brand-new',
+ name: 'Brand New',
+ version: '1',
+ source: 'registry',
+ supported: true,
+ featured: false,
+ harness: { cli: 'brand-new', availability: 'present', credentials: 'unknown' },
+ },
+ ],
+ };
+ await client.invalidateQueries({ queryKey: ['acp-catalog'] });
+
+ await screen.findByText('Brand New');
+ const inApp = within(
+ document.querySelector<HTMLElement>(
+ 'section[aria-labelledby="settings-configure-agents-in-app"]',
+ ) as HTMLElement,
+ );
+ const names = (): string[] =>
+ inApp
+ .getAllByText(/^(Claude Agent|Gemini|Brand New|Cline|Cursor|OpenCode)$/)
+ .map((node) => node.textContent ?? '');
+ expect(names()).toEqual(['Claude Agent', 'Gemini', 'Brand New']);
+
+ await expandInApp();
+ expect(names()).toEqual(['Claude Agent', 'Gemini', 'Brand New', 'Cline', 'Cursor', 'OpenCode']);
+ });
+
+ test('keeps a late catalog agent in place when it is enabled', async () => {
+ let refreshedCatalog = structuredClone(catalog);
+ fetchCatalog = () => Promise.resolve(refreshedCatalog);
+ const user = userEvent.setup();
+ const client = renderSection();
+ await screen.findByText('Claude Agent');
+
+ refreshedCatalog = {
+ ...refreshedCatalog,
+ agents: [
+ ...refreshedCatalog.agents,
+ {
+ id: 'late-arrival',
+ name: 'Late Arrival',
+ version: '1',
+ source: 'registry',
+ supported: true,
+ featured: false,
+ },
+ ],
+ };
+ await client.invalidateQueries({ queryKey: ['acp-catalog'] });
+ await expandInApp();
+
+ const inApp = within(
+ document.querySelector<HTMLElement>(
+ 'section[aria-labelledby="settings-configure-agents-in-app"]',
+ ) as HTMLElement,
+ );
+ const names = (): string[] =>
+ inApp
+ .getAllByText(/^(Claude Agent|Gemini|Cline|Cursor|OpenCode|Late Arrival)$/)
+ .map((node) => node.textContent ?? '');
+ const expected = ['Claude Agent', 'Gemini', 'Cline', 'Cursor', 'OpenCode', 'Late Arrival'];
+ expect(names()).toEqual(expected);
+ const lateArrival = await screen.findByTestId('configure-agents-in-app-registry:late-arrival');
+
+ await user.click(lateArrival);
+
+ expect(lateArrival.getAttribute('aria-checked')).toBe('true');
+ expect(names()).toEqual(expected);
+ });
+
+ test('keeps an existing agent folded when detection refreshes', async () => {
+ let refreshedCatalog = structuredClone(catalog);
+ fetchCatalog = () => Promise.resolve(refreshedCatalog);
+ const client = renderSection();
+ await screen.findByText('Claude Agent');
+ const toggle = screen.getByTestId('configure-agents-in-app-show-more');
+
+ expect(screen.queryByText('ACP wrapper for Cursor')).toBeNull();
+ expect(toggle.textContent).toContain('Show 3 more');
+
+ refreshedCatalog = {
+ ...refreshedCatalog,
+ agents: refreshedCatalog.agents.map((agent) =>
+ agent.id === 'cursor'
+ ? {
+ ...agent,
+ harness: { cli: 'cursor', availability: 'present', credentials: 'unknown' },
+ }
+ : agent,
+ ),
+ };
+ await client.invalidateQueries({ queryKey: ['acp-catalog'] });
+ await waitFor(() =>
+ expect(screen.getByTestId('configure-agents-in-app-show-more').textContent).toContain(
+ 'Show 3 more',
+ ),
+ );
+
+ expect(screen.queryByText('ACP wrapper for Cursor')).toBeNull();
+ await expandInApp();
+ expect(
+ screen.getByTestId('configure-agents-in-app-registry:cursor').getAttribute('aria-checked'),
+ ).toBe('true');
+ });
+
+ test('keeps an initially enabled agent visible after disabling and resorts on remount', async () => {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ 'in-app:registry:cursor': true }));
+ reloadEnabledAgentsFromStorage();
+ const user = userEvent.setup();
+ renderSection();
+
+ const cursor = await screen.findByTestId('configure-agents-in-app-registry:cursor');
+ await user.click(cursor);
+
+ expect(cursor.getAttribute('aria-checked')).toBe('false');
+ expect(screen.getByText('ACP wrapper for Cursor')).toBeTruthy();
+
+ cleanup();
+ renderSection();
+ await screen.findByText('Claude Agent');
+ expect(screen.queryByText('ACP wrapper for Cursor')).toBeNull();
+ });
+
+ test('preserves the initial order when expanding after disabling an agent', async () => {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ 'in-app:registry:cursor': true }));
+ reloadEnabledAgentsFromStorage();
+ const user = userEvent.setup();
+ renderSection();
+ const inApp = within(
+ document.querySelector<HTMLElement>(
+ 'section[aria-labelledby="settings-configure-agents-in-app"]',
+ ) as HTMLElement,
+ );
+ const names = (): string[] =>
+ inApp
+ .getAllByText(/^(Claude Agent|Gemini|Cursor|OpenCode|Cline)$/)
+ .map((node) => node.textContent ?? '');
+
+ const cursor = await screen.findByTestId('configure-agents-in-app-registry:cursor');
+ const initialPrimaryOrder = names();
+ await user.click(cursor);
+ await expandInApp();
+
+ expect(names().slice(0, initialPrimaryOrder.length)).toEqual(initialPrimaryOrder);
+ });
+
+ test('promotes an agent enabled in search when the search is cleared', async () => {
+ const user = userEvent.setup();
+ renderSection();
+ await screen.findByText('Claude Agent');
+ const search = screen.getByTestId('configure-agents-search');
+ await user.type(search, 'cursor');
+ const cursor = screen.getByTestId('configure-agents-in-app-registry:cursor');
+
+ await user.click(cursor);
+ await user.clear(search);
+
+ expect(cursor.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByText('ACP wrapper for Cursor')).toBeTruthy();
+ expect(
+ screen.getByTestId('configure-agents-in-app-show-more').getAttribute('aria-expanded'),
+ ).toBe('false');
+ });
+
+ test('promotes an agent enabled in the expanded list before collapsing it', async () => {
+ const user = userEvent.setup();
+ renderSection();
+ await screen.findByText('Claude Agent');
+ await expandInApp();
+ const cursor = screen.getByTestId('configure-agents-in-app-registry:cursor');
+
+ await user.click(cursor);
+ await user.click(screen.getByTestId('configure-agents-in-app-show-more'));
+
+ expect(cursor.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByText('ACP wrapper for Cursor')).toBeTruthy();
+ expect(screen.queryByText('Cline')).toBeNull();
+ expect(
+ screen.getByTestId('configure-agents-in-app-show-more').getAttribute('aria-expanded'),
+ ).toBe('false');
+ });
+
test('a group with something installed sorts above one with nothing', async () => {
const gemini = catalog.agents.find((a) => a.id === 'gemini');
const claude = catalog.agents.find((a) => a.id === 'claude-acp');
diff --git a/packages/app/src/components/settings/AgentConnectionsSection.tsx b/packages/app/src/components/settings/AgentConnectionsSection.tsx
index ec090ed94..49e9d6c1b 100644
--- a/packages/app/src/components/settings/AgentConnectionsSection.tsx
+++ b/packages/app/src/components/settings/AgentConnectionsSection.tsx
@@ -38,12 +38,14 @@ import {
} from '@/lib/acp/catalog';
import {
desktopEnabledKey,
+ type EnabledOverrides,
inAppEnabledKey,
setAgentEnabled,
terminalEnabledKey,
useEnabledOverrides,
} from '@/lib/acp/enabled-agents';
import {
+ type RegisteredAgent,
reassignDefaultIfDisabled,
registerAgent,
useRegisteredAgents,
@@ -376,6 +378,93 @@ function readProducedFacts(snapshot: HostSnapshot | null): boolean {
);
}
+interface InAppOrdering {
+ primaryKeys: ReadonlySet<string>;
+ ranks: ReadonlyMap<string, number>;
+}
+
+function inAppAgentKey(agent: { source: string; id: string }): string {
+ return `${agent.source}:${agent.id}`;
+}
+
+function isInAppAgentChecked(
+ overrides: EnabledOverrides,
+ registeredKeys: ReadonlySet<string>,
+ agent: CatalogAgent,
+): boolean {
+ const isRegistered = registeredKeys.has(inAppAgentKey(agent));
+ const isDetected = isHarnessDetected(agent);
+ return isInAppAgentEnabled(
+ overrides,
+ agent.source,
+ agent.id,
+ isRegistered || isDetected,
+ agent.supported,
+ );
+}
+
+function isPrimaryInAppAgent(
+ overrides: EnabledOverrides,
+ registeredKeys: ReadonlySet<string>,
+ agent: CatalogAgent,
+): boolean {
+ return (
+ (agent.harness !== undefined && harnessPresenceRank(agent) === 0) ||
+ isInAppAgentChecked(overrides, registeredKeys, agent)
+ );
+}
+
+function createInAppOrdering(
+ agents: readonly CatalogAgent[],
+ overrides: EnabledOverrides,
+ registered: readonly RegisteredAgent[],
+): InAppOrdering {
+ const registeredKeys = new Set(registered.map((agent) => inAppAgentKey(agent)));
+ const isPrimary = (agent: CatalogAgent): boolean =>
+ isPrimaryInAppAgent(overrides, registeredKeys, agent);
+ const ordered = [...agents].sort(
+ (a, b) => Number(isPrimary(b)) - Number(isPrimary(a)) || a.name.localeCompare(b.name),
+ );
+ return {
+ primaryKeys: new Set(ordered.filter(isPrimary).map(inAppAgentKey)),
+ ranks: new Map(ordered.map((agent, index) => [inAppAgentKey(agent), index])),
+ };
+}
+
+function extendInAppOrdering(
+ ordering: InAppOrdering,
+ agents: readonly CatalogAgent[],
+ overrides: EnabledOverrides,
+ registered: readonly RegisteredAgent[],
+): InAppOrdering {
+ const unseen = agents.filter((agent) => !ordering.ranks.has(inAppAgentKey(agent)));
+ if (unseen.length === 0) return ordering;
+
+ const registeredKeys = new Set(registered.map((agent) => inAppAgentKey(agent)));
+ const isPrimary = (agent: CatalogAgent): boolean =>
+ isPrimaryInAppAgent(overrides, registeredKeys, agent);
+ const unseenPrimary = unseen.filter(isPrimary).sort((a, b) => a.name.localeCompare(b.name));
+ const unseenSecondary = unseen
+ .filter((agent) => !isPrimary(agent))
+ .sort((a, b) => a.name.localeCompare(b.name));
+ const existingKeys = [...ordering.ranks.entries()]
+ .sort(([, a], [, b]) => a - b)
+ .map(([key]) => key);
+ const existingPrimary = existingKeys.filter((key) => ordering.primaryKeys.has(key));
+ const existingSecondary = existingKeys.filter((key) => !ordering.primaryKeys.has(key));
+ const orderedKeys = [
+ ...existingPrimary,
+ ...unseenPrimary.map(inAppAgentKey),
+ ...existingSecondary,
+ ...unseenSecondary.map(inAppAgentKey),
+ ];
+
+ return {
+ primaryKeys: new Set([...ordering.primaryKeys, ...unseenPrimary.map(inAppAgentKey)]),
+ ranks: new Map(orderedKeys.map((key, index) => [key, index])),
+ };
+}
+
export function AgentConnectionsSection({
applyConnections = applyAgentConnectionIntents,
}: {
@@ -404,6 +493,20 @@ export function AgentConnectionsSection({
queryFn: ({ signal }) => fetchAgentCatalog(signal),
staleTime: 5 * 60 * 1000,
});
+ const [inAppOrdering, setInAppOrdering] = useState<InAppOrdering | null>(() =>
+ catalog.data === undefined
+ ? null
+ : createInAppOrdering(catalog.data.agents, overrides, registered),
+ );
+ let activeInAppOrdering = inAppOrdering ?? createInAppOrdering([], overrides, registered);
+ if (catalog.data !== undefined) {
+ const nextInAppOrdering =
+ inAppOrdering === null
+ ? createInAppOrdering(catalog.data.agents, overrides, registered)
+ : extendInAppOrdering(inAppOrdering, catalog.data.agents, overrides, registered);
+ if (nextInAppOrdering !== inAppOrdering) setInAppOrdering(nextInAppOrdering);
+ activeInAppOrdering = nextInAppOrdering;
+ }
const refreshOnMount = useEffectEvent(() => {
void refresh();
@@ -432,7 +535,7 @@ export function AgentConnectionsSection({
}, [applyConnections, reloadInstallState]);
const catalogAgents = catalog.data?.agents;
- const registeredKeys = new Set(registered.map((a) => `${a.source}:${a.id}`));
+ const registeredKeys = new Set(registered.map((agent) => inAppAgentKey(agent)));
const installedClis = terminalLaunch?.installedClis ?? {};
const connections = snapshot === null ? [] : connectionsFromSnapshot(snapshot);
@@ -593,6 +696,22 @@ export function AgentConnectionsSection({
setConfigureId(agentId);
}
+ function refreshInAppOrdering(): void {
+ if (catalogAgents !== undefined) {
+ setInAppOrdering(createInAppOrdering(catalogAgents, overrides, registered));
+ }
+ }
+
+ function updateQuery(nextQuery: string): void {
+ if (query.trim() !== '' && nextQuery.trim() === '') refreshInAppOrdering();
+ setQuery(nextQuery);
+ }
+
+ function toggleInAppOverflow(): void {
+ if (showInAppOverflow) refreshInAppOrdering();
+ setShowInAppOverflow(!showInAppOverflow);
+ }
+
const q = query.trim().toLowerCase();
const matches = (text: string): boolean => q === '' || text.toLowerCase().includes(q);
@@ -637,21 +756,17 @@ export function AgentConnectionsSection({
const showDesktop = !searching || desktopTargets.length > 0 || unlaunchableIds.length > 0;
const inAppChecked = (agent: CatalogAgent): boolean => {
- const isRegistered = registeredKeys.has(`${agent.source}:${agent.id}`);
- const isDetected = isHarnessDetected(agent);
- return isInAppAgentEnabled(
- overrides,
- agent.source,
- agent.id,
- isRegistered || isDetected,
- agent.supported,
- );
+ return isInAppAgentChecked(overrides, registeredKeys, agent);
+ };
+ const wasPrimaryAgentAtOrderingBoundary = (agent: CatalogAgent): boolean => {
+ return activeInAppOrdering.primaryKeys.has(inAppAgentKey(agent));
+ };
+ const orderingRank = (agent: CatalogAgent): number => {
+ return activeInAppOrdering.ranks.get(inAppAgentKey(agent)) ?? Number.MAX_SAFE_INTEGER;
};
- const isPrimaryAgent = (a: CatalogAgent): boolean =>
- (a.harness !== undefined && harnessPresenceRank(a) === 0) || inAppChecked(a);
- const inAppPrimary = inAppAgents.filter(isPrimaryAgent);
+ const inAppPrimary = inAppAgents.filter(wasPrimaryAgentAtOrderingBoundary);
const inAppShown = [...(searching || showInAppOverflow ? inAppAgents : inAppPrimary)].sort(
- (a, b) => Number(isPrimaryAgent(b)) - Number(isPrimaryAgent(a)) || a.name.localeCompare(b.name),
+ (a, b) => orderingRank(a) - orderingRank(b) || a.name.localeCompare(b.name),
);
const inAppHiddenCount = searching ? 0 : inAppAgents.length - inAppPrimary.length;
@@ -703,11 +818,12 @@ export function AgentConnectionsSection({
) : (
<>
{inAppShown.map((agent: CatalogAgent) => {
+ const agentKey = inAppAgentKey(agent);
const checked = inAppChecked(agent);
const hint = !agent.supported ? t`Not available on this platform` : agent.description;
return (
<AgentRow
- key={`${agent.source}:${agent.id}`}
+ key={agentKey}
icon={
<RegisteredAgentIcon
agentId={agent.id}
@@ -720,8 +836,8 @@ export function AgentConnectionsSection({
checked={checked}
disabled={!agent.supported}
ariaLabel={t`Enable ${agent.name}`}
- testId={`configure-agents-in-app-${agent.source}:${agent.id}`}
- rowTestId={`configure-agents-in-app-row-${agent.source}:${agent.id}`}
+ testId={`configure-agents-in-app-${agentKey}`}
+ rowTestId={`configure-agents-in-app-row-${agentKey}`}
onToggle={(next) => {
if (next) {
registerAgent(
@@ -738,7 +854,7 @@ export function AgentConnectionsSection({
setAgentEnabled(inAppEnabledKey(agent.source, agent.id), true);
} else {
setAgentEnabled(inAppEnabledKey(agent.source, agent.id), false);
- reassignDefaultIfDisabled(`${agent.source}:${agent.id}`, (a) =>
+ reassignDefaultIfDisabled(agentKey, (a) =>
isInAppAgentEnabled(overrides, a.source, a.id, true, a.supported),
);
}
@@ -749,7 +865,7 @@ export function AgentConnectionsSection({
<FoldToggleButton
hiddenCount={inAppHiddenCount}
expanded={showInAppOverflow}
- onToggle={() => setShowInAppOverflow((v) => !v)}
+ onToggle={toggleInAppOverflow}
testId="configure-agents-in-app-show-more"
/>
</>
@@ -945,7 +1061,7 @@ export function AgentConnectionsSection({
/>
<Input
value={query}
- onChange={(event) => setQuery(event.target.value)}
+ onChange={(event) => updateQuery(event.target.value)}
placeholder={t`Search agents`}
aria-label={t`Search agents`}
className="ps-8"