Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): stop the sidebar create crash on an occupied destination (#4106)
Nick Gomez8d74ce0bdbb8
diff --git a/.changeset/sidebar-create-shell-crash.md b/.changeset/sidebar-create-shell-crash.mdnew file mode 100644index 000000000..0063eaea1--- /dev/null+++ b/.changeset/sidebar-create-shell-crash.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++Renaming a file in the sidebar no longer crashes the app when the destination name is already taken.++If the sidebar's tree already held an entry at the name a file was being renamed into, the rename asked the tree to move an item onto an occupied path, which throws. Because that happened while React was rendering, the surrounding error handling could not catch it and the whole window was replaced with "Something went wrong" instead of the renamed document.++The move is now skipped when the destination is already in place, matching what the same routine already did for assets, so the rename finishes normally.diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsxindex 4d5fe5682..14ceadef1 100644--- a/packages/app/src/components/FileTree.tsx+++ b/packages/app/src/components/FileTree.tsx@@ -1261,7 +1261,9 @@ export function FileTree({ ref }: { ref?: Ref<FileTreeHandle | null> }) {(entry): entry is DocumentEntry => isDocumentEntry(entry) && entry.docName === toDocName,);const canonicalTreePath = docNameToTreePath(toDocName, destination?.docExt ?? source.docExt);- model.move(toDocName, canonicalTreePath);+ if (model.getItem(canonicalTreePath) == null) {+ model.move(toDocName, canonicalTreePath);+ }lastCanonical = canonicalTreePath;reconciledCount += 1;}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 f266bb6cd..d7aa3e1d5 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@@ -190,6 +190,9 @@ class StubModel {if (item == null) {throw new Error(`Source path does not exist: "${source}"`);}+ if (this.items.has(dest)) {+ throw new Error(`Destination already exists: "${dest}"`);+ }if (this.focusedPath === source) {this.focusedPath = dest;}@@ -555,6 +558,42 @@ describe('FileTree post-rename Pierre/React store reconciliation', () => {expect(toastErrorMock).not.toHaveBeenCalled();});+ test('DESTINATION_OCCUPIED — canonical destination already in the store; reconciliation short-circuits instead of throwing', async () => {+ documentsFetchResult = [+ ...INITIAL_DOCUMENTS,+ {+ kind: 'document',+ docName: 'bar',+ docExt: '.md',+ size: 1,+ modified: '2026-05-22T00:00:00.000Z',+ },+ ];++ render(<FileTree />);++ await waitFor(() => {+ expect(capturedOptions).not.toBeNull();+ });+ await waitFor(() => {+ expect(model.getItem('foo.md')).not.toBeNull();+ });+ await waitFor(() => {+ expect(model.getItem('bar.md')).not.toBeNull();+ });++ model.focusPath('foo.md');+ simulatePierreCommitRename('foo.md', 'bar', false);++ await waitFor(() => {+ expect(addPageMock).toHaveBeenCalledWith('bar');+ });+ expect(model.getItem('bar.md')).not.toBeNull();+ expect(model.getFocusedPath()).toBe('bar.md');+ expect(model.getItem('bar')).toBeNull();+ expect(toastErrorMock).not.toHaveBeenCalled();+ });+test('FOLDER_CASCADE — children pre-canonical in Pierre store; reconciliation guard short-circuits per child', async () => {renameResponseBody = {renamed: [diff --git a/packages/app/tests/stress/_helpers/index.ts b/packages/app/tests/stress/_helpers/index.tsindex fb43d2be9..e06d3ef84 100644--- a/packages/app/tests/stress/_helpers/index.ts+++ b/packages/app/tests/stress/_helpers/index.ts@@ -53,7 +53,11 @@ export {setPluginEnabled,waitForSettingsPanel,} from './settings.ts';-export { createFileViaSidebar, createFolderViaSidebar, sidebarFileButton } from './sidebar.ts';+export {+ createFileViaSidebar,+ createFolderViaSidebar,+ expectActiveEditorTab,+} from './sidebar.ts';export {getSelectedItemSnapshot,type SelectedItemSnapshot,diff --git a/packages/app/tests/stress/_helpers/sidebar.ts b/packages/app/tests/stress/_helpers/sidebar.tsindex 39c280d58..513b2fd59 100644--- a/packages/app/tests/stress/_helpers/sidebar.ts+++ b/packages/app/tests/stress/_helpers/sidebar.ts@@ -2,11 +2,6 @@ import type { Locator, Page } from '@playwright/test';import { expect } from './fixtures.ts';import { escapeRegExp } from './regexp.ts';-export function sidebarFileButton(page: Page, name: string): Locator {- const sidebar = page.locator('[data-slot="sidebar-container"]');- return sidebar.getByText(name, { exact: true });-}-function sidebarTreeItem(page: Page, name: string): Locator {return page.locator('[data-slot="sidebar-container"]')@@ -19,6 +14,134 @@ function activeEditorTabButton(page: Page, name: string): Locator {const CREATE_CONVERGED_TIMEOUT = process.env.CI ? 15_000 : 10_000;+const APP_SHELL_CRASH_LOG = '[AppErrorBoundary]';+const PROBE_TIMEOUT = 2_000;++interface EditorTabStripEntry {+ active: boolean;+ paneId: string | null;+ tabId: string | null;+ labels: string[];+}++interface ProbeFailure {+ probeError: string;+}++async function withProbeTimeout<T>(work: Promise<T>): Promise<T | ProbeFailure> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const guard = new Promise<ProbeFailure>((resolve) => {+ timer = setTimeout(+ () => resolve({ probeError: `probe did not settle within ${PROBE_TIMEOUT}ms` }),+ PROBE_TIMEOUT,+ );+ });+ try {+ return await Promise.race([work, guard]);+ } catch (error: unknown) {+ return { probeError: String(error) };+ } finally {+ clearTimeout(timer);+ }+}++function editorTabStrip(page: Page): Promise<EditorTabStripEntry[] | ProbeFailure> {+ return withProbeTimeout(+ page.evaluate(() =>+ Array.from(+ document.querySelectorAll('[data-editor-pane-tabs] [data-editor-tab-sortable]'),+ ).map((tab) => ({+ active: tab.getAttribute('data-active-tab') === 'true',+ paneId: tab.getAttribute('data-editor-pane-id'),+ tabId: tab.getAttribute('data-editor-tab-id'),+ labels: Array.from(tab.querySelectorAll('button')).map(+ (button) => button.getAttribute('aria-label') ?? button.textContent?.trim() ?? '',+ ),+ })),+ ),+ );+}++function persistedTabSessions(page: Page): Promise<Record<string, unknown> | ProbeFailure> {+ return withProbeTimeout(+ page.evaluate(() => {+ const out: Record<string, unknown> = {};+ for (let i = 0; i < localStorage.length; i += 1) {+ const key = localStorage.key(i);+ if (!key?.startsWith('ok-editor-tabs-v1:')) continue;+ const raw = localStorage.getItem(key) ?? '';+ try {+ out[key] = JSON.parse(raw);+ } catch {+ out[key] = raw;+ }+ }+ return out;+ }),+ );+}++interface AppShellCrashLogs {+ total: number;+ matches: string[];+}++function appShellCrashLogs(page: Page): Promise<AppShellCrashLogs | ProbeFailure> {+ return withProbeTimeout(+ page.consoleMessages({ filter: 'all' }).then((messages) => ({+ total: messages.length,+ matches: messages+ .map((message) => message.text())+ .filter((text) => text.includes(APP_SHELL_CRASH_LOG)),+ })),+ );+}++function appShellCrash(page: Page): Promise<string | null | ProbeFailure> {+ return withProbeTimeout(+ page.evaluate(+ () => document.querySelector('[data-slot="app-error-boundary"]')?.textContent?.trim() ?? null,+ ),+ );+}++export async function expectActiveEditorTab(+ page: Page,+ name: string,+ options: { timeout?: number } = {},+): Promise<void> {+ try {+ await expect(activeEditorTabButton(page, name)).toBeVisible({+ timeout: options.timeout ?? CREATE_CONVERGED_TIMEOUT,+ });+ } catch (cause) {+ const strip = await editorTabStrip(page);+ const sessions = await persistedTabSessions(page);+ const crash = await appShellCrash(page);+ const crashLogs = await appShellCrashLogs(page);+ const wrapped = new Error(+ [+ `active editor tab never became "${name}".`,+ `url=${page.url()}`,+ ...(Array.isArray(strip)+ ? [`activeTabCount=${strip.filter((tab) => tab.active).length}`]+ : []),+ `appShellCrash=${JSON.stringify(crash)}`,+ `appShellCrashLogs=${JSON.stringify(crashLogs)}`,+ `strip=${JSON.stringify(strip)}`,+ `persistedTabSessions=${JSON.stringify(sessions)}`,+ ].join(' '),+ { cause },+ );+ if (cause !== null && typeof cause === 'object' && 'matcherResult' in cause) {+ (wrapped as { matcherResult?: unknown }).matcherResult = (+ cause as { matcherResult?: unknown }+ ).matcherResult;+ }+ throw wrapped;+ }+}+export async function createFolderViaSidebar(page: Page, name: string): Promise<void> {await page.getByRole('button', { name: 'New folder', exact: true }).click();const input = page.getByRole('textbox', { name: /rename New Folder/i });@@ -27,9 +150,7 @@ export async function createFolderViaSidebar(page: Page, name: string): Promise<await input.press('Enter');await expect(sidebarTreeItem(page, name)).toBeVisible({ timeout: CREATE_CONVERGED_TIMEOUT });- await expect(activeEditorTabButton(page, `${name}/`)).toBeVisible({- timeout: CREATE_CONVERGED_TIMEOUT,- });+ await expectActiveEditorTab(page, `${name}/`);await expect(page).toHaveURL(new RegExp(`#/${escapeRegExp(name)}/$`), {timeout: CREATE_CONVERGED_TIMEOUT,});@@ -45,9 +166,7 @@ export async function createFileViaSidebar(page: Page, name: string): Promise<voawait expect(sidebarTreeItem(page, `${name}.md`)).toBeVisible({timeout: CREATE_CONVERGED_TIMEOUT,});- await expect(activeEditorTabButton(page, `${name}.md`)).toBeVisible({- timeout: CREATE_CONVERGED_TIMEOUT,- });+ await expectActiveEditorTab(page, `${name}.md`);await expect(page).toHaveURL(new RegExp(`#/${escapeRegExp(name)}$`), {timeout: CREATE_CONVERGED_TIMEOUT,});diff --git a/packages/app/tests/stress/file-tree-create.e2e.ts b/packages/app/tests/stress/file-tree-create.e2e.tsindex f648e9a7f..d5d62857d 100644--- a/packages/app/tests/stress/file-tree-create.e2e.ts+++ b/packages/app/tests/stress/file-tree-create.e2e.ts@@ -7,6 +7,7 @@ import {createFileViaSidebar,createFolderViaSidebar,expect,+ expectActiveEditorTab,test,} from './_helpers';@@ -112,10 +113,6 @@ function editorTabButton(page: Page, name: string) {return page.getByRole('main').getByRole('button', { name, exact: true });}-function activeEditorTabButton(page: Page, name: string) {- return page.locator('[data-active-tab="true"]').getByRole('button', { name, exact: true });-}-async function selectAllSidebarItems(page: Page, focusItemName: string) {const focusTarget = sidebarTreeItem(page, focusItemName);await focusTarget.focus();@@ -822,15 +819,11 @@ test.describe('FileTree sidebar create', () => {await folderItem.click();await expect(page).toHaveURL(new RegExp(`#/${name}/$`));- await expect(activeEditorTabButton(page, `${name}/`)).toBeVisible({- timeout: 10_000,- });+ await expectActiveEditorTab(page, `${name}/`, { timeout: 10_000 });await fileItem.click();await expect(page).toHaveURL(new RegExp(`#/${name}$`));- await expect(activeEditorTabButton(page, `${name}.md`)).toBeVisible({- timeout: 10_000,- });+ await expectActiveEditorTab(page, `${name}.md`, { timeout: 10_000 });expect(existsSync(join(workerServer.contentDir, name))).toBe(true);expect(statSync(join(workerServer.contentDir, name)).isDirectory()).toBe(true);