Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): float code-block chrome above + Ask AI on the fence (#2542)

Abrahamd3fa29722b60
diff --git a/.changeset/codeblock-chrome-above-ask-ai.md b/.changeset/codeblock-chrome-above-ask-ai.md
new file mode 100644
index 000000000..7595cee2c
--- /dev/null
+++ b/.changeset/codeblock-chrome-above-ask-ai.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Code block chrome (language picker, edit source, hide preview, settings, copy, delete) now floats above the block on hover instead of overlapping the top-right corner — same visual pattern as the text-selection bubble menu, so it does not sit on top of an html preview iframe. Adds a sparkles Ask AI button next to copy that grounds the whole fence (language + meta + body) as the passage, wired through the same composer/terminal path as the text-selection Ask AI. Hidden inside an embedded agent host, same as the text-selection Ask AI.
diff --git a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
index b044c1384..6623f9fa0 100644
--- a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
+++ b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
@@ -15,6 +15,7 @@ import { act, cleanup, fireEvent, render } from '@testing-library/react';
import type { NodeViewProps } from '@tiptap/core';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
import { CodeBlockView } from './CodeBlockView';
+import { setEditorDocName } from './doc-context';
function makeConfigValue(merged: Config | null): ConfigContextValue {
return {
@@ -213,3 +214,113 @@ describe('CodeBlockView CSP-violation notice wiring', () => {
expect(container.querySelector('[role="status"]')).toBeNull();
});
});
+
+/**
+ * Pins the Ask AI click handler on the code-block chrome — specifically the
+ * hand-built triple-backtick fence around the block body. A body containing
+ * literal ``` sequences would close a 3-backtick wrapper early and the
+ * receiving agent would see truncated code + orphan closer text.
+ */
+describe('CodeBlockView Ask AI click handler', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ function makePropsWithBody(body: string, language = 'html', meta = 'preview'): NodeViewProps {
+ return {
+ editor: makeEditor(),
+ node: { attrs: { language, meta }, textContent: body },
+ getPos: () => 0,
+ selected: false,
+ updateAttributes: () => {},
+ } as unknown as NodeViewProps;
+ }
+
+ async function captureTerminalDispatch(
+ props: NodeViewProps,
+ docName: string,
+ ): Promise<string | null> {
+ setEditorDocName(props.editor, docName);
+ const received: string[] = [];
+ const handler = (e: Event) => {
+ received.push((e as CustomEvent<string>).detail);
+ };
+ window.addEventListener('open-knowledge:active-terminal-input', handler);
+ try {
+ const { container } = render(
+ <ConfigContext value={makeConfigValue(null)}>
+ <CodeBlockView {...props} />
+ </ConfigContext>,
+ );
+ const askBtn = container.querySelector(
+ '[data-testid="ok-codeblock-ask-ai-btn"]',
+ ) as HTMLButtonElement | null;
+ expect(askBtn).toBeTruthy();
+ fireEvent.click(askBtn as HTMLButtonElement);
+ // Click handler defers to rAF; give one paint tick for the dispatch.
+ await act(async () => {
+ await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
+ });
+ return received[0] ?? null;
+ } finally {
+ window.removeEventListener('open-knowledge:active-terminal-input', handler);
+ }
+ }
+
+ // Read the run of backticks that opens the passage's inner fence, keyed off
+ // the info-string sentinel that follows it. `composeSelectionPrompt` wraps
+ // OUR selectionMarkdown inside its own OUTER fence (whose length is our
+ // fence + 1), so we can't just count leading backticks in the dispatch —
+ // we have to isolate the run immediately preceding the info string.
+ function readInnerFenceLength(prompt: string, infoSentinel: string): number {
+ const idx = prompt.indexOf(infoSentinel);
+ if (idx <= 0) return 0;
+ let n = 0;
+ for (let i = idx - 1; i >= 0 && prompt[i] === '`'; i--) n++;
+ return n;
+ }
+
+ test('body without triple-backticks wraps in a 3-backtick fence', async () => {
+ const dispatched = await captureTerminalDispatch(
+ makePropsWithBody('<div id="probe">hello</div>'),
+ 'notes/example',
+ );
+ expect(dispatched).not.toBeNull();
+ const fenceLen = readInnerFenceLength(dispatched ?? '', 'html preview\n<div id=');
+ // A body without any backtick run → CommonMark minimum fence (3).
+ expect(fenceLen).toBe(3);
+ // The body's exact content survives inside the wrapper.
+ expect(dispatched).toContain('<div id="probe">hello</div>');
+ });
+
+ test('body containing ``` is wrapped in a fence long enough to outlast the inner run', async () => {
+ // Nested markdown: the fenced example inside the outer body includes a
+ // 3-backtick block. A hand-built 3-backtick wrapper would truncate here
+ // after the first inner closer and the receiving agent would see mangled
+ // markdown. The outer fence must be at least 4.
+ const body = 'Nested:\n```js\nconsole.log(1);\n```\ntrailing';
+ const dispatched = await captureTerminalDispatch(
+ makePropsWithBody(body, 'markdown', ''),
+ 'notes/example',
+ );
+ expect(dispatched).not.toBeNull();
+ const fenceLen = readInnerFenceLength(dispatched ?? '', 'markdown\nNested:');
+ expect(fenceLen).toBe(4);
+ // The inner 3-backtick example must survive verbatim (no truncation).
+ expect(dispatched).toContain('```js\nconsole.log(1);\n```');
+ expect(dispatched).toContain('\ntrailing\n');
+ });
+
+ test('body containing a 4-backtick run bumps the outer fence to 5', async () => {
+ const body = 'longer:\n````\nunusual\n````';
+ const dispatched = await captureTerminalDispatch(
+ makePropsWithBody(body, 'markdown', ''),
+ 'notes/example',
+ );
+ expect(dispatched).not.toBeNull();
+ const fenceLen = readInnerFenceLength(dispatched ?? '', 'markdown\nlonger:');
+ expect(fenceLen).toBe(5);
+ // The inner 4-backtick block survives verbatim (unusual, but round-trips).
+ expect(dispatched).toContain('````\nunusual\n````');
+ });
+});
diff --git a/packages/app/src/editor/extensions/CodeBlockView.tsx b/packages/app/src/editor/extensions/CodeBlockView.tsx
index bf36312d7..839844e53 100644
--- a/packages/app/src/editor/extensions/CodeBlockView.tsx
+++ b/packages/app/src/editor/extensions/CodeBlockView.tsx
@@ -2,18 +2,31 @@
* React NodeView for the visual-mode code block.
*
* Visual design — zero permanent chrome: the code body renders solo, with a
- * hover/selection-revealed overlay bar in the top-right carrying the
- * language picker, a copy-to-clipboard button, and a delete affordance.
- * Mirrors the JsxComponentView chrome pattern (precedent #30) so codeblocks
- * compose visually with other rich blocks.
+ * hover/selection-revealed chrome bar floating above the block edge that
+ * carries the language picker, edit-source, preview toggle, settings, Ask AI,
+ * copy, and delete affordances. Mirrors the JsxComponentView chrome pattern
+ * (precedent #30) so codeblocks compose visually with other rich blocks.
*/
+import { composeSelectionPrompt } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import type { NodeViewProps } from '@tiptap/core';
import { NodeViewContent, NodeViewWrapper } from '@tiptap/react';
-import { Check, ChevronDown, Copy, Eye, EyeOff, Pencil, Settings2, Trash2 } from 'lucide-react';
+import {
+ Check,
+ ChevronDown,
+ Copy,
+ Eye,
+ EyeOff,
+ Pencil,
+ Settings2,
+ Sparkles,
+ Trash2,
+} from 'lucide-react';
import { useTheme } from 'next-themes';
import { useEffect, useId, useRef, useState } from 'react';
+import { emitOpenAskAiComposer } from '@/components/ask-ai-composer-events';
+import { requestActiveTerminalInput } from '@/components/handoff/terminal-input-events';
import {
Command,
CommandEmpty,
@@ -24,7 +37,9 @@ import {
} from '@/components/ui/command';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { useIsEmbedded } from '@/hooks/use-is-embedded';
import { cn } from '@/lib/utils';
+import { docNameToRelativePath } from '@/lib/workspace-paths';
import { OPT_OUT_ATTR } from '../clipboard/index.ts';
import { CodePreviewEditModal } from '../components/CodePreviewEditModal';
import { PreviewBlockedNotice } from '../components/PreviewBlockedNotice';
@@ -42,6 +57,7 @@ import {
setMetaTitle,
shouldShowPreview,
} from './code-block-meta';
+import { getEditorDocName } from './doc-context';
import {
buildPreviewIframeHeader,
buildPreviewThemeMessage,
@@ -153,6 +169,18 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selected
// because "edit source" is a primary action when the preview is the
// dominant on-screen surface (HTML preview hides the code by default).
const [editOpen, setEditOpen] = useState(false);
+ // Ask AI on this code block. Chrome-hosted (not the bubble menu),
+ // because the block isn't a text selection — the whole fence is the
+ // context we want to hand to the agent. Hidden inside an embedded agent
+ // host, same as the text bubble menu's Ask AI button.
+ const isEmbedded = useIsEmbedded();
+ // Hovered state — the html preview iframe consumes 100% of the block's
+ // pointer events, so the CSS `:hover` selector never fires on the wrapper.
+ // Mirror mouseenter/mouseleave into a data attribute so the chrome-reveal
+ // rule (`.ok-codeblock[data-hovered="true"] > .ok-codeblock-chrome`) still
+ // works over the iframe. React's synthetic mouseenter/leave fire on the
+ // wrapper regardless of which descendant consumes pointer events.
+ const [hovered, setHovered] = useState(false);
// React's `useId` gives each NodeView instance its own DOM ids so a doc
// with multiple code blocks doesn't collide on `htmlFor` ↔ `id`
// association (clicking one block's title label would otherwise focus a
@@ -332,6 +360,9 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selected
data-selected={selected ? 'true' : undefined}
data-preview={previewActive ? 'true' : undefined}
data-code-visible={codeVisible ? 'true' : 'false'}
+ data-hovered={hovered ? 'true' : undefined}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
>
{previewActive ? (
// biome-ignore lint/a11y/noStaticElementInteractions: stopPropagation required so resize-handle drags don't bubble into PM
@@ -593,6 +624,54 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selected
</Popover>
) : null}
+ {isEmbedded ? null : (
+ <button
+ type="button"
+ className="ok-codeblock-chrome-btn"
+ aria-label={t`Ask AI about this code block`}
+ data-testid="ok-codeblock-ask-ai-btn"
+ onClick={() => {
+ // Ground the passage the same way the text-selection bubble
+ // menu's Ask AI does — doc named as an `@`-mention, block
+ // source inline (or a locus pointer when it is large). The
+ // fence markers are preserved so the agent can drop the
+ // edited version back in place without stripping/rewrapping.
+ const docName = getEditorDocName(editor);
+ const language = rawLanguage ?? '';
+ const infoString = rawMeta ? `${language} ${rawMeta}`.trim() : language;
+ const body = node.textContent;
+ // Fence must outlast the longest backtick run inside the body
+ // (CommonMark §4.5): a body containing ``` would close a
+ // 3-backtick wrapper early and the receiving agent would see
+ // truncated code + orphan closer text. Same guarantee
+ // `composeSelectionPrompt`'s own internal `fenceFor` gives its
+ // locus-pointer path.
+ const longestBacktickRun = (body.match(/`+/g) ?? []).reduce(
+ (m, r) => Math.max(m, r.length),
+ 0,
+ );
+ const fence = '`'.repeat(Math.max(3, longestBacktickRun + 1));
+ const selectionMarkdown = `${fence}${infoString}\n${body}\n${fence}`;
+ requestAnimationFrame(() => {
+ if (docName === null || body.trim() === '') {
+ emitOpenAskAiComposer();
+ return;
+ }
+ requestActiveTerminalInput(
+ composeSelectionPrompt({
+ relativePath: docNameToRelativePath(docName),
+ instruction: '',
+ selectionMarkdown,
+ target: 'claude-code',
+ }),
+ );
+ });
+ }}
+ >
+ <Sparkles className="size-3.5" aria-hidden="true" />
+ </button>
+ )}
+
<button
type="button"
className="ok-codeblock-chrome-btn"
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index b17e161c2..67d0d7c2a 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -1266,9 +1266,9 @@
}
/* .ok-codeblock — zero permanent chrome (precedent #30). Single rounded
- container, generous padding, no border. Hover/selection reveals the
- floating chrome bar at top-right. Dark theme inverts the surface so the
- block reads as a code surface in either color mode. */
+ container, generous padding, no border. Hover/selection reveals a chrome
+ bar floating above the block edge. Dark theme inverts the surface so
+ the block reads as a code surface in either color mode. */
.ProseMirror .ok-codeblock {
position: relative;
}
@@ -1329,17 +1329,27 @@
border-radius: 0 0 0.5rem 0.5rem;
}
-/* Hover-revealed chrome bar — language picker + copy + delete. Mirrors
- `.jsx-component-chrome` placement (top-right, opacity-toggled) so the
- editing affordance is consistent across rich block types. */
+/* Hover-revealed chrome bar hosting the language picker, edit-source,
+ preview toggle, settings, Ask AI, copy, and delete affordances. Floats
+ above the block edge (opacity-toggled) so the surface stays clean and
+ the chrome does not overlap a preview iframe's content. */
.ok-codeblock-chrome {
position: absolute;
- top: 0.5rem;
- right: 0.5rem;
+ /* Float above the block edge (same visual pattern as the text-selection
+ bubble menu) rather than inside the top-right corner, where the chrome
+ was intrusive over an html preview iframe's content. Flush with the
+ block edge (no gap) so the wrapper's mouseleave doesn't fire while the
+ user's pointer travels from the block up into the chrome buttons. */
+ bottom: 100%;
+ right: 0;
display: flex;
align-items: center;
gap: 0.125rem;
padding: 0.1875rem;
+ /* Preserve the visual gap between block and chrome via padding-bottom on
+ the chrome itself, which stays inside the hover-tracked box. Must sit
+ AFTER the `padding` shorthand or biome flags a shorthand-override. */
+ padding-bottom: calc(0.1875rem + 0.375rem);
border-radius: 0.375rem;
background: var(--popover);
border: 1px solid var(--border);
@@ -1359,6 +1369,16 @@
pointer-events: auto;
}
+/* HTML preview blocks: the iframe fills the block area with its own
+ pointer-events, so the native `:hover` selector never fires on the
+ wrapper. `CodeBlockView` mirrors hover state onto `data-hovered="true"`
+ via native mouseenter/mouseleave listeners so the chrome still reveals
+ on interaction. */
+.ProseMirror .ok-codeblock[data-hovered="true"] > .ok-codeblock-chrome {
+ opacity: 1;
+ pointer-events: auto;
+}
+
.ok-codeblock-chrome-btn {
display: inline-flex;
align-items: center;
@@ -1385,6 +1405,21 @@
color: var(--accent-foreground);
}
+/* Persistent pressed indicator for toggle buttons: preview-shown
+ (`Eye`/`EyeOff`) and settings-carrying-title (`Settings2`) both emit
+ `data-active="true"` when their underlying state is on. Mirrors the
+ sibling `.jsx-chrome-btn[data-active="true"]` treatment so the two
+ chrome surfaces read the same to a user. */
+.ok-codeblock-chrome-btn[data-active="true"] {
+ background: var(--accent);
+ color: var(--accent-foreground);
+}
+
+.ok-codeblock-chrome-btn:focus-visible {
+ outline: 2px solid var(--color-ring);
+ outline-offset: 2px;
+}
+
.ok-codeblock-chrome-btn:disabled {
cursor: default;
opacity: 0.6;
@@ -5042,6 +5077,14 @@ html.electron-mode [data-slot="sidebar-inner"] {
contain-intrinsic-size: 0 var(--ok-cv-h, 80px);
}
+/* Code-block wrapper needs an unclipped paint area — the block's chrome
+ floats above the block edge (see `.ok-codeblock-chrome`). content-visibility
+ auto's paint containment would otherwise clip the chrome to the wrapper's box,
+ hiding it entirely. */
+.ProseMirror .ok-chunk-wrapper.node-codeBlock {
+ content-visibility: visible;
+}
+
/* Neutralize Electron `-webkit-app-region: drag` regions while a Popper-based
floater (Popover / DropdownMenu / ContextMenu) is open so outside-click
dismissal works on the macOS title-bar zone.
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 5ddd785b2..935d65f43 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -33,6 +33,7 @@
"-zA2E7": ["Couldn't create the worktree. Try a different name."],
"-zy2Nq": ["Type"],
"0-31GV": ["Removing"],
+ "00c7t0": ["Ask AI about this code block"],
"02P3hL": ["Upload failed: ", ["message"]],
"04RA0-": ["Failed to enable sync — ", ["detail"]],
"04XyCH": ["Adds a managed block to ", ["0"]],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 8163f96ec..3c673c919 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -892,6 +892,10 @@ msgstr "Ask AI"
msgid "Ask AI (from selection)"
msgstr "Ask AI (from selection)"
+#: src/editor/extensions/CodeBlockView.tsx
+msgid "Ask AI about this code block"
+msgstr "Ask AI about this code block"
+
#: src/editor/extensions/WikiLinkPropPanel.tsx
#: src/editor/link-path-suggestions.tsx
msgid "Asset"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index e545a2a79..7d861fdee 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -33,6 +33,7 @@
"-zA2E7": ["Ćōũĺďń'ţ ćŕēàţē ţĥē ŵōŕķţŕēē. Ţŕŷ à ďĩƒƒēŕēńţ ńàḿē."],
"-zy2Nq": ["Ţŷƥē"],
"0-31GV": ["Ŕēḿōvĩńĝ"],
+ "00c7t0": ["Àśķ ÀĨ àƀōũţ ţĥĩś ćōďē ƀĺōćķ"],
"02P3hL": ["Ũƥĺōàď ƒàĩĺēď: ", ["message"]],
"04RA0-": ["Ƒàĩĺēď ţō ēńàƀĺē śŷńć — ", ["detail"]],
"04XyCH": ["Àďďś à ḿàńàĝēď ƀĺōćķ ţō ", ["0"]],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 5f5693e43..14fd423b0 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -887,6 +887,10 @@ msgstr ""
msgid "Ask AI (from selection)"
msgstr ""
+#: src/editor/extensions/CodeBlockView.tsx
+msgid "Ask AI about this code block"
+msgstr ""
+
#: src/editor/extensions/WikiLinkPropPanel.tsx
#: src/editor/link-path-suggestions.tsx
msgid "Asset"