Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Fix sidebar create-rename editor editability in packaged builds (#1840)
Dimitri POSTOLOV982455dd058b
diff --git a/.changeset/sidebar-rename-editable.md b/.changeset/sidebar-rename-editable.mdnew file mode 100644index 000000000..4fd9fc945--- /dev/null+++ b/.changeset/sidebar-rename-editable.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Keep the desktop editor editable after creating and inline-renaming successive sidebar files in packaged builds. The editor now repairs a stale TipTap `EditorContent` portal attachment after rename churn and avoids clearing the freshly reopened destination provider during active renames.diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsxindex fff5b5081..e54410dec 100644--- a/packages/app/src/components/FileTree.tsx+++ b/packages/app/src/components/FileTree.tsx@@ -151,6 +151,7 @@ import {} from '@/components/ui/dropdown-menu';import { Skeleton } from '@/components/ui/skeleton';import { asDirectoryHandle, useSelectionMirror } from '@/components/use-selection-mirror';+import { getEditorForDoc } from '@/editor/active-editor';import { useDocumentContext } from '@/editor/DocumentContext';import { captureRenameSnapshots } from '@/editor/editor-cache';import { assetTabId, docTabId, folderTabId, remapPathForFolderRenames } from '@/editor/editor-tabs';@@ -204,6 +205,16 @@ function markdownTreeExtension(path: string): string | null {return match ? match[0] : null;}+function focusEditorAfterRename(docName: string): void {+ window.requestAnimationFrame(() => {+ const editor = getEditorForDoc(docName);+ if (!editor || editor.isDestroyed) return;+ try {+ editor.commands.focus();+ } catch {}+ });+}+async function copyToClipboard(text: string, kind: 'full' | 'relative'): Promise<void> {try {await navigator.clipboard.writeText(text);@@ -1903,7 +1914,8 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {) {navigateToFolderWithPulse(nextActiveFolderPath);} else if (nextActiveDocName && nextActiveDocName !== currentActiveDocName) {- window.location.hash = hashFromDocName(nextActiveDocName);+ navigateToWithPulse(nextActiveDocName);+ focusEditorAfterRename(nextActiveDocName);} else if (currentActiveAssetPath &&nextActiveAssetPath &&diff --git a/packages/app/src/components/file-tree-operations.test.ts b/packages/app/src/components/file-tree-operations.test.tsindex e806a5717..71810caff 100644--- a/packages/app/src/components/file-tree-operations.test.ts+++ b/packages/app/src/components/file-tree-operations.test.ts@@ -251,10 +251,10 @@ describe('file-tree-operations', () => {).toBe('README');});- describe('planRenameCleanupCalls — symptom 1+3 race gate', () => {+ describe('planRenameCleanupCalls', () => {const poolHasAll = () => true;- test('pool active === toDocName → skip the destructive `to` clear', () => {+ test('skips destination cleanup when redirect already reopened it', () => {expect(planRenameCleanupCalls([{ fromDocName: 'docs/notes', toDocName: 'docs/renamed' }],@@ -264,7 +264,7 @@ describe('file-tree-operations', () => {).toEqual(['docs/notes']);});- test('pool active === fromDocName (server-push not yet run) → clear BOTH ends', () => {+ test('clears both ends when redirect has not run yet', () => {expect(planRenameCleanupCalls([{ fromDocName: 'docs/notes', toDocName: 'docs/renamed' }],@@ -274,7 +274,7 @@ describe('file-tree-operations', () => {).toEqual(['docs/notes', 'docs/renamed']);});- test('pool active is unrelated (renamed doc was never active) → clear BOTH ends', () => {+ test('clears both ends when the active doc is unrelated', () => {expect(planRenameCleanupCalls([{ fromDocName: 'docs/notes', toDocName: 'docs/renamed' }],@@ -284,7 +284,7 @@ describe('file-tree-operations', () => {).toEqual(['docs/notes', 'docs/renamed']);});- test('pool active is null (collabUrl unresolved) → clear BOTH ends', () => {+ test('clears both ends when active doc is unknown', () => {expect(planRenameCleanupCalls([{ fromDocName: 'docs/notes', toDocName: 'docs/renamed' }],@@ -294,7 +294,7 @@ describe('file-tree-operations', () => {).toEqual(['docs/notes', 'docs/renamed']);});- test('multi-rename batch — gate is per-entry', () => {+ test('applies redirect guard per rename entry', () => {expect(planRenameCleanupCalls([@@ -313,7 +313,7 @@ describe('file-tree-operations', () => {expect(planRenameCleanupCalls([], 'anything', poolHasAll)).toEqual([]);});- test('pool has no entry for toDocName (never-opened) → skip toDocName cleanup', () => {+ test('skips destination cleanup when the pool never opened it', () => {expect(planRenameCleanupCalls([{ fromDocName: 'Untitled', toDocName: 'dhx' }],@@ -323,7 +323,7 @@ describe('file-tree-operations', () => {).toEqual(['Untitled']);});- test('bulk rename — per-entry poolHas decision', () => {+ test('applies pool presence guard per rename entry', () => {const poolHas = (docName: string) => docName === 'archive/a' || docName === 'archive/c';expect(planRenameCleanupCalls(diff --git a/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx b/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsxindex 24520ddf0..8be79dfa8 100644--- a/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx+++ b/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx@@ -271,7 +271,7 @@ mock.module('@/editor/DocumentContext', () => ({}));mock.module('@/components/PageListContext', () => ({- usePageList: () => ({ addPage: addPageMock }),+ usePageList: () => ({ addPage: addPageMock, pageMeta: new Map() }),}));mock.module('./ui/sidebar', () => ({diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsxindex 4b05acf01..4fef8b03b 100644--- a/packages/app/src/editor/TiptapEditor.tsx+++ b/packages/app/src/editor/TiptapEditor.tsx@@ -103,6 +103,37 @@ interface TiptapEditorProps {type ClipboardState = ReturnType<typeof buildClipboardState>;+type EditorContentBindingState = Editor & {+ contentComponent: unknown | null;+ isEditorContentInitialized: boolean;+};++function hasEditorContentBindingState(editor: Editor): editor is EditorContentBindingState {+ return 'contentComponent' in editor && 'isEditorContentInitialized' in editor;+}++function repairDetachedEditorContent(editor: Editor, portalTarget: HTMLElement): boolean {+ const view = getEditorView(editor);+ if (!view || portalTarget.contains(view.dom)) return false;++ if (!hasEditorContentBindingState(editor)) {+ console.warn(+ '[TiptapEditor] TipTap EditorContent binding fields missing; detached editor repair skipped',+ );+ return false;+ }++ const editorWithContent = editor;+ if (editorWithContent.contentComponent == null) return false;++ try {+ view.setProps({ nodeViews: {} });+ } catch {}+ editorWithContent.contentComponent = null;+ editorWithContent.isEditorContentInitialized = false;+ return true;+}+type ProsemirrorMapping = ReturnType<typeof initProseMirrorDoc>['mapping'];function buildClipboardState() {@@ -382,6 +413,7 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({portalTarget,}) => {const portalSlotRef = useRef<HTMLDivElement | null>(null);+ const [editorContentRevision, setEditorContentRevision] = useState(0);useLayoutEffect(() => {const slot = portalSlotRef.current;if (!slot) return;@@ -392,6 +424,12 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({}};}, [portalTarget]);++ useEffect(() => {+ if (repairDetachedEditorContent(editor, portalTarget)) {+ setEditorContentRevision((revision) => revision + 1);+ }+ }, [editor, portalTarget]);useEffect(() => {const docName = provider.configuration.name ?? null;setEditorDocName(editor, docName);@@ -859,7 +897,11 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({<div ref={portalSlotRef} style={{ display: 'contents' }} />{createPortal(// biome-ignore lint/plugin/no-unportaled-editor-content: canonical portaled site — H6 fix per PRECEDENTS.md #44- <EditorContent editor={editor} className="tiptap-editor-portal-content h-full" />,+ <EditorContent+ key={editorContentRevision}+ editor={editor}+ className="tiptap-editor-portal-content h-full"+ />,portalTarget,)}{/* Aria-live announcer for selection changes. Always in the DOMdiff --git a/packages/app/src/editor/provider-pool.ts b/packages/app/src/editor/provider-pool.tsindex ac67a7607..217ada58c 100644--- a/packages/app/src/editor/provider-pool.ts+++ b/packages/app/src/editor/provider-pool.ts@@ -84,6 +84,12 @@ interface TearingDownPoolEntry extends PoolEntryBase {type PoolEntry = ActivePoolEntry | TearingDownPoolEntry;+type RenameRedirectHandler = (args: {+ fromDocName: string;+ toDocName: string;+ hadOpenProvider: boolean;+}) => void;+type ObserverCounterMap = { providerObserverFires: Record<string, number> };const counterGlobal = globalThis as unknown as { __okPerfCounters?: ObserverCounterMap };@@ -753,16 +759,10 @@ export class ProviderPool {};}- private onRenameRedirect:- | ((args: { fromDocName: string; toDocName: string; hadOpenProvider: boolean }) => void)- | null = null;+ private onRenameRedirect: RenameRedirectHandler | null = null;private onDocDeleted: ((args: { docName: string; hadOpenProvider: boolean }) => void) | null =null;- setOnRenameRedirect(- cb:- | ((args: { fromDocName: string; toDocName: string; hadOpenProvider: boolean }) => void)- | null,- ): void {+ setOnRenameRedirect(cb: RenameRedirectHandler | null): void {this.onRenameRedirect = cb;}setOnDocDeleted(@@ -1026,7 +1026,11 @@ export class ProviderPool {this.deleteLineageEpochRecord(fromDocName);const existing = this.entries.get(fromDocName);const hadOpenProvider = existing !== undefined && existing.kind === 'active';- this.onRenameRedirect?.({ fromDocName, toDocName, hadOpenProvider });+ this.onRenameRedirect?.({+ fromDocName,+ toDocName,+ hadOpenProvider,+ });return;}if (typed === 'doc-deleted') {diff --git a/packages/desktop/tests/smoke/sidebar-create-rename-editable.e2e.ts b/packages/desktop/tests/smoke/sidebar-create-rename-editable.e2e.tsnew file mode 100644index 000000000..aecf794b6--- /dev/null+++ b/packages/desktop/tests/smoke/sidebar-create-rename-editable.e2e.ts@@ -0,0 +1,170 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import type { ElectronApplication, Page } from '@playwright/test';+import { _electron as electron } from '@playwright/test';+import { expect, test } from './_helpers/smoke-test';++const __dirname = dirname(fileURLToPath(import.meta.url));+const PACKAGED_EXECUTABLE = resolve(+ __dirname,+ '..',+ '..',+ 'dist-desktop',+ 'mac-arm64',+ 'Open Knowledge.app',+ 'Contents',+ 'MacOS',+ 'Open Knowledge',+);++const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';+const DARWIN = process.platform === 'darwin';+const PACKAGED_BUILD_EXISTS = existsSync(PACKAGED_EXECUTABLE);++interface SeededProject {+ tmpHome: string;+ userDataDir: string;+ projectDir: string;+}++function userDataDirFor(home: string): string {+ return join(home, 'electron-userdata');+}++function seedProject(prefix: string): SeededProject {+ const tmpHome = mkdtempSync(join(tmpdir(), `ok-sidebar-create-${prefix}-home-`));+ const projectDir = mkdtempSync(join(tmpdir(), `ok-sidebar-create-${prefix}-project-`));+ mkdirSync(join(projectDir, '.ok'), { recursive: true });+ writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");+ writeFileSync(join(projectDir, 'start.md'), '# Start\n\nSeed document.\n');++ const userDataDir = userDataDirFor(tmpHome);+ mkdirSync(userDataDir, { recursive: true });+ writeFileSync(+ join(userDataDir, 'state.json'),+ JSON.stringify({+ recentProjects: [+ {+ path: projectDir,+ name: 'Sidebar Create Smoke',+ lastOpenedAt: new Date().toISOString(),+ },+ ],+ lastOpenedProject: projectDir,+ versionPendingInstall: null,+ lastSeenVersion: null,+ lastSuccessfulCheckAt: null,+ stuckHintShown: false,+ }),+ );++ return { tmpHome, userDataDir, projectDir };+}++async function launchApp(seed: SeededProject): Promise<ElectronApplication> {+ const deepLink = `openknowledge://open?project=${encodeURIComponent(seed.projectDir)}&doc=start`;+ const args = [`--user-data-dir=${seed.userDataDir}`, deepLink];+ return electron.launch({+ executablePath: PACKAGED_EXECUTABLE,+ args,+ timeout: 30_000,+ env: {+ ...process.env,+ HOME: seed.tmpHome,+ OK_DESKTOP_E2E_SMOKE: '1',+ OK_RECLAIM_DISABLE: '1',+ NODE_ENV: 'production',+ },+ });+}++async function findEditorWindow(app: ElectronApplication, docName: string): Promise<Page> {+ const expectedHashSuffix = `#/${docName}`;+ let editorPage: Page | undefined;+ await expect(async () => {+ for (const page of app.windows()) {+ const hash = await page.evaluate(() => window.location.hash).catch(() => '');+ if (hash.endsWith(expectedHashSuffix)) {+ editorPage = page;+ return;+ }+ }+ throw new Error(`no window matches ${expectedHashSuffix} yet`);+ }).toPass({ timeout: 30_000 });+ if (!editorPage) throw new Error('editor window vanished after readiness poll');+ return editorPage;+}++async function createSidebarFileAndType(+ page: Page,+ seed: SeededProject,+ docName: string,+ bodyText: string,+): Promise<void> {+ await page.getByRole('button', { name: 'New File' }).click();+ const renameInput = page.getByRole('textbox', { name: /rename Untitled\.md/i });+ await renameInput.fill(docName);+ await renameInput.press('Enter');++ await expect(page.getByRole('treeitem', { name: new RegExp(`${docName}\\.md`) })).toBeVisible({+ timeout: 30_000,+ });+ await expect+ .poll(() => page.evaluate(() => window.location.hash), {+ timeout: 30_000,+ message: `${docName} did not become active`,+ })+ .toBe(`#/${docName}`);++ const editor = page.locator('.ProseMirror[contenteditable="true"]').first();+ await expect(editor).toBeVisible({ timeout: 30_000 });+ await expect+ .poll(+ () =>+ page.evaluate(() => {+ const active = document.activeElement;+ return active instanceof HTMLElement && active.classList.contains('ProseMirror');+ }),+ { timeout: 5_000, message: `${docName} editor did not receive focus after rename` },+ )+ .toBe(true);++ await page.keyboard.type(bodyText);+ await expect(editor).toContainText(bodyText, { timeout: 5_000 });+ await expect+ .poll(+ () => {+ const diskPath = join(seed.projectDir, `${docName}.md`);+ return existsSync(diskPath) ? readFileSync(diskPath, 'utf8') : '';+ },+ { timeout: 10_000, message: `${docName} typed text was not persisted` },+ )+ .toContain(bodyText);+}++test.describe('Sidebar create and rename editability smoke', () => {+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');+ test.skip(!DARWIN, 'Smoke harness is darwin-only in v0.');+ test.skip(+ !PACKAGED_BUILD_EXISTS,+ `Packaged desktop build missing at ${PACKAGED_EXECUTABLE} — run an unpacked packaged build first.`,+ );++ test('successive sidebar-created files remain editable after inline rename commit', async ({+ captureStderrFor,+ }) => {+ const seed = seedProject('editable');+ const app = await launchApp(seed);+ captureStderrFor(app, { cleanupDirs: [seed.tmpHome, seed.projectDir] });++ const page = await findEditorWindow(app, 'start');+ await expect(page.locator('.ProseMirror[contenteditable="true"]').first()).toBeVisible({+ timeout: 30_000,+ });++ await createSidebarFileAndType(page, seed, 'dd', 'first sidebar-created file is editable');+ await createSidebarFileAndType(page, seed, 'ddd', 'second sidebar-created file is editable');+ });+});