Repository navigation
Description
Feature request: make the Copilot's entity context selector navigable
Repo: umbraco/Umbraco.AI
Versions: Umbraco.AI 17.4.0-rc.2, Umbraco.AI.Agent.Copilot 17.1.0-rc.2, Umbraco.AI.Agent.UI 17.1.0-rc.2, Umbraco CMS 17.6.2
Summary
The Copilot's entity selector renders one chip per detected entity. On a content page with a block list this does not scale.
Concretely, on one of our pages: a document chip labelled "11 tips voor het maken van een goede contactpagina" followed by ten chips that all read "Block", wrapping over four rows and taking up the top fifth of the panel before the conversation has started. They are not in the order the blocks appear on the page, and a block nested inside another block looks exactly like a top-level one. Picking the right chip is guesswork.
Three concrete defects, then a proposal. The proposal runs today as a local App_Plugin (source at the bottom) and works on every block, so this is not a question of missing API. What a third party cannot do is fix the list it is working around.
Defect 1 — the order does not match the page
The chips are not in document order, and the cause is mechanical.
UaiWorkspaceRegistryContext.getAll() returns a Map's values, so insertion order:
getAll(): WorkspaceEntry[] {
return Array.from(this.#entries.values());
}_rekey() deletes and re-sets, which in a JS Map moves the entry to the end:
_rekey(oldKey: string, newKey: string, entry: WorkspaceEntry): void {
const existing = this.#entries.get(newKey);
if (existing && existing.context !== entry.context) {
this.#entries.delete(newKey);
}
this.#entries.delete(oldKey);
this.#entries.set(newKey, entry);
...
}And every workspace is first registered under a temporary key, then re-keyed once its unique observable emits (workspace.decorator.ts):
// Start with temporary UUID key
let currentKey: string = crypto.randomUUID();
...
subscription = uniqueObservable.subscribe((uniqueValue: string | null | undefined) => {
if (uniqueValue && currentKey.includes("-")) {
// Re-key with entity-based key
const entityKey = `${entityType}:${uniqueValue}`;
registry._rekey(currentKey, entityKey, createEntry(uniqueValue));
currentKey = entityKey;
}
});Net effect: the final order is the order in which those observables happened to resolve — asynchronous and timing dependent — not the order the blocks appear in on the page. UaiEntityAdapterContext.#refresh() iterates getAll() directly, so the selector inherits it.
This looks fixable on its own, independent of the rest of this request.
Related side effect worth a look: #refresh() picks the fallback selection as detected[detected.length - 1], commented "Auto-select deepest (last)". Under this ordering that is not reliably the deepest entity — it is whichever one re-keyed last.
Defect 2 — no hierarchy is visible
A block nested inside another block looks identical to a top-level block. Indenting nested entries in the list would make the list readable even before anything else changes.
The relationship is available:
-
Block Grid carries it explicitly.
UmbBlockGridWorkspaceOriginDataholdsparentUniqueandareaKey, and the grid entries context tracks them:#parentUnique?: string | null; #areaKey?: string | null; ... getParentUnique(): string | null | undefined { return this.#parentUnique; } getAreaKey(): string | null | undefined { return this.#areaKey; }
-
Block List nested inside a block has no origin data for it — the nesting runs through the property editor tree instead — but it is derivable from context ancestry.
UmbContextConsumerdefaults tostopAtContextMatch, so a request resolves to the innermostUmbBlockEntryContext; the plugin below relies on exactly that.
Defect 3 — placement and space
The row sits at the top of the panel and grows downward: eleven chips over four rows on the page described above, before the conversation has started. Even with labels fixed (see the related bug report) and ordering fixed, a page with a few dozen blocks will not fit — and long labels make it worse, not better.
Suggestion: move it to the bottom, directly above the chat input, and make it a fixed-height control rather than a growing row.
Copilot in Visual Studio is a reasonable reference for the shape. It puts a single compact row immediately above the input: a + button to add context, then one chip per active context item — "Active Document" — each with an × to remove it, with the input directly below and the agent and model pickers under that. The row never wraps; additional context lives behind the + rather than expanding into the conversation area. Applied here that would mean the active entity visible as one chip, the rest reachable through a dropdown.
This one genuinely cannot be done from outside the package: uai-entity-selector is a plain @customElement used in the Copilot panel template, not a manifest-driven slot. Third parties can add selection behaviour alongside it, but cannot replace or condense the UI.
Proposal: click a block to make it the active entity
Rather than hunting for the right chip, click the block in the workspace.
The selection half is already fully supported from outside the package, which is why the proof of concept is small:
-
UAI_COPILOT_CONTEXTis registered as aglobalContext, so it is reachable from anywhere in the DOM tree — including from a block in the document workspace, which is not inside the Copilot panel. -
It exposes
setSelectedEntityKey(key), where the key is`${entityType}:${unique}`. -
A block workspace's
uniqueis the block'scontentKey:readonly unique = this.#layout.asObservablePart((x) => x?.contentKey);
-
UmbBlockEntryContextknows that samecontentKey.
So the whole bridge is: resolve the nearest block entry from the click, and hand its key over.
Why this belongs in the package
The plugin below works in practice: clicking any block in the list makes it the Copilot's active entity, collapsed or expanded. So this is not blocked on missing API — the behaviour is a small amount of code on top of what is already public.
It belongs upstream because of the three defects above, and because the one thing a third party cannot touch is the selector UI itself (defect 3). Behaviour can be added alongside it; the row cannot be replaced or condensed.
One robustness note for whoever implements it. UaiEntityAdapterContext.#refresh() overwrites a selection whose key is not in the detected list:
// Auto-select deepest (last) if no selection or selection no longer exists
if (!currentKey || !detected.find((e) => e.key === currentKey)) {
this.#selectedKey$.next(detected[detected.length - 1]?.key);
}The plugin therefore only sets a key it can already see in detectedEntities$, so that a click can never snap the selection to some unrelated entity. On the pages we tested, every block in a block list has a live workspace context and the guard simply passes — but a built-in implementation would want to decide deliberately what should happen when it does not, rather than inheriting the fallback.
Working example
This runs today as an App_Plugin against the versions listed above. It uses context aliases rather than imported tokens because UAI_COPILOT_CONTEXT lives in an @umbraco-ai/* package whose availability to third-party App_Plugins we do not control.
umbraco-package.json:
{
"alias": "TP.CopilotBlockFocus",
"name": "TP Copilot Block Focus",
"version": "1.0.0",
"extensions": [
{
"type": "appEntryPoint",
"alias": "TP.CopilotBlockFocus.EntryPoint",
"name": "Copilot Block Focus",
"js": "/App_Plugins/TP.CopilotBlockFocus/copilot-block-focus.js"
}
]
}copilot-block-focus.js:
import { UmbContextConsumer } from '@umbraco-cms/backoffice/context-api';
const BLOCK_ENTRY_CONTEXT_ALIAS = 'UmbBlockEntryContext';
const COPILOT_CONTEXT_ALIAS = 'UaiCopilotContext';
const BLOCK_ENTITY_TYPE = 'block';
export const onInit = () => {
// Capture phase so we see the click before anything can stop propagation, passive so this
// can never interfere with the click itself.
document.addEventListener('click', onDocumentClick, { capture: true, passive: true });
};
export const onUnload = () => {
document.removeEventListener('click', onDocumentClick, { capture: true });
};
async function onDocumentClick(event) {
// composedPath()[0] is the true innermost node; event.target is retargeted at shadow
// boundaries and would point at the host element instead of what was clicked.
const origin = event.composedPath().find((node) => node instanceof Element);
if (!origin) return;
const blockEntry = await requestContext(origin, BLOCK_ENTRY_CONTEXT_ALIAS);
if (!blockEntry) return; // not a click inside a block; leave the selection alone
const contentKey = blockEntry.getLayout?.()?.contentKey;
if (!contentKey) return;
const copilot = await requestContext(origin, COPILOT_CONTEXT_ALIAS);
if (!copilot?.IS_COPILOT_CONTEXT || typeof copilot.setSelectedEntityKey !== 'function') return;
const key = `${BLOCK_ENTITY_TYPE}:${contentKey}`;
// Only set a key the Copilot can already see, so a click can never snap the selection to an
// unrelated entity via the auto-select fallback. See the robustness note above.
const detected = readCurrentValue(copilot.detectedEntities$) ?? [];
if (!detected.some((entity) => entity?.key === key)) return;
copilot.setSelectedEntityKey(key);
}
/** Reads a BehaviorSubject-backed observable's current value without keeping a subscription. */
function readCurrentValue(observable) {
if (!observable?.subscribe) return undefined;
let value;
observable.subscribe((next) => { value = next; }).unsubscribe();
return value;
}
/**
* Resolves the nearest provider of a context, starting from the given element. A context request
* is a plain bubbling, composed Event, so an element is all that is needed — no controller host.
* stopAtContextMatch defaults to true, so nested blocks resolve to the innermost one.
*/
async function requestContext(element, alias) {
if (!element.isConnected) return undefined;
const consumer = new UmbContextConsumer(element, alias);
try {
// asPromise() must precede request(): request() only arms its rejection timer once a
// promise resolver is registered.
const promise = consumer.asPromise();
consumer.request();
return await promise;
} catch {
return undefined; // nothing answered within a frame
} finally {
consumer.destroy?.();
}
}Related
The chips being labelled "Block" is filed separately as #343. It is independent of this request, but it is a large part of why the row is unusable rather than merely cramped.
Activity