Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): code-block Ask AI passes the block as passage on composer fallback (#2613)
Abraham082e43ba38cc
diff --git a/.changeset/codeblock-ask-ai-composer-fallback.md b/.changeset/codeblock-ask-ai-composer-fallback.mdnew file mode 100644index 000000000..b164ae4f8--- /dev/null+++ b/.changeset/codeblock-ask-ai-composer-fallback.md@@ -0,0 +1,8 @@+---+'@inkeep/open-knowledge': patch+---++**Fix:** the code-block chrome's Ask AI now grounds the composer with the+selected block's fenced source on first click, matching the second-click and+text-selection Ask AI paths. Previously, when no terminal was live, the+composer opened with an empty pill and the receiving agent got no passage.diff --git a/packages/app/src/components/TerminalSessionsHost.tsx b/packages/app/src/components/TerminalSessionsHost.tsxindex fdf6a6ff2..85a6733a7 100644--- a/packages/app/src/components/TerminalSessionsHost.tsx+++ b/packages/app/src/components/TerminalSessionsHost.tsx@@ -12,9 +12,9 @@ import {} from '@/lib/terminal-new-tab-store';import { loadStickyAgent, saveStickyAgent, terminalCliId } from '@/lib/unified-agent-store';import { cn } from '@/lib/utils';-import { emitOpenAskAiComposer } from './ask-ai-composer-events';import type { TerminalLaunchIntent } from './EditorPane';import { subscribeToActiveTerminalInput } from './handoff/terminal-input-events';+import { requestTerminalLaunch } from './handoff/terminal-launch-events';import { TerminalGate } from './TerminalGate';import type { TerminalNewTabChoice } from './TerminalNewChatButton';import { TerminalTabStrip } from './TerminalTabStrip';@@ -543,12 +543,12 @@ export function TerminalSessionsHost({};}, [bridge]);- // The editor's "Ask AI" selection affordance routes here: when a terminal is- // open with a live PTY, write the selected text straight into the active shell- // (e.g. a running claude TUI). No trailing newline — the user reviews/sends it.- // With no terminal open, fall back to the bottom Ask-AI composer, the same- // surface a caret-only Ask AI opens. The host is mounted whenever the desktop- // bridge exists (even with zero sessions), so this subscription is always live.+ // The editor's "Ask AI" selection affordance routes here. Live PTY → write+ // the composed prompt into the active shell (e.g. a running claude TUI); no+ // trailing newline so the user reviews/sends. No PTY → launch a fresh Claude+ // tab pre-loaded with the same prompt (mirrors the "Open in terminal" path+ // used by menu surfaces). The host is mounted whenever the desktop bridge+ // exists (even with zero sessions), so this subscription is always live.useEffect(() => {return subscribeToActiveTerminalInput((text) => {const activeId = activeSessionIdRef.current;@@ -557,7 +557,7 @@ export function TerminalSessionsHost({bridge.terminal.input(livePtyId, text);queueMicrotask(() => focusTerminalSession(activeId));} else {- emitOpenAskAiComposer();+ requestTerminalLaunch(text, 'claude');}});}, [bridge]);diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsxindex e70e88b29..ff2b22135 100644--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx+++ b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx@@ -1,15 +1,15 @@/**- * "Ask AI" button for the WYSIWYG bubble menu. When a terminal is already open,- * it sends the selected passage into the active shell (e.g. a running `claude`- * TUI) via `requestActiveTerminalInput` — the host owns the PTY state and falls- * back to the composer when no terminal is open. The passage is not pasted raw:- * it rides as the same grounded selection prompt the bottom "Ask AI" composer- * builds (`composeSelectionPrompt`) — the doc named as an `@`-mention plus the- * passage inline (or a locus "read via OK MCP" pointer when it is large) — so- * the running agent can place the passage in its doc instead of receiving an- * unattributed blob. With no selection to send it opens and focuses the docked- * bottom "Ask AI" composer, the same path the ⌘L shortcut runs; the composer- * pins the live selection as a removable context pill.+ * "Ask AI" button for the WYSIWYG bubble menu. Sends the selected passage into+ * the active shell (e.g. a running `claude` TUI) via+ * `requestActiveTerminalInput` — the host owns PTY state and launches a fresh+ * Claude tab when none is open, either way pre-loaded with the same grounded+ * selection prompt (`composeSelectionPrompt` builds it: doc named as an+ * `@`-mention plus the passage inline, or a locus "read via OK MCP" pointer+ * when it is large) — so the running agent can place the passage in its doc+ * instead of receiving an unattributed blob. With no selection to send+ * (caret-only or no active doc) it opens the docked "Ask AI" composer, the+ * same path the ⌘L shortcut runs; the composer pins the live selection as a+ * removable context pill.** Mounted only in the bubble menu's text branch: image / file node selections* swap the whole bar to a separate control tree, and selection handoff does@@ -104,18 +104,19 @@ function EditWithAiBubbleMenu({size="sm"data-testid="edit-with-ai-bubble-button"className="gap-1 px-2 text-sm font-medium text-accent-foreground/80"- // With a terminal open, send the selected passage into the active shell- // (the host decides reuse vs. composer-fallback) as a GROUNDED prompt- // (see `composeTerminalSelectionPaste`). Caret-only / empty selection- // (or no active doc to ground against) has nothing to send, so open the+ // Send the selected passage into the active shell (host reuses a live+ // PTY or launches a fresh Claude tab) as a GROUNDED prompt (see+ // `composeTerminalSelectionPaste`). Caret-only / empty selection (or+ // no active doc to ground against) has nothing to send, so open the// composer.//- // Deferred a frame: the composer-fallback focus (and a terminal focus)- // fires synchronously inside this click, before ProseMirror's own focus- // handling on the trailing mouseup, which would steal the caret back to- // the doc and leave the composer unfocused. Reading the selection first- // keeps the passage from the click moment even though the write runs- // later. Mirrors LinkEditPopover's rAF focus.+ // Deferred a frame: the composer focus (empty-selection branch) and+ // the terminal focus fire synchronously inside this click, before+ // ProseMirror's own focus handling on the trailing mouseup, which+ // would steal the caret back to the doc and leave the composer+ // unfocused. Reading the selection first keeps the passage from the+ // click moment even though the write runs later. Mirrors+ // LinkEditPopover's rAF focus.onClick={() => {const docName = getEditorDocName(editor);const selectionMarkdown = serializeWysiwygSelection(editor);diff --git a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsxindex 6623f9fa0..dc46154c7 100644--- a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx+++ b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx@@ -9,14 +9,24 @@* `srcdoc`.*/-import { afterEach, describe, expect, test } from 'bun:test';+import { afterEach, describe, expect, mock, test } from 'bun:test';import type { Config } from '@inkeep/open-knowledge-core';-import { act, cleanup, fireEvent, render } from '@testing-library/react';+import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';import type { NodeViewProps } from '@tiptap/core';+import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-events';+import { subscribeToActiveTerminalInput } from '@/components/handoff/terminal-input-events';import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';import { CodeBlockView } from './CodeBlockView';import { setEditorDocName } from './doc-context';+// The Ask AI click handler routes through `serializeWysiwygSelection`, which+// runs the full markdown pipeline against the selected slice. Testing that+// pipeline end-to-end is the fidelity suite's job; this file tests the+// click→dispatch contract, so stub the serializer to a fixed fenced body.+mock.module('../edit-with-ai-selection', () => ({+ serializeWysiwygSelection: () => '```json\n{ "name": "sample" }\n```',+}));+function makeConfigValue(merged: Config | null): ConfigContextValue {return {userBinding: null,@@ -216,111 +226,188 @@ describe('CodeBlockView CSP-violation notice wiring', () => {});/**- * 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.+ * Pins the click→dispatch contract for the code-block chrome's Ask AI button.+ * The button drives the block through `setNodeSelection` → serialize →+ * `composeSelectionPrompt` → `requestActiveTerminalInput`; `TerminalSessionsHost`+ * either pastes into a live PTY or launches a fresh Claude tab. This file+ * exercises the button's own decisions (guarded position lookup, doc-grounded+ * dispatch, composer fallback for the empty / no-doc branches); the serializer+ * is stubbed above and the pipeline is covered by the fidelity suite.*/-describe('CodeBlockView Ask AI click handler', () => {+describe('CodeBlockView Ask AI dispatch', () => {+ // rAF is used to defer the dispatch a frame; polyfill for jsdom under bun.+ if (typeof globalThis.requestAnimationFrame === 'undefined') {+ globalThis.requestAnimationFrame = ((cb: FrameRequestCallback) => {+ queueMicrotask(() => cb(0));+ return 0;+ }) as typeof globalThis.requestAnimationFrame;+ }++ let terminalInputs: string[] = [];+ let composerOpens = 0;+ let unsubscribeTerminal: (() => void) | null = null;+ let unsubscribeComposer: (() => void) | null = null;+afterEach(() => {+ unsubscribeTerminal?.();+ unsubscribeTerminal = null;+ unsubscribeComposer?.();+ unsubscribeComposer = null;+ terminalInputs = [];+ composerOpens = 0;cleanup();});- function makePropsWithBody(body: string, language = 'html', meta = 'preview'): NodeViewProps {+ function subscribeAll() {+ unsubscribeTerminal = subscribeToActiveTerminalInput((text) => {+ terminalInputs.push(text);+ });+ unsubscribeComposer = subscribeToOpenAskAiComposer(() => {+ composerOpens += 1;+ });+ }++ interface EditorMockOverrides {+ setNodeSelectionThrows?: 'range' | 'other';+ }++ // Fake editor shaped enough for the click handler: `.commands.setNodeSelection`+ // is a spy that either records the pos or throws, and `state.selection.empty`+ // reads false (my code doesn't check it, but leaving a NodeSelection-ish+ // shape here matches production). `serializeWysiwygSelection` is stubbed at+ // module load so it never touches `state` directly.+ function makeEditorWithCommands(overrides: EditorMockOverrides = {}) {+ const setNodeSelection = (_pos: number) => {+ if (overrides.setNodeSelectionThrows === 'range') {+ throw new RangeError('Position 5 out of range');+ }+ if (overrides.setNodeSelectionThrows === 'other') {+ throw new Error('unrelated failure');+ }+ };+ return {+ isEditable: true,+ isDestroyed: false,+ commands: { setNodeSelection },+ state: {+ doc: { nodeAt: () => ({ nodeSize: 10 }) },+ selection: { from: 0, to: 0, empty: false },+ },+ on: () => {},+ off: () => {},+ } as unknown as NodeViewProps['editor'];+ }++ function makeAskAiProps(overrides: EditorMockOverrides = {}, pos: number | undefined = 5) {return {- editor: makeEditor(),- node: { attrs: { language, meta }, textContent: body },- getPos: () => 0,+ editor: makeEditorWithCommands(overrides),+ node: {+ attrs: { language: 'json', meta: null },+ textContent: '{ "name": "sample" }',+ },+ getPos: pos === undefined ? undefined : () => pos,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);+ function renderAskAi(props: NodeViewProps) {+ return render(+ <ConfigContext value={makeConfigValue(null)}>+ <CodeBlockView {...props} />+ </ConfigContext>,+ );+ }++ test('click with a grounded doc dispatches a composed prompt to the terminal input channel', async () => {+ subscribeAll();+ const props = makeAskAiProps();+ setEditorDocName(props.editor, 'specs/foo/SPEC');+ const { container } = renderAskAi(props);++ const askBtn = container.querySelector(+ '[data-testid="ok-codeblock-ask-ai-btn"]',+ ) as HTMLButtonElement | null;+ expect(askBtn).toBeTruthy();+ fireEvent.click(askBtn as HTMLButtonElement);++ await waitFor(() => expect(terminalInputs).toHaveLength(1));+ const [prompt] = terminalInputs;+ // Doc named as an @-mention (grounding contract from composeSelectionPrompt).+ expect(prompt).toContain('@specs/foo/SPEC.md');+ // Stubbed fenced body survives verbatim into the composed prompt.+ expect(prompt).toContain('```json');+ expect(prompt).toContain('{ "name": "sample" }');+ // Terminal-input branch does NOT open the composer.+ expect(composerOpens).toBe(0);+ });++ test('click with no registered doc name opens the composer instead of dispatching', async () => {+ subscribeAll();+ const props = makeAskAiProps();+ // No setEditorDocName — getEditorDocName returns null.+ renderAskAi(props);+ const askBtn = document.querySelector(+ '[data-testid="ok-codeblock-ask-ai-btn"]',+ ) as HTMLButtonElement | null;+ expect(askBtn).toBeTruthy();+ fireEvent.click(askBtn as HTMLButtonElement);++ await waitFor(() => expect(composerOpens).toBe(1));+ expect(terminalInputs).toEqual([]);+ });++ test('click with a stale position (setNodeSelection throws RangeError) neither crashes nor dispatches', async () => {+ subscribeAll();+ const props = makeAskAiProps({ setNodeSelectionThrows: 'range' });+ setEditorDocName(props.editor, 'specs/foo/SPEC');+ // Silence the classified warn so the test log stays clean; the classification+ // itself is what we're asserting via the no-dispatch + no-throw combo.+ const originalWarn = console.warn;+ console.warn = () => {};try {- const { container } = render(- <ConfigContext value={makeConfigValue(null)}>- <CodeBlockView {...props} />- </ConfigContext>,- );- const askBtn = container.querySelector(+ renderAskAi(props);+ const askBtn = document.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;+ expect(() => fireEvent.click(askBtn as HTMLButtonElement)).not.toThrow();+ // Give any deferred rAF a chance to fire before asserting nothing landed.+ await new Promise((resolve) => queueMicrotask(() => resolve(null)));+ expect(terminalInputs).toEqual([]);+ expect(composerOpens).toBe(0);} finally {- window.removeEventListener('open-knowledge:active-terminal-input', handler);+ console.warn = originalWarn;}- }-- // 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('a non-RangeError from setNodeSelection is re-thrown (guard does not swallow real bugs)', async () => {+ subscribeAll();+ const props = makeAskAiProps({ setNodeSelectionThrows: 'other' });+ setEditorDocName(props.editor, 'specs/foo/SPEC');+ renderAskAi(props);+ const askBtn = document.querySelector(+ '[data-testid="ok-codeblock-ask-ai-btn"]',+ ) as HTMLButtonElement | null;+ expect(askBtn).toBeTruthy();+ // React attaches synthetic handlers; a throw from the handler bubbles+ // through fireEvent as a plain Error. Assert on the message so the guard+ // is proven to only class-catch RangeError, not shallow every throw.+ expect(() => fireEvent.click(askBtn as HTMLButtonElement)).toThrow(/unrelated failure/);});- 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````');+ test('click with getPos absent (unrenderable NodeView) is a no-op', async () => {+ subscribeAll();+ const props = makeAskAiProps({}, /* pos */ undefined);+ setEditorDocName(props.editor, 'specs/foo/SPEC');+ renderAskAi(props);+ const askBtn = document.querySelector(+ '[data-testid="ok-codeblock-ask-ai-btn"]',+ ) as HTMLButtonElement | null;+ expect(askBtn).toBeTruthy();+ expect(() => fireEvent.click(askBtn as HTMLButtonElement)).not.toThrow();+ await new Promise((resolve) => queueMicrotask(() => resolve(null)));+ expect(terminalInputs).toEqual([]);+ expect(composerOpens).toBe(0);});});diff --git a/packages/app/src/editor/extensions/CodeBlockView.tsx b/packages/app/src/editor/extensions/CodeBlockView.tsxindex 839844e53..63f2b7a8c 100644--- a/packages/app/src/editor/extensions/CodeBlockView.tsx+++ b/packages/app/src/editor/extensions/CodeBlockView.tsx@@ -44,6 +44,7 @@ import { OPT_OUT_ATTR } from '../clipboard/index.ts';import { CodePreviewEditModal } from '../components/CodePreviewEditModal';import { PreviewBlockedNotice } from '../components/PreviewBlockedNotice';import { ResizeHandles } from '../components/ResizeHandles.tsx';+import { serializeWysiwygSelection } from '../edit-with-ai-selection';import { CODE_BLOCK_LANGUAGES, normalizeCodeLanguage } from './code-block-languages';import {addMetaToken,@@ -631,29 +632,31 @@ export function CodeBlockView({ node, updateAttributes, editor, getPos, selectedaria-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.+ // Make this code block the WYSIWYG selection so+ // `serializeWysiwygSelection` emits the canonical fenced form+ // (the code-block-fidelity extension's `fenceLength` outlasts+ // any inner backtick run). `composeSelectionPrompt` then+ // decides inline vs locus against the encoded-URL budget; the+ // dispatch routes through `TerminalSessionsHost` which pastes+ // to a live PTY or launches a fresh Claude tab.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}`;+ const pos = typeof getPos === 'function' ? getPos() : undefined;+ if (typeof pos !== 'number') return;+ try {+ editor.commands.setNodeSelection(pos);+ } catch (err) {+ // Mirrors `handleDelete`'s classification — concurrent remote+ // edits or Observer B re-parse can shift `pos` between+ // getPos() and setNodeSelection, producing a RangeError. The+ // block has moved or vanished, so there is nothing to Ask AI+ // about; keep the error off the boundary for benign races.+ if (!(err instanceof RangeError)) throw err;+ console.warn('[CodeBlockView] Ask AI failed — position race', err);+ return;+ }+ const selectionMarkdown = serializeWysiwygSelection(editor);requestAnimationFrame(() => {- if (docName === null || body.trim() === '') {+ if (docName === null || !selectionMarkdown.trim()) {emitOpenAskAiComposer();return;}