Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): folder create/rename no longer closes your tabs (PRD-8316) (#3903)

Andrew Mikofalvyc3792936a51f
diff --git a/.changeset/folder-tab-survives-stale-sync.md b/.changeset/folder-tab-survives-stale-sync.md
new file mode 100644
index 000000000..5f05101b1
--- /dev/null
+++ b/.changeset/folder-tab-survives-stale-sync.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Creating a folder from the sidebar, or renaming one while you have it open, no longer closes its tab and drops you back on the empty workspace screen. A folder tab was kept only while its folder appeared in the server's folder listing, and an empty folder does not reach that listing until the server has caught up. A background refresh landing inside that window closed the folder you had just navigated into, and because a freshly created folder is usually the only thing open, the workspace was left with nothing and fell back to the onboarding view. The folder you are currently viewing is now held open through that window, matching the protection documents already had, whether you reached it from the sidebar or from a wiki link. Folder tabs you have navigated away from are still tidied up as before, and deleting a folder yourself still closes its tab straight away.
+
+One behavior worth knowing, because it is new: a folder deleted outside the app, by an agent or another client, keeps its tab open for as long as you are viewing that folder.
diff --git a/packages/app/src/editor/DocumentContext.folder-tab-sync.dom.test.tsx b/packages/app/src/editor/DocumentContext.folder-tab-sync.dom.test.tsx
new file mode 100644
index 000000000..abd5692d0
--- /dev/null
+++ b/packages/app/src/editor/DocumentContext.folder-tab-sync.dom.test.tsx
@@ -0,0 +1,200 @@
+import { act, cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+
+vi.doMock('@/lib/use-collab-url', () => ({
+ useCollabUrl: () => ({
+ collabUrl: 'ws://localhost:1/collab',
+ attempts: 0,
+ terminal: false,
+ lastError: null,
+ retry: () => {},
+ }),
+}));
+
+const { DocumentProvider, useDocumentContext } = await import('./DocumentContext');
+const { folderTabId, docTabId, localTabSessionStorageKey } = await import('./editor-tabs');
+
+/**
+ * Drives the real `syncOpenTabsWithKnownTargets` on the real provider, so the
+ * derivation that decides whether an exemption exists at all is under test, not
+ * just the predicate it feeds. A literal `keepFolderPaths` would leave that
+ * derivation free to return nothing and still look green.
+ */
+function Harness() {
+ const ctx = useDocumentContext();
+ return (
+ <>
+ <span data-testid="open-tabs">{ctx.openTabs.join('|')}</span>
+ <button
+ type="button"
+ onClick={() =>
+ ctx.openTarget(
+ { kind: 'folder', target: 'notes', folderPath: 'notes' },
+ { disposition: 'permanent', consumeActiveNewTab: false },
+ )
+ }
+ >
+ Open notes folder
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ ctx.openTarget(
+ { kind: 'folder', target: 'stale', folderPath: 'stale' },
+ { disposition: 'permanent', consumeActiveNewTab: false },
+ )
+ }
+ >
+ Open stale folder
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ ctx.openTarget(
+ { kind: 'doc', target: 'readme', docName: 'readme' },
+ { disposition: 'permanent', consumeActiveNewTab: false },
+ )
+ }
+ >
+ Open readme doc
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ void ctx.reconcileLocalRename({
+ renamed: [],
+ renamedFolders: [{ fromPath: 'notes', toPath: 'renamed' }],
+ });
+ }}
+ >
+ Rename notes folder
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ // The lag window: the folder exists on disk but the server listing has
+ // not caught up, so `folderPaths` is empty.
+ ctx.syncOpenTabsWithKnownTargets({
+ pages: new Set<string>(),
+ folderPaths: new Set<string>(),
+ assetPaths: new Set<string>(),
+ filePaths: new Set<string>(),
+ })
+ }
+ >
+ Sync empty listing
+ </button>
+ </>
+ );
+}
+
+async function renderHarness() {
+ render(
+ <DocumentProvider>
+ <Harness />
+ </DocumentProvider>,
+ );
+ await act(async () => {});
+}
+
+afterEach(() => {
+ cleanup();
+ window.localStorage.clear();
+ window.location.hash = '';
+});
+
+describe('folder tab survives a stale page-list sync', () => {
+ test.each([
+ ['trailing-slash hash, the sidebar create and rename form', '#/notes/'],
+ ['slashless hash, the wiki-link and Links panel form', '#/notes'],
+ ])('%s', async (_label, hash) => {
+ window.location.hash = hash;
+ const user = userEvent.setup();
+ await renderHarness();
+
+ await user.click(screen.getByRole('button', { name: 'Open notes folder' }));
+ expect(screen.getByTestId('open-tabs').textContent).toContain(folderTabId('notes'));
+
+ await user.click(screen.getByRole('button', { name: 'Sync empty listing' }));
+ await act(async () => {});
+
+ expect(screen.getByTestId('open-tabs').textContent).toContain(folderTabId('notes'));
+ });
+
+ test('a restored session keeps its folder tab through a stale sync', async () => {
+ // The session-restore path, distinct from the openTarget path above: the
+ // tab comes back from storage rather than from a navigation. Kept because
+ // the restore resolves the pane's target, which is what the exemption reads.
+ window.localStorage.setItem(
+ localTabSessionStorageKey(window.location.origin),
+ JSON.stringify({
+ updatedAt: new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ panes: [
+ {
+ id: 'pane-main',
+ openTabs: [folderTabId('notes')],
+ pinnedTabIds: [],
+ activeTabId: folderTabId('notes'),
+ size: 100,
+ },
+ ],
+ focusedPaneId: 'pane-main',
+ }),
+ );
+ window.location.hash = '#/notes/';
+ const user = userEvent.setup();
+ render(
+ <DocumentProvider>
+ <Harness />
+ </DocumentProvider>,
+ );
+ await act(async () => {});
+ expect(screen.getByTestId('open-tabs').textContent).toContain(folderTabId('notes'));
+ await user.click(screen.getByRole('button', { name: 'Sync empty listing' }));
+ await act(async () => {});
+ expect(screen.getByTestId('open-tabs').textContent).toContain(folderTabId('notes'));
+ });
+
+ test('a renamed folder keeps its tab through a stale sync', async () => {
+ // The traced scenario end to end: the sidebar creates a folder, the inline
+ // rename commits, and a refresh lands before the server listing catches up.
+ // `remapWorkspaceTabs` NULLS `activeTarget` when a tab id changes, so this
+ // only holds because the commit re-derives it from `activeTabId` (see
+ // `paneWithResolvedTarget`) before anything can observe the pane.
+ window.location.hash = '#/notes/';
+ const user = userEvent.setup();
+ await renderHarness();
+
+ await user.click(screen.getByRole('button', { name: 'Open notes folder' }));
+ await user.click(screen.getByRole('button', { name: 'Rename notes folder' }));
+ await act(async () => {});
+ window.location.hash = '#/renamed/';
+ expect(screen.getByTestId('open-tabs').textContent).toContain(folderTabId('renamed'));
+
+ await user.click(screen.getByRole('button', { name: 'Sync empty listing' }));
+ await act(async () => {});
+
+ expect(screen.getByTestId('open-tabs').textContent).toContain(folderTabId('renamed'));
+ });
+
+ test('a folder the user is not on is still pruned', async () => {
+ // Separates the exemption from a blanket folder carve-out. `stale` is open
+ // but no pane displays it and the hash does not name it, so the prune must
+ // still take it while the doc the hash points at survives.
+ window.location.hash = '#/readme';
+ const user = userEvent.setup();
+ await renderHarness();
+
+ await user.click(screen.getByRole('button', { name: 'Open stale folder' }));
+ await user.click(screen.getByRole('button', { name: 'Open readme doc' }));
+ expect(screen.getByTestId('open-tabs').textContent).toContain(folderTabId('stale'));
+
+ await user.click(screen.getByRole('button', { name: 'Sync empty listing' }));
+ await act(async () => {});
+
+ const openTabs = screen.getByTestId('open-tabs').textContent ?? '';
+ expect(openTabs).not.toContain(folderTabId('stale'));
+ expect(openTabs).toContain(docTabId('readme'));
+ });
+});
diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsx
index e83e00273..1554e20c2 100644
--- a/packages/app/src/editor/DocumentContext.tsx
+++ b/packages/app/src/editor/DocumentContext.tsx
@@ -626,6 +626,21 @@ function resolvedTargetForTabId(tabId: string): ResolvedNavigationTarget {
}
}
+/**
+ * Re-derive a pane's `activeTarget` from its own `activeTabId`.
+ *
+ * The workspace invariant this establishes: every pane in `workspaceRef.current`
+ * carries a target derived from ITS OWN `activeTabId`. `commitWorkspace` is the
+ * single site that assigns that ref, and it maps this over every pane first, so
+ * no reader can observe a target belonging to some other tab, or a null one left
+ * behind by a transition.
+ *
+ * That is load-bearing because transitions do NOT carry a target across a tab-id
+ * change: `remapWorkspaceTabs` NULLS `activeTarget` whenever the id moves rather
+ * than remapping it, and this re-derive is what puts it back. Readers that key
+ * off `activeTarget` depend on this invariant, not on ids and targets moving
+ * together — they do not.
+ */
function paneWithResolvedTarget(pane: EditorPaneState): EditorPaneState {
if (pane.activeNewTabId !== null || pane.activeTabId === null) {
return pane.activeTarget === null ? pane : { ...pane, activeTarget: null };
@@ -2168,6 +2183,23 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
// can race ahead of.
const keepHashDocName =
typeof window !== 'undefined' ? docNameFromHash(window.location.hash) : null;
+ // Folder counterpart of the insurance above, read from the panes' RESOLVED
+ // targets rather than from the hash.
+ //
+ // Hash SHAPE cannot answer this. A folder opened from a wiki link or the
+ // Links panel is addressed by `hashFromDocName`, which emits no trailing
+ // slash, so `#/notes` is byte-identical whether `notes` is a doc or a
+ // folder. What tells them apart is `resolveNavigationTarget`, and it does
+ // so by consulting `folderPaths` — the very set that is stale here. The
+ // target a pane already resolved is the only non-circular answer, and
+ // reading it also avoids a second hash decoder that could drift from
+ // `tabIdFromHash`. Rebuilt per sync, so it tracks whatever the panes
+ // currently display.
+ const keepFolderPaths = new Set(
+ workspaceRef.current.panes.flatMap((pane) =>
+ pane.activeTarget?.kind === 'folder' ? [pane.activeTarget.folderPath] : [],
+ ),
+ );
const allOpenTabs = flattenWorkspaceTabs(workspaceRef.current);
const nextOpenTabs = filterOpenTabsForKnownTargets(allOpenTabs, {
pages: new Set([...pages, ...missingDocNames]),
@@ -2176,6 +2208,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
filePaths,
keepMissingDocName: null,
keepHashDocName,
+ keepFolderPaths,
});
if (nextOpenTabs.length === allOpenTabs.length) return;
diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.ts
index d7eb93995..4f4afcce8 100644
--- a/packages/app/src/editor/editor-tabs.test.ts
+++ b/packages/app/src/editor/editor-tabs.test.ts
@@ -210,6 +210,39 @@ describe('editor tab state', () => {
).toEqual(['docs/a', folderTabId('hello')]);
});
+ test('filterOpenTabsForKnownTargets keeps a displayed folder absent from folderPaths', () => {
+ // Folder twin of the `keepHashDocName` case. Why an existing folder can be
+ // missing from `folderPaths` at all is on the `keepFolderPaths` JSDoc.
+ expect(
+ filterOpenTabsForKnownTargets([folderTabId('hello')], {
+ pages: new Set(),
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ keepFolderPaths: new Set(['hello']),
+ }),
+ ).toEqual([folderTabId('hello')]);
+ // It spares ONLY the folders passed in. A blanket folder exemption would
+ // satisfy the assertion above while disabling folder pruning outright, so
+ // pin that stale siblings still go.
+ expect(
+ filterOpenTabsForKnownTargets([folderTabId('hello'), folderTabId('old-folder')], {
+ pages: new Set(),
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ keepFolderPaths: new Set(['hello']),
+ }),
+ ).toEqual([folderTabId('hello')]);
+ // And with no displayed folder there is no exemption at all.
+ expect(
+ filterOpenTabsForKnownTargets([folderTabId('hello')], {
+ pages: new Set(),
+ folderPaths: new Set(),
+ assetPaths: new Set(),
+ keepFolderPaths: new Set<string>(),
+ }),
+ ).toEqual([]);
+ });
+
test('filterOpenTabsForKnownTargets keeps the SKILL doc that left the page list', () => {
// A scope move deletes the source bundle BEFORE its response lands, so the
// source doc stops being a page mid-move. Pruning it there closed the tab
diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.ts
index 245eaa961..450ca0d0e 100644
--- a/packages/app/src/editor/editor-tabs.ts
+++ b/packages/app/src/editor/editor-tabs.ts
@@ -63,8 +63,37 @@ interface KnownTabTargets {
* target — the cold-start race evicts before that resolution runs.
*/
keepHashDocName?: string | null;
+ /**
+ * Folders the caller is currently displaying, kept even when absent from
+ * `folderPaths`. Only the server's folder listing can carry an EMPTY folder,
+ * since nothing derives one from `pages`, and unlike `pages` that listing has
+ * no optimistic bridge. A folder therefore stays unknown here for the whole
+ * create or rename round-trip, and a sync landing inside that window would
+ * otherwise prune the folder tab the user had just navigated into. Folder counterpart of
+ * `keepHashDocName`. Order-independent with respect to a rename, because the
+ * caller reads a target the commit re-derived from the pane's own tab id (see
+ * `paneWithResolvedTarget`), so this matches whether the prune runs before or
+ * after the remap.
+ *
+ * A SET of paths rather than one name, because the caller resolves this from
+ * the panes' active targets, not from the hash: a folder reached by wiki link
+ * carries no trailing slash and is indistinguishable from a doc by shape, and
+ * a split workspace can display more than one folder at once.
+ *
+ * This DEFERS a close rather than preventing one, and only for folders on
+ * screen. In-app deletion closes these tabs by id through
+ * `reconcileLocalRemoval`, so that path is unaffected. An EXTERNAL delete
+ * (agent, MCP, another client) has no folder equivalent of the provider pool's
+ * `doc-deleted` signal, which is what lets the doc branch above lean on a
+ * deletion path, so for folders this prune is the only closer and such a tab
+ * survives while its folder is displayed. A folder tab holds no collaboration
+ * provider, so a stale one cannot diverge a room the way a stale doc tab
+ * could.
+ */
+ keepFolderPaths?: ReadonlySet<string>;
}
+const EMPTY_FOLDER_PATHS: ReadonlySet<string> = new Set<string>();
const LOCAL_TAB_SESSION_PREFIX = 'ok-editor-tabs-v1:';
const FOLDER_TAB_PREFIX = '\u0000folder:';
const ASSET_TAB_PREFIX = '\u0000asset:';
@@ -739,11 +768,14 @@ export function filterOpenTabsForKnownTargets(
filePaths,
keepMissingDocName = null,
keepHashDocName = null,
+ keepFolderPaths = EMPTY_FOLDER_PATHS,
}: KnownTabTargets,
): string[] {
return normalizeOpenTabs(tabs, Number.MAX_SAFE_INTEGER).filter((tabId) => {
const tab = parseEditorTabId(tabId);
- if (tab.kind === 'folder') return folderPaths.has(tab.folderPath);
+ if (tab.kind === 'folder') {
+ return folderPaths.has(tab.folderPath) || keepFolderPaths.has(tab.folderPath);
+ }
if (tab.kind === 'asset') {
return assetPaths.has(tab.assetPath) || filePaths?.has(tab.assetPath) === true;
}