Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Stop ok stop from killing another channel's server (#5516)
tim-inkeep6a14330fec41
diff --git a/.changeset/stop-refuses-other-channel.md b/.changeset/stop-refuses-other-channel.mdnew file mode 100644index 000000000..5f709b469--- /dev/null+++ b/.changeset/stop-refuses-other-channel.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++`ok stop` no longer stops a project server that another OpenKnowledge app (Stable, Beta) started; it names that app and asks you to stop it there, or pass `--force`.diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex 5d72fb8a4..520c9286e 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -124,7 +124,7 @@ Each project runs its own local server. These commands let you see and stop them| --- | --- || `ok status` | Show whether a server and UI are running for the current project || `ok ps` | List every running OpenKnowledge server on your machine |-| `ok stop` | Stop the server for the current directory — or pass a port, path, or PID to stop a specific server, or `all` to stop every server. Declines when something is still connected to the target, naming how many clients are attached; pass `--force` to stop it anyway. A server it cannot reach is stopped without the check |+| `ok stop` | Stop the server for the current directory — or pass a port, path, or PID to stop a specific server, or `all` to stop every server. Declines when the server's lock records a different OpenKnowledge app (Stable or Beta) than [the CLI's own](/docs/reference/what-open-knowledge-writes#beta-uses-its-own-entry), naming that app, and when something is still connected to the target, naming how many clients are attached. Either way it exits `1`; pass `--force` to stop it anyway. A lock with no recorded app is stopped as before, and a server it cannot reach is stopped without the connected-clients check || `ok clean` | Remove a stale lock file left behind by a crash (never touches live servers) |`ok clean` retains a lock and exits `1` if it cannot read it, it records another machine, or it has no recorded owner and its PID is still running locally. A PID that has exited is not running even while it lingers as a defunct entry in the process table, so `ok clean` prunes the lock naming it. The error names the lock and explains what to check. For an unverified owner, inspect the named local PID and stop it if it is an OpenKnowledge server; do not delete the lock while that process is running.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 0a2fe9409..6eab6fe44 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -173,7 +173,7 @@ On each launch and project open, the app also runs **repair sweeps**: it rewriteOnly one OpenKnowledge app serves a project at a time. `server.lock` records which product started the server, resolved the same way a [CLI process picks its product](#beta-uses-its-own-entry). When OpenKnowledge Beta opens a project that Stable is serving, or the other way round, it does not connect to that server, take it over, or stop it on its own. It shows **This project is open in another OpenKnowledge app**, naming the app that holds it (for example **OpenKnowledge (Stable)**), and **Restart server** reports that the other app keeps the project. A lock that names a product this app does not know gets the same treatment. The same dialog appears when another app's lock blocks the open in other ways too: its server is not answering, a server of this app collided with that lock, or a new server timed out because that lock was already held. This dialog is the only way the app stops another app's server.-Closing the other app's window does not free the project, because its server keeps running in the background. To move the project, choose the dialog's **Stop … Server & Open Here** button (for example **Stop OpenKnowledge (Stable) Server & Open Here**). Every window, editor, or agent connected to that server loses its connection to the project. Cancel is the default and stops nothing. From a terminal, `ok stop` in the project folder does the same.+Closing the other app's window does not free the project, because its server keeps running in the background. To move the project, choose the dialog's **Stop … Server & Open Here** button (for example **Stop OpenKnowledge (Stable) Server & Open Here**). Every window, editor, or agent connected to that server loses its connection to the project. Cancel is the default and stops nothing. From a terminal, `ok stop --force` in the project folder does the same. Without `--force`, `ok stop` declines, and exits `1`, when the lock names a different app than the one its CLI resolves to.A server you start with `ok start`, or one an editor's MCP connection starts, counts as the product its CLI resolves to. Under plain Node that is Stable unless `OK_CHANNEL=beta` is set, so OpenKnowledge Beta also refuses a project served that way. A server an editor's MCP connection started does not stop when that session ends. It stops on its own once nothing has had the project open for a while (30 minutes by default), so you can also wait for it. Stopping it from the dialog interrupts whatever the agent or editor is doing right now, and the agent's next request reaches the server the app opened.diff --git a/packages/cli/src/commands/stop.test.ts b/packages/cli/src/commands/stop.test.tsindex bc98591c3..8aae827a9 100644--- a/packages/cli/src/commands/stop.test.ts+++ b/packages/cli/src/commands/stop.test.ts@@ -172,6 +172,97 @@ describe('runStop with foreign-host states', () => {});});+describe('runStop channel guard', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ const lockOf = (channel: string | undefined, state = aliveLock(100, 3001)): LockState =>+ (state.status === 'alive' || state.status === 'foreign-host') && channel !== undefined+ ? { ...state, lock: { ...state.lock, channel } }+ : state;+ const run = (+ channel: string | undefined,+ overrides: Partial<Parameters<typeof runStop>[0]> = {},+ ) => {+ const killed: Array<[number, string]> = [];+ const errors: string[] = [];+ const outcome = runStop({+ lockDir: '/tmp/channel',+ inspect: () => lockOf(channel),+ selfChannel: 'beta',+ kill: (pid, sig) => killed.push([pid, sig]),+ log: () => {},+ error: (msg) => errors.push(msg),+ probeClients: async () => 0,+ ...overrides,+ });+ return { outcome, killed, errors };+ };++ test("refuses to stop another channel's server", async () => {+ const { outcome, killed, errors } = run('stable');+ expect((await outcome).declined).toEqual({ otherChannel: 'stable' });+ expect(killed).toEqual([]);+ expect(errors[0]).toContain('OpenKnowledge (Stable)');+ expect(errors[0]).toContain('--force');+ });++ test("--force stops another channel's server", async () => {+ const { outcome, killed } = run('stable', { force: true });+ expect((await outcome).stopped).toHaveLength(1);+ expect(killed).toEqual([[100, 'SIGTERM']]);+ });++ test('stops a server of the same channel', async () => {+ const { outcome, killed } = run('beta');+ expect((await outcome).declined).toBeUndefined();+ expect(killed).toEqual([[100, 'SIGTERM']]);+ });++ test('stops a server whose lock records no channel', async () => {+ const { outcome, killed } = run(undefined);+ expect((await outcome).declined).toBeUndefined();+ expect(killed).toEqual([[100, 'SIGTERM']]);+ });++ test("OK_CHANNEL=beta refuses Stable's server", async () => {+ vi.stubEnv('OK_CHANNEL', 'beta');+ const { outcome, killed } = run('stable', { selfChannel: undefined });+ expect((await outcome).declined).toEqual({ otherChannel: 'stable' });+ expect(killed).toEqual([]);+ });++ test("OK_CHANNEL=stable stops Stable's server", async () => {+ vi.stubEnv('OK_CHANNEL', 'stable');+ const { outcome, killed } = run('stable', { selfChannel: undefined });+ expect((await outcome).declined).toBeUndefined();+ expect(killed).toEqual([[100, 'SIGTERM']]);+ });++ test('an unsupported OK_CHANNEL skips the check, warns, and stops as before', async () => {+ vi.stubEnv('OK_CHANNEL', 'bogus');+ const warnings: string[] = [];+ const logger = {+ info: () => {},+ warn: (_obj: unknown, msg: string) => warnings.push(msg),+ } as unknown as Parameters<typeof runStop>[0]['logger'];+ const { outcome, killed } = run('stable', { selfChannel: undefined, logger });+ expect((await outcome).declined).toBeUndefined();+ expect(killed).toEqual([[100, 'SIGTERM']]);+ expect(warnings.some((msg) => msg.includes('Unsupported OK_CHANNEL'))).toBe(true);+ });++ test('refuses a foreign-host lock of another channel whose pid is alive here', async () => {+ const { outcome, killed } = run('stable', {+ inspect: () => lockOf('stable', foreign(100, 3001)),+ isAlive: () => true,+ });+ expect((await outcome).declined).toEqual({ otherChannel: 'stable' });+ expect(killed).toEqual([]);+ });+});+describe('runStop in-use guard', () => {const oneAlive = () => ({lockDir: '/tmp/guard',diff --git a/packages/cli/src/commands/stop.ts b/packages/cli/src/commands/stop.tsindex f3a22208c..c1a38ffe5 100644--- a/packages/cli/src/commands/stop.ts+++ b/packages/cli/src/commands/stop.ts@@ -1,4 +1,5 @@import { resolve } from 'node:path';+import { desktopChannelLabel, resolveDesktopProductName } from '@inkeep/open-knowledge-core';import {type Config,isProcessAlive,@@ -90,13 +91,26 @@ interface RunStopDeps {error?: (msg: string) => void;probeClients?: (lockDir: string, logger?: PinoLoggerInstance) => Promise<number | null>;logger?: PinoLoggerInstance;+ selfChannel?: 'stable' | 'beta';}interface StopOutcome {stopped: StopTargetPlan[];failed: Array<{ target: StopTargetPlan; error: string }>;hadTargets: boolean;- declined?: { clients: number };+ declined?: { clients: number } | { otherChannel: string };+}++function currentChannel(logger: PinoLoggerInstance | undefined): RunStopDeps['selfChannel'] {+ try {+ return resolveDesktopProductName();+ } catch (err) {+ logger?.warn(+ { err },+ `stop channel check skipped: ${err instanceof Error ? err.message : String(err)}`,+ );+ return undefined;+ }}export async function runStop(deps: RunStopDeps): Promise<StopOutcome> {@@ -116,6 +130,30 @@ export async function runStop(deps: RunStopDeps): Promise<StopOutcome> {return { stopped: [], failed: [], hadTargets: false };}+ const holder =+ serverState.status === 'alive' || serverState.status === 'foreign-host'+ ? serverState.lock.channel+ : undefined;+ if (deps.force !== true && typeof holder === 'string' && holder.length > 0) {+ const self = deps.selfChannel ?? currentChannel(logger);+ if (self !== undefined && holder !== self) {+ error(+ `Not stopping: the server at ${deps.lockDir} belongs to ${desktopChannelLabel(holder)}. ` ++ 'Stop it from that app or its CLI, or re-run with --force to terminate anyway.',+ );+ logger?.warn(+ {+ lockDir: deps.lockDir,+ holderChannel: holder,+ selfChannel: self,+ pids: plan.targets.map((t) => t.pid),+ },+ 'stop declined: server belongs to another channel',+ );+ return { stopped: [], failed: [], hadTargets: true, declined: { otherChannel: holder } };+ }+ }+if (deps.force !== true) {const clients = await probeClients(deps.lockDir, logger);if (clients !== null && clients > 0) {@@ -233,7 +271,10 @@ export function stopCommand(getConfig: () => Config): Command {'Pass a port number, a directory path, or "all" to target globally.',).argument('[target...]', 'port number, directory path (spaces OK), or "all"')- .option('--force', 'Stop even when editor windows or agents are still connected to the server')+ .option(+ '--force',+ 'Stop even when the server belongs to another OpenKnowledge app (Stable or Beta) or editor windows or agents are still connected to it',+ ).action(async (parts: string[], options: { force?: boolean }) => {const force = options.force === true;const target = parts.length === 0 ? undefined : parts.join(' ');diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex c5f61ea67..7722cf76c 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -2221,7 +2221,7 @@ async function openProjectOrFallbackToNavigator(`${projectPath}\n\n` +(prompt.reason === 'eperm'? 'The conflicting server belongs to another user account and cannot be stopped from here. Quit it from that account and try again.'- : 'Could not stop the conflicting server. Quit it manually (`ok stop`) and try again.'),+ : `Could not stop the conflicting server. Quit it manually (\`ok stop --force ${quoteStopCommandPath(projectPath, process.platform)}\`) and try again.`),);} else {getLogger('project').info(