Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Fix OK unit-test flakes, a quadratic scan, and slow credential lookups (#5334)

Andrew Mikofalvy7d4c6199370e
diff --git a/.changeset/unclosed-tag-scan-bound.md b/.changeset/unclosed-tag-scan-bound.md
new file mode 100644
index 000000000..e97819606
--- /dev/null
+++ b/.changeset/unclosed-tag-scan-bound.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Documents with many unclosed component tags in separate paragraphs open in milliseconds instead of stalling for seconds.
diff --git a/packages/app/src/components/CommandPalette.test.ts b/packages/app/src/components/CommandPalette.test.ts
index 73a35889f..9063dde6a 100644
--- a/packages/app/src/components/CommandPalette.test.ts
+++ b/packages/app/src/components/CommandPalette.test.ts
@@ -1,23 +1,21 @@
import { describe, expect, test, vi } from 'vitest';
+import { CommandPalette, runWithToast } from './CommandPalette';
describe('CommandPalette module', () => {
- test('Component module imports cleanly', async () => {
- const mod = await import('./CommandPalette');
- expect(typeof mod.CommandPalette).toBe('function');
- expect(typeof mod.runWithToast).toBe('function');
+ test('Component module imports cleanly', () => {
+ expect(typeof CommandPalette).toBe('function');
+ expect(typeof runWithToast).toBe('function');
});
});
describe('CommandPalette.runWithToast (IPC rejection → toast feedback)', () => {
test('success: no toast.error fires', async () => {
- const { runWithToast } = await import('./CommandPalette');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.resolve(), 'Command failed.', toastApi);
expect(toastApi.error).not.toHaveBeenCalled();
});
test('Error rejection: toast.error fires with Error.message', async () => {
- const { runWithToast } = await import('./CommandPalette');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(
() => Promise.reject(new Error('utility failed to boot')),
@@ -28,21 +26,18 @@ describe('CommandPalette.runWithToast (IPC rejection → toast feedback)', () =>
});
test('non-Error rejection: toast.error fires with fallback', async () => {
- const { runWithToast } = await import('./CommandPalette');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.reject('network dropped'), 'Command failed.', toastApi);
expect(toastApi.error).toHaveBeenCalledWith('Command failed.');
});
test('empty-message Error: toast.error fires with fallback', async () => {
- const { runWithToast } = await import('./CommandPalette');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.reject(new Error('')), 'Command failed.', toastApi);
expect(toastApi.error).toHaveBeenCalledWith('Command failed.');
});
test('does not re-throw on rejection (runAction continues)', async () => {
- const { runWithToast } = await import('./CommandPalette');
const toastApi = { error: vi.fn(() => {}) };
let afterAwait = false;
await runWithToast(() => Promise.reject(new Error('x')), 'Command failed.', toastApi);
@@ -51,14 +46,12 @@ describe('CommandPalette.runWithToast (IPC rejection → toast feedback)', () =>
});
test('success path fires NO toast even on the internal setError(null) clear', async () => {
- const { runWithToast } = await import('./CommandPalette');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.resolve(), 'Command failed.', toastApi);
expect(toastApi.error).not.toHaveBeenCalled();
});
test('falls back to module sonner toast when toastApi is omitted', async () => {
- const { runWithToast } = await import('./CommandPalette');
await expect(runWithToast(() => Promise.resolve(), 'fallback')).resolves.toBeUndefined();
});
});
diff --git a/packages/app/src/components/EditorActivityPool.lazy.test.ts b/packages/app/src/components/EditorActivityPool.lazy.test.ts
index 8729321fa..72c3f55a4 100644
--- a/packages/app/src/components/EditorActivityPool.lazy.test.ts
+++ b/packages/app/src/components/EditorActivityPool.lazy.test.ts
@@ -1,23 +1,22 @@
import { describe, expect, test, vi } from 'vitest';
+import { EditorActivityPool, loadSourceEditorModule } from './EditorActivityPool';
-describe('EditorActivityPool source lazy boundary', () => {
- test('does not import SourceEditor until the lazy loader runs', async () => {
- let sourceEditorModuleLoads = 0;
-
- vi.doMock('@/editor/SourceEditor', () => {
- sourceEditorModuleLoads += 1;
- return {
- SourceEditor: () => null,
- };
- });
+const sourceEditorModuleLoads = vi.hoisted(() => ({ count: 0 }));
- const mod = await import('./EditorActivityPool');
+vi.mock('@/editor/SourceEditor', () => {
+ sourceEditorModuleLoads.count += 1;
+ return {
+ SourceEditor: () => null,
+ };
+});
- expect(typeof mod.EditorActivityPool).toBe('function');
- expect(sourceEditorModuleLoads).toBe(0);
+describe('EditorActivityPool source lazy boundary', () => {
+ test('does not import SourceEditor until the lazy loader runs', async () => {
+ expect(typeof EditorActivityPool).toBe('function');
+ expect(sourceEditorModuleLoads.count).toBe(0);
- const sourceEditorModule = await mod.loadSourceEditorModule();
+ const sourceEditorModule = await loadSourceEditorModule();
expect(typeof sourceEditorModule.SourceEditor).toBe('function');
- expect(sourceEditorModuleLoads).toBe(1);
+ expect(sourceEditorModuleLoads.count).toBe(1);
});
});
diff --git a/packages/app/src/components/EditorArea.test.ts b/packages/app/src/components/EditorArea.test.ts
index fe2689457..f67ce1c20 100644
--- a/packages/app/src/components/EditorArea.test.ts
+++ b/packages/app/src/components/EditorArea.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, test } from 'vitest';
+import { EditorArea } from './EditorArea';
describe('EditorArea module', () => {
- test('exports EditorArea component', async () => {
- const mod = await import('./EditorArea');
- expect(typeof mod.EditorArea).toBe('function');
+ test('exports EditorArea component', () => {
+ expect(typeof EditorArea).toBe('function');
});
});
diff --git a/packages/app/src/components/EditorTabs.test.ts b/packages/app/src/components/EditorTabs.test.ts
index 4f2dccab9..bbd5e7937 100644
--- a/packages/app/src/components/EditorTabs.test.ts
+++ b/packages/app/src/components/EditorTabs.test.ts
@@ -1,14 +1,13 @@
import { describe, expect, test } from 'vitest';
+import * as EditorTabsModule from './EditorTabs';
describe('EditorTabs module', () => {
- test('exports the EditorTabs component', async () => {
- const mod = await import('./EditorTabs');
- expect(typeof mod.EditorTabs).toBe('function');
+ test('exports the EditorTabs component', () => {
+ expect(typeof EditorTabsModule.EditorTabs).toBe('function');
});
- test('does NOT re-export tabParts — canonical home is @/editor/editor-tabs', async () => {
- const mod = await import('./EditorTabs');
- expect('tabParts' in mod).toBe(false);
+ test('does NOT re-export tabParts — canonical home is @/editor/editor-tabs', () => {
+ expect('tabParts' in EditorTabsModule).toBe(false);
});
test('tabParts is exported from @/editor/editor-tabs and parses paths correctly', async () => {
diff --git a/packages/app/src/components/FileSidebar.test.ts b/packages/app/src/components/FileSidebar.test.ts
index 42531f809..c700c2a30 100644
--- a/packages/app/src/components/FileSidebar.test.ts
+++ b/packages/app/src/components/FileSidebar.test.ts
@@ -1,15 +1,13 @@
import { describe, expect, test } from 'vitest';
-import { isInteractiveSidebarControl } from './FileSidebar';
+import { FileSidebar, isInteractiveSidebarControl } from './FileSidebar';
describe('FileSidebar module', () => {
- test('exports the FileSidebar component', async () => {
- const mod = await import('./FileSidebar');
- expect(typeof mod.FileSidebar).toBe('function');
+ test('exports the FileSidebar component', () => {
+ expect(typeof FileSidebar).toBe('function');
});
- test('exports isInteractiveSidebarControl for the sidebar surface context-menu opt-out', async () => {
- const mod = await import('./FileSidebar');
- expect(typeof mod.isInteractiveSidebarControl).toBe('function');
+ test('exports isInteractiveSidebarControl for the sidebar surface context-menu opt-out', () => {
+ expect(typeof isInteractiveSidebarControl).toBe('function');
});
});
diff --git a/packages/app/src/components/NavigatorApp.test.ts b/packages/app/src/components/NavigatorApp.test.ts
index 4eedc26d3..a120734a3 100644
--- a/packages/app/src/components/NavigatorApp.test.ts
+++ b/packages/app/src/components/NavigatorApp.test.ts
@@ -1,4 +1,8 @@
import { describe, expect, test, vi } from 'vitest';
+import * as NavigatorAppModule from './NavigatorApp';
+
+const { displayNameForPath, removeRecentFromList, resolveErrorMessage, runWithErrorStatePure } =
+ NavigatorAppModule;
interface MockBridge {
config: {
@@ -68,11 +72,10 @@ function makeBridge(overrides: Partial<MockBridge> = {}): MockBridge {
}
describe('NavigatorApp bridge contract', () => {
- test('Component module imports cleanly', async () => {
- const mod = await import('./NavigatorApp');
- expect(typeof mod.NavigatorApp).toBe('function');
- expect(typeof mod.resolveErrorMessage).toBe('function');
- expect(typeof mod.runWithErrorStatePure).toBe('function');
+ test('Component module imports cleanly', () => {
+ expect(typeof NavigatorAppModule.NavigatorApp).toBe('function');
+ expect(typeof NavigatorAppModule.resolveErrorMessage).toBe('function');
+ expect(typeof NavigatorAppModule.runWithErrorStatePure).toBe('function');
});
test('bridge.project.listRecent returns RecentProjectEntry[] shape', async () => {
@@ -187,7 +190,6 @@ describe('NavigatorApp bridge contract', () => {
describe('NavigatorApp recent-project removal helpers', () => {
test('removeRecentFromList drops only the matching path and preserves order', async () => {
- const { removeRecentFromList } = await import('./NavigatorApp');
const next = removeRecentFromList(
[
{ path: '/tmp/a', name: 'a', lastOpenedAt: '2026-04-20T00:00:00Z' },
@@ -200,7 +202,6 @@ describe('NavigatorApp recent-project removal helpers', () => {
});
test('removeRecentFromList is a no-op for unknown paths', async () => {
- const { removeRecentFromList } = await import('./NavigatorApp');
const recents = [{ path: '/tmp/a', name: 'a', lastOpenedAt: '2026-04-20T00:00:00Z' }];
expect(removeRecentFromList(recents, '/tmp/missing')).toEqual(recents);
});
@@ -208,17 +209,14 @@ describe('NavigatorApp recent-project removal helpers', () => {
describe('NavigatorApp error-state helpers', () => {
test('resolveErrorMessage prefers Error.message', async () => {
- const { resolveErrorMessage } = await import('./NavigatorApp');
expect(resolveErrorMessage(new Error('boom'), 'fallback')).toBe('boom');
});
test('resolveErrorMessage falls back when message is empty', async () => {
- const { resolveErrorMessage } = await import('./NavigatorApp');
expect(resolveErrorMessage(new Error(''), 'fallback')).toBe('fallback');
});
test('resolveErrorMessage falls back for non-Error throws (string, undefined, object)', async () => {
- const { resolveErrorMessage } = await import('./NavigatorApp');
expect(resolveErrorMessage('plain-string', 'fallback')).toBe('fallback');
expect(resolveErrorMessage(undefined, 'fallback')).toBe('fallback');
expect(resolveErrorMessage({ weird: 'object' }, 'fallback')).toBe('fallback');
@@ -226,7 +224,6 @@ describe('NavigatorApp error-state helpers', () => {
});
test('runWithErrorStatePure clears error state then awaits the wrapped fn', async () => {
- const { runWithErrorStatePure } = await import('./NavigatorApp');
const setError = vi.fn(() => {});
const fn = vi.fn(() => Promise.resolve());
await runWithErrorStatePure(fn, 'fallback', setError);
@@ -235,7 +232,6 @@ describe('NavigatorApp error-state helpers', () => {
});
test('runWithErrorStatePure surfaces rejections via setError with Error.message', async () => {
- const { runWithErrorStatePure } = await import('./NavigatorApp');
const setErrorCalls: Array<string | null> = [];
await runWithErrorStatePure(
() => Promise.reject(new Error('boot failed')),
@@ -248,7 +244,6 @@ describe('NavigatorApp error-state helpers', () => {
});
test('runWithErrorStatePure falls back when rejection has no usable message', async () => {
- const { runWithErrorStatePure } = await import('./NavigatorApp');
const setErrorCalls: Array<string | null> = [];
await runWithErrorStatePure(
() => Promise.reject('network dropped'),
@@ -261,7 +256,6 @@ describe('NavigatorApp error-state helpers', () => {
});
test('runWithErrorStatePure does NOT re-throw on rejection (caller continues)', async () => {
- const { runWithErrorStatePure } = await import('./NavigatorApp');
let afterAwait = false;
await runWithErrorStatePure(
() => Promise.reject(new Error('x')),
@@ -273,7 +267,6 @@ describe('NavigatorApp error-state helpers', () => {
});
test('displayNameForPath returns the last path segment for the Opening… overlay', async () => {
- const { displayNameForPath } = await import('./NavigatorApp');
expect(displayNameForPath('/Users/me/Documents/oktest')).toBe('oktest');
expect(displayNameForPath('/Users/me/Documents/oktest/')).toBe('oktest');
expect(displayNameForPath('C:\\Users\\me\\oktest')).toBe('oktest');
diff --git a/packages/app/src/components/ProjectSwitcher.test.ts b/packages/app/src/components/ProjectSwitcher.test.ts
index b3ca67f86..6109070e7 100644
--- a/packages/app/src/components/ProjectSwitcher.test.ts
+++ b/packages/app/src/components/ProjectSwitcher.test.ts
@@ -1,23 +1,21 @@
import { describe, expect, test, vi } from 'vitest';
+import { ProjectSwitcher, runWithToast } from './ProjectSwitcher';
describe('ProjectSwitcher module', () => {
- test('Component module imports cleanly', async () => {
- const mod = await import('./ProjectSwitcher');
- expect(typeof mod.ProjectSwitcher).toBe('function');
- expect(typeof mod.runWithToast).toBe('function');
+ test('Component module imports cleanly', () => {
+ expect(typeof ProjectSwitcher).toBe('function');
+ expect(typeof runWithToast).toBe('function');
});
});
describe('runWithToast (IPC rejection → toast feedback)', () => {
test('success: no toast.error fires', async () => {
- const { runWithToast } = await import('./ProjectSwitcher');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.resolve(), 'Failed to open.', toastApi);
expect(toastApi.error).not.toHaveBeenCalled();
});
test('Error rejection: toast.error fires with Error.message', async () => {
- const { runWithToast } = await import('./ProjectSwitcher');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(
() => Promise.reject(new Error('utility failed to boot')),
@@ -28,21 +26,18 @@ describe('runWithToast (IPC rejection → toast feedback)', () => {
});
test('non-Error rejection: toast.error fires with fallback', async () => {
- const { runWithToast } = await import('./ProjectSwitcher');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.reject('network dropped'), 'Failed to open.', toastApi);
expect(toastApi.error).toHaveBeenCalledWith('Failed to open.');
});
test('empty-message Error: toast.error fires with fallback', async () => {
- const { runWithToast } = await import('./ProjectSwitcher');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.reject(new Error('')), 'Failed to open.', toastApi);
expect(toastApi.error).toHaveBeenCalledWith('Failed to open.');
});
test('does not re-throw on rejection (caller awaits without try/catch)', async () => {
- const { runWithToast } = await import('./ProjectSwitcher');
const toastApi = { error: vi.fn(() => {}) };
let afterAwait = false;
await runWithToast(() => Promise.reject(new Error('x')), 'Failed to open.', toastApi);
@@ -51,14 +46,12 @@ describe('runWithToast (IPC rejection → toast feedback)', () => {
});
test('success path fires NO toast even on the internal setError(null) clear', async () => {
- const { runWithToast } = await import('./ProjectSwitcher');
const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.resolve(), 'Failed to open.', toastApi);
expect(toastApi.error).not.toHaveBeenCalled();
});
test('falls back to module sonner toast when toastApi is omitted', async () => {
- const { runWithToast } = await import('./ProjectSwitcher');
await expect(runWithToast(() => Promise.resolve(), 'fallback')).resolves.toBeUndefined();
});
});
diff --git a/packages/app/src/components/command-palette-flicker.test.ts b/packages/app/src/components/command-palette-flicker.test.ts
index 7c894d433..0db04da6c 100644
--- a/packages/app/src/components/command-palette-flicker.test.ts
+++ b/packages/app/src/components/command-palette-flicker.test.ts
@@ -1,21 +1,10 @@
import { describe, expect, test } from 'vitest';
+import { computeVisibleSearchResults } from './CommandPalette';
import type { WorkspaceEntry, WorkspaceSearchEntry } from './command-palette-search';
-interface VisibleSearchResultsHelperArgs {
- searchResults: readonly WorkspaceSearchEntry[];
- fallbackSearchResults: readonly WorkspaceEntry[];
- searchStatus: 'idle' | 'loading' | 'success' | 'error';
-}
+type VisibleSearchResultsHelper = typeof computeVisibleSearchResults;
-type VisibleSearchResultsHelper = (
- args: VisibleSearchResultsHelperArgs,
-) => readonly (WorkspaceEntry | WorkspaceSearchEntry)[];
-
-async function loadHelper(): Promise<VisibleSearchResultsHelper | undefined> {
- const mod = (await import('./CommandPalette')) as Record<string, unknown>;
- const candidate = mod.computeVisibleSearchResults;
- return typeof candidate === 'function' ? (candidate as VisibleSearchResultsHelper) : undefined;
-}
+const helper: VisibleSearchResultsHelper = computeVisibleSearchResults;
const apiResultsForPriorQuery: readonly WorkspaceSearchEntry[] = [
{ kind: 'file', path: 'aa.md', name: 'aa', snippet: 'queue manager handles items' },
@@ -29,18 +18,11 @@ const apiResultsForCurrentQuery: readonly WorkspaceSearchEntry[] = [
const fallbackResults: readonly WorkspaceEntry[] = [{ kind: 'file', path: 'cc.md', name: 'cc' }];
describe('computeVisibleSearchResults — stale-while-revalidate contract', () => {
- test('helper is exported and is a function', async () => {
- const helper = await loadHelper();
+ test('helper is exported and is a function', () => {
expect(typeof helper).toBe('function');
});
- test('mid-keystroke loading: prior API results stay visible (stale-while-revalidate)', async () => {
- const helper = await loadHelper();
- if (!helper) {
- expect(typeof helper).toBe('function');
- return;
- }
-
+ test('mid-keystroke loading: prior API results stay visible (stale-while-revalidate)', () => {
const visible = helper({
searchResults: apiResultsForPriorQuery,
fallbackSearchResults: fallbackResults,
@@ -50,13 +32,7 @@ describe('computeVisibleSearchResults — stale-while-revalidate contract', () =
expect(visible).toEqual(apiResultsForPriorQuery);
});
- test('loading with empty results: fall back to local corpus', async () => {
- const helper = await loadHelper();
- if (!helper) {
- expect(typeof helper).toBe('function');
- return;
- }
-
+ test('loading with empty results: fall back to local corpus', () => {
const visible = helper({
searchResults: [],
fallbackSearchResults: fallbackResults,
@@ -66,13 +42,7 @@ describe('computeVisibleSearchResults — stale-while-revalidate contract', () =
expect(visible).toEqual(fallbackResults);
});
- test('idle with empty results: fall back to local corpus', async () => {
- const helper = await loadHelper();
- if (!helper) {
- expect(typeof helper).toBe('function');
- return;
- }
-
+ test('idle with empty results: fall back to local corpus', () => {
const visible = helper({
searchResults: [],
fallbackSearchResults: fallbackResults,
@@ -82,13 +52,7 @@ describe('computeVisibleSearchResults — stale-while-revalidate contract', () =
expect(visible).toEqual(fallbackResults);
});
- test('error with empty results: fall back to local corpus', async () => {
- const helper = await loadHelper();
- if (!helper) {
- expect(typeof helper).toBe('function');
- return;
- }
-
+ test('error with empty results: fall back to local corpus', () => {
const visible = helper({
searchResults: [],
fallbackSearchResults: fallbackResults,
@@ -98,13 +62,7 @@ describe('computeVisibleSearchResults — stale-while-revalidate contract', () =
expect(visible).toEqual(fallbackResults);
});
- test('success with empty result: empty list, NOT fallback', async () => {
- const helper = await loadHelper();
- if (!helper) {
- expect(typeof helper).toBe('function');
- return;
- }
-
+ test('success with empty result: empty list, NOT fallback', () => {
const visible = helper({
searchResults: [],
fallbackSearchResults: fallbackResults,
@@ -114,13 +72,7 @@ describe('computeVisibleSearchResults — stale-while-revalidate contract', () =
expect(visible).toEqual([]);
});
- test('post-fetch swap: new API results replace prior results', async () => {
- const helper = await loadHelper();
- if (!helper) {
- expect(typeof helper).toBe('function');
- return;
- }
-
+ test('post-fetch swap: new API results replace prior results', () => {
const visible = helper({
searchResults: apiResultsForCurrentQuery,
fallbackSearchResults: fallbackResults,
diff --git a/packages/app/src/components/settings/SettingsDialogBody.test.ts b/packages/app/src/components/settings/SettingsDialogBody.test.ts
index d5846ea73..54150eadc 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.test.ts
+++ b/packages/app/src/components/settings/SettingsDialogBody.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, test } from 'vitest';
+import { SettingsDialogBody } from './SettingsDialogBody';
describe('SettingsDialogBody module', () => {
- test('exports SettingsDialogBody component', async () => {
- const mod = await import('./SettingsDialogBody');
- expect(typeof mod.SettingsDialogBody).toBe('function');
+ test('exports SettingsDialogBody component', () => {
+ expect(typeof SettingsDialogBody).toBe('function');
});
});
diff --git a/packages/app/src/components/settings/SettingsDialogShell.test.ts b/packages/app/src/components/settings/SettingsDialogShell.test.ts
index 28bac811c..2ef3a57a3 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.test.ts
+++ b/packages/app/src/components/settings/SettingsDialogShell.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, test } from 'vitest';
+import { SettingsDialogShell } from './SettingsDialogShell';
describe('SettingsDialogShell module', () => {
- test('exports SettingsDialogShell component', async () => {
- const mod = await import('./SettingsDialogShell');
- expect(typeof mod.SettingsDialogShell).toBe('function');
+ test('exports SettingsDialogShell component', () => {
+ expect(typeof SettingsDialogShell).toBe('function');
});
});
diff --git a/packages/app/src/lib/config-provider.test.tsx b/packages/app/src/lib/config-provider.test.tsx
index ee06ad19e..c5242abb7 100644
--- a/packages/app/src/lib/config-provider.test.tsx
+++ b/packages/app/src/lib/config-provider.test.tsx
@@ -1,9 +1,9 @@
import { describe, expect, test } from 'vitest';
+import { ConfigProvider, useConfigContext } from './config-provider';
describe('ConfigProvider module surface', () => {
- test('exports ConfigProvider component and useConfigContext hook', async () => {
- const mod = await import('./config-provider');
- expect(typeof mod.ConfigProvider).toBe('function');
- expect(typeof mod.useConfigContext).toBe('function');
+ test('exports ConfigProvider component and useConfigContext hook', () => {
+ expect(typeof ConfigProvider).toBe('function');
+ expect(typeof useConfigContext).toBe('function');
});
});
diff --git a/packages/app/tests/integration/mock-module-completeness.test.ts b/packages/app/tests/integration/mock-module-completeness.test.ts
index 5e6cac8d0..7410253de 100644
--- a/packages/app/tests/integration/mock-module-completeness.test.ts
+++ b/packages/app/tests/integration/mock-module-completeness.test.ts
@@ -13,12 +13,7 @@ import { isTestOnlySourceFile } from '../../../../test-support/test-only-source-
const APP_ROOT = join(import.meta.dir, '..', '..');
-const ALLOWLIST: Record<string, string> = {
- 'src/components/EditorActivityPool.lazy.test.ts::@/editor/SourceEditor':
- 'The factory COUNTS module loads to assert lazy non-loading — spreading the real module would ' +
- "load it and defeat the test. Safe: the factory provides SourceEditor, the module's only " +
- 'value export consumed by plain tests in this process.',
-};
+const ALLOWLIST: Record<string, string> = {};
interface DoMockCall {
specifier: string | null;
diff --git a/packages/cli/src/commands/auth/git-credential.test.ts b/packages/cli/src/commands/auth/git-credential-get.test.ts
similarity index 99%
rename from packages/cli/src/commands/auth/git-credential.test.ts
rename to packages/cli/src/commands/auth/git-credential-get.test.ts
index 4358c82a1..9b01ac6ac 100644
--- a/packages/cli/src/commands/auth/git-credential.test.ts
+++ b/packages/cli/src/commands/auth/git-credential-get.test.ts
@@ -4,7 +4,7 @@ import { join } from 'node:path';
import { Readable, Writable } from 'node:stream';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { FileBackend } from '../../auth/token-store.ts';
-import { type CredentialGetLogContext, handleCredentialGet } from './git-credential.ts';
+import { type CredentialGetLogContext, handleCredentialGet } from './git-credential-get.ts';
function makeStream(content: string): Readable {
return Readable.from([Buffer.from(content, 'utf-8')]);
diff --git a/packages/cli/src/commands/auth/git-credential-get.ts b/packages/cli/src/commands/auth/git-credential-get.ts
new file mode 100644
index 000000000..5edc6d664
--- /dev/null
+++ b/packages/cli/src/commands/auth/git-credential-get.ts
@@ -0,0 +1,87 @@
+import type { Readable, Writable } from 'node:stream';
+import type { Logger as PinoLoggerInstance } from 'pino';
+import type { TokenStore, TokenStoreDiagnostics } from '../../auth/token-store.ts';
+
+export type KeychainReadInfo = Parameters<NonNullable<TokenStoreDiagnostics['onKeychainRead']>>[0];
+
+export interface CredentialGetLogContext {
+ log?: PinoLoggerInstance;
+ getDiag?: () => KeychainReadInfo | undefined;
+}
+
+export async function handleCredentialGet(
+ input: Readable,
+ output: Writable,
+ tokenStore: TokenStore,
+ ctx?: CredentialGetLogContext,
+): Promise<number> {
+ const text = await readAll(input);
+ const attrs = parseCredentialInput(text);
+ const host = attrs.host ?? '';
+
+ const safeLine = (s: string) => s.replace(/[\r\n]/g, '');
+
+ if (!host) {
+ ctx?.log?.warn(
+ { outcome: 'no-host', backend: tokenStore.backend },
+ '[auth] git-credential get',
+ );
+ return 1;
+ }
+
+ const relayToken = process.env.OK_GH_TOKEN;
+ const relayTokenHost = process.env.OK_GH_TOKEN_HOST;
+ if (relayToken && relayTokenHost === host) {
+ ctx?.log?.debug(
+ {
+ host,
+ outcome: 'gh-env-token',
+ backend: tokenStore.backend,
+ relayLogin: process.env.OK_GH_TOKEN_LOGIN,
+ },
+ '[auth] git-credential get',
+ );
+ output.write(`username=x-access-token\npassword=${safeLine(relayToken)}\n`);
+ return 0;
+ }
+
+ const entry = await tokenStore.get(host);
+ const diag = ctx?.getDiag?.();
+ const outcome = entry != null ? 'found' : (diag?.kind ?? 'absent');
+ if (ctx?.log) {
+ const fields = {
+ host,
+ outcome,
+ backend: tokenStore.backend,
+ ...(diag?.error ? { keychainError: diag.error } : {}),
+ };
+ if (outcome === 'found') ctx.log.debug(fields, '[auth] git-credential get');
+ else ctx.log.warn(fields, '[auth] git-credential get');
+ }
+
+ if (entry == null) return 1;
+
+ output.write(`username=${safeLine(entry.login)}\npassword=${safeLine(entry.token)}\n`);
+ return 0;
+}
+
+function parseCredentialInput(text: string): Record<string, string> {
+ const result: Record<string, string> = {};
+ for (const line of text.split('\n')) {
+ const trimmed = line.trim();
+ if (trimmed === '') continue;
+ const eq = trimmed.indexOf('=');
+ if (eq === -1) continue;
+ result[trimmed.slice(0, eq)] = trimmed.slice(eq + 1);
+ }
+ return result;
+}
+
+function readAll(stream: Readable): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ stream.on('data', (chunk: Buffer) => chunks.push(chunk));
+ stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
+ stream.on('error', reject);
+ });
+}
diff --git a/packages/cli/src/commands/auth/git-credential.ts b/packages/cli/src/commands/auth/git-credential.ts
index 8e4cd6c05..3e7aa7f5b 100644
--- a/packages/cli/src/commands/auth/git-credential.ts
+++ b/packages/cli/src/commands/auth/git-credential.ts
@@ -1,92 +1,8 @@
-import type { Readable, Writable } from 'node:stream';
import { flushFileLogger } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import type { Logger as PinoLoggerInstance } from 'pino';
import type { TokenStore, TokenStoreDiagnostics } from '../../auth/token-store.ts';
-
-type KeychainReadInfo = Parameters<NonNullable<TokenStoreDiagnostics['onKeychainRead']>>[0];
-
-export interface CredentialGetLogContext {
- log?: PinoLoggerInstance;
- getDiag?: () => KeychainReadInfo | undefined;
-}
-
-export async function handleCredentialGet(
- input: Readable,
- output: Writable,
- tokenStore: TokenStore,
- ctx?: CredentialGetLogContext,
-): Promise<number> {
- const text = await readAll(input);
- const attrs = parseCredentialInput(text);
- const host = attrs.host ?? '';
-
- const safeLine = (s: string) => s.replace(/[\r\n]/g, '');
-
- if (!host) {
- ctx?.log?.warn(
- { outcome: 'no-host', backend: tokenStore.backend },
- '[auth] git-credential get',
- );
- return 1;
- }
-
- const relayToken = process.env.OK_GH_TOKEN;
- const relayTokenHost = process.env.OK_GH_TOKEN_HOST;
- if (relayToken && relayTokenHost === host) {
- ctx?.log?.debug(
- {
- host,
- outcome: 'gh-env-token',
- backend: tokenStore.backend,
- relayLogin: process.env.OK_GH_TOKEN_LOGIN,
- },
- '[auth] git-credential get',
- );
- output.write(`username=x-access-token\npassword=${safeLine(relayToken)}\n`);
- return 0;
- }
-
- const entry = await tokenStore.get(host);
- const diag = ctx?.getDiag?.();
- const outcome = entry != null ? 'found' : (diag?.kind ?? 'absent');
- if (ctx?.log) {
- const fields = {
- host,
- outcome,
- backend: tokenStore.backend,
- ...(diag?.error ? { keychainError: diag.error } : {}),
- };
- if (outcome === 'found') ctx.log.debug(fields, '[auth] git-credential get');
- else ctx.log.warn(fields, '[auth] git-credential get');
- }
-
- if (entry == null) return 1;
-
- output.write(`username=${safeLine(entry.login)}\npassword=${safeLine(entry.token)}\n`);
- return 0;
-}
-
-function parseCredentialInput(text: string): Record<string, string> {
- const result: Record<string, string> = {};
- for (const line of text.split('\n')) {
- const trimmed = line.trim();
- if (trimmed === '') continue;
- const eq = trimmed.indexOf('=');
- if (eq === -1) continue;
- result[trimmed.slice(0, eq)] = trimmed.slice(eq + 1);
- }
- return result;
-}
-
-function readAll(stream: Readable): Promise<string> {
- return new Promise((resolve, reject) => {
- const chunks: Buffer[] = [];
- stream.on('data', (chunk: Buffer) => chunks.push(chunk));
- stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
- stream.on('error', reject);
- });
-}
+import { handleCredentialGet, type KeychainReadInfo } from './git-credential-get.ts';
export function gitCredentialCommand(
getTokenStore: (diag?: TokenStoreDiagnostics) => Promise<TokenStore>,
diff --git a/packages/cli/src/commands/git-credential-fixtures.test-helper.ts b/packages/cli/src/commands/git-credential-fixtures.test-helper.ts
index 4334efba5..a57147dae 100644
--- a/packages/cli/src/commands/git-credential-fixtures.test-helper.ts
+++ b/packages/cli/src/commands/git-credential-fixtures.test-helper.ts
@@ -87,7 +87,7 @@ export function writeCliCredentialStandIn(options: {
runner,
[
`import { FileBackend } from ${moduleUrl('src/auth/token-store.ts')};`,
- `import { handleCredentialGet } from ${moduleUrl('src/commands/auth/git-credential.ts')};`,
+ `import { handleCredentialGet } from ${moduleUrl('src/commands/auth/git-credential-get.ts')};`,
`const store = new FileBackend(${JSON.stringify(options.authFile)});`,
'process.exit(await handleCredentialGet(process.stdin, process.stdout, store));',
'',
diff --git a/packages/core/src/markdown/autolink-void-html-guard.ts b/packages/core/src/markdown/autolink-void-html-guard.ts
index 3f9fada8b..178991863 100644
--- a/packages/core/src/markdown/autolink-void-html-guard.ts
+++ b/packages/core/src/markdown/autolink-void-html-guard.ts
@@ -111,6 +111,16 @@ function indexGreaterThan(source: string): number[] {
return positions;
}
+function indexLiteralDoubleNewlines(source: string): number[] {
+ const offsets: number[] = [];
+ let i = source.indexOf('\n\n');
+ while (i !== -1) {
+ offsets.push(i);
+ i = source.indexOf('\n\n', i + 1);
+ }
+ return offsets;
+}
+
const ANGLE_DEST_SCAN_CAP = 1024;
function isAngleBracketDestinationOpen(offset: number, result: string): boolean {
@@ -179,6 +189,7 @@ function isSelfClosingTagAt(
function indexUppercaseTagSpans(source: string): Array<[number, number]> {
const spans: Array<[number, number]> = [];
+ const doubleNewlineOffsets = indexLiteralDoubleNewlines(source);
const TAG_START_RE = /<\/?([A-Z][A-Za-z0-9.]*)/g;
for (const m of source.matchAll(TAG_START_RE)) {
const tagStart = m.index;
@@ -187,12 +198,15 @@ function indexUppercaseTagSpans(source: string): Array<[number, number]> {
if (tagStart > prevStart && tagStart <= prevEnd) continue;
}
let i = tagStart + m[0].length;
+ const dnIdx = lowerBound(doubleNewlineOffsets, tagStart);
+ const scanEnd =
+ dnIdx < doubleNewlineOffsets.length ? doubleNewlineOffsets[dnIdx] : source.length;
let inSingleQuote = false;
let inDoubleQuote = false;
let inBacktick = false;
let braceDepth = 0;
let terminator = -1;
- while (i < source.length) {
+ while (i < scanEnd) {
const ch = source[i];
if (inSingleQuote) {
if (ch === "'") inSingleQuote = false;
@@ -219,10 +233,7 @@ function indexUppercaseTagSpans(source: string): Array<[number, number]> {
}
i++;
}
- if (terminator !== -1) {
- if (source.slice(tagStart, terminator).includes('\n\n')) continue;
- spans.push([tagStart, terminator]);
- }
+ if (terminator !== -1) spans.push([tagStart, terminator]);
}
return spans;
}
diff --git a/packages/core/src/y-prosemirror-patch.test.ts b/packages/core/src/y-prosemirror-patch.test.ts
index d9926c1a2..b75ddbdcb 100644
--- a/packages/core/src/y-prosemirror-patch.test.ts
+++ b/packages/core/src/y-prosemirror-patch.test.ts
@@ -294,5 +294,5 @@ describe('R13 patch verification (y-prosemirror + @tiptap/y-tiptap)', () => {
`broadcast the delete to all peers (see PRECEDENTS.md precedent #9):\n${details}`,
);
}
- }, 30_000);
+ }, 120_000);
});
diff --git a/packages/desktop/tests/smoke/_helpers/electron-cleanup.reap-servers.test.ts b/packages/desktop/tests/smoke/_helpers/electron-cleanup.reap-servers.test.ts
index 3f9fa0bc8..1d7cbc831 100644
--- a/packages/desktop/tests/smoke/_helpers/electron-cleanup.reap-servers.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/electron-cleanup.reap-servers.test.ts
@@ -15,6 +15,7 @@ const SECOND_PID_BEYOND_ANY_KERNEL_LIMIT = 4_194_337;
const STAND_IN_LIFETIME_MS = 5_000;
const LOCK_READY_BOUND_MS = 20_000;
const REAP_LIVENESS_BOUND_MS = 120_000;
+const INJECTED_RELEASE_BOUND_MS = 1_000;
const STAND_IN_SERVER = [
"const fs = require('node:fs');",
@@ -305,8 +306,11 @@ describe('reapDetachedServers — reports what outlives the release bound, never
let survivors: unknown;
let aliveWhenTheReaperReturned = false;
+ let reapedForMs = 0;
try {
- survivors = await reapDetachedServers([root]);
+ const reapStartedAt = Date.now();
+ survivors = await reapDetachedServers([root], { boundMs: INJECTED_RELEASE_BOUND_MS });
+ reapedForMs = Date.now() - reapStartedAt;
aliveWhenTheReaperReturned = standIn.exitCode === null && standIn.signalCode === null;
} finally {
standIn.stdin?.end();
@@ -315,10 +319,14 @@ describe('reapDetachedServers — reports what outlives the release bound, never
expect({
releaseBoundIsExported: typeof DETACHED_SERVER_RELEASE_BOUND_MS === 'number',
+ waitedOutTheBound: reapedForMs >= INJECTED_RELEASE_BOUND_MS,
aliveWhenTheReaperReturned,
survivors,
warnedWithPidAndLockPath: warnings().some(
- (line) => line.includes(lockPath) && mentionsPid(line, standInPid),
+ (line) =>
+ line.includes(lockPath) &&
+ mentionsPid(line, standInPid) &&
+ line.includes(`after ${INJECTED_RELEASE_BOUND_MS}ms`),
),
staleLockReported: warnings().some(
(line) => line.includes(staleLockPath) || mentionsPid(line, PID_BEYOND_ANY_KERNEL_LIMIT),
@@ -330,6 +338,7 @@ describe('reapDetachedServers — reports what outlives the release bound, never
],
}).toEqual({
releaseBoundIsExported: true,
+ waitedOutTheBound: true,
aliveWhenTheReaperReturned: true,
survivors: [{ lockPath, pid: standInPid }],
warnedWithPidAndLockPath: true,
@@ -338,7 +347,7 @@ describe('reapDetachedServers — reports what outlives the release bound, never
signalsThatReachedTheStandIn: [],
});
},
- REAP_LIVENESS_BOUND_MS + DETACHED_SERVER_RELEASE_BOUND_MS,
+ REAP_LIVENESS_BOUND_MS + INJECTED_RELEASE_BOUND_MS,
);
test.each<[string, (lockText: string) => string]>([
@@ -357,7 +366,7 @@ describe('reapDetachedServers — reports what outlives the release bound, never
let lockTextWhenTheReaperReturned: string | undefined;
let aliveWhenTheReaperReturned = false;
try {
- const reaping = reapDetachedServers([root]);
+ const reaping = reapDetachedServers([root], { boundMs: INJECTED_RELEASE_BOUND_MS });
probedBeforeTheTear = boundary.probes.some((probe) => probe.target === standInPid);
writeFileSync(lockPath, tornText);
survivors = await reaping;
@@ -388,7 +397,7 @@ describe('reapDetachedServers — reports what outlives the release bound, never
signalsThatReachedTheStandIn: [],
});
},
- REAP_LIVENESS_BOUND_MS + DETACHED_SERVER_RELEASE_BOUND_MS,
+ REAP_LIVENESS_BOUND_MS + INJECTED_RELEASE_BOUND_MS,
);
test(
@@ -442,7 +451,7 @@ describe('reapDetachedServers — reports what outlives the release bound, never
let aliveWhenTheReaperReturned = false;
try {
writeFileSync(lockPath, '');
- const reaping = reapDetachedServers([root]);
+ const reaping = reapDetachedServers([root], { boundMs: INJECTED_RELEASE_BOUND_MS });
writeFileSync(lockPath, lockText);
survivors = await reaping;
aliveWhenTheReaperReturned = standIn.exitCode === null && standIn.signalCode === null;
@@ -467,6 +476,6 @@ describe('reapDetachedServers — reports what outlives the release bound, never
signalsThatReachedTheStandIn: [],
});
},
- REAP_LIVENESS_BOUND_MS + DETACHED_SERVER_RELEASE_BOUND_MS,
+ REAP_LIVENESS_BOUND_MS + INJECTED_RELEASE_BOUND_MS,
);
});
diff --git a/packages/server/src/qa-sweep-lens.test.ts b/packages/server/src/qa-sweep-lens.test.ts
index adde96d0b..3a6effd16 100644
--- a/packages/server/src/qa-sweep-lens.test.ts
+++ b/packages/server/src/qa-sweep-lens.test.ts
@@ -5,6 +5,7 @@ import { resolve } from 'node:path';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { type BridgeRaceRig, createBridgeRaceRig } from './bridge-race-rig.test-helper.ts';
+import type { LossCaptureEventInput } from './loss-capture.ts';
import { getMetrics } from './metrics.ts';
import { initShadowRepo, type ShadowHandle, shadowGit } from './shadow-repo.ts';
import { getDocumentHistory } from './timeline-query.ts';
@@ -153,12 +154,21 @@ describe('QA-009: restore is NEVER automatic — checkpoint content stays out of
test('a force-resolve checkpoint is restore-reachable via history, but its content is NEVER auto-re-inserted into the live Y.Text/fragment (no user rollback)', async () => {
const shadow = await setupShadow();
+ const { promise: checkpointWrite, resolve: checkpointWritten } =
+ Promise.withResolvers<LossCaptureEventInput>();
const rig = createBridgeRaceRig({
docName: 'qa009',
setupOverrides: {
shadow: () => shadow,
getBranch: () => 'main',
contentRoot: CONTENT_ROOT,
+ lossRing: {
+ record: async (event) => {
+ if (event.event === 'checkpoint-write' && event.site === 'derive-timing-exhaustion') {
+ checkpointWritten(event);
+ }
+ },
+ },
},
});
const before = getMetrics().deriveTimingDeferForceResolved;
@@ -173,15 +183,15 @@ describe('QA-009: restore is NEVER automatic — checkpoint content stays out of
expect(count(rig.serializeFragment(), PENDING_LINE)).toBe(0);
expect(count(rig.ytext.toString(), PENDING_LINE)).toBe(0);
- await vi.waitFor(async () => {
- const hist = await getDocumentHistory(shadow, { docName: 'qa009' }, CONTENT_ROOT);
- const cp = hist.entries.find((e) => e.checkpoint?.kind === 'defer-exhaustion-loss');
- expect(cp?.sha).toMatch(/^[0-9a-f]{40}$/);
- const blob = (
- await shadowGit(shadow).raw('show', `${cp?.sha}:${CONTENT_ROOT}/qa009`)
- ).toString();
- expect(blob).toContain(PENDING_LINE);
- });
+ const written = await checkpointWrite;
+ expect(written.checkpointSha).toMatch(/^[0-9a-f]{40}$/);
+ const hist = await getDocumentHistory(shadow, { docName: 'qa009' }, CONTENT_ROOT);
+ const cp = hist.entries.find((e) => e.checkpoint?.kind === 'defer-exhaustion-loss');
+ expect(cp?.sha).toBe(written.checkpointSha);
+ const blob = (
+ await shadowGit(shadow).raw('show', `${cp?.sha}:${CONTENT_ROOT}/qa009`)
+ ).toString();
+ expect(blob).toContain(PENDING_LINE);
rig.settle(6);
expect(count(rig.serializeFragment(), PENDING_LINE)).toBe(0);
diff --git a/packages/server/src/shadow-repo.test.ts b/packages/server/src/shadow-repo.test.ts
index 23b16d672..6d1509fa1 100644
--- a/packages/server/src/shadow-repo.test.ts
+++ b/packages/server/src/shadow-repo.test.ts
@@ -2259,7 +2259,7 @@ describe('shadow repo excludes OpenKnowledge machine-local state', () => {
expect(freshTree).toContain('intro.md');
expect(freshTree.filter((p) => p.startsWith('.ok/local/'))).toEqual([]);
- });
+ }, 120_000);
test('a repair the index sweep cannot run does not abort initialization, but degrades the shadow', async () => {
writeFileSync(resolve(shadow.gitDir, FANOUT_INDEX_NAME), 'GARBAGE-NOT-AN-INDEX-FILE');
diff --git a/packages/server/src/timeline-query.test.ts b/packages/server/src/timeline-query.test.ts
index cc71b727a..3bbd78edc 100644
--- a/packages/server/src/timeline-query.test.ts
+++ b/packages/server/src/timeline-query.test.ts
@@ -32,6 +32,11 @@ import { getDocumentHistory, getFolderTimeline, historyWalkCap } from './timelin
const CHAIN_PERF_SAMPLES = 3;
const CHECKPOINT_PERF_SAMPLES = 3;
+const BENCH_ENABLED = process.env.RUN_BENCH === '1' || process.env.RUN_BENCH === 'true';
+const CHECKPOINT_PERF_NAMES = ['a', 'b', 'c', 'd', 'e', 'f'];
+const CHECKPOINT_PERF_REVISIONS_PER_EPOCH = BENCH_ENABLED ? 17 : 3;
+const CHECKPOINT_PERF_CHECKPOINTS =
+ CHECKPOINT_PERF_NAMES.length * CHECKPOINT_PERF_REVISIONS_PER_EPOCH;
type TimelineQueryRun = () => Promise<Awaited<ReturnType<typeof getDocumentHistory>>>;
@@ -774,11 +779,11 @@ describe('getDocumentHistory — rename-history mitigation (US-004)', () => {
);
}, 30_000);
- test('perf: chain depth 5 + ~100 checkpoints walk reaches every epoch, and records its relative cost', async () => {
+ test(`perf: chain depth 5 + ${CHECKPOINT_PERF_CHECKPOINTS} checkpoints walk reaches every epoch, and records its relative cost`, async () => {
const { contentDir, shadow } = await setup();
const { cw, sv } = datedCommits(shadow);
- const names = ['a', 'b', 'c', 'd', 'e', 'f'];
- const revisionsPerEpoch = 17;
+ const names = CHECKPOINT_PERF_NAMES;
+ const revisionsPerEpoch = CHECKPOINT_PERF_REVISIONS_PER_EPOCH;
const commitsPerEpoch = 1 + revisionsPerEpoch * 2;
const index = createEmptyIndex();
let prevName: string | null = null;
@@ -827,7 +832,7 @@ describe('getDocumentHistory — rename-history mitigation (US-004)', () => {
const withoutMedian = median(withoutMs);
console.log(
- `[perf] chain depth 5 + ~100 checkpoints, ${CHECKPOINT_PERF_SAMPLES} pairs: median per-pair ` +
+ `[perf] chain depth 5 + ${CHECKPOINT_PERF_CHECKPOINTS} checkpoints, ${CHECKPOINT_PERF_SAMPLES} pairs: median per-pair ` +
`ratio ${ratio.toFixed(2)}x; arm medians with-chain ${withMedian.toFixed(0)}ms, no-chain ` +
`${withoutMedian.toFixed(0)}ms. All three are observations, not assertions. A ceiling of ` +
`${names.length}x, the number of name epochs the chain spans, was measured against a ` +