diff --git a/orchestrator/templates/index.html.j2 b/orchestrator/templates/index.html.j2
index 20d8d03..507f620 100644
--- a/orchestrator/templates/index.html.j2
+++ b/orchestrator/templates/index.html.j2
@@ -650,6 +650,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "page-palette.js" %}
+{% include "page-context.js" %}
+
{% include "page-load.js" %}
{% include "page-boot.js" %}
diff --git a/orchestrator/templates/page-ancestry.js b/orchestrator/templates/page-ancestry.js
index 5cd9817..57b34d6 100644
--- a/orchestrator/templates/page-ancestry.js
+++ b/orchestrator/templates/page-ancestry.js
@@ -51,10 +51,13 @@
}));
}
+ function glossarySections() {
+ return Glossary.explain().map(([heading, rows]) => h("section", {}, h("h4", {}, heading),
+ h("dl", {class: "glossary"}, rows.map(([term, meaning]) => h("div", {}, h("dt", {}, term), h("dd", {}, meaning))))));
+ }
+
function gateExplain() {
- return h("details", {class: "gate-explain"}, h("summary", {title: "Explain: what each mark of this branch means"}, icon("bi-question-circle"), "Explain"),
- Glossary.explain().map(([heading, rows]) => h("section", {}, h("h4", {}, heading),
- h("dl", {class: "glossary"}, rows.map(([term, meaning]) => h("div", {}, h("dt", {}, term), h("dd", {}, meaning)))))));
+ return h("details", {class: "gate-explain"}, h("summary", {title: "Explain: what each mark of this branch means"}, icon("bi-question-circle"), "Explain"), glossarySections());
}
function gateApply() {
diff --git a/orchestrator/templates/page-boot.js b/orchestrator/templates/page-boot.js
index d199b41..924733c 100644
--- a/orchestrator/templates/page-boot.js
+++ b/orchestrator/templates/page-boot.js
@@ -28,7 +28,8 @@
document.addEventListener("keydown", context, {once: true});
document.addEventListener("pointerdown", unlock);
document.addEventListener("keydown", keyboard);
- document.addEventListener("contextmenu", feedbackMenu);
+ document.addEventListener("keydown", ctxKeydown);
+ document.addEventListener("contextmenu", ctxContextMenu);
document.addEventListener("selectionchange", feedbackButton);
document.addEventListener("visibilitychange", refresh);
window.addEventListener("focus", refresh);
diff --git a/orchestrator/templates/page-constants.js b/orchestrator/templates/page-constants.js
index c18bc9e..a02820b 100644
--- a/orchestrator/templates/page-constants.js
+++ b/orchestrator/templates/page-constants.js
@@ -76,7 +76,7 @@
direct: [[740, 0, 0.2]],
radio: [[520, 0, 0.07]],
};
- const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Feedback on the selected lines of a diff or a command"], ["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
+ const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Feedback on the selected lines of a diff or a command"], ["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
const calm = window.matchMedia("(prefers-reduced-motion: reduce)");
const relative = new Intl.RelativeTimeFormat("en", {numeric: "auto"});
const absolute = new Intl.DateTimeFormat("en-GB", {dateStyle: "medium", timeStyle: "short"});
diff --git a/orchestrator/templates/page-context.js b/orchestrator/templates/page-context.js
new file mode 100644
index 0000000..1aa6e25
--- /dev/null
+++ b/orchestrator/templates/page-context.js
@@ -0,0 +1,250 @@
+ const ctxMenu = {node: null, back: null};
+ const CTX_FIELDS = ["INPUT", "TEXTAREA", "SELECT"];
+ const CTX_GAP = 8;
+ const CTX_MODIFIERS = ["Shift", "Control", "Alt", "Meta"];
+ const CTX_OPENS = {task: "Open task", message: "Open message", artifact: "Open artifact"};
+ const ctxAttr = (...names) => (node) => names.map((name) => node.getAttribute(name)).find(Boolean) || null;
+ const ctxField = (node) => Boolean(node.isContentEditable) || CTX_FIELDS.includes(node.tagName);
+ const ctxInside = (node) => Boolean(ctxMenu.node) && ctxMenu.node.contains(node);
+ const ctxCopyItem = (label, text) => ({label, hint: text, run: () => ctxCopy(text)});
+
+ function ctxAgentOf(node) {
+ const raw = ctxAttr("data-agent", "data-face", "data-name", "data-session")(node);
+ return raw && raw !== HUMAN ? agentKey(raw) : null;
+ }
+
+ function ctxPinOf(node) {
+ return node.matches(Panels.HOSTS) ? Panels.targetOf(node) : null;
+ }
+
+ const ctxPinEntry = (target) => (target.id && !target.refused ? Panels.lookup(target.kind, target.id, target.view) : null);
+ const ctxEntryOf = (ref) => state.inbox.find((entry) => keyOf(entry) === ref) || null;
+ const ctxArtifactOf = (id) => (tree.model ? tree.model.byId.get(id) || null : null);
+
+ function ctxTaskItems(node, id) {
+ const known = state.tasks.some((row) => row.task === id);
+ return [...(known ? [{label: "Open task", hint: id, run: () => taskSheet(id)}] : []), ctxCopyItem("Copy task id", id)];
+ }
+
+ function ctxAgentItems(node, key) {
+ return [ctxCopyItem("Copy name", nameOf(key))];
+ }
+
+ function ctxBranchItems(node, name) {
+ const ref = `branch:${node.getAttribute("data-repo")}\u0000${name}`;
+ const open = ctxArtifactOf(ref) ? [{label: "Open branch", hint: name, run: () => artSelect(ref)}] : [];
+ return [...open, ctxCopyItem("Copy branch name", name), {label: "Explain", hint: "what each mark of a branch means", run: () => openSheet("Explain", glossarySections(), false)}];
+ }
+
+ function ctxPathItems(node, path) {
+ return [...feedbackItems(), ...(path === "-" ? [] : [ctxCopyItem("Copy path", path)])];
+ }
+
+ function ctxEntryItems(node, ref) {
+ const item = ctxEntryOf(ref);
+ return item ? [{label: "Open entry", hint: item.title, run: () => openItem(item)}, ctxCopyItem("Copy id", item.id)] : [];
+ }
+
+ function ctxPickItems(node, id) {
+ const found = ctxArtifactOf(id);
+ if (found) {
+ return [{label: "Open artifact", hint: found.label, run: () => artSelect(id)}];
+ }
+ const sub = state.graph.nodes.find((entry) => entry.id === id && entry.kind === "subagent");
+ return sub ? [{label: "Open parent agent", hint: labelOf(sub.parent), run: () => select(id)}] : [];
+ }
+
+ function ctxPickTitle(id) {
+ const found = ctxArtifactOf(id) || state.graph.nodes.find((entry) => entry.id === id);
+ return found ? found.label : id;
+ }
+
+ function ctxPinItems(node, target) {
+ const entry = ctxPinEntry(target);
+ if (!entry) {
+ return [];
+ }
+ const opens = Object.hasOwn(CTX_OPENS, target.kind) ? [{label: CTX_OPENS[target.kind], hint: entry.title, run: () => HOME_OPENERS[target.kind](Panels.raw(target.id), target.id)}] : [];
+ const pinned = Panels.has(homePins(), target.kind, target.id);
+ return [...opens, {label: pinned ? "Unpin from Home" : "Pin to Home", hint: entry.title, run: () => homePress(target.kind, target.id, entry.title, target.view)}];
+ }
+
+ const CTX_KINDS = [
+ {kind: "task", id: ctxAttr("data-task"), title: (id) => `Task ${id}`, items: ctxTaskItems},
+ {kind: "agent", id: ctxAgentOf, title: (key) => nameOf(key), items: ctxAgentItems},
+ {kind: "branch", id: ctxAttr("data-branch"), title: (name) => `Branch ${name}`, items: ctxBranchItems},
+ {kind: "path", id: ctxAttr("data-path"), title: (path) => path, items: ctxPathItems},
+ {kind: "entry", id: ctxAttr("data-ref"), title: (ref) => ctxEntryOf(ref).title, items: ctxEntryItems},
+ {kind: "rule", id: ctxAttr("data-rule", "data-entry"), title: (id) => `Rule ${id}`, items: (node, id) => [ctxCopyItem("Copy rule", id)]},
+ {kind: "pick", id: ctxAttr("data-pick"), title: ctxPickTitle, items: ctxPickItems},
+ {kind: "pin", id: ctxPinOf, title: (target) => ctxPinEntry(target).title, items: ctxPinItems},
+ ];
+
+ /**
+ * @param target - the element a right-click or the menu key hit.
+ * @returns [{kind, id, node, entry}]: per kind of CTX_KINDS the nearest marked element from target up, nearest first.
+ */
+ function ctxFound(target) {
+ const found = [];
+ for (let node = target; node; node = node.parentElement) {
+ for (const entry of CTX_KINDS.filter((kind) => !found.some((seen) => seen.kind === kind.kind))) {
+ const id = entry.id(node);
+ if (id) {
+ found.push({kind: entry.kind, id, node, entry});
+ }
+ }
+ }
+ return found;
+ }
+
+ function ctxOwn(found, items) {
+ const groups = found.map((seen) => ({seen, items: items.filter((item) => item.scope === seen.kind && item.id === seen.id)})).filter((group) => group.items.length);
+ const flat = groups.flatMap((group) => group.items);
+ return {title: groups.length ? groups[0].seen.entry.title(groups[0].seen.id) : "", items: flat.filter((item, index) => flat.findIndex((other) => other.label === item.label) === index)};
+ }
+
+ /**
+ * @param target - the element the menu is for.
+ * @returns [{scope, title, items}]: the element's own items, then the current tab's, then the general ones; empty
+ * sections left out.
+ */
+ function ctxSections(target) {
+ const found = ctxFound(target);
+ const provided = found.flatMap((seen) => seen.entry.items(seen.node, seen.id).map((item) => ({...item, scope: seen.kind, id: seen.id})));
+ const items = [...paletteItems(), ...provided];
+ const own = ctxOwn(found, items);
+ const tab = Nav.TABS.find(([id]) => id === Nav.tabOf(ui.screen));
+ return [
+ {scope: "element", title: own.title, items: own.items},
+ ...(tab ? [{scope: tab[0], title: tab[1], items: items.filter((item) => item.scope === tab[0])}] : []),
+ {scope: "general", title: "General", items: items.filter((item) => item.scope === "general")},
+ ].filter((section) => section.items.length);
+ }
+
+ async function ctxCopy(text) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast("Copied", [revealed(text)], true);
+ } catch {
+ toast("Not copied", ["The browser refused the clipboard."], false);
+ }
+ }
+
+ function ctxNode() {
+ if (!ctxMenu.node) {
+ ctxMenu.node = h("div", {class: "ctx-menu", role: "menu", "aria-label": "Context menu", tabindex: -1, hidden: true, on: {keydown: ctxKeys}});
+ document.body.append(ctxMenu.node);
+ }
+ return ctxMenu.node;
+ }
+
+ function ctxItem(item) {
+ return h("button", {type: "button", role: "menuitem", tabindex: -1, class: "ctx-item", title: revealed(item.hint), on: {click: () => ctxRun(item)}},
+ item.face ? face(item.face, false) : null, h("span", {class: "ctx-label"}, revealed(item.label)), h("span", {class: "muted"}, revealed(item.hint)));
+ }
+
+ function ctxGroup(section, index) {
+ return [index ? h("div", {role: "separator", class: "ctx-rule"}) : null,
+ h("div", {role: "group", class: "ctx-group", "aria-label": revealed(section.title), "data-scope": section.scope}, h("div", {class: "ctx-head", "aria-hidden": "true"}, revealed(section.title)), section.items.map(ctxItem))];
+ }
+
+ function ctxPlace(node, at) {
+ node.style.left = "0px";
+ node.style.top = "0px";
+ const box = node.getBoundingClientRect();
+ const below = at.y + box.height + CTX_GAP <= window.innerHeight;
+ node.style.left = `${Math.max(CTX_GAP, Math.min(at.x, window.innerWidth - box.width - CTX_GAP))}px`;
+ node.style.top = `${Math.max(CTX_GAP, Math.min(below ? at.y : at.y - box.height, window.innerHeight - box.height - CTX_GAP))}px`;
+ }
+
+ /**
+ * @param sections - what ctxSections gives.
+ * @param at - {x, y}, the viewport point the menu opens at; it moves inside the viewport when it would run past it.
+ */
+ function ctxShow(sections, at) {
+ const node = ctxNode();
+ node.replaceChildren(...sections.flatMap(ctxGroup).filter(Boolean));
+ node.hidden = false;
+ ctxPlace(node, at);
+ const first = node.querySelector('[role="menuitem"]');
+ if (first) {
+ first.focus({preventScroll: true});
+ }
+ }
+
+ function ctxOpen(target, at) {
+ closeMenus(null);
+ ctxMenu.back = document.activeElement;
+ ctxShow(ctxSections(target), at);
+ }
+
+ function ctxClose(restore) {
+ if (!ctxMenu.node || ctxMenu.node.hidden) {
+ return;
+ }
+ const back = ctxMenu.back;
+ ctxMenu.back = null;
+ ctxMenu.node.hidden = true;
+ ctxMenu.node.replaceChildren();
+ if (restore && back && back.isConnected && typeof back.focus === "function") {
+ back.focus({preventScroll: true});
+ }
+ }
+
+ function ctxRun(item) {
+ ctxClose(true);
+ item.run();
+ }
+
+ /**
+ * @param keep - the menu a click landed in, as closeMenus gets it; the context menu stays open when it is that menu.
+ */
+ function ctxDismiss(keep) {
+ if (ctxMenu.node && ctxMenu.node !== keep) {
+ ctxClose(ctxMenu.node.contains(document.activeElement));
+ }
+ }
+
+ function ctxKeys(event) {
+ const items = [...ctxMenu.node.querySelectorAll('[role="menuitem"]')];
+ const at = items.indexOf(document.activeElement);
+ const moves = {ArrowDown: at + 1, ArrowUp: Math.max(at, 0) - 1, Home: 0, End: items.length - 1};
+ if (Object.hasOwn(moves, event.key)) {
+ items[(moves[event.key] + items.length) % items.length].focus();
+ } else if (event.key === "Enter" || event.key === " ") {
+ items[Math.max(at, 0)].click();
+ } else if (CTX_MODIFIERS.includes(event.key)) {
+ return;
+ } else {
+ ctxClose(true);
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ function ctxContextMenu(event) {
+ const target = event.target;
+ if (!(target instanceof Element) || event.defaultPrevented) {
+ return;
+ }
+ if (ctxInside(target)) {
+ event.preventDefault();
+ return;
+ }
+ if (event.shiftKey || ctxField(target)) {
+ return;
+ }
+ event.preventDefault();
+ ctxOpen(target, {x: event.clientX, y: event.clientY});
+ }
+
+ function ctxKeydown(event) {
+ const pressed = event.key === "ContextMenu" || (event.key === "F10" && event.shiftKey);
+ const target = document.activeElement;
+ if (!pressed || event.ctrlKey || event.altKey || event.metaKey || !(target instanceof Element) || ctxField(target) || ctxInside(target)) {
+ return;
+ }
+ event.preventDefault();
+ const box = target.getBoundingClientRect();
+ ctxOpen(target, {x: box.left, y: box.bottom});
+ }
diff --git a/orchestrator/templates/page-diff.js b/orchestrator/templates/page-diff.js
index 1441202..48a5904 100644
--- a/orchestrator/templates/page-diff.js
+++ b/orchestrator/templates/page-diff.js
@@ -113,9 +113,9 @@
diffView.picked = null;
}
- function showFeedback(picked, x, y, menu) {
+ function showFeedback(picked, x, y) {
if (!diffView.float) {
- diffView.float = h("div", {class: "feedback-float", hidden: true},
+ diffView.float = h("div", {class: "feedback-float", role: "toolbar", hidden: true},
h("button", {type: "button", class: "btn small primary icon-only", ...named("Feedback", "Feedback (f): a post with the selected lines to the requesting agent"), on: {
mousedown: (event) => event.preventDefault(),
click: () => diffView.picked && feedbackSheet(diffView.picked),
@@ -123,8 +123,6 @@
document.body.append(diffView.float);
}
diffView.picked = picked;
- diffView.float.setAttribute("role", menu ? "menu" : "toolbar");
- diffView.float.firstChild.setAttribute("role", menu ? "menuitem" : "button");
diffView.float.style.left = `${Math.max(Math.min(x, window.innerWidth - 44), 4)}px`;
diffView.float.style.top = `${Math.max(Math.min(y, window.innerHeight - 44), 4)}px`;
diffView.float.hidden = false;
@@ -135,21 +133,20 @@
diffView.timer = window.setTimeout(() => {
const picked = selectionFeedback();
if (picked) {
- showFeedback(picked, picked.rect.right + 4, picked.rect.bottom + 4, false);
+ showFeedback(picked, picked.rect.right + 4, picked.rect.bottom + 4);
} else if (!diffView.float || !diffView.float.contains(document.activeElement)) {
hideFeedback();
}
}, 120);
}
- function feedbackMenu(event) {
+ /**
+ * @returns the context menu items of a [data-path] region, a diff file or a command: Feedback while lines of one are
+ * selected.
+ */
+ function feedbackItems() {
const picked = selectionFeedback();
- if (!picked || !(event.target instanceof Element) || !event.target.closest("[data-path]")) {
- return;
- }
- event.preventDefault();
- showFeedback(picked, event.clientX, event.clientY, true);
- diffView.float.firstChild.focus();
+ return picked ? [{label: "Feedback", hint: "f: a post with the selected lines to the requesting agent", run: () => feedbackSheet(picked)}] : [];
}
function feedbackKey() {
diff --git a/orchestrator/templates/page-dom.js b/orchestrator/templates/page-dom.js
index 78112eb..178e6df 100644
--- a/orchestrator/templates/page-dom.js
+++ b/orchestrator/templates/page-dom.js
@@ -138,7 +138,7 @@
return button;
}
- const MENUS = "details.menu, details.radio-station";
+ const MENUS = "details.menu, details.radio-station, .ctx-menu";
function closeMenus(keep) {
for (const menu of document.querySelectorAll(MENUS)) {
@@ -150,6 +150,7 @@
}
}
}
+ ctxDismiss(keep);
}
function openSheet(title, body, wide) {
diff --git a/orchestrator/templates/page-palette.js b/orchestrator/templates/page-palette.js
index b916511..97d6728 100644
--- a/orchestrator/templates/page-palette.js
+++ b/orchestrator/templates/page-palette.js
@@ -1,20 +1,24 @@
+ /**
+ * @returns every command: {label, hint, run, scope, face, id}; scope is "general", a tab id of Nav.TABS, or an element
+ * kind of CTX_KINDS, which the item carries with the id of the one element it belongs to, such as an agent key.
+ */
function paletteItems() {
return [
- ...Nav.TABS.flatMap(([id, label], index) => [{label: `View: ${label}`, hint: String(index + 1), run: () => go(id, null)}, ...(Nav.SUBS[id] || []).map(([sub, name]) => ({label: `View: ${label} › ${name}`, hint: Nav.hashOf(sub, null), run: () => go(sub, null)}))]),
- ...["agents", "artifacts", "tasks"].flatMap((screen) => Nav.viewsOf(screen).map(([id, name]) => ({label: `${Nav.TABS.find(([tab]) => tab === screen)[1]}: ${name}`, hint: Nav.hashOf(screen, id), run: () => go(screen, id)}))),
- ...Object.entries(state.views).map(([id, view]) => ({label: `Stream: ${view.label}`, hint: "Category", run: () => useView(id)})),
- ...userViews.map((view) => ({label: `Stream: ${view.name}`, hint: "saved view", run: () => useSaved(view)})),
- ...agentNames().map((name) => ({label: name, hint: "Agent", face: name, run: () => openAgent(name)})),
- {label: "Radio …", hint: "Post, Call, Newsletter, Broadcast, Pan-Pan, Security, Mayday; the gear holds tones and read aloud", run: openRadio},
- ...ACTIONS.map(([id, label]) => ({label, hint: id === "clear-mayday" ? "Mayday" : "Day/Night", run: () => confirmAct(id, [])})),
- {label: "Priority …", hint: "agent order in the hierarchy", run: openAgentOrder},
- {label: "Firewall …", hint: "automatic grants", run: () => go("rules", null)},
- {label: "Settings …", hint: "Ambience, location, colors, music, notifications, internet radio", run: settingsSheet},
- {label: settings.music.on ? "Music off" : "Music on", hint: "Ambience", run: toggleMusic},
- {label: space.look ? "Leave the sky" : "Look at the sky", hint: "h", run: () => skyLook(!space.look)},
- {label: "Toggle control room", hint: "Ambience", run: toggleLeitstand},
- {label: "Enable notifications", hint: "Ambience", run: askNotify},
- {label: "Keyboard shortcuts", hint: "?", run: helpSheet},
+ ...Nav.TABS.flatMap(([id, label], index) => [{label: `View: ${label}`, hint: String(index + 1), scope: "general", run: () => go(id, null)}, ...(Nav.SUBS[id] || []).map(([sub, name]) => ({label: `View: ${label} › ${name}`, hint: Nav.hashOf(sub, null), scope: id, run: () => go(sub, null)}))]),
+ ...["agents", "artifacts", "tasks"].flatMap((screen) => Nav.viewsOf(screen).map(([id, name]) => ({label: `${Nav.TABS.find(([tab]) => tab === screen)[1]}: ${name}`, hint: Nav.hashOf(screen, id), scope: screen, run: () => go(screen, id)}))),
+ ...Object.entries(state.views).map(([id, view]) => ({label: `Stream: ${view.label}`, hint: "Category", scope: "stream", run: () => useView(id)})),
+ ...userViews.map((view) => ({label: `Stream: ${view.name}`, hint: "saved view", scope: "stream", run: () => useSaved(view)})),
+ ...agentNames().map((name) => ({label: name, hint: "Agent", face: name, scope: "agent", id: agentKey(name), run: () => openAgent(name)})),
+ {label: "Radio …", hint: "Post, Call, Newsletter, Broadcast, Pan-Pan, Security, Mayday; the gear holds tones and read aloud", scope: "general", run: openRadio},
+ ...ACTIONS.map(([id, label]) => ({label, hint: id === "clear-mayday" ? "Mayday" : "Day/Night", scope: "general", run: () => confirmAct(id, [])})),
+ {label: "Priority …", hint: "agent order in the hierarchy", scope: "agents", run: openAgentOrder},
+ {label: "Firewall …", hint: "automatic grants", scope: "stream", run: () => go("rules", null)},
+ {label: "Settings …", hint: "Ambience, location, colors, music, notifications, internet radio", scope: "general", run: settingsSheet},
+ {label: settings.music.on ? "Music off" : "Music on", hint: "Ambience", scope: "general", run: toggleMusic},
+ {label: space.look ? "Leave the sky" : "Look at the sky", hint: "h", scope: "general", run: () => skyLook(!space.look)},
+ {label: "Toggle control room", hint: "Ambience", scope: "general", run: toggleLeitstand},
+ {label: "Enable notifications", hint: "Ambience", scope: "general", run: askNotify},
+ {label: "Keyboard shortcuts", hint: "?", scope: "general", run: helpSheet},
];
}
diff --git a/orchestrator/templates/style-ui.css b/orchestrator/templates/style-ui.css
index 9b0d185..3bfd1a7 100644
--- a/orchestrator/templates/style-ui.css
+++ b/orchestrator/templates/style-ui.css
@@ -240,3 +240,12 @@ body.fit .spot-host { flex: none; }
.radio-spot .radio-tabs button { padding-block: 1px; }
.radio-spot .radio-logbox :is(.radio-filters .field, input[type="search"]) { padding-block: 1px; }
}
+.ctx-menu { position: fixed; z-index: 55; display: grid; gap: 2px; width: max-content; min-width: min(220px, calc(100vw - 16px)); max-width: min(360px, calc(100vw - 16px)); max-height: calc(100dvh - 16px); padding: 4px; overflow-y: auto; overscroll-behavior: contain; background: var(--glass-card); border: 1px solid var(--line-strong); border-radius: var(--radius); box-shadow: var(--shadow-lift); -webkit-backdrop-filter: var(--blur); backdrop-filter: var(--blur); }
+.ctx-menu[hidden] { display: none; }
+.ctx-group { display: grid; min-width: 0; }
+.ctx-head { padding: 4px 10px 2px; overflow: hidden; color: var(--muted); font-size: var(--fs-xs); font-weight: 650; letter-spacing: .04em; text-overflow: ellipsis; text-transform: uppercase; white-space: nowrap; }
+.ctx-rule { height: 1px; margin: 2px 6px; background: var(--line); }
+.ctx-item { display: flex; align-items: center; gap: 8px; min-width: 0; padding: 5px 10px; border: 0; border-radius: 8px; background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; }
+.ctx-item:is(:hover, :focus) { background: var(--accent-soft); color: var(--accent); outline: none; }
+.ctx-item .ctx-label { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.ctx-item .muted { flex: 0 1 auto; max-width: 45%; overflow: hidden; font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
diff --git a/tests/e2e/test_hub_context_menu_e2e.py b/tests/e2e/test_hub_context_menu_e2e.py
new file mode 100644
index 0000000..4561732
--- /dev/null
+++ b/tests/e2e/test_hub_context_menu_e2e.py
@@ -0,0 +1,201 @@
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import sys
+import unittest
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path[:0] = [str(HERE.parent), str(HERE)]
+
+import hub_e2e_kit as base
+
+OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-context-menu-shots"))
+GAP = 8
+TASK = ["element", "Task work/feature", ["Open task", "Copy task id", "Pin to Home"]]
+TASKS_TAB = ["tasks", "Tasks", ["Tasks: List", "Tasks: Board", "Tasks: RASCI", "Tasks: Gantt", "Tasks: Burndown and burnup", "Tasks: 3D"]]
+GENERAL_HEAD = [f"View: {tab}" for tab in base.TABS] + ["Radio …", "Cancel mayday", "Drain", "Suspend", "Resume", "Settings …"]
+GENERAL_TAIL = ["Look at the sky", "Toggle control room", "Enable notifications", "Keyboard shortcuts"]
+MOVES = ["Copy task id", "Pin to Home", "Copy task id", "Keyboard shortcuts", "Open task", "Keyboard shortcuts"]
+MENU = base.UNLABELLED + """
+ const shownMenu = () => document.querySelector(".ctx-menu:not([hidden])");
+ const itemLabel = (node) => (node && node.closest('[role="menuitem"]') ? text(node.closest('[role="menuitem"]').querySelector(".ctx-label")) : null);
+ const key = (word, extra) => (document.activeElement || document.body).dispatchEvent(new KeyboardEvent("keydown", {key: word, bubbles: true, cancelable: true, ...extra}));
+ const menuState = () => {
+ const menu = shownMenu();
+ if (!menu) {
+ return {open: false};
+ }
+ const box = menu.getBoundingClientRect();
+ return {
+ open: true, role: menu.getAttribute("role"), roles: [...new Set(all("button", menu).map((node) => node.getAttribute("role")))],
+ groups: all('[role="group"]', menu).map((group) => [group.dataset.scope, group.getAttribute("aria-label"), all('[role="menuitem"]', group).map(itemLabel)]),
+ box: [box.left, box.top, box.right, box.bottom].map(Math.round), focused: itemLabel(document.activeElement),
+ wide: document.documentElement.scrollWidth > innerWidth + 1, unlabelled: unlabelled(menu),
+ };
+ };
+ const rowOf = () => document.querySelector('#main li.task-row[data-task="work/feature"]');
+ const cardOf = () => document.querySelector('#main .kanban-card[data-task="work/feature"]');
+"""
+MOUSE = """(async () => {@HELPERS@@MENU@
+ await screenShown(8000);
+ const row = await until(rowOf, 10000);
+ if (!row) {
+ return {error: text(document.getElementById("main"))};
+ }
+ row.scrollIntoView({block: "center"});
+ await sleep(300);
+ const spot = row.querySelector("code.task-id");
+ const box = spot.getBoundingClientRect();
+ const at = {clientX: Math.round(box.left + box.width / 2), clientY: Math.round(box.top + box.height / 2)};
+ const prevented = !spot.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, ...at}));
+ await sleep(200);
+ return {prevented, at: [at.clientX, at.clientY], ...menuState()};
+})()"""
+STEER = """(async () => {@HELPERS@@MENU@
+ const moves = [];
+ for (const word of ["ArrowDown", "ArrowDown", "ArrowUp", "End", "Home", "ArrowUp"]) {
+ key(word);
+ moves.push(itemLabel(document.activeElement));
+ }
+ key("Escape");
+ await sleep(100);
+ const closed = !shownMenu();
+ const spot = rowOf().querySelector("code.task-id");
+ const box = spot.getBoundingClientRect();
+ const passed = spot.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, shiftKey: true, clientX: box.left + 2, clientY: box.top + 2}));
+ await sleep(100);
+ const shift = {passed, open: Boolean(shownMenu())};
+ key("k", {ctrlKey: true});
+ await sleep(200);
+ const palette = all("#palette:not([hidden]) .palette-list li").map((li) => text(li.querySelector("span")));
+ key("Escape");
+ await sleep(100);
+ return {moves, closed, shift, palette, paletteClosed: document.getElementById("palette").hidden};
+})()"""
+KEYED = """(async () => {@HELPERS@@MENU@
+ await screenShown(8000);
+ const card = await until(cardOf, 10000);
+ if (!card) {
+ return {error: text(document.getElementById("main"))};
+ }
+ card.scrollIntoView({block: "center"});
+ await sleep(300);
+ card.focus();
+ const anchor = card.getBoundingClientRect();
+ const prevented = !key("ContextMenu");
+ await sleep(200);
+ return {prevented, at: [Math.round(anchor.left), Math.round(anchor.bottom)], ...menuState()};
+})()"""
+RUN = """(async () => {@HELPERS@@MENU@
+ const first = itemLabel(document.activeElement);
+ key("Enter");
+ const sheet = await until(() => all('#sheet:not([hidden]) [role="dialog"]').find((node) => node.getAttribute("aria-label") === "work/feature"), 4000);
+ await sleep(200);
+ return {first, closed: !shownMenu(), sheet: Boolean(sheet)};
+})()"""
+SHIFT_F10 = """(async () => {@HELPERS@@MENU@
+ document.querySelector('#sheet:not([hidden]) .sheet-head button[aria-label="Close"]').click();
+ await sleep(150);
+ const card = cardOf();
+ card.focus();
+ const prevented = !key("F10", {shiftKey: true});
+ await sleep(150);
+ const opened = menuState();
+ key("?");
+ await sleep(100);
+ const help = Boolean(document.querySelector("#sheet:not([hidden])"));
+ return {prevented, element: opened.groups ? opened.groups[0] : null, closed: !shownMenu(), back: document.activeElement === cardOf(), help};
+})()"""
+
+
+def probe(template: str) -> str:
+ return template.replace("@HELPERS@", base.HELPERS).replace("@MENU@", MENU)
+
+
+@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
+class TestHubContextMenu(base.OrchestratorE2ECase):
+ def setUp(self):
+ super().setUp()
+ OUT.mkdir(parents=True, exist_ok=True)
+
+ def steps(self, browser: str) -> list[dict]:
+ local = f"http://localhost:{self.port}/"
+ steps = []
+ for width, height in base.WIDTHS:
+ shot = str(OUT / f"{browser}-{width}-context")
+ steps += [
+ {"width": width, "height": height, "url": f"{local}?{width}-mouse#tasks/list", "wait": 1500, "probe": probe(MOUSE), "shot": f"{shot}-mouse.png"},
+ {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(STEER), "shot": None},
+ {"width": width, "height": height, "url": f"{local}?{width}-keyed#tasks/board", "wait": 1500, "probe": probe(KEYED), "shot": f"{shot}-key.png"},
+ {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(RUN), "shot": f"{shot}-task-sheet.png"},
+ {"width": width, "height": height, "url": None, "wait": 0, "probe": probe(SHIFT_F10), "shot": None},
+ ]
+ return steps
+
+ def placed(self, menu: dict, at: list[int], size: tuple[int, int]) -> None:
+ """Args:
+ menu: the menuState of an open menu.
+ at: the viewport point the menu was opened at.
+ size: the viewport width and height.
+ """
+ left, top, right, bottom = menu["box"]
+ width, height = size
+ self.assertTrue(0 <= left and right <= width and 0 <= top and bottom <= height, menu["box"])
+ if at[0] + right - left <= width - GAP:
+ self.assertLessEqual(abs(left - at[0]), 1, (menu["box"], at))
+ else:
+ self.assertGreaterEqual(right, width - GAP - 1, (menu["box"], at))
+ if at[1] + bottom - top <= height - GAP:
+ self.assertLessEqual(abs(top - at[1]), 1, (menu["box"], at))
+ else:
+ self.assertTrue(bottom <= at[1] + 1 or top <= GAP + 1, (menu["box"], at))
+
+ def grouped(self, menu: dict) -> None:
+ self.assertEqual((menu["open"], menu["role"], menu["roles"], menu["unlabelled"], menu["wide"]), (True, "menu", ["menuitem"], [], False), menu)
+ self.assertEqual(menu["groups"][:2], [TASK, TASKS_TAB])
+ scope, title, general = menu["groups"][2]
+ self.assertEqual((scope, title, len(menu["groups"])), ("general", "General", 3))
+ self.assertEqual(general[: len(GENERAL_HEAD)], GENERAL_HEAD)
+ self.assertEqual(general[-len(GENERAL_TAIL) :], GENERAL_TAIL)
+ self.assertIn(general[len(GENERAL_HEAD)], ("Music on", "Music off"))
+ self.assertEqual(menu["focused"], "Open task")
+
+ def check(self, data: dict) -> None:
+ per = 5
+ for index, (width, height) in enumerate(base.WIDTHS):
+ mouse, steer, keyed, ran, shifted = data["results"][per * index : per * (index + 1)]
+ with self.subTest(width=width):
+ for result in (mouse, steer, keyed, ran, shifted):
+ self.assertNotIn("error", result, result)
+ self.assertTrue(mouse["prevented"], mouse)
+ self.grouped(mouse)
+ self.placed(mouse, mouse["at"], (width, height))
+ self.assertEqual((steer["moves"], steer["closed"]), (MOVES, True), steer)
+ self.assertEqual(steer["shift"], {"passed": True, "open": False})
+ self.assertLessEqual({"View: Home", "Tasks: List", "Stage", "Priority …", "Keyboard shortcuts"}, set(steer["palette"]), steer["palette"])
+ self.assertTrue(steer["paletteClosed"])
+ self.assertTrue(keyed["prevented"], keyed)
+ self.grouped(keyed)
+ self.placed(keyed, keyed["at"], (width, height))
+ self.assertEqual(ran, {"first": "Open task", "closed": True, "sheet": True})
+ self.assertEqual(shifted, {"prevented": True, "element": TASK, "closed": True, "back": True, "help": False})
+
+ def run_browser(self, browser: str, driver: str, binary: str) -> None:
+ data = self.drive(self.steps(browser), None, driver, binary)
+ (OUT / f"{browser}-context-menu.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
+ self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
+ self.check(data)
+
+ def test_chromium_right_click_and_menu_key_open_the_grouped_context_menu_and_run_an_item_at_three_widths(self):
+ self.run_browser("chromium", "cdp.mjs", os.environ.get("CHROMIUM", "chromium"))
+
+ @unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
+ def test_firefox_right_click_and_menu_key_open_the_grouped_context_menu_and_run_an_item_at_three_widths(self):
+ self.run_browser("firefox", "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/e2e/test_workbench_w1_e2e.py b/tests/e2e/test_workbench_w1_e2e.py
index 9a9e274..bb43fd6 100644
--- a/tests/e2e/test_workbench_w1_e2e.py
+++ b/tests/e2e/test_workbench_w1_e2e.py
@@ -105,9 +105,12 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@
const nearby = Boolean(floating && !floating.hidden);
rows[1].querySelector("td.code").dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: box.left + 4, clientY: box.top + 4}));
await sleep(200);
- const menu = floating && floating.getAttribute("role");
- const labels = {float: floating ? unlabelled(floating) : null};
- floating.querySelector("button").click();
+ const context = document.querySelector(".ctx-menu:not([hidden])");
+ const menu = context && context.getAttribute("role");
+ const labels = {float: floating ? unlabelled(floating) : null, menu: context ? unlabelled(context) : null};
+ const first = context && context.querySelector('[role="menuitem"]');
+ const item = first ? text(first.querySelector(".ctx-label")) : null;
+ first.click();
const sheet = await until(() => document.querySelector(".sheet-box textarea"), 4000);
const writing = document.querySelector("#sheet .sheet-box");
labels.sheet = writing ? unlabelled(writing) : null;
@@ -132,7 +135,7 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@
keyed.value = "key f note";
all(".sheet-box button").find((button) => name(button) === "Send feedback").click();
await sleep(1500);
- return {nearby, menu, title, range, keyRange, labels, shown: shown || "", posted: window.e2eFeedback, wide: document.documentElement.scrollWidth > window.innerWidth + 1};
+ return {nearby, menu, item, title, range, keyRange, labels, shown: shown || "", posted: window.e2eFeedback, wide: document.documentElement.scrollWidth > window.innerWidth + 1};
})()"""
@@ -183,7 +186,7 @@ class TestWorkbenchOperatorTasks(HubCase):
self.assertNotIn("error", tasks, tasks)
self.assertNotIn("error", feedback, feedback)
self.assertEqual(tasks["unlabelled"], {"main": [], "sheet": []})
- self.assertEqual(feedback["labels"], {"float": [], "sheet": []})
+ self.assertEqual(feedback["labels"], {"float": [], "menu": [], "sheet": []})
with self.subTest(browser=browser, width=width):
self.assertNotIn("error", tasks, tasks)
self.assertEqual((tasks["hash"], tasks["tabs"], tasks["subs"], tasks["streamInbox"], tasks["current"]), ("#tasks/operator", base.TABS, ["Firewall"], False, ["Tasks"]))
@@ -202,7 +205,7 @@ class TestWorkbenchOperatorTasks(HubCase):
self.assertEqual(tasks["posted"], [["/api/sign", kinds], *([["/api/inbox/approve", kinds]] if signs else [])])
self.assertFalse(tasks["wide"])
self.assertNotIn("error", feedback, feedback)
- self.assertEqual((feedback["nearby"], feedback["menu"], feedback["title"]), (True, "menu", "Feedback"))
+ self.assertEqual((feedback["nearby"], feedback["menu"], feedback["item"], feedback["title"]), (True, "menu", "Feedback", "Feedback"))
self.assertEqual((feedback["range"], feedback["keyRange"]), ("src/app.py:2-2", "/repo:1-1"))
ref = f"review:{self.reviews[(tag, 'second')]}"
texts = [text for path, text in feedback["posted"] if path == "/api/messages/sign"]
diff --git a/tests/test_hub_context_menu.py b/tests/test_hub_context_menu.py
new file mode 100644
index 0000000..0e4f810
--- /dev/null
+++ b/tests/test_hub_context_menu.py
@@ -0,0 +1,175 @@
+from __future__ import annotations
+
+import json
+import subprocess
+import unittest
+
+from hub_support import HUB
+
+TEMPLATES = HUB / "templates"
+SOURCES = ["page-constants.js", "page-diff.js", "page-palette.js", "page-context.js"]
+GENERAL = [
+ "View: Home", "View: Stream", "View: Agents", "View: Artifacts", "View: Tasks", "View: Resources", "Radio …", "Cancel mayday", "Drain", "Suspend", "Resume",
+ "Settings …", "Music on", "Look at the sky", "Toggle control room", "Enable notifications", "Keyboard shortcuts",
+]
+TASKS_TAB = ["Tasks: List", "Tasks: Board", "Tasks: RASCI", "Tasks: Gantt", "Tasks: Burndown and burnup", "Tasks: 3D"]
+AGENTS_TAB = ["Agents: Orbit", "Agents: Chord", "Agents: Swimlane", "Agents: Tree", "Agents: 3D", "Agents: Hierarchy", "Priority …"]
+TABS = ["home", "stream", "agents", "artifacts", "tasks", "resources"]
+PROBE = r"""
+const fs = require("fs");
+const vm = require("vm");
+const [dir, names] = [process.argv[1], JSON.parse(process.argv[2])];
+const Nav = require(`${dir}/nav.js`);
+const Panels = require(`${dir}/panels.js`);
+class Element {
+ constructor(tag, attrs, parent) {
+ Object.assign(this, {tagName: tag.toUpperCase(), attrs: {...attrs}, parentElement: parent || null, rect: null});
+ }
+ getAttribute(name) { return Object.hasOwn(this.attrs, name) ? this.attrs[name] : null; }
+ hasAttribute(name) { return Object.hasOwn(this.attrs, name); }
+ matches(selector) { return selector.split(",").map((part) => part.trim()).some((part) => (part.startsWith("[") ? this.hasAttribute(part.slice(1, -1)) : this.tagName === part.toUpperCase())); }
+ closest(selector) { return this.matches(selector) ? this : this.parentElement && this.parentElement.closest(selector); }
+ contains(node) { return Boolean(node) && (node === this || this.contains(node.parentElement)); }
+ getBoundingClientRect() { return this.rect; }
+}
+Panels.item("task", (id) => `Task ${id}`, () => null);
+const KEYS_OF = {Stage: "s2", Docs: "s3"};
+const NAMES = {s2: "Stage", s3: "Docs"};
+const calls = {tasks: [], pins: [], feedback: [], shown: [], closed: 0};
+const context = {
+ console, Nav, Panels, Element, JSON, Math, Object, Array, String, Number, Boolean, Promise, Map, Set, Intl,
+ document: {activeElement: null, currentScript: null}, window: {innerWidth: 1366, innerHeight: 768, matchMedia: () => ({matches: false})}, navigator: {},
+ state: {views: {"fuer-dich": {label: "For you"}}, tasks: [{task: "work/feature"}], inbox: [{kind: "review", id: "r1", title: "feat: x"}], graph: {nodes: []}},
+ ui: {screen: "tasks"}, tree: {model: null}, settings: {music: {on: false}}, space: {look: false}, userViews: [{name: "Mine"}],
+ palette: {plan: null, input: {value: ""}, index: 0, items: [], list: {replaceChildren: () => {}, children: []}},
+ h: (tag, attrs, ...children) => ({tag, attrs, children}), face: () => null, revealed: (text) => text,
+ agentNames: () => ["Docs", "Stage"], agentKey: (who) => KEYS_OF[who] || who, nameOf: (key) => NAMES[key] || key, labelOf: (key) => NAMES[key] || key, keyOf: (item) => `${item.kind}:${item.id}`,
+ go: () => {}, useView: () => {}, useSaved: () => {}, openAgent: () => {}, openRadio: () => {}, confirmAct: () => {}, openAgentOrder: () => {}, settingsSheet: () => {},
+ toggleMusic: () => {}, skyLook: () => {}, toggleLeitstand: () => {}, askNotify: () => {}, helpSheet: () => {}, micButton: () => null,
+ taskSheet: (id) => calls.tasks.push(id), artSelect: () => {}, select: () => {}, openItem: () => {}, openSheet: () => {}, glossarySections: () => [], toast: () => {},
+ homePins: () => [], homePress: (kind, id) => calls.pins.push(`${kind}:${id}`), HOME_OPENERS: {task: (id) => calls.tasks.push(`home ${id}`)},
+ closeMenus: () => { calls.closed += 1; }, calls,
+};
+const probe = `
+ctxShow = (sections, at) => calls.shown.push({at, sections: labels(sections)});
+selectionFeedback = () => null;
+feedbackSheet = (picked) => calls.feedback.push(picked.path);
+const labels = (sections) => sections.map((section) => [section.scope, section.title, section.items.map((item) => item.label)]);
+const out = {};
+const panel = new Element("div", {"data-panel": "tasks/list"});
+const card = new Element("li", {"data-task": "work/feature", "data-item": "task:work/feature"}, panel);
+const inside = new Element("span", {}, card);
+const taskSections = ctxSections(inside);
+out.task = labels(taskSections);
+taskSections[0].items.forEach((item) => item.label !== "Copy task id" && item.run());
+out.ran = {tasks: calls.tasks, pins: calls.pins};
+ui.screen = "agents";
+out.agent = labels(ctxSections(new Element("g", {"data-face": "s2", "data-pick": "s2"})));
+out.operator = labels(ctxSections(new Element("span", {"data-face": "Operator"})))[0][0];
+ui.screen = "rules";
+out.rules = labels(ctxSections(new Element("main", {})));
+ui.screen = "tasks";
+const fire = (target, extra) => {
+ let prevented = false;
+ const before = calls.shown.length;
+ ctxContextMenu({target, clientX: 12, clientY: 34, shiftKey: false, defaultPrevented: false, ...extra, preventDefault: () => { prevented = true; }});
+ const last = calls.shown.length > before ? calls.shown[calls.shown.length - 1] : null;
+ return {prevented, at: last && last.at, sections: last && last.sections};
+};
+out.mouse = {plain: fire(inside, {}), shift: fire(inside, {shiftKey: true}), handled: fire(inside, {defaultPrevented: true}), field: fire(new Element("textarea", {}, card), {})};
+out.closed = calls.closed;
+const key = (target, extra) => {
+ document.activeElement = target;
+ let prevented = false;
+ const before = calls.shown.length;
+ ctxKeydown({key: "ContextMenu", shiftKey: false, ctrlKey: false, altKey: false, metaKey: false, ...extra, preventDefault: () => { prevented = true; }});
+ const last = calls.shown.length > before ? calls.shown[calls.shown.length - 1] : null;
+ return {prevented, at: last && last.at, element: last && last.sections[0][1]};
+};
+const focused = new Element("article", {"data-task": "work/feature", tabindex: "0"});
+focused.rect = {left: 30, top: 40, right: 230, bottom: 90, width: 200, height: 50};
+out.keys = {menu: key(focused, {}), shiftF10: key(focused, {key: "F10", shiftKey: true}), f10: key(focused, {key: "F10"}), ctrl: key(focused, {ctrlKey: true}), field: key(new Element("input", {}), {})};
+ui.screen = "inbox";
+const entry = new Element("li", {"data-ref": "review:r1", "data-to": "Skills"});
+const file = new Element("section", {"data-path": "src/app.py"}, entry);
+const cell = new Element("td", {}, file);
+out.unselected = labels(ctxSections(cell))[0];
+selectionFeedback = () => ({ref: "review:r1", to: "Skills", path: "src/app.py", from: 2, until: 3, quote: "new"});
+out.selected = fire(cell, {});
+ctxSections(cell)[0].items[0].run();
+out.feedback = calls.feedback;
+out.palette = paletteItems().map((item) => [item.label, item.scope, item.id === undefined ? null : item.id]);
+drawPalette();
+out.paletteShown = palette.items.length;
+out.keysHelp = KEYS.map(([name]) => name);
+console.log(JSON.stringify(out));
+`;
+const source = names.map((name) => fs.readFileSync(`${dir}/${name}`, "utf8")).join("\n");
+vm.runInNewContext(`${source}\n${probe}`, context);
+"""
+
+
+class TestHubContextMenu(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ done = subprocess.run(["node", "-e", PROBE, str(TEMPLATES), json.dumps(SOURCES)], capture_output=True, text=True, timeout=60, check=False)
+ if done.returncode != 0:
+ raise AssertionError(done.stderr.strip()[:1200])
+ cls.data = json.loads(done.stdout)
+
+ def test_the_element_items_come_first_then_the_tab_then_the_general_ones(self):
+ self.assertEqual(self.data["task"], [
+ ["element", "Task work/feature", ["Open task", "Copy task id", "Pin to Home"]],
+ ["tasks", "Tasks", TASKS_TAB],
+ ["general", "General", GENERAL],
+ ])
+
+ def test_the_element_items_act_on_the_clicked_element(self):
+ self.assertEqual(self.data["ran"], {"tasks": ["work/feature"], "pins": ["task:work/feature"]})
+
+ def test_an_agent_scoped_palette_item_shows_only_on_its_own_agent(self):
+ self.assertEqual(self.data["agent"], [["element", "Stage", ["Stage", "Copy name"]], ["agents", "Agents", AGENTS_TAB], ["general", "General", GENERAL]])
+ self.assertEqual(self.data["operator"], "agents")
+
+ def test_a_sub_screen_takes_the_items_of_its_tab(self):
+ self.assertEqual(self.data["rules"], [["stream", "Stream", ["View: Stream › Firewall", "Stream: For you", "Stream: Mine", "Firewall …"]], ["general", "General", GENERAL]])
+
+ def test_every_palette_item_has_a_scope_and_the_palette_still_lists_them_all(self):
+ palette = self.data["palette"]
+ self.assertLessEqual({scope for _, scope, _ in palette}, {"general", "agent", *TABS})
+ self.assertEqual([[label, key] for label, scope, key in palette if scope == "agent"], [["Docs", "s3"], ["Stage", "s2"]])
+ self.assertEqual([key for _, scope, key in palette if scope != "agent"], [None] * (len(palette) - 2))
+ self.assertEqual([label for label, scope, _ in palette if scope == "general"], GENERAL)
+ self.assertEqual(self.data["paletteShown"], len(palette))
+
+ def test_a_right_click_opens_the_menu_at_the_pointer_and_shift_or_a_handled_event_or_a_text_field_keep_the_native_one(self):
+ mouse = self.data["mouse"]
+ self.assertEqual((mouse["plain"]["prevented"], mouse["plain"]["at"]), (True, {"x": 12, "y": 34}))
+ self.assertEqual(mouse["plain"]["sections"], self.data["task"])
+ for case in ("shift", "handled", "field"):
+ with self.subTest(case=case):
+ self.assertEqual(mouse[case], {"prevented": False, "at": None, "sections": None})
+ self.assertEqual(self.data["closed"], 1)
+
+ def test_the_menu_key_and_shift_f10_open_the_menu_of_the_focused_element_at_its_rect(self):
+ keys = self.data["keys"]
+ opened = {"prevented": True, "at": {"x": 30, "y": 90}, "element": "Task work/feature"}
+ self.assertEqual((keys["menu"], keys["shiftF10"]), (opened, opened))
+ for case in ("f10", "ctrl", "field"):
+ with self.subTest(case=case):
+ self.assertEqual(keys[case], {"prevented": False, "at": None, "element": None})
+
+ def test_a_selection_in_a_diff_makes_feedback_the_first_item_of_the_menu(self):
+ self.assertEqual(self.data["unselected"], ["element", "src/app.py", ["Copy path", "Open entry", "Copy id"]])
+ selected = self.data["selected"]
+ self.assertTrue(selected["prevented"])
+ self.assertEqual(selected["sections"][0], ["element", "src/app.py", ["Feedback", "Copy path", "Open entry", "Copy id"]])
+ self.assertEqual(self.data["feedback"], ["src/app.py"])
+
+ def test_the_shortcuts_sheet_names_the_context_menu_keys(self):
+ keys = self.data["keysHelp"]
+ self.assertEqual(keys[:4], ["Ctrl+K", "Right-click", "Shift+right-click", "Menu key · Shift+F10"])
+
+
+if __name__ == "__main__":
+ unittest.main()