Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(desktop): surface why a server spawn failed (PRD-7469) (#3267)

Andrew Mikofalvy877fa358b857
diff --git a/.changeset/desktop-spawn-failure-reason.md b/.changeset/desktop-spawn-failure-reason.md
new file mode 100644
index 000000000..2602d97bc
--- /dev/null
+++ b/.changeset/desktop-spawn-failure-reason.md
@@ -0,0 +1,19 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Desktop now reports why a project's server failed to start, instead of only that it timed out.
+
+When the managed server exited before binding a port, Desktop waited the full 15 seconds and then
+showed `OpenKnowledge server did not bind a port within 15000ms` — with no exit code, no signal, and
+often an empty capture log. A crash 200 ms in was indistinguishable from a slow start, and the
+actual cause was unrecoverable after the fact.
+
+The spawn now observes the child's exit, so failures report their real reason
+(`OpenKnowledge server exited before binding a port (pid=123, killed by SIGKILL)`), and the wait ends
+as soon as the child is gone rather than running out the deadline.
+
+A child that is alive but still starting keeps the full deadline, and its message now says the
+process was still running, so a slow start no longer reads the same as a crash. The wait also still
+runs to the deadline when our child lost a startup race to another process that is mid-bind, so a
+contended launch keeps attaching to the winner instead of reporting an error.
diff --git a/knip.config.ts b/knip.config.ts
index 13582ee18..f004e6bc3 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -123,7 +123,9 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index d7a845280..dfd95ef49 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,3 +1,4 @@
+
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 005627195..8bfdb40cd 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,3 +1,4 @@
+
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 9d9c244b0..463e89595 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,3 +1,4 @@
+
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index c43fdd7e7..0939885bb 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,3 +1,4 @@
+
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 251560a35..c0dc65705 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,6 +65,7 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
+
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 01ac80099..dcc5b0690 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,3 +1,4 @@
+
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 754dc5cc2..0be5203e4 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
+
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -127,6 +128,7 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
+
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -248,6 +250,7 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
+
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index af20de1e2..dca644141 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,3 +1,4 @@
+
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index 83d47404a..a363dfd54 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,3 +1,4 @@
+
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 9807a7e82..4499dbc92 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,3 +1,4 @@
+
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 7415c474a..34704165b 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index ece5c02a1..b6299a948 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,3 +1,4 @@
+
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index 54774764a..acd398aa6 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index 43ecdc709..ba9b56384 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 6d3f3643e..4513da9bb 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,3 +1,4 @@
+
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 00f5771ee..6931623c7 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
+
interface GfmExample {
section: string;
markdown: string;
@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
+
interface MdxCrashEntry {
id: string;
input: string;
@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
+
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
+
export interface NgPinnedCase {
id: string;
name: string;
@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
+
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index 8b1eb8519..daa3ef82b 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
+
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
+
const WORDS = [
'lorem',
'ipsum',
@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
+
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
+
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 420dc0fe5..32c055c5b 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,6 +7,7 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
+
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 2653473da..283913255 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,3 +1,4 @@
+
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index da0a81d23..5d1000cc4 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 787315157..9681c0056 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,3 +1,4 @@
+
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -128,7 +129,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified().use(rehypeParse, { fragment: true });
+ const processor = unified()
+ .use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 706fa9afb..994eb6917 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index 9075aa7f1..69221627d 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -206,6 +207,7 @@ export class MarkdownManager {
}
}
+
const registry = createRegistry();
function destructureAttrs(
@@ -254,6 +256,7 @@ function destructureAttrs(
return result;
}
+
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -276,6 +279,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
+
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -344,6 +348,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
+
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -596,6 +601,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -676,6 +682,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -973,6 +980,7 @@ function buildMdastToPmHandlers(
};
}
+
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1098,6 +1106,7 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
+
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index fa0be9e86..b79e9aef7 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,3 +1,4 @@
+
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 312c9c74b..94b34dee1 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,3 +1,4 @@
+
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index 0ba33b7d8..e413367ef 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -38,6 +38,7 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
+
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index d48eea5e4..a51f2ffb0 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
+
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index ef478e268..9c9542661 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,3 +1,4 @@
+
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index 0d4c9a0df..b96d19182 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,3 +1,4 @@
+
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 00d08265a..48d260ed6 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,3 +1,4 @@
+
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 5e832aa19..be5871ed9 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,3 +1,4 @@
+
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -13,6 +14,7 @@ import {
type MarkdownlintSlice,
} from './types.ts';
+
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 3918e657c..833c3a727 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,3 +1,4 @@
+
export const LINT_PLUGIN_IDS = ['markdownlint', 'frontmatter'] as const;
export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];
@@ -71,6 +72,7 @@ export interface FrontmatterSlice {
schemas: ResolvedFrontmatterSchemaEntry[];
}
+
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 98238656e..437cc539a 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,3 +1,4 @@
+
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index a5b511f25..bd79424c7 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index ed89371d0..00fbc0035 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index 8ce2b2492..df788a80d 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 1a897fca8..17ed2b829 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index d988f4b8b..4aa0490c4 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,6 +168,7 @@ export function parseRecursive(
}
}
+
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
+
interface Region {
start: number;
end: number;
@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
+
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
+
interface SourceBlock {
src: string;
start: number;
@@ -452,6 +456,7 @@ function tryPerBlockFallback(
};
}
+
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index e6ab4fd57..43d420187 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,3 +1,4 @@
+
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 449e6f12f..5af2f05f5 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 91cdf658f..ccf06e94d 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,3 +1,4 @@
+
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 0f399d34c..e5b4c9eba 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- } else if (first === '[') {
+ }
+ else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index db10fa54b..ca225ce9b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 34068d103..3a2524a9a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 93151d43b..2279a0189 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index 188f02d83..a0f467c42 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4ba2c3418..4e8542a21 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index 1a74b1272..a3c96b24a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index de35e7b79..e95cf43d6 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index b4be1b2ea..ffdb4d5b5 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index 3c8d88b7c..e2a96d1a7 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index cf2c9da8e..0389575ac 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,3 +1,4 @@
+
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 0dd54070e..96304e7a5 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,3 +1,4 @@
+
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 7cac5b042..93798cf83 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,3 +1,4 @@
+
import type { Node as PmNode } from '@tiptap/pm/model';
import type {
MdxJsxAttribute,
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index b012a5aff..8c08b7a04 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 3e79f8cb6..959cc0bd2 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 0f1b0f27d..6e6d73400 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 1a082bda7..932d7d2a8 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,3 +1,4 @@
+
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index d578476a7..ac9f5239b 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,3 +1,4 @@
+
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index 6dad26200..afd9936fe 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {
}
}
+
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {
};
}
+
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
+
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 6a70bd43a..03d57f0cc 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -1605,6 +1605,21 @@ function ensureWindowManager() {
// Best-effort.
}
}
+ // Observe how the child dies. Exit code + signal are the only
+ // failure evidence always available to the parent: a child can die
+ // having written nothing to the capture log (killed by a signal,
+ // or reporting on stdout, which is not captured), and without this
+ // the caller cannot tell "still starting" from "died 200ms ago".
+ // Retaining a listener also keeps Node reaping the child rather
+ // than leaving it defunct in the process table.
+ //
+ // Order matters: registered before `unref()` so an exit in the
+ // handshake window is not missed. `unref()` releases the
+ // event-loop reference only; it does not detach listeners.
+ let exitRecord: { code: number | null; signal: string | null } | null = null;
+ childRef.on('exit', (code, signal) => {
+ exitRecord = { code, signal };
+ });
childRef.unref();
const pid = childRef.pid;
if (pid === undefined) {
@@ -1613,7 +1628,7 @@ function ensureWindowManager() {
'spawnDetachedServer: child_process.spawn did not return a pid after spawn-event resolution.',
);
}
- return { pid };
+ return { pid, readExit: () => exitRecord };
},
}
: {}),
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index d05dd8931..73376988d 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -500,6 +500,20 @@ export interface WindowManagerDeps {
projectDir?: string;
}): Promise<{
pid: number;
+ /**
+ * How the child died, or `null` while it is still running.
+ *
+ * The parent has no other channel for a reason. `stdio` captures the
+ * child's output to `SPAWN_ERROR_LOG`, but a child can exit having written
+ * nothing there — a failure reported on stdout, or a signal death — which
+ * leaves the operator with a bare deadline and no way to tell a fast crash
+ * from a slow start. Exit code + signal are the two facts always available
+ * to the parent, so they must not be dropped.
+ *
+ * Optional: callers that spawn without observing exit (and every existing
+ * test stub) stay valid, and the poll degrades to the deadline.
+ */
+ readExit?: () => { code: number | null; signal: string | null } | null;
}>;
/**
* Create the throwaway `projectDir` for an ephemeral single-file session
@@ -1689,8 +1703,15 @@ export class WindowManager {
});
this.spawnedDetachedPids.set(canonicalKey, handle.pid);
const POLL_DEADLINE_MS = this.deps.spawnLockPollDeadlineMs ?? 15_000;
- const lock = await this.pollServerLock(lockDir, POLL_DEADLINE_MS);
+ const lock = await this.pollServerLock(lockDir, POLL_DEADLINE_MS, handle);
if (lock === null) {
+ // Both sampled BEFORE the SIGTERM below — afterwards they would be
+ // observing our own kill and would report a merely-slow child as
+ // having crashed. `childExited` is `undefined` when there is no probe.
+ const childExited = this.deps.isProcessAlive
+ ? !this.deps.isProcessAlive(handle.pid)
+ : undefined;
+ const childExit = handle.readExit?.() ?? null;
// The detached spawn is `.unref()`ed, so a server that started but
// failed to bind a port (or stalled before writing its lock) will
// continue running as an orphan after we throw. Idle-shutdown may
@@ -1718,31 +1739,16 @@ export class WindowManager {
}
}
this.spawnedDetachedPids.delete(canonicalKey);
- // Read the spawned child's stderr capture so the surfaced error
- // points at the actual failure (port-bind error, missing native
- // dep, bootServer init throw) instead of leaving the user with a
- // generic 15-second timeout. Bound the tail so a runaway log
- // doesn't blow up the error envelope. Best-effort: missing log
- // file just falls through with no `stderrTail`.
- const STDERR_TAIL_BYTES = 8192;
- let stderrTail: string | undefined;
- try {
- const raw = readFileSync(join(lockDir, SPAWN_ERROR_LOG), 'utf-8');
- stderrTail = raw.length > STDERR_TAIL_BYTES ? `…${raw.slice(-STDERR_TAIL_BYTES)}` : raw;
- } catch {
- // Best-effort: the spawn might have died before opening the fd.
- }
- const messageBase = `OpenKnowledge server did not bind a port within ${POLL_DEADLINE_MS}ms after spawn (pid=${handle.pid}).`;
- const err = Object.assign(
- new Error(stderrTail ? `${messageBase}\n--- stderr ---\n${stderrTail}` : messageBase),
- {
- name: 'SpawnLockTimeoutError' as const,
- kind: 'spawn-lock-timeout' as const,
- pid: handle.pid,
- ...(stderrTail !== undefined && { stderrTail }),
- },
- );
- throw err;
+ // Surface the child's own account of the failure (exit code/signal,
+ // plus its captured stderr) rather than only the deadline.
+ throw this.buildSpawnFailureError({
+ pid: handle.pid,
+ exit: childExit,
+ lockDir,
+ deadlineMs: POLL_DEADLINE_MS,
+ spawnLabel: 'spawn',
+ childExited,
+ });
}
this.deps.log?.info(
{ event: 'desktop-server-spawned-detached', pid: handle.pid, port: lock.port, lockDir },
@@ -2145,7 +2151,10 @@ export class WindowManager {
const lockDir = getLocalDir(tempProjectDir);
const reactShellDistDir = dirname(this.deps.rendererEntryPath);
- let handle: { pid: number };
+ // Derived from the dep rather than hand-written, so the handle keeps every
+ // field the spawn actually returns (the exit record among them) instead of
+ // being silently narrowed away by a stale local annotation.
+ let handle: Awaited<ReturnType<NonNullable<WindowManagerDeps['spawnDetachedServer']>>>;
try {
handle = await spawnDetachedServer({
contentDir: opts.contentDir,
@@ -2161,8 +2170,15 @@ export class WindowManager {
}
const POLL_DEADLINE_MS = this.deps.spawnLockPollDeadlineMs ?? 15_000;
- const lock = await this.pollServerLock(lockDir, POLL_DEADLINE_MS);
+ const lock = await this.pollServerLock(lockDir, POLL_DEADLINE_MS, handle);
if (lock === null) {
+ // Both sampled BEFORE the SIGTERM below — see the project-open path.
+ // This path additionally awaits `removeDir` before throwing, so a
+ // re-read after the kill would very likely observe it.
+ const childExited = this.deps.isProcessAlive
+ ? !this.deps.isProcessAlive(handle.pid)
+ : undefined;
+ const childExit = handle.readExit?.() ?? null;
// Server never bound — SIGTERM the orphan (the spawn is `.unref()`ed, so a
// half-started server would otherwise leak), remove the temp dir, and
// surface the captured stderr (same shape as the project spawn-timeout).
@@ -2183,24 +2199,14 @@ export class WindowManager {
}
}
await removeDir(tempProjectDir).catch(() => {});
- const STDERR_TAIL_BYTES = 8192;
- let stderrTail: string | undefined;
- try {
- const raw = readFileSync(join(lockDir, SPAWN_ERROR_LOG), 'utf-8');
- stderrTail = raw.length > STDERR_TAIL_BYTES ? `…${raw.slice(-STDERR_TAIL_BYTES)}` : raw;
- } catch {
- // Best-effort: the spawn might have died before opening the fd.
- }
- const messageBase = `OpenKnowledge server did not bind a port within ${POLL_DEADLINE_MS}ms after ephemeral spawn (pid=${handle.pid}).`;
- throw Object.assign(
- new Error(stderrTail ? `${messageBase}\n--- stderr ---\n${stderrTail}` : messageBase),
- {
- name: 'SpawnLockTimeoutError' as const,
- kind: 'spawn-lock-timeout' as const,
- pid: handle.pid,
- ...(stderrTail !== undefined && { stderrTail }),
- },
- );
+ throw this.buildSpawnFailureError({
+ pid: handle.pid,
+ exit: childExit,
+ lockDir,
+ deadlineMs: POLL_DEADLINE_MS,
+ spawnLabel: 'ephemeral spawn',
+ childExited,
+ });
}
const port = lock.port;
@@ -2370,18 +2376,107 @@ export class WindowManager {
return true;
}
+ /**
+ * Build the error for a detached spawn that never produced a usable lock.
+ *
+ * Two distinct failures reach here and they need different framings. A child
+ * that is still running simply missed the deadline — the deadline is the
+ * story. A child that has already exited did not "take too long"; it died,
+ * and reporting a 15-second timeout for a crash that happened in 200 ms sends
+ * the reader looking for a slow start that never occurred. That
+ * misdescription is the reported defect, so the framing is chosen from
+ * observed liveness rather than fixed.
+ *
+ * Takes the child's state as already-observed values rather than probing for
+ * it, because BOTH facts must be sampled at one instant: the moment the poll
+ * gave up, before the orphan SIGTERM. Re-reading either one here would let
+ * our own kill land in between and be reported as the child's failure — a
+ * merely-slow child described as `killed by SIGTERM`.
+ *
+ * `childExited: undefined` means liveness was never probed (no
+ * `isProcessAlive` wired), which is distinct from "probed and alive": the
+ * message may only claim the process was running when that was observed.
+ */
+ private buildSpawnFailureError(opts: {
+ pid: number;
+ exit: { code: number | null; signal: string | null } | null;
+ lockDir: string;
+ deadlineMs: number;
+ spawnLabel: string;
+ childExited: boolean | undefined;
+ }): Error {
+ const { pid, exit, lockDir, deadlineMs, spawnLabel, childExited } = opts;
+ // Bound the tail so a runaway log doesn't blow up the error envelope.
+ // Best-effort: a missing log file just falls through with no `stderrTail`.
+ const STDERR_TAIL_BYTES = 8192;
+ let stderrTail: string | undefined;
+ try {
+ const raw = readFileSync(join(lockDir, SPAWN_ERROR_LOG), 'utf-8');
+ stderrTail = raw.length > STDERR_TAIL_BYTES ? `…${raw.slice(-STDERR_TAIL_BYTES)}` : raw;
+ } catch (readErr) {
+ // An absent log is expected — the child can die before opening the fd.
+ // Anything else (permissions, a bad path) would otherwise vanish here and
+ // leave the failure report silently thinner than it should be, on the one
+ // path whose entire job is explaining a failure.
+ const code = (readErr as NodeJS.ErrnoException).code;
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') {
+ this.deps.log?.warn(
+ { event: 'desktop-spawn-error-log-read-failed', err: readErr, code, lockDir },
+ '[window-manager] could not read the spawn error log',
+ );
+ }
+ }
+
+ const exited = exit !== null || childExited === true;
+
+ let messageBase: string;
+ if (exited) {
+ const reason =
+ exit === null
+ ? ''
+ : exit.signal !== null
+ ? `, killed by ${exit.signal}`
+ : exit.code !== null
+ ? `, exit code ${exit.code}`
+ : '';
+ messageBase = `OpenKnowledge server exited before binding a port (pid=${pid}${reason}).`;
+ } else {
+ // A crash and a hung start otherwise render as the same bare deadline,
+ // leaving no way to tell which happened. Saying the process was still
+ // running names this as the slow/stuck case — but only when liveness was
+ // actually observed, never as an assumption.
+ const liveness = childExited === false ? ', still running' : '';
+ messageBase = `OpenKnowledge server did not bind a port within ${deadlineMs}ms after ${spawnLabel} (pid=${pid}${liveness}).`;
+ }
+
+ return Object.assign(
+ new Error(stderrTail ? `${messageBase}\n--- stderr ---\n${stderrTail}` : messageBase),
+ {
+ name: 'SpawnLockTimeoutError' as const,
+ // Discriminant held stable across both framings — `index.ts` branches
+ // on it, and the distinction between the two lives in the exit fields.
+ kind: 'spawn-lock-timeout' as const,
+ pid,
+ ...(exit !== null && { exitCode: exit.code, exitSignal: exit.signal }),
+ ...(stderrTail !== undefined && { stderrTail }),
+ },
+ );
+ }
+
/**
* Poll `<lockDir>/server.lock` until a valid lock appears with `port > 0`
- * and a known `kind`, or until `deadlineMs` elapses. Used by the detached-
- * spawn path to wait for the freshly-spawned CLI to bind a port and write
- * its lock atomically (the lock writer in `bootServer` only flips port from
- * `0` to the bound port after `httpServer.listen` resolves, so seeing
- * `port > 0` is the readiness signal).
+ * and a known `kind`, or until `deadlineMs` elapses — or, when `child` is
+ * supplied, until that child is observed to have exited (a dead child will
+ * never publish a lock, so the rest of the deadline is dead time). Used by
+ * the detached-spawn path to wait for the freshly-spawned CLI to bind a port
+ * and write its lock atomically (the lock writer in `bootServer` only flips
+ * port from `0` to the bound port after `httpServer.listen` resolves, so
+ * seeing `port > 0` is the readiness signal).
*
- * Returns the parsed lock metadata on success, or `null` on timeout. When
- * `readServerLock` is not wired in `deps` (back-compat with tests that
- * don't exercise the detached path), returns `null` immediately — the
- * caller propagates that as a spawn-failure error.
+ * Returns the parsed lock metadata on success, or `null` on timeout or child
+ * death. When `readServerLock` is not wired in `deps` (back-compat with
+ * tests that don't exercise the detached path), returns `null` immediately —
+ * the caller propagates that as a spawn-failure error.
*
* Polling cadence: 50 ms. Uses `deps.setTimeout` so test injections that
* fire the timer synchronously make the loop deterministic.
@@ -2389,10 +2484,12 @@ export class WindowManager {
private async pollServerLock(
lockDir: string,
deadlineMs: number,
+ child?: { pid: number },
): Promise<ServerLockMetadataLike | null> {
const POLL_INTERVAL_MS = 50;
const reader = this.deps.readServerLock;
if (!reader) return null;
+ const isAlive = this.deps.isProcessAlive;
const deadline = Date.now() + deadlineMs;
while (Date.now() < deadline) {
const lock = reader(lockDir);
@@ -2402,6 +2499,25 @@ export class WindowManager {
if (lock !== null && lock.draining !== true && lock.port > 0 && lock.kind !== undefined) {
return lock;
}
+ // Liveness, not wall-clock, ends the wait once the child is gone: a dead
+ // child will never publish a lock, so the rest of the deadline is dead
+ // time, and spending it reframes a fast crash as a slow start.
+ //
+ // Checked AFTER the lock read — a child that bound and then exited still
+ // leaves a usable lock, and that read must win.
+ //
+ // The exception is load-bearing: the lock is keyed by PROJECT, not by
+ // process. When a concurrent starter wins the acquire, our child exits
+ // BY DESIGN (a lock collision) while the winner is still on its way to
+ // binding — the documented `port=0`-but-not-yet-bound window. Bailing on
+ // our child's death would then report a failure that another process is
+ // about to resolve. A non-draining lock held by a different, live pid is
+ // exactly that signal, so keep waiting for the winner to publish a port.
+ if (child !== undefined && isAlive !== undefined && !isAlive(child.pid)) {
+ const winnerStillStarting =
+ lock !== null && lock.draining !== true && lock.pid !== child.pid && isAlive(lock.pid);
+ if (!winnerStillStarting) return null;
+ }
await new Promise<void>((resolveSleep) => {
this.deps.setTimeout(() => {
resolveSleep();
diff --git a/packages/desktop/tests/integration/detached-lifecycle.test.ts b/packages/desktop/tests/integration/detached-lifecycle.test.ts
index 105fb466b..28a18b93a 100644
--- a/packages/desktop/tests/integration/detached-lifecycle.test.ts
+++ b/packages/desktop/tests/integration/detached-lifecycle.test.ts
@@ -191,4 +191,70 @@ describe('detached-server lifecycle integration', () => {
}
}
}, 60_000);
+
+ /**
+ * Pins the Node-level assumption the spawn-failure reporting rests on.
+ *
+ * `spawnDetachedServer` reports a child's exit code/signal by attaching an
+ * `'exit'` listener and then calling `.unref()`. That is only sound if
+ * `unref()` releases the event-loop reference WITHOUT detaching listeners —
+ * true, but a semantic that is easy to regress by reordering the two calls,
+ * and not something reading the code can confirm. A real detached child is
+ * the only way to check it.
+ *
+ * Without this, a reordering would silently restore the original defect: the
+ * parent again learns nothing about how the child died.
+ */
+ test('an unref-ed detached child still reports its exit code and signal', async () => {
+ async function captureExit(
+ args: string[],
+ ): Promise<{ code: number | null; signal: string | null }> {
+ const child = spawn(process.execPath, args, { detached: true, stdio: 'ignore' });
+ await new Promise<void>((res, rej) => {
+ child.once('spawn', res);
+ child.once('error', rej);
+ });
+
+ // Same order as production: listener first, then unref.
+ let exitRecord: { code: number | null; signal: string | null } | null = null;
+ child.on('exit', (code, signal) => {
+ exitRecord = { code, signal };
+ });
+ child.unref();
+
+ const deadline = Date.now() + 10_000;
+ while (exitRecord === null && Date.now() < deadline) {
+ await wait(25);
+ }
+ if (exitRecord === null) throw new Error('child exit was never observed');
+ return exitRecord;
+ }
+
+ expect(await captureExit(['-e', 'process.exit(3)'])).toEqual({ code: 3, signal: null });
+ }, 30_000);
+
+ test('a signal-killed detached child reports the signal, not an exit code', async () => {
+ const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60000)'], {
+ detached: true,
+ stdio: 'ignore',
+ });
+ await new Promise<void>((res, rej) => {
+ child.once('spawn', res);
+ child.once('error', rej);
+ });
+
+ let exitRecord: { code: number | null; signal: string | null } | null = null;
+ child.on('exit', (code, signal) => {
+ exitRecord = { code, signal };
+ });
+ child.unref();
+
+ process.kill(child.pid as number, 'SIGKILL');
+
+ const deadline = Date.now() + 10_000;
+ while (exitRecord === null && Date.now() < deadline) {
+ await wait(25);
+ }
+ expect(exitRecord).toEqual({ code: null, signal: 'SIGKILL' });
+ }, 30_000);
});
diff --git a/packages/desktop/tests/main/window-manager-ephemeral.test.ts b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
index 1837feb31..af40ce0d2 100644
--- a/packages/desktop/tests/main/window-manager-ephemeral.test.ts
+++ b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
@@ -330,6 +330,42 @@ describe('createEphemeralWindow', () => {
expect(env.windows).toHaveLength(0);
});
+ // This path SIGTERMs the orphan and then awaits `removeDir` before throwing.
+ // The child therefore dies, and its exit record lands, inside that await. If
+ // the error consulted the exit record at throw time it would report our own
+ // kill as the child's failure — a merely-slow start described as "killed by
+ // SIGTERM", with the deadline dropped from the message entirely.
+ test('a slow child killed by our own SIGTERM is not reported as having crashed', async () => {
+ env.publishLock = false; // server never publishes its lock
+ env.deps.spawnLockPollDeadlineMs = 0; // deadline already elapsed, child still alive
+
+ // The exit record appears only once WE signal, mirroring production where
+ // the 'exit' listener fires during the removeDir await.
+ let exitRecord: { code: number | null; signal: string | null } | null = null;
+ const recordingKill = env.deps.killProbe;
+ env.deps.killProbe = (pid, signal) => {
+ recordingKill(pid, signal);
+ if (signal === 'SIGTERM') exitRecord = { code: null, signal: 'SIGTERM' };
+ };
+ env.deps.spawnDetachedServer = async () => ({ pid: 42001, readExit: () => exitRecord });
+
+ const wm = new WindowManager(env.deps);
+ const err = await wm
+ .createEphemeralWindow({ canonicalFilePath: FILE, contentDir: PARENT, docName: 'todo' })
+ .then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ // Reported as what it was: a deadline reached with the process alive.
+ expect(err?.message).toMatch(/did not bind a port/);
+ expect(err?.message).not.toMatch(/killed by SIGTERM/);
+ expect(err?.message).not.toMatch(/exited before binding/);
+ // The orphan is still signalled and the temp dir still cleaned up.
+ expect(env.killCalls).toContainEqual({ pid: 42001, signal: 'SIGTERM' });
+ expect(env.removedDirs).toEqual(['/tmp/ok-ephemeral-1']);
+ });
+
test('a spawn failure removes the temp dir before rethrowing (no leak)', async () => {
env.deps.spawnDetachedServer = async () => {
throw Object.assign(new Error('spawn boom'), { kind: 'spawn-error' });
diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.ts
index 90caef2a2..a5803ca96 100644
--- a/packages/desktop/tests/main/window-manager.test.ts
+++ b/packages/desktop/tests/main/window-manager.test.ts
@@ -1536,6 +1536,194 @@ describe('WindowManager', () => {
expect(pids.size).toBe(0);
});
+ // A hung start and a crash otherwise render as the same bare deadline.
+ // Naming the surviving process is what lets the reader tell them apart.
+ test('a deadline reached with the child alive says the process was still running', async () => {
+ enableSyncTimers();
+ env.deps.readServerLock = () => null;
+ env.deps.isProcessAlive = () => true;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: 88001 });
+ env.deps.spawnLockPollDeadlineMs = 1;
+
+ const wm = new WindowManager(env.deps);
+ const err = await wm.createProjectWindow({ projectPath: '/tmp/slow-child' }).then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ expect(err?.message).toMatch(/did not bind a port/);
+ expect(err?.message).toMatch(/still running/);
+ });
+
+ // Never claim liveness that was not observed: with no probe wired, the
+ // message must stay agnostic rather than assert a state we cannot see.
+ test('with no liveness probe wired the message claims nothing about the process', async () => {
+ enableSyncTimers();
+ env.deps.readServerLock = () => null;
+ env.deps.isProcessAlive = undefined;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: 88001 });
+ env.deps.spawnLockPollDeadlineMs = 1;
+
+ const wm = new WindowManager(env.deps);
+ const err = await wm.createProjectWindow({ projectPath: '/tmp/unprobed' }).then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ expect(err?.message).toMatch(/did not bind a port/);
+ expect(err?.message).not.toMatch(/still running/);
+ expect(err?.message).not.toMatch(/exited before binding/);
+ });
+
+ // The sibling case to the test above: there, the child is ALIVE and
+ // simply never binds, so waiting out the deadline is the correct
+ // behavior. Here the child is DEAD. Waiting is then pure dead time, and
+ // the deadline framing ("did not bind a port within 15000ms") actively
+ // misdescribes a fast crash as a slow start.
+ test('a dead child ends the lock poll immediately instead of waiting out the deadline', async () => {
+ enableSyncTimers();
+ let readCount = 0;
+ env.deps.readServerLock = () => {
+ readCount++;
+ return null;
+ };
+ // Child exited between spawn and the first poll tick.
+ env.deps.isProcessAlive = () => false;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: 88001 });
+ // A realistic deadline. The poll must NOT consume it: liveness, not
+ // wall-clock, is what ends the wait once the child is gone.
+ env.deps.spawnLockPollDeadlineMs = 500;
+
+ const wm = new WindowManager(env.deps);
+ const err = await wm.createProjectWindow({ projectPath: '/tmp/dead-child' }).then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ expect(err).toMatchObject({ pid: 88001 });
+ // Framed as a death, not as a deadline — reporting "did not bind within
+ // 500ms" for a child that died immediately is the original defect.
+ expect(err?.message).toMatch(/exited before binding a port/);
+ expect(err?.message).not.toMatch(/did not bind a port/);
+
+ // Bounded, not exhaustive. Spinning the full 500ms window produces
+ // reads in the thousands; noticing the death costs a handful.
+ expect(readCount).toBeLessThanOrEqual(3);
+ });
+
+ // The lock is keyed by project, not by process. A concurrent starter that
+ // wins the acquire makes OUR child exit by design, while the winner is
+ // still mid-bind (lock present, port still 0). Treating our child's death
+ // as "no lock is coming" would report a failure another process is about
+ // to resolve — the project would fail to open where it previously did.
+ test('a losing child does not abort the wait while a live winner is still binding', async () => {
+ enableSyncTimers();
+ const WINNER_PID = 77001;
+ const winnerLock = (port: number): ServerLockMetadataLike => ({
+ pid: WINNER_PID,
+ hostname: 'my-host',
+ port,
+ startedAt: '2026-08-05T00:00:00.000Z',
+ worktreeRoot: '/tmp/contended',
+ kind: 'interactive',
+ capabilities: ['ws'],
+ });
+
+ // Winner holds the lock at port 0 (acquired, not yet bound), then binds.
+ let reads = 0;
+ env.deps.readServerLock = () => {
+ reads++;
+ if (reads === 1) return null; // pre-spawn attach gate: nothing usable yet
+ if (reads < 4) return winnerLock(0); // winner acquired, still binding
+ return winnerLock(52999); // winner bound
+ };
+ // Our spawned child lost the acquire and exited; the winner is alive.
+ env.deps.isProcessAlive = (pid) => pid === WINNER_PID;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: 88001 });
+ env.deps.spawnLockPollDeadlineMs = 500;
+
+ const wm = new WindowManager(env.deps);
+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/contended' });
+
+ // Attached to the winner rather than erroring on our child's death.
+ expect(ctx.port).toBe(52999);
+ expect(env.windows.length).toBe(1);
+ });
+
+ test('a child that exits before binding surfaces its exit code and signal', async () => {
+ enableSyncTimers();
+ env.deps.readServerLock = () => null;
+ env.deps.isProcessAlive = () => false;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ // The spawn handle reports how the child died. `readExit` returns null
+ // while it is still running and the exit record once it has exited —
+ // the parent's only channel for a reason, since stdout/stderr may be
+ // empty (the reported failure had an empty capture log).
+ env.deps.spawnDetachedServer = () =>
+ Promise.resolve({
+ pid: 88001,
+ readExit: () => ({ code: 1, signal: null }),
+ });
+ env.deps.spawnLockPollDeadlineMs = 500;
+
+ const wm = new WindowManager(env.deps);
+ await expect(
+ wm.createProjectWindow({ projectPath: '/tmp/exited-child' }),
+ ).rejects.toMatchObject({ pid: 88001, exitCode: 1, exitSignal: null });
+ });
+
+ test('a signal-killed child surfaces the signal in its error message', async () => {
+ enableSyncTimers();
+ env.deps.readServerLock = () => null;
+ env.deps.isProcessAlive = () => false;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.spawnDetachedServer = () =>
+ Promise.resolve({
+ pid: 88001,
+ readExit: () => ({ code: null, signal: 'SIGKILL' }),
+ });
+ env.deps.spawnLockPollDeadlineMs = 500;
+
+ const wm = new WindowManager(env.deps);
+ const err = await wm.createProjectWindow({ projectPath: '/tmp/killed-child' }).then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ // The reason belongs in the message, not only in a structured field —
+ // this string is what reaches the user in the "Unable to open project"
+ // dialog, and a bare deadline there is the reported complaint.
+ expect(err?.message).toMatch(/SIGKILL/);
+ });
+
+ // Degradation guard: a handle with no exit record (child still running,
+ // or a caller that predates `readExit`) must still produce the ordinary
+ // timeout rather than throwing on an absent accessor.
+ test('an unavailable exit record still yields the ordinary timeout error', async () => {
+ enableSyncTimers();
+ env.deps.readServerLock = () => null;
+ env.deps.isProcessAlive = () => true;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: 88001, readExit: () => null });
+ env.deps.spawnLockPollDeadlineMs = 1;
+
+ const wm = new WindowManager(env.deps);
+ await expect(
+ wm.createProjectWindow({ projectPath: '/tmp/still-running' }),
+ ).rejects.toMatchObject({ kind: 'spawn-lock-timeout', pid: 88001 });
+ });
+
test('detached-mode window close: no shutdown IPC, no spawn pid removal', async () => {
enableSyncTimers();
// Same attach-then-spawn split as the previous test: first read no