Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): keep one writer per project across channels (#5328)
tim-inkeep8a88425c5381
diff --git a/.changeset/one-app-per-project.md b/.changeset/one-app-per-project.mdnew file mode 100644index 000000000..9e9064cf9--- /dev/null+++ b/.changeset/one-app-per-project.md@@ -0,0 +1,6 @@+---+"@inkeep/open-knowledge": patch+"@inkeep/open-knowledge-desktop": patch+---++Stable and Beta no longer share a project's server: the second app offers to stop the first one's server instead of attaching to it. This holds once both apps are on this release. [Details](https://openknowledge.ai/docs/reference/what-open-knowledge-writes#stable-and-beta-on-the-same-project).diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 3d126834d..0a2fe9409 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -124,7 +124,7 @@ The **Scope** column assumes you share this setup with your team. New projects d#### Beta uses its own entry-Each product registers under its own name, so Stable and Beta can both be connected to the same editor without overwriting each other. Stable uses `open-knowledge`; Beta uses `open-knowledge-beta`, with its own launcher that runs OpenKnowledge Beta and falls back to `npx @inkeep/open-knowledge@beta`. Everywhere this page names the `open-knowledge` entry, Beta's app, repair sweeps, and `ok-beta init` act only on `open-knowledge-beta`, and Beta's Pi bridge is `.pi/extensions/open-knowledge-beta.ts`. Agents see Beta's tools as `mcp__open-knowledge-beta__*`, and Pi sees them as `ok-beta_*`.+Each product registers under its own name, so Stable and Beta can both be connected to the same editor without overwriting each other. Stable uses `open-knowledge`; Beta uses `open-knowledge-beta`, with its own launcher that runs OpenKnowledge Beta and falls back to `npx @inkeep/open-knowledge@beta`. Everywhere this page names the `open-knowledge` entry, Beta's app, repair sweeps, and `ok-beta init` act only on `open-knowledge-beta`, and Beta's Pi bridge is `.pi/extensions/open-knowledge-beta.ts`. Agents see Beta's tools as `mcp__open-knowledge-beta__*`, and Pi sees them as `ok-beta_*`. The two apps do not share a project's server, though; see [Stable and Beta on the same project](#stable-and-beta-on-the-same-project).Earlier releases of the separately installed `OpenKnowledge Beta` app registered under `open-knowledge`, and updating does not move that entry. If an editor's config has no `open-knowledge-beta` entry, reconnect that editor from **Settings → Agent connections** in OpenKnowledge Beta, then remove the old `open-knowledge` entry from the file listed under [`ok init`](#ok-init) if you don't also run Stable. An older Beta install still named `OpenKnowledge` keeps using `open-knowledge`; leave that entry in place.@@ -142,7 +142,7 @@ The app runs a collaboration server for the open project. It writes runtime stat| Path | What it is | Scope || --- | --- | --- |-| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server) | In-project, gitignored |+| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server), and the product that started it (`channel`: `stable` or `beta`); see [Stable and Beta on the same project](#stable-and-beta-on-the-same-project) | In-project, gitignored || `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored || `.ok/local/sync-state.json` | GitHub-sync engine state | In-project, gitignored || `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored |@@ -169,6 +169,16 @@ On each launch and project open, the app also runs **repair sweeps**: it rewrite**Skills are never installed by a sweep.** OpenKnowledge writes a skill into editor folders only when you ask for one — the first-launch setup dialog, the Settings toggles, Skills Studio, or `ok init`. A launch does two housekeeping passes over installed editor skills and writes nothing new into those folders: it removes superseded pre-split `open-knowledge` copies OpenKnowledge itself left in your agent folders, and it removes a bundle you switched off that is still on disk.+#### Stable and Beta on the same project++Only 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.++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.++A lock written by an earlier release has no `channel`, and both apps attach to it as before. An app from an earlier release does not read `channel` at all, so the rule holds only once both apps are on this release.+### Home directory and credentials (`~/.ok/`)Beta writes the `~/.ok/` entries below under `~/.ok-beta/` instead, except the shared Global-scope skill files (`~/.ok/local/installed-skills.json`, `~/.ok/local/skill-placements.json`, `~/.ok/local/skill-move-retained.json`, and `~/.ok/skills-lock.json`), which every product keeps in `~/.ok/`; see [Stable and Beta home folders](#stable-and-beta-home-folders).@@ -274,7 +284,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a| Path | What it is | Scope || --- | --- | --- |-| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server) | In-project, gitignored |+| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server), and the product that started it (`channel`: `stable` or `beta`); see [Stable and Beta on the same project](#stable-and-beta-on-the-same-project) | In-project, gitignored || `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored || `.ok/local/sync-state.json` | GitHub-sync engine state | In-project, gitignored || `.ok/local/conflicts.json` | Every conflict the app is holding a document for, including conflicts that involve no remote. A row for OpenKnowledge's own merge of the editor against disk embeds up to three full copies of the document body, so **keep this file while any conflict is open**. Deleting it loses those copies. If the app cannot read the file, it renames it to `conflicts.json.corrupt-<timestamp>` and leaves it in place | In-project, gitignored |diff --git a/packages/app/src/lib/install-server-drift-listener.test.ts b/packages/app/src/lib/install-server-drift-listener.test.tsindex 9fb51a4d9..f4eed7987 100644--- a/packages/app/src/lib/install-server-drift-listener.test.ts+++ b/packages/app/src/lib/install-server-drift-listener.test.ts@@ -126,14 +126,22 @@ describe('drift copy', () => {});test('eperm failure points at a different account + reboot, never `ok stop all`', () => {- const msg = restartFailureMessage('eperm');+ const msg = restartFailureMessage({ ok: false, reason: 'eperm' });expect(msg.toLowerCase()).toContain('different account');expect(msg.toLowerCase()).toContain('restart your computer');expect(msg).not.toContain('ok stop all');});test('other failure suggests `ok stop all`', () => {- expect(restartFailureMessage('other')).toContain('ok stop all');+ expect(restartFailureMessage({ ok: false, reason: 'other' })).toContain('ok stop all');+ });++ test("another channel's server is left running and never offered `ok stop all`", () => {+ expect(+ restartFailureMessage({ ok: false, reason: 'other-channel', holderChannel: 'stable' }),+ ).toBe(+ "OpenKnowledge (Stable) is serving this project, so this app won't stop it. Close this window and open the project again to stop OpenKnowledge (Stable)'s server and open the project here.",+ );});});@@ -184,7 +192,9 @@ describe('installServerDriftListener', () => {expect(toastDismiss).toHaveBeenCalledWith('toast-1');expect(h.restartServer).toHaveBeenCalledWith('/tmp/proj');expect(toastError).toHaveBeenCalledTimes(1);- expect(toastError.mock.calls[0]?.[0]).toBe(restartFailureMessage('eperm'));+ expect(toastError.mock.calls[0]?.[0]).toBe(+ restartFailureMessage({ ok: false, reason: 'eperm' }),+ );});test('a restart that recreates the window (invoke rejects) shows no failure toast', async () => {diff --git a/packages/app/src/lib/install-server-drift-listener.ts b/packages/app/src/lib/install-server-drift-listener.tsindex c8dae67cd..aa2fe428a 100644--- a/packages/app/src/lib/install-server-drift-listener.ts+++ b/packages/app/src/lib/install-server-drift-listener.ts@@ -4,9 +4,11 @@ import { toast } from 'sonner';import { ServerDriftToast } from '@/components/ServerDriftToast';import type {OkDesktopBridge,+ OkServerRestartFailure,OkServerRestartOutcome,OkServerVersionDriftInfo,} from '@/lib/desktop-bridge-types';+import { otherChannelRestartMessage } from '@/lib/restart-collab-server';export function restartDisruptionWarning(): string {return t`Restarting closes this project's server. Connected agents (Claude Code, Codex, Cursor) will see their OpenKnowledge MCP connection close unexpectedly — you may need to restart the agent, or toggle its OpenKnowledge MCP server off and on, to reconnect.`;@@ -25,10 +27,15 @@ export function restartSuccessMessage(appRuntime: string): string {return t`Restarted — now running v${appRuntime}.`;}-export function restartFailureMessage(reason: 'eperm' | 'other'): string {- return reason === 'eperm'- ? t`Couldn't restart the server — it's running under a different account. Restart your computer to clear it, then reopen this project.`- : t`Couldn't restart the server automatically. Try running \`ok stop all\` in a terminal, then reopen this project — or restart your computer if it persists.`;+export function restartFailureMessage(failure: OkServerRestartFailure): string {+ switch (failure.reason) {+ case 'other-channel':+ return otherChannelRestartMessage(failure.holderChannel);+ case 'eperm':+ return t`Couldn't restart the server — it's running under a different account. Restart your computer to clear it, then reopen this project.`;+ case 'other':+ return t`Couldn't restart the server automatically. Try running \`ok stop all\` in a terminal, then reopen this project — or restart your computer if it persists.`;+ }}async function runRestart(bridge: OkDesktopBridge): Promise<void> {@@ -43,7 +50,7 @@ async function runRestart(bridge: OkDesktopBridge): Promise<void> {}toast.dismiss(loadingId);if (outcome.ok === false) {- toast.error(restartFailureMessage(outcome.reason), {+ toast.error(restartFailureMessage(outcome), {duration: Number.POSITIVE_INFINITY,});}diff --git a/packages/app/src/lib/restart-collab-server.test.ts b/packages/app/src/lib/restart-collab-server.test.tsindex a1fb0b359..6e7466e73 100644--- a/packages/app/src/lib/restart-collab-server.test.ts+++ b/packages/app/src/lib/restart-collab-server.test.ts@@ -3,14 +3,22 @@ import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';import { restartCollabServer, restartServerFailureMessage } from './restart-collab-server';describe('restartServerFailureMessage', () => {+ test('other-channel says the other app keeps the project', () => {+ expect(+ restartServerFailureMessage({ ok: false, reason: 'other-channel', holderChannel: 'stable' }),+ ).toBe(+ "OpenKnowledge (Stable) is serving this project, so this app won't stop it. Close this window and open the project again to stop OpenKnowledge (Stable)'s server and open the project here.",+ );+ });+test('eperm names the ownership conflict', () => {- expect(restartServerFailureMessage('eperm')).toBe(+ expect(restartServerFailureMessage({ ok: false, reason: 'eperm' })).toBe("Couldn't restart the server — another process owns it. Quit other OpenKnowledge windows for this project, then try again.",);});test('other points at the ok start fallback', () => {- expect(restartServerFailureMessage('other')).toBe(+ expect(restartServerFailureMessage({ ok: false, reason: 'other' })).toBe("Couldn't restart the server. Try `ok start` in this folder.",);});@@ -41,12 +49,18 @@ describe('restartCollabServer', () => {test('maps an eperm failure to the ownership message', async () => {const { bridge } = makeBridge({ ok: false, reason: 'eperm' });const result = await restartCollabServer(bridge);- expect(result).toEqual({ ok: false, message: restartServerFailureMessage('eperm') });+ expect(result).toEqual({+ ok: false,+ message: restartServerFailureMessage({ ok: false, reason: 'eperm' }),+ });});test('maps an other failure to the ok start fallback message', async () => {const { bridge } = makeBridge({ ok: false, reason: 'other' });const result = await restartCollabServer(bridge);- expect(result).toEqual({ ok: false, message: restartServerFailureMessage('other') });+ expect(result).toEqual({+ ok: false,+ message: restartServerFailureMessage({ ok: false, reason: 'other' }),+ });});});diff --git a/packages/app/src/lib/restart-collab-server.ts b/packages/app/src/lib/restart-collab-server.tsindex 024b96037..f71613430 100644--- a/packages/app/src/lib/restart-collab-server.ts+++ b/packages/app/src/lib/restart-collab-server.ts@@ -1,10 +1,21 @@+import { desktopChannelLabel } from '@inkeep/open-knowledge-core';import { t } from '@lingui/core/macro';-import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';+import type { OkDesktopBridge, OkServerRestartFailure } from '@/lib/desktop-bridge-types';-export function restartServerFailureMessage(reason: 'eperm' | 'other'): string {- return reason === 'eperm'- ? t`Couldn't restart the server — another process owns it. Quit other OpenKnowledge windows for this project, then try again.`- : t`Couldn't restart the server. Try \`ok start\` in this folder.`;+export function restartServerFailureMessage(failure: OkServerRestartFailure): string {+ switch (failure.reason) {+ case 'other-channel':+ return otherChannelRestartMessage(failure.holderChannel);+ case 'eperm':+ return t`Couldn't restart the server — another process owns it. Quit other OpenKnowledge windows for this project, then try again.`;+ case 'other':+ return t`Couldn't restart the server. Try \`ok start\` in this folder.`;+ }+}++export function otherChannelRestartMessage(holderChannel: string): string {+ const holder = desktopChannelLabel(holderChannel);+ return t`${holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop ${holder}'s server and open the project here.`;}export async function restartCollabServer(@@ -12,5 +23,5 @@ export async function restartCollabServer(): Promise<{ ok: true } | { ok: false; message: string }> {const outcome = await bridge.restartServer(bridge.config.projectPath);if (outcome.ok) return { ok: true };- return { ok: false, message: restartServerFailureMessage(outcome.reason) };+ return { ok: false, message: restartServerFailureMessage(outcome) };}diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex 077af351e..09c1f3f1b 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -1341,6 +1341,12 @@"هذا الملف أكبر من أن يُفتح في محرر النصوص المدمج (الحد 1 ميغابايت). استخدم «فتح ملف» أدناه لفتحه في تطبيق آخر."],"C_cPoW": ["انتهت صلاحية جلسة GitHub لديك — سجّل الدخول مرة أخرى للتحقق من صلاحية الدفع."],+ "CacpkO": [+ ["holder"],+ " يخدم هذا المشروع، لذا لن يوقفه هذا التطبيق. أغلق هذه النافذة وافتح المشروع مرة أخرى لإيقاف خادم ",+ ["holder"],+ " وفتح المشروع هنا."+ ],"CbxTfe": ["تحديد الكتلة"],"CcaU4i": ["تُطبّق التعديلات مباشرة وتُحفظ تلقائيًا في هذه السمة."],"ChMshD": ["إنهاء ", ["appName"]],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 3ab16e1a6..f9828371f 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, zero {مجلدات} one {مجلد} two {مجلداmsgid "{formatted} GitHub stars"msgstr "{formatted} نجمة على GitHub"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} يخدم هذا المشروع، لذا لن يوقفه هذا التطبيق. أغلق هذه النافذة وافتح المشروع مرة أخرى لإيقاف خادم {holder} وفتح المشروع هنا."+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex 17cb43956..a956502d3 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -1112,6 +1112,12 @@"এই ফাইলটি অন্তর্নির্মিত টেক্সট সম্পাদকে খোলার জন্য অত্যন্ত বড় (১ MB সীমা)। অন্য অ্যাপে খুলতে নিচের Open file ব্যবহার করুন।"],"C_cPoW": ["আপনার GitHub সেশনের মেয়াদ শেষ — পুশের প্রবেশাধিকার যাচাই করতে আবার সাইন ইন করুন।"],+ "CacpkO": [+ ["holder"],+ " এই প্রজেক্টটি সার্ভ করছে, তাই এই অ্যাপ এটি বন্ধ করবে না। এই উইন্ডোটি বন্ধ করুন এবং ",+ ["holder"],+ "-এর সার্ভার বন্ধ করে প্রজেক্টটি এখানে খুলতে আবার প্রজেক্টটি খুলুন।"+ ],"CbxTfe": ["ব্লক নির্বাচন করুন"],"CcaU4i": ["সম্পাদনাগুলি সঙ্গে সঙ্গে প্রয়োগ হয় এবং এই থিমে স্বয়ংক্রিয়ভাবে সংরক্ষিত হয়।"],"ChMshD": [["appName"], " থেকে প্রস্থান"],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex b16878250..7fc90cf0d 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {ফোল্ডার} other {ফোল্ডmsgid "{formatted} GitHub stars"msgstr "{formatted}টি GitHub স্টার"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} এই প্রজেক্টটি সার্ভ করছে, তাই এই অ্যাপ এটি বন্ধ করবে না। এই উইন্ডোটি বন্ধ করুন এবং {holder}-এর সার্ভার বন্ধ করে প্রজেক্টটি এখানে খুলতে আবার প্রজেক্টটি খুলুন।"+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 6dd6708d2..0f25adafc 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -1154,6 +1154,12 @@"This file is too large to open in the built-in text editor (1 MB limit). Use Open file below to open it in another app."],"C_cPoW": ["Your GitHub session expired — sign in again to verify push access."],+ "CacpkO": [+ ["holder"],+ " is serving this project, so this app won't stop it. Close this window and open the project again to stop ",+ ["holder"],+ "'s server and open the project here."+ ],"CbxTfe": ["Select block"],"CcaU4i": ["Edits apply live and save automatically to this theme."],"ChMshD": ["Quit ", ["appName"]],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex f5dcfb096..605e6af89 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {folder} other {folders}}"msgid "{formatted} GitHub stars"msgstr "{formatted} GitHub stars"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex b3b77e796..863370246 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -1357,6 +1357,12 @@"C_cPoW": ["Tu sesión de GitHub ha caducado: inicia sesión de nuevo para verificar el acceso de push."],+ "CacpkO": [+ ["holder"],+ " está sirviendo este proyecto, así que esta app no lo detendrá. Cierra esta ventana y vuelve a abrir el proyecto para detener el servidor de ",+ ["holder"],+ " y abrir el proyecto aquí."+ ],"CbxTfe": ["Seleccionar bloque"],"CcaU4i": ["Los cambios se aplican al instante y se guardan automáticamente en este tema."],"ChMshD": ["Salir de ", ["appName"]],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex d0598b4c4..f490b467c 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {carpeta} many {carpetas} other {carpetas}}"msgid "{formatted} GitHub stars"msgstr "{formatted} estrellas en GitHub"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} está sirviendo este proyecto, así que esta app no lo detendrá. Cierra esta ventana y vuelve a abrir el proyecto para detener el servidor de {holder} y abrir el proyecto aquí."+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex bb921aceb..2e9aa5433 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -1384,6 +1384,12 @@"C_cPoW": ["Votre session GitHub a expiré — reconnectez-vous pour vérifier l'accès en écriture."],+ "CacpkO": [+ ["holder"],+ " sert ce projet, cette app ne l'arrêtera donc pas. Fermez cette fenêtre et rouvrez le projet pour arrêter le serveur de ",+ ["holder"],+ " et ouvrir le projet ici."+ ],"CbxTfe": ["Sélectionner le bloc"],"CcaU4i": ["Les modifications s’appliquent immédiatement et sont automatiquement enregistrées dans ce thème."diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 71568ea26..402f32771 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {dossier} many {dossiers} other {dossiers}}"msgid "{formatted} GitHub stars"msgstr "{formatted} étoiles GitHub"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} sert ce projet, cette app ne l'arrêtera donc pas. Fermez cette fenêtre et rouvrez le projet pour arrêter le serveur de {holder} et ouvrir le projet ici."+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex c1b876443..e00f71e3b 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -1123,6 +1123,12 @@"यह फ़ाइल अंतर्निहित पाठ संपादक में खोलने के लिए बहुत बड़ी है (1 MB की सीमा)। इसे किसी दूसरे ऐप में खोलने के लिए नीचे Open file का उपयोग करें।"],"C_cPoW": ["आपका GitHub सत्र समाप्त हो गया — पुश की पहुँच जाँचने के लिए फिर से साइन इन करें।"],+ "CacpkO": [+ ["holder"],+ " इस प्रोजेक्ट को सर्व कर रहा है, इसलिए यह ऐप उसे नहीं रोकेगा। यह विंडो बंद करें और ",+ ["holder"],+ " का सर्वर रोककर प्रोजेक्ट यहाँ खोलने के लिए प्रोजेक्ट फिर से खोलें।"+ ],"CbxTfe": ["ब्लॉक चुनें"],"CcaU4i": ["संपादन तुरंत लागू होते हैं और इस थीम में अपने आप सहेजे जाते हैं।"],"ChMshD": [["appName"], " से बाहर निकलें"],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex 37d9c34d8..dc79d3a84 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {फ़ोल्डर} other {फ़ोल्msgid "{formatted} GitHub stars"msgstr "{formatted} GitHub स्टार"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} इस प्रोजेक्ट को सर्व कर रहा है, इसलिए यह ऐप उसे नहीं रोकेगा। यह विंडो बंद करें और {holder} का सर्वर रोककर प्रोजेक्ट यहाँ खोलने के लिए प्रोजेक्ट फिर से खोलें।"+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex d0fa35e70..974f965ed 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -1146,6 +1146,12 @@"Berkas ini terlalu besar untuk dibuka di penyunting teks bawaan (batas 1 MB). Gunakan Buka berkas di bawah untuk membukanya di aplikasi lain."],"C_cPoW": ["Sesi GitHub Anda kedaluwarsa — masuk lagi untuk memverifikasi akses push."],+ "CacpkO": [+ ["holder"],+ " sedang melayani proyek ini, jadi aplikasi ini tidak akan menghentikannya. Tutup jendela ini lalu buka proyek lagi untuk menghentikan server ",+ ["holder"],+ " dan membuka proyek di sini."+ ],"CbxTfe": ["Pilih blok"],"CcaU4i": ["Suntingan langsung diterapkan dan disimpan otomatis ke tema ini."],"ChMshD": ["Keluar dari ", ["appName"]],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex 3bab2fb77..80589ebab 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, other {folder}}"msgid "{formatted} GitHub stars"msgstr "{formatted} bintang GitHub"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} sedang melayani proyek ini, jadi aplikasi ini tidak akan menghentikannya. Tutup jendela ini lalu buka proyek lagi untuk menghentikan server {holder} dan membuka proyek di sini."+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex 9d3a4056f..498380d94 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -1110,6 +1110,12 @@"이 파일은 기본 제공 텍스트 편집기에서 열기에는 너무 큽니다(1MB 제한). 아래의 파일 열기를 사용해 다른 앱에서 여세요."],"C_cPoW": ["GitHub 세션이 만료되었습니다. 푸시 권한을 확인하려면 로그인합니다."],+ "CacpkO": [+ ["holder"],+ "이(가) 이 프로젝트를 서비스하고 있으므로 이 앱은 중지하지 않습니다. 이 창을 닫고 프로젝트를 다시 열면 ",+ ["holder"],+ "의 서버를 중지하고 여기에서 프로젝트를 열 수 있습니다."+ ],"CbxTfe": ["블록 선택"],"CcaU4i": ["편집 내용이 실시간으로 적용되고 이 테마에 자동으로 저장됩니다."],"ChMshD": [["appName"], " 종료"],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 760ddd8dc..28f88313d 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, other {폴더}}"msgid "{formatted} GitHub stars"msgstr "{formatted} GitHub 스타"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder}이(가) 이 프로젝트를 서비스하고 있으므로 이 앱은 중지하지 않습니다. 이 창을 닫고 프로젝트를 다시 열면 {holder}의 서버를 중지하고 여기에서 프로젝트를 열 수 있습니다."+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/pl/messages.json b/packages/app/src/locales/pl/messages.jsonindex cf1dacc27..89f7f5665 100644--- a/packages/app/src/locales/pl/messages.json+++ b/packages/app/src/locales/pl/messages.json@@ -1392,6 +1392,12 @@"C_cPoW": ["Twoja sesja GitHub wygasła — zaloguj się ponownie, aby zweryfikować dostęp do wysyłania."],+ "CacpkO": [+ ["holder"],+ " obsługuje ten projekt, więc ta aplikacja go nie zatrzyma. Zamknij to okno i otwórz projekt ponownie, aby zatrzymać serwer aplikacji ",+ ["holder"],+ " i otworzyć projekt tutaj."+ ],"CbxTfe": ["Zaznacz blok"],"CcaU4i": ["Zmiany są widoczne na żywo i zapisują się automatycznie w tym motywie."],"ChMshD": ["Zakończ ", ["appName"]],diff --git a/packages/app/src/locales/pl/messages.po b/packages/app/src/locales/pl/messages.poindex 519680fa1..80c3e1565 100644--- a/packages/app/src/locales/pl/messages.po+++ b/packages/app/src/locales/pl/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {folder} few {foldery} many {folderów} othermsgid "{formatted} GitHub stars"msgstr "{formatted} gwiazdek na GitHubie"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} obsługuje ten projekt, więc ta aplikacja go nie zatrzyma. Zamknij to okno i otwórz projekt ponownie, aby zatrzymać serwer aplikacji {holder} i otworzyć projekt tutaj."+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 8191e299b..f5f330af0 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -1154,6 +1154,12 @@"Ţĥĩś ƒĩĺē ĩś ţōō ĺàŕĝē ţō ōƥēń ĩń ţĥē ƀũĩĺţ-ĩń ţēxţ ēďĩţōŕ (1 Ḿß ĺĩḿĩţ). Ũśē Ōƥēń ƒĩĺē ƀēĺōŵ ţō ōƥēń ĩţ ĩń àńōţĥēŕ àƥƥ."],"C_cPoW": ["Ŷōũŕ ĜĩţĤũƀ śēśśĩōń ēxƥĩŕēď — śĩĝń ĩń àĝàĩń ţō vēŕĩƒŷ ƥũśĥ àććēśś."],+ "CacpkO": [+ ["holder"],+ " ĩś śēŕvĩńĝ ţĥĩś ƥŕōĴēćţ, śō ţĥĩś àƥƥ ŵōń'ţ śţōƥ ĩţ. Ćĺōśē ţĥĩś ŵĩńďōŵ àńď ōƥēń ţĥē ƥŕōĴēćţ àĝàĩń ţō śţōƥ ",+ ["holder"],+ "'ś śēŕvēŕ àńď ōƥēń ţĥē ƥŕōĴēćţ ĥēŕē."+ ],"CbxTfe": ["Śēĺēćţ ƀĺōćķ"],"CcaU4i": ["Ēďĩţś àƥƥĺŷ ĺĩvē àńď śàvē àũţōḿàţĩćàĺĺŷ ţō ţĥĩś ţĥēḿē."],"ChMshD": ["Ǫũĩţ ", ["appName"]],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 8472dab41..5930b6b69 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -912,6 +912,10 @@ msgstr ""msgid "{formatted} GitHub stars"msgstr ""+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr ""+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 45d7496d0..f7676a078 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -1331,6 +1331,12 @@"Este arquivo é grande demais para abrir no editor de texto integrado (limite de 1 MB). Use Abrir arquivo, abaixo, para abri-lo em outro app."],"C_cPoW": ["Sua sessão do GitHub expirou — entre de novo para verificar o acesso de envio."],+ "CacpkO": [+ ["holder"],+ " está servindo este projeto, então este app não vai pará-lo. Feche esta janela e abra o projeto novamente para parar o servidor de ",+ ["holder"],+ " e abrir o projeto aqui."+ ],"CbxTfe": ["Selecionar bloco"],"CcaU4i": ["As alterações são aplicadas imediatamente e salvas automaticamente neste tema."],"ChMshD": ["Encerrar o ", ["appName"]],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex ef1cc3219..f7319c600 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {pasta} many {pastas} other {pastas}}"msgid "{formatted} GitHub stars"msgstr "{formatted} estrelas no GitHub"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} está servindo este projeto, então este app não vai pará-lo. Feche esta janela e abra o projeto novamente para parar o servidor de {holder} e abrir o projeto aqui."+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex a4b9f78ce..b68b5b678 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -1164,6 +1164,12 @@"یہ فائل بلٹ اِن ٹیکسٹ ایڈیٹر میں کھولنے کے لیے بہت بڑی ہے (حد 1 MB)۔ اسے کسی اور ایپ میں کھولنے کے لیے نیچے «فائل کھولیں» استعمال کریں۔"],"C_cPoW": ["آپ کا GitHub سیشن ختم ہو گیا — پُش کی رسائی کی توثیق کے لیے دوبارہ سائن اِن کریں۔"],+ "CacpkO": [+ ["holder"],+ " اس پروجیکٹ کو سرو کر رہا ہے، اس لیے یہ ایپ اسے نہیں روکے گی۔ یہ ونڈو بند کریں اور ",+ ["holder"],+ " کا سرور روک کر پروجیکٹ یہاں کھولنے کے لیے پروجیکٹ دوبارہ کھولیں۔"+ ],"CbxTfe": ["بلاک منتخب کریں"],"CcaU4i": ["ترامیم فوراً لاگو ہوتی ہیں اور خودکار طور پر اس تھیم میں محفوظ ہو جاتی ہیں۔"],"ChMshD": [["appName"], " سے باہر نکلیں"],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex 45334715f..0e179f602 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, one {فولڈر} other {فولڈرز}}"msgid "{formatted} GitHub stars"msgstr "{formatted} GitHub ستارے"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} اس پروجیکٹ کو سرو کر رہا ہے، اس لیے یہ ایپ اسے نہیں روکے گی۔ یہ ونڈو بند کریں اور {holder} کا سرور روک کر پروجیکٹ یہاں کھولنے کے لیے پروجیکٹ دوبارہ کھولیں۔"+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex 4d960d4cd..f66e15e5a 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -1003,6 +1003,12 @@"这个文件太大,无法在内置文本编辑器中打开(上限 1 MB)。请用下方的「打开文件」在其他应用中打开它。"],"C_cPoW": ["你的 GitHub 会话已过期——请重新登录以验证推送权限。"],+ "CacpkO": [+ ["holder"],+ " 正在为此项目提供服务,因此此应用不会停止它。关闭此窗口并再次打开项目,即可停止 ",+ ["holder"],+ " 的服务器并在此处打开项目。"+ ],"CbxTfe": ["选择块"],"CcaU4i": ["编辑会实时生效,并自动保存到此主题。"],"ChMshD": ["退出 ", ["appName"]],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex 72e16d5bc..2f2d94a9c 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, other {文件夹}}"msgid "{formatted} GitHub stars"msgstr "{formatted} 个 GitHub star"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} 正在为此项目提供服务,因此此应用不会停止它。关闭此窗口并再次打开项目,即可停止 {holder} 的服务器并在此处打开项目。"+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex 2af09153c..db1f44a69 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -1003,6 +1003,12 @@"這個檔案太大,無法在內建文字編輯器中開啟(上限 1 MB)。請用下面的「開啟檔案」在其他應用程式中開啟它。"],"C_cPoW": ["你的 GitHub 工作階段已過期——請重新登入以確認推送權限。"],+ "CacpkO": [+ ["holder"],+ " 正在為此專案提供服務,因此此應用程式不會停止它。關閉此視窗並再次開啟專案,即可停止 ",+ ["holder"],+ " 的伺服器並在此處開啟專案。"+ ],"CbxTfe": ["選取區塊"],"CcaU4i": ["編輯會即時套用,並自動儲存到這個主題。"],"ChMshD": ["結束 ", ["appName"]],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex eafe59364..98d0ff02b 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -912,6 +912,10 @@ msgstr "{folderCount, plural, other {資料夾}}"msgid "{formatted} GitHub stars"msgstr "{formatted} 個 GitHub star"+#: src/lib/restart-collab-server.ts+msgid "{holder} is serving this project, so this app won't stop it. Close this window and open the project again to stop {holder}'s server and open the project here."+msgstr "{holder} 正在為此專案提供服務,因此此應用程式不會停止它。關閉此視窗並再次開啟專案,即可停止 {holder} 的伺服器並在此處開啟專案。"+#: src/components/ActivityModeContent.tsx#: src/components/ActivityPanelFileRow.tsx#: src/components/SyncStatusBadge.tsxdiff --git a/packages/app/src/presence/use-sync-toasts.test.ts b/packages/app/src/presence/use-sync-toasts.test.tsindex 386e62bba..acfc9867f 100644--- a/packages/app/src/presence/use-sync-toasts.test.ts+++ b/packages/app/src/presence/use-sync-toasts.test.ts@@ -36,14 +36,18 @@ describe('runDisconnectRestart', () => {const { bridge } = makeBridge({ ok: false, reason: 'eperm' });await runDisconnectRestart(bridge);expect(errorSpy).toHaveBeenCalledTimes(1);- expect(errorSpy.mock.calls[0]?.[0]).toBe(restartServerFailureMessage('eperm'));+ expect(errorSpy.mock.calls[0]?.[0]).toBe(+ restartServerFailureMessage({ ok: false, reason: 'eperm' }),+ );});test('surfaces an error toast with the mapped message on an other failure', async () => {const { bridge } = makeBridge({ ok: false, reason: 'other' });await runDisconnectRestart(bridge);expect(errorSpy).toHaveBeenCalledTimes(1);- expect(errorSpy.mock.calls[0]?.[0]).toBe(restartServerFailureMessage('other'));+ expect(errorSpy.mock.calls[0]?.[0]).toBe(+ restartServerFailureMessage({ ok: false, reason: 'other' }),+ );});test('swallows a thrown invoke (window torn down mid-restart) — no error toast', async () => {diff --git a/packages/core/src/constants/product.test.ts b/packages/core/src/constants/product.test.tsindex 71380b267..24e3d4660 100644--- a/packages/core/src/constants/product.test.ts+++ b/packages/core/src/constants/product.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { DESKTOP_PRODUCTS, resolveDesktopProductName } from './product.ts';+import { DESKTOP_PRODUCTS, desktopChannelLabel, resolveDesktopProductName } from './product.ts';describe('resolveDesktopProductName', () => {it.each([@@ -50,3 +50,13 @@ describe('resolveDesktopProductName', () => {expect(DESKTOP_PRODUCTS.stable.keyringService).toBe('open-knowledge');});});++describe('desktopChannelLabel', () => {+ it.each([+ ['stable', 'OpenKnowledge (Stable)'],+ ['beta', 'OpenKnowledge Beta'],+ ['cloud', 'OpenKnowledge (cloud)'],+ ])('%s is named %s', (channel, expected) => {+ expect(desktopChannelLabel(channel)).toBe(expected);+ });+});diff --git a/packages/core/src/constants/product.ts b/packages/core/src/constants/product.tsindex cab573218..3b6a6b90f 100644--- a/packages/core/src/constants/product.ts+++ b/packages/core/src/constants/product.ts@@ -52,6 +52,13 @@ function isDesktopProductName(value: string): value is DesktopProductName {return Object.hasOwn(DESKTOP_PRODUCTS, value);}+export function desktopChannelLabel(channel: string): string {+ if (channel === 'stable') return `${PRODUCT_NAME} (Stable)`;+ return isDesktopProductName(channel)+ ? DESKTOP_PRODUCTS[channel].productName+ : `${PRODUCT_NAME} (${channel})`;+}+function executableBaseName(execPath: string): string {return (execPath.split(/[\\/]/).pop() ?? '').replace(/\.exe$/i, '');}diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex af76a8bac..23900e8b1 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -914,9 +914,11 @@ export interface OkRecentRemovedMissingInfo {readonly projectName: string;}-export type OkServerRestartOutcome =- | { readonly ok: true }- | { readonly ok: false; readonly reason: 'eperm' | 'other' };+export type OkServerRestartFailure =+ | { readonly ok: false; readonly reason: 'eperm' | 'other' }+ | { readonly ok: false; readonly reason: 'other-channel'; readonly holderChannel: string };++export type OkServerRestartOutcome = { readonly ok: true } | OkServerRestartFailure;export type OkPtyCreateReason = 'no-project' | 'not-consented';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 7d3f71f1d..02d7bf105 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -543,6 +543,7 @@ export {DESKTOP_PRODUCTS,type DesktopProduct,type DesktopProductName,+ desktopChannelLabel,desktopWindowsExecutableName,desktopWindowsInstallDirNames,OK_CHANNEL_ENV,diff --git a/packages/desktop/src/main/holder-stop-prompt.test.ts b/packages/desktop/src/main/holder-stop-prompt.test.tsnew file mode 100644index 000000000..3ec389768--- /dev/null+++ b/packages/desktop/src/main/holder-stop-prompt.test.ts@@ -0,0 +1,174 @@+import { describe, expect, test } from 'vitest';+import {+ failedOpenHolder,+ type HolderStopPromptDeps,+ type HolderStopPromptInput,+ promptHolderStop,+} from './holder-stop-prompt.ts';+import type { ForceStopOutcome, OtherChannelHolderError } from './window-manager.ts';++const stableHolder: OtherChannelHolderError = Object.assign(new Error('held'), {+ kind: 'other-channel-holder' as const,+ holderPid: 65792,+ holderChannel: 'stable',+ holderKind: 'interactive' as const,+ selfChannel: 'beta',+});++function baseInput(overrides: Partial<HolderStopPromptInput> = {}): HolderStopPromptInput {+ return {+ projectPath: '/tmp/dragon',+ kind: 'other-channel-holder',+ errorMessage: 'held',+ dialogTitle: 'This project is open in another OpenKnowledge app',+ dialogBody: '/tmp/dragon\n\nheld',+ otherChannelHolder: stableHolder,+ warnsHolderMayBeLive: false,+ holderIsOwnChild: false,+ ...overrides,+ };+}++async function run(+ input: HolderStopPromptInput,+ response: number,+ stopOutcome: ForceStopOutcome = { ok: true },+) {+ const calls: string[] = [];+ let shown: Parameters<HolderStopPromptDeps['showMessageBox']>[0] | null = null;+ let stopTarget: unknown = 'not-called';+ const result = await promptHolderStop(input, {+ showMessageBox: async (options) => {+ shown = options;+ calls.push('dialog');+ return { response };+ },+ forceStop: async (expectedHolder) => {+ stopTarget = expectedHolder;+ calls.push('stop');+ return stopOutcome;+ },+ retryOpen: async () => {+ calls.push('retry');+ return true;+ },+ reopen: async () => {+ calls.push('reopen');+ return true;+ },+ });+ const dialog = shown as Parameters<HolderStopPromptDeps['showMessageBox']>[0] | null;+ return {+ result,+ calls,+ stopTarget,+ title: dialog?.title,+ detail: dialog?.detail,+ buttons: dialog?.buttons,+ defaultId: dialog?.defaultId,+ cancelId: dialog?.cancelId,+ };+}++describe('promptHolderStop', () => {+ test('another channel holding the project gets a handoff button that defaults to Cancel', async () => {+ expect(await run(baseInput(), 1)).toEqual({+ result: { kind: 'declined' },+ calls: ['dialog'],+ stopTarget: 'not-called',+ title: 'This project is open in another OpenKnowledge app',+ detail:+ '/tmp/dragon\n\nheld\n\nThis OpenKnowledge (Stable) server keeps running after any window showing the project closes, so the project stays busy until the server stops. OpenKnowledge Beta can stop it now and open the project here. Every window, editor, or agent connected to it loses its connection to this project.',+ buttons: ['Stop OpenKnowledge (Stable) Server & Open Here', 'Cancel'],+ defaultId: 1,+ cancelId: 1,+ });+ });++ test('accepting the handoff stops exactly the named holder, then opens the project again', async () => {+ expect(await run(baseInput(), 0)).toMatchObject({+ result: { kind: 'retried', opened: true },+ calls: ['dialog', 'stop', 'retry'],+ stopTarget: { pid: 65792, channel: 'stable' },+ });+ });++ test('a holder that changed while the dialog was open is re-prompted from a fresh open, not retried as if it stopped', async () => {+ expect(await run(baseInput(), 0, { ok: false, reason: 'holder-changed' })).toMatchObject({+ result: { kind: 'reopened', opened: true },+ calls: ['dialog', 'stop', 'reopen'],+ });+ });++ test('a same-channel lock collision keeps the plain stop-and-retry default', async () => {+ expect(+ await run(baseInput({ kind: 'lock-collision', otherChannelHolder: null }), 0),+ ).toMatchObject({+ result: { kind: 'retried', opened: true },+ stopTarget: undefined,+ buttons: ['Stop Server & Retry', 'Cancel'],+ defaultId: 0,+ });+ });++ for (const kind of ['lock-collision', 'stale-lock-holder', 'spawn-lock-timeout'] as const) {+ test(`a ${kind} dialog over another channel's lock is the named, bound, Cancel-default handoff`, async () => {+ expect(+ await run(+ baseInput({+ kind,+ errorMessage: 'OpenKnowledge server already running at port 0',+ dialogTitle: 'A stopped server is still holding this project',+ dialogBody: '/tmp/dragon\n\nheld (pid 65792)',+ otherChannelHolder: {+ holderPid: 65792,+ holderChannel: 'stable',+ holderKind: 'interactive',+ selfChannel: 'beta',+ },+ }),+ 0,+ ),+ ).toMatchObject({+ result: { kind: 'retried', opened: true },+ stopTarget: { pid: 65792, channel: 'stable' },+ title: 'This project is open in another OpenKnowledge app',+ detail:+ "/tmp/dragon\n\nOpenKnowledge (Stable) holds this project's server lock (pid 65792) and may still be serving it.\n\nThis OpenKnowledge (Stable) server keeps running after any window showing the project closes, so the project stays busy until the server stops. OpenKnowledge Beta can stop it now and open the project here. Every window, editor, or agent connected to it loses its connection to this project.",+ buttons: ['Stop OpenKnowledge (Stable) Server & Open Here', 'Cancel'],+ defaultId: 1,+ });+ });+ }++ test('a failure with no holder in the way shows no stop offer', async () => {+ expect(+ await run(baseInput({ kind: 'spawn-failed', otherChannelHolder: null }), 0),+ ).toMatchObject({ result: { kind: 'not-offered' }, calls: [] });+ });++ test('the failed-open holder never builds a window manager and takes the lock holder only from an existing one', () => {+ const lockHolder = {+ holderPid: 70001,+ holderChannel: 'stable',+ holderKind: 'interactive' as const,+ selfChannel: 'beta',+ };+ const lookups: string[] = [];+ const wm = {+ otherChannelLockHolder: (projectPath: string) => {+ lookups.push(projectPath);+ return lockHolder;+ },+ };+ expect(failedOpenHolder(new Error('spawn timed out'), '/tmp/dragon', undefined)).toBeNull();+ expect(failedOpenHolder(stableHolder, '/tmp/dragon', wm)).toBe(stableHolder);+ expect(failedOpenHolder(new Error('spawn timed out'), '/tmp/dragon', wm)).toBe(lockHolder);+ expect(+ failedOpenHolder(new Error('spawn timed out'), '/tmp/dragon', {+ otherChannelLockHolder: () => null,+ }),+ ).toBeNull();+ expect(lookups).toEqual(['/tmp/dragon']);+ });+});diff --git a/packages/desktop/src/main/holder-stop-prompt.ts b/packages/desktop/src/main/holder-stop-prompt.tsnew file mode 100644index 000000000..60e55c75d--- /dev/null+++ b/packages/desktop/src/main/holder-stop-prompt.ts@@ -0,0 +1,98 @@+import { desktopChannelLabel } from '@inkeep/open-knowledge-core';+import {+ type ForceStopOutcome,+ isOtherChannelHolderError,+ type OtherChannelHolder,+ otherChannelStopOffer,+ type WindowManager,+} from './window-manager.ts';++const OTHER_CHANNEL_DIALOG_TITLE = 'This project is open in another OpenKnowledge app';++export function failedOpenHolder(+ err: unknown,+ projectPath: string,+ wm: Pick<WindowManager, 'otherChannelLockHolder'> | undefined,+): OtherChannelHolder | null {+ if (isOtherChannelHolderError(err)) return err;+ return wm === undefined ? null : wm.otherChannelLockHolder(projectPath);+}++export interface HolderStopPromptInput {+ projectPath: string;+ kind: string | undefined;+ errorMessage: string;+ dialogTitle: string;+ dialogBody: string;+ otherChannelHolder: OtherChannelHolder | null;+ warnsHolderMayBeLive: boolean;+ holderIsOwnChild: boolean;+}++export interface HolderStopPromptDeps {+ showMessageBox(options: {+ type: 'warning';+ title: string;+ message: string;+ detail: string;+ buttons: string[];+ defaultId: number;+ cancelId: number;+ }): Promise<{ response: number }>;+ forceStop(expectedHolder?: { pid: number; channel: string }): Promise<ForceStopOutcome>;+ retryOpen(): Promise<boolean>;+ reopen(): Promise<boolean>;+}++export type HolderStopPromptResult =+ | { kind: 'not-offered' }+ | { kind: 'declined' }+ | { kind: 'reopened'; opened: boolean }+ | { kind: 'stop-failed'; reason: 'eperm' | 'other' }+ | { kind: 'retried'; opened: boolean };++export async function promptHolderStop(+ input: HolderStopPromptInput,+ deps: HolderStopPromptDeps,+): Promise<HolderStopPromptResult> {+ const holder = input.otherChannelHolder;+ const holderInTheWay =+ input.kind === 'other-channel-holder' ||+ input.kind === 'lock-collision' ||+ input.kind === 'stale-lock-holder' ||+ (input.kind === 'spawn-lock-timeout' && input.errorMessage.includes('already running'));+ if (!holderInTheWay) return { kind: 'not-offered' };+ const offer = holder === null ? null : otherChannelStopOffer(holder);+ const title = holder === null ? input.dialogTitle : OTHER_CHANNEL_DIALOG_TITLE;+ const body =+ holder === null || input.kind === 'other-channel-holder'+ ? input.dialogBody+ : `${input.projectPath}\n\n${desktopChannelLabel(holder.holderChannel)} holds ` ++ `this project's server lock (pid ${holder.holderPid}) and may still be serving it.`;+ const { response } = await deps.showMessageBox({+ type: 'warning',+ title,+ message: title,+ detail:+ `${body}\n\n` ++ (offer !== null+ ? offer.detail+ : input.warnsHolderMayBeLive+ ? `OpenKnowledge can stop that process and retry opening the project. It may still be ` ++ `running, so stop it only if you do not need it.`+ : input.holderIsOwnChild+ ? `OpenKnowledge already asked that server to stop during this open. It can make ` ++ `sure it is gone and try again.`+ : `OpenKnowledge can stop the conflicting server process and retry opening the project.`),+ buttons: [offer?.button ?? 'Stop Server & Retry', 'Cancel'],+ defaultId: input.warnsHolderMayBeLive || offer !== null ? 1 : 0,+ cancelId: 1,+ });+ if (response !== 0) return { kind: 'declined' };+ const stop = await deps.forceStop(+ holder === null ? undefined : { pid: holder.holderPid, channel: holder.holderChannel },+ );+ if (stop.ok) return { kind: 'retried', opened: await deps.retryOpen() };+ if (stop.reason === 'holder-changed') return { kind: 'reopened', opened: await deps.reopen() };+ return { kind: 'stop-failed', reason: stop.reason };+}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 37d1faa13..e2e2a7c22 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -56,6 +56,7 @@ import {OPENKNOWLEDGE_SKILLS_REPO,PROTOCOL_VERSION,projectWorktreeCreateResult,+ resolveDesktopProductName,ServerInfoSuccessSchema,SPAWN_ERROR_LOG,TERMINAL_CLIS,@@ -287,6 +288,7 @@ import {import { createBootBudgetDirSizeProbe } from './fs-walk-budget.ts';import { ensureGitAvailable } from './git-preflight-handler.ts';import { readCanonicalGitHubRemoteUrl } from './git-remote.ts';+import { failedOpenHolder, promptHolderStop } from './holder-stop-prompt.ts';import { classifyInstallShape } from './install-shape.ts';import {combineInstanceLabels,@@ -1516,6 +1518,7 @@ function ensureWindowManager() {appVersion: app.getVersion(),selfProtocolVersion: PROTOCOL_VERSION,selfRuntimeVersion: RUNTIME_VERSION,+ selfChannel: resolveDesktopProductName(),spawnLockPollDeadlineMs: readPositiveIntEnv('OK_SPAWN_STARTUP_TIMEOUT_MS'),spawnLockProgressDeadlineMs: readPositiveIntEnv('OK_SPAWN_BIND_TIMEOUT_MS'),reclaimForeignServerInDev: !app.isPackaged,@@ -2105,7 +2108,9 @@ async function openProjectOrFallbackToNavigator(} catch (err) {const errorMessage = (err as Error).message;const kind = (err as Error & { kind?: string }).kind;- const holderPid = (err as Error & { holderPid?: number }).holderPid;+ const otherChannelHolder = failedOpenHolder(err, projectPath, wm as WindowManager | undefined);+ const holderPid =+ otherChannelHolder?.holderPid ?? (err as Error & { holderPid?: number }).holderPid;const isStaleLockHolder = kind === 'stale-lock-holder';const staleLockReason = isStaleLockHolder? (err as Error & { reason?: string }).reason@@ -2119,6 +2124,8 @@ async function openProjectOrFallbackToNavigator(projectPath,entryPoint,kind,+ holderPid,+ holderChannel: otherChannelHolder?.holderChannel,exitCode: (err as Error & { exitCode?: number | null }).exitCode,exitSignal: (err as Error & { exitSignal?: string | null }).exitSignal,err,@@ -2145,35 +2152,27 @@ async function openProjectOrFallbackToNavigator(: 'A stopped server is still holding this project';dialogBody = `${projectPath}\n\n${errorMessage}`;}- const holderInTheWay =- kind === 'lock-collision' ||- kind === 'stale-lock-holder' ||- (kind === 'spawn-lock-timeout' && errorMessage.includes('already running'));const warnsHolderMayBeLive = staleLockReason === 'lock-not-attachable' && !holderIsOwnChild;- if (holderInTheWay) {- const { response } = await dialog.showMessageBox({- type: 'warning',- title: dialogTitle,- message: dialogTitle,- detail:- `${dialogBody}\n\n` +- (warnsHolderMayBeLive- ? `OpenKnowledge can stop that process and retry opening the project. It may still be ` +- `running, so stop it only if you do not need it.`- : holderIsOwnChild- ? `OpenKnowledge already asked that server to stop during this open. It can make ` +- `sure it is gone and try again.`- : `OpenKnowledge can stop the conflicting server process and retry opening the project.`),- buttons: ['Stop Server & Retry', 'Cancel'],- defaultId: warnsHolderMayBeLive ? 1 : 0,- cancelId: 1,- });- if (response === 0) {- ensureWindowManager();- const stop = await wm.forceStopConflictingServer(projectPath);- if (stop.ok) {+ const prompt = await promptHolderStop(+ {+ projectPath,+ kind,+ errorMessage,+ dialogTitle,+ dialogBody,+ otherChannelHolder,+ warnsHolderMayBeLive,+ holderIsOwnChild,+ },+ {+ showMessageBox: (options) => dialog.showMessageBox(options),+ forceStop: (expectedHolder) => {+ ensureWindowManager();+ return wm.forceStopConflictingServer(projectPath, expectedHolder);+ },+ retryOpen: async () => {try {- const opened = await openProject(+ return await openProject(projectPath,entryPoint,pendingDeepLinkTarget,@@ -2183,7 +2182,6 @@ async function openProjectOrFallbackToNavigator(pendingTargetMissing,options,);- return opened;} catch (retryErr) {getLogger('project').error({@@ -2199,17 +2197,34 @@ async function openProjectOrFallbackToNavigator('Unable to open project',`${projectPath}\n\n${(retryErr as Error).message}`,);+ openNavigator();+ return false;}- } else {- flushDesktopLogger();- dialog.showErrorBox(- 'Unable to open project',- `${projectPath}\n\n` +- (stop.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.'),- );- }+ },+ reopen: () =>+ openProjectOrFallbackToNavigator(+ projectPath,+ entryPoint,+ pendingDeepLinkTarget,+ pendingBranch,+ pendingMultiCandidate,+ pendingShareBranchSwitch,+ pendingTargetMissing,+ options,+ ),+ },+ );+ if (prompt.kind === 'retried' || prompt.kind === 'reopened') return prompt.opened;+ if (prompt.kind !== 'not-offered') {+ if (prompt.kind === 'stop-failed') {+ flushDesktopLogger();+ dialog.showErrorBox(+ 'Unable to open project',+ `${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.'),+ );} else {getLogger('project').info({@@ -2220,7 +2235,7 @@ async function openProjectOrFallbackToNavigator(},'user declined the stop-and-retry remedy',);- if (isStaleLockHolder) {+ if (isStaleLockHolder && otherChannelHolder === null) {const stopCommandTarget = quoteStopCommandPath(projectPath, process.platform);flushDesktopLogger();dialog.showErrorBox(diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 1ef385275..2b377adab 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -4,6 +4,8 @@ import {DEFAULT_SERVER_HOST,DEFAULT_SIGTERM_GRACE_MS,DEFAULT_SIGTERM_POLL_MS,+ type DesktopProductName,+ desktopChannelLabel,SPAWN_ERROR_LOG,sliceLastSpawnAttempt,} from '@inkeep/open-knowledge-core';@@ -156,8 +158,82 @@ export interface ServerLockMetadataLike {runtimeVersion?: string;machineId?: string;draining?: boolean;+ channel?: string;}+export type OtherChannelHolderError = Error & {+ kind: 'other-channel-holder';+ holderPid: number;+ holderChannel: string;+ holderKind: ServerLockMetadataLike['kind'];+ selfChannel: string;+};++function otherChannelHolderError(+ lock: ServerLockMetadataLike,+ { holderChannel, selfChannel }: ChannelConflict,+): OtherChannelHolderError {+ return Object.assign(+ new Error(+ `${desktopChannelLabel(holderChannel)} is serving this project (pid ${lock.pid}). Only one ` ++ `OpenKnowledge app can edit a project at a time.`,+ ),+ {+ name: 'OtherChannelHolderError',+ kind: 'other-channel-holder' as const,+ holderPid: lock.pid,+ holderChannel,+ holderKind: lock.kind,+ selfChannel,+ },+ );+}++export function isOtherChannelHolderError(err: unknown): err is OtherChannelHolderError {+ if (!(err instanceof Error)) return false;+ const fields = err as Partial<OtherChannelHolderError>;+ return (+ fields.kind === 'other-channel-holder' &&+ typeof fields.holderPid === 'number' &&+ typeof fields.holderChannel === 'string' &&+ typeof fields.selfChannel === 'string'+ );+}++export type OtherChannelHolder = Pick<+ OtherChannelHolderError,+ 'holderPid' | 'holderChannel' | 'holderKind' | 'selfChannel'+>;++export function otherChannelStopOffer(+ holder: Pick<OtherChannelHolderError, 'holderChannel' | 'holderKind' | 'selfChannel'>,+): { detail: string; button: string } {+ const holderLabel = desktopChannelLabel(holder.holderChannel);+ const selfLabel = desktopChannelLabel(holder.selfChannel);+ const situation =+ holder.holderKind === 'mcp-spawned'+ ? `An agent or editor started this ${holderLabel} server over MCP. It 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).`+ : `This ${holderLabel} server keeps running after any window showing the project closes, ` ++ `so the project stays busy until the server stops.`;+ const loses =+ holder.holderKind === 'mcp-spawned'+ ? 'Whatever the agent or editor is doing right now is interrupted, and its next request ' ++ 'reaches the server opened here.'+ : 'Every window, editor, or agent connected to it loses its connection to this project.';+ return {+ detail: `${situation} ${selfLabel} can stop it now and open the project here. ${loses}`,+ button: `Stop ${holderLabel} Server & Open Here`,+ };+}++type ChannelConflict = { holderChannel: string; selfChannel: DesktopProductName };++export type ForceStopOutcome =+ | { ok: true }+ | { ok: false; reason: 'eperm' | 'other' | 'holder-changed' };+function loopbackOriginFromUrl(url: unknown): string | null {if (typeof url !== 'string' || url.length === 0) return null;let parsed: URL | null = null;@@ -279,6 +355,7 @@ export interface WindowManagerDeps {appVersion: string;selfProtocolVersion?: number;selfRuntimeVersion?: string;+ selfChannel?: DesktopProductName;reclaimForeignServerInDev?: boolean;isFirstLaunchAfterUpgrade?(): boolean;setTimeout(cb: () => void, ms: number): unknown;@@ -566,8 +643,47 @@ export class WindowManager {return lock !== null && lock.draining !== true;}+ private otherChannelOf(lock: Pick<ServerLockMetadataLike, 'channel'>): ChannelConflict | null {+ const self = this.deps.selfChannel;+ return self !== undefined && lock.channel !== undefined && lock.channel !== self+ ? { holderChannel: lock.channel, selfChannel: self }+ : null;+ }++ private logOtherChannelRefusal(args: {+ lock: Pick<ServerLockMetadataLike, 'pid'>;+ holderChannel: string;+ projectPath: string;+ operation: 'attach' | 'spawn' | 'restart' | 'force-stop';+ }): void {+ this.deps.log?.warn(+ {+ event: 'desktop-server-refused-other-channel',+ operation: args.operation,+ lockPid: args.lock.pid,+ holderChannel: args.holderChannel,+ selfChannel: this.deps.selfChannel ?? null,+ projectPath: args.projectPath,+ },+ "[window-manager] refusing another channel's server for this project",+ );+ }++ private sigtermSpawnOrphan(pid: number, projectPath: string, message: string): void {+ try {+ this.deps.killProbe(pid, 'SIGTERM');+ } catch (signalErr) {+ const code = (signalErr as NodeJS.ErrnoException).code;+ if (code !== 'ESRCH') {+ this.deps.log?.warn(+ { event: 'desktop-spawn-orphan-sigterm-failed', err: signalErr, code, pid, projectPath },+ message,+ );+ }+ }+ }+private async terminateServerByPid(- _lockDir: string,pid: number,): Promise<{ ok: true; escalated: boolean } | { ok: false; reason: 'eperm' | 'other' }> {try {@@ -675,29 +791,78 @@ export class WindowManager {return true;}+ otherChannelLockHolder(projectPath: string): OtherChannelHolder | null {+ const lock = this.deps.readServerLock?.(getLocalDir(resolve(projectPath))) ?? null;+ if (lock === null || !isValidLockPidLocal(lock.pid)) return null;+ const conflict = this.otherChannelOf(lock);+ if (conflict === null) return null;+ return {+ holderPid: lock.pid,+ holderChannel: conflict.holderChannel,+ holderKind: lock.kind,+ selfChannel: conflict.selfChannel,+ };+ }+async forceStopConflictingServer(projectPath: string,- ): Promise<{ ok: true } | { ok: false; reason: 'eperm' | 'other' }> {+ expectedHolder?: { pid: number; channel: string },+ ): Promise<ForceStopOutcome> {const lockDir = getLocalDir(resolve(projectPath));let pid: unknown;let rawPort: unknown;let rawUrl: unknown;+ let rawChannel: unknown;try {const raw = JSON.parse(readFileSync(join(lockDir, 'server.lock'), 'utf-8')) as {pid?: unknown;port?: unknown;url?: unknown;+ channel?: unknown;};pid = raw?.pid;rawPort = raw?.port;rawUrl = raw?.url;+ rawChannel = raw?.channel;} catch {return { ok: true };}if (!isValidLockPidLocal(pid) || pid === process.pid) {return { ok: true };}- const term = await this.terminateServerByPid(lockDir, pid);+ const holderChannel = typeof rawChannel === 'string' ? rawChannel : null;+ const unboundConflict =+ expectedHolder === undefined+ ? this.otherChannelOf({ channel: holderChannel ?? undefined })+ : null;+ if (unboundConflict !== null) {+ this.logOtherChannelRefusal({+ lock: { pid },+ holderChannel: unboundConflict.holderChannel,+ projectPath,+ operation: 'force-stop',+ });+ return { ok: false, reason: 'holder-changed' };+ }+ if (+ expectedHolder !== undefined &&+ (pid !== expectedHolder.pid || holderChannel !== expectedHolder.channel)+ ) {+ this.deps.log?.warn(+ {+ event: 'desktop-force-stop-conflicting-server',+ outcome: 'holder-changed',+ pid,+ holderChannel,+ expectedPid: expectedHolder.pid,+ expectedHolderChannel: expectedHolder.channel,+ projectPath,+ },+ '[window-manager] lock holder changed since the user agreed to stop it; not signalling',+ );+ return { ok: false, reason: 'holder-changed' };+ }+ const term = await this.terminateServerByPid(pid);if (!term.ok && term.reason === 'eperm') {const broke = await this.breakUnservingHolderLock({lockDir,@@ -715,6 +880,7 @@ export class WindowManager {{event: 'desktop-force-stop-conflicting-server',pid,+ holderChannel,projectPath,outcome: term.ok ? 'stopped' : term.reason,},@@ -731,8 +897,18 @@ export class WindowManager {const canonicalKey = this.canonicalizeKey(resolved);const lockDir = getLocalDir(resolved);const lock = this.deps.readServerLock?.(lockDir) ?? null;+ const conflict = lock === null ? null : this.otherChannelOf(lock);+ if (lock !== null && conflict !== null) {+ this.logOtherChannelRefusal({+ lock,+ holderChannel: conflict.holderChannel,+ projectPath: resolved,+ operation: 'restart',+ });+ return { ok: false, reason: 'other-channel', holderChannel: conflict.holderChannel };+ }if (lock && isValidLockPidLocal(lock.pid)) {- const term = await this.terminateServerByPid(lockDir, lock.pid);+ const term = await this.terminateServerByPid(lock.pid);if (!term.ok) {const broke =term.reason === 'eperm' &&@@ -999,11 +1175,21 @@ export class WindowManager {const candidate = this.tryAttachExistingServer(lockDir);const attached =candidate !== null && (await this.probeAttachableLock(candidate)) ? candidate : null;+ const attachedConflict = attached === null ? null : this.otherChannelOf(attached);+ if (attached !== null && attachedConflict !== null) {+ this.logOtherChannelRefusal({+ lock: attached,+ holderChannel: attachedConflict.holderChannel,+ projectPath,+ operation: 'attach',+ });+ throw otherChannelHolderError(attached, attachedConflict);+ }if (attached) {const isForeign = this.spawnedDetachedPids.get(canonicalKey) !== attached.pid;let reclaimed = false;if (this.deps.reclaimForeignServerInDev === true && isForeign) {- const term = await this.terminateServerByPid(lockDir, attached.pid);+ const term = await this.terminateServerByPid(attached.pid);if (term.ok) {this.deps.log?.info({@@ -1037,7 +1223,7 @@ export class WindowManager {{ protocolVersion: selfProtocol, runtimeVersion: selfRuntime },);if (drift.relation === 'older' || drift.relation === 'newer') {- const term = await this.terminateServerByPid(lockDir, attached.pid);+ const term = await this.terminateServerByPid(attached.pid);if (term.ok) {this.deps.log?.info({@@ -1110,23 +1296,11 @@ export class WindowManager {? !this.deps.isProcessAlive(handle.pid): undefined;const childExit = handle.readExit?.() ?? null;- try {- this.deps.killProbe(handle.pid, 'SIGTERM');- } catch (signalErr) {- const code = (signalErr as NodeJS.ErrnoException).code;- if (code !== 'ESRCH') {- this.deps.log?.warn(- {- event: 'desktop-spawn-orphan-sigterm-failed',- err: signalErr,- code,- pid: handle.pid,- projectPath,- },- '[window-manager] SIGTERM on orphan after spawn-lock-timeout failed',- );- }- }+ this.sigtermSpawnOrphan(+ handle.pid,+ projectPath,+ '[window-manager] SIGTERM on orphan after spawn-lock-timeout failed',+ );this.spawnedDetachedPids.delete(canonicalKey);throw this.buildSpawnFailureError({pid: handle.pid,@@ -1144,30 +1318,20 @@ export class WindowManager {? !this.deps.isProcessAlive(handle.pid): undefined;const childExit = handle.readExit?.() ?? null;- try {- this.deps.killProbe(handle.pid, 'SIGTERM');- } catch (signalErr) {- const code = (signalErr as NodeJS.ErrnoException).code;- if (code !== 'ESRCH') {- this.deps.log?.warn(- {- event: 'desktop-spawn-orphan-sigterm-failed',- err: signalErr,- code,- pid: handle.pid,- projectPath,- },- '[window-manager] SIGTERM on orphan after refusing a stale lock failed',- );- }- }+ this.sigtermSpawnOrphan(+ handle.pid,+ projectPath,+ '[window-manager] SIGTERM on orphan after refusing a stale lock failed',+ );this.spawnedDetachedPids.delete(canonicalKey);+ const staleConflict = adoptedForeignLock ? this.otherChannelOf(lock) : null;this.deps.log?.warn({event: 'desktop-server-spawn-refused-stale-lock',reason: unusableLock ? 'lock-not-attachable' : 'holder-not-serving',pid: handle.pid,lockPid: lock.pid,+ ...(staleConflict !== null && { holderChannel: staleConflict.holderChannel }),port: lock.port,portType: typeof lock.port,rawPort: String(lock.port),@@ -1202,6 +1366,22 @@ export class WindowManager {},);}+ const adoptedConflict = adoptedForeignLock ? this.otherChannelOf(lock) : null;+ if (adoptedConflict !== null) {+ this.sigtermSpawnOrphan(+ handle.pid,+ projectPath,+ "[window-manager] SIGTERM on orphan after refusing another channel's server failed",+ );+ this.spawnedDetachedPids.delete(canonicalKey);+ this.logOtherChannelRefusal({+ lock,+ holderChannel: adoptedConflict.holderChannel,+ projectPath,+ operation: 'spawn',+ });+ throw otherChannelHolderError(lock, adoptedConflict);+ }this.deps.log?.info({event: 'desktop-server-spawned-detached',@@ -1801,7 +1981,7 @@ export class WindowManager {lockDir: string;}): Promise<void> {try {- const term = await this.terminateServerByPid(session.lockDir, session.pid);+ const term = await this.terminateServerByPid(session.pid);if (!term.ok) {this.deps.log?.warn({diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex f3f6aa0bf..6af88be6e 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -5,11 +5,14 @@ import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';import { DEFAULT_SERVER_HOST, formatSpawnAttemptHeader } from '@inkeep/open-knowledge-core';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { failedOpenHolder, promptHolderStop } from '../../src/main/holder-stop-prompt.ts';import { resolveLocalOpCliInvocation } from '../../src/main/local-op-cli-invocation.ts';import { breakServerLockHeldBy } from '../../src/main/server-lock-break.ts';import type { ShowGateRegistry } from '../../src/main/show-gate.ts';import {type BrowserWindowLike,+ isOtherChannelHolderError,+ otherChannelStopOffer,type ServerLockMetadataLike,type UtilityProcessLike,WindowManager,@@ -771,6 +774,437 @@ describe('WindowManager', () => {env.deps.probeWsUpgrade = overrides?.probeWsUpgrade ?? (() => Promise.resolve(true));}+ describe('one writer per project across channels', () => {+ const stableLock: ServerLockMetadataLike = { ...liveLock, channel: 'stable' };++ async function openOutcome(wm: WindowManager) {+ return wm.createProjectWindow({ projectPath: '/tmp/dragon' }).then(+ (ctx) => ({ kind: 'attached' as const, port: ctx.port }),+ (err) => ({+ kind: 'refused' as const,+ errKind: (err as Error & { kind?: string }).kind,+ holderChannel: (err as Error & { holderChannel?: string }).holderChannel,+ message: (err as Error).message,+ }),+ );+ }++ test("beta refuses to attach to stable's live server and never stops it, even on a reclaiming or post-upgrade launch", async () => {+ const killProbe = vi.fn(() => {});+ env.deps.killProbe = killProbe;+ env.deps.selfChannel = 'beta';+ env.deps.reclaimForeignServerInDev = true;+ env.deps.isFirstLaunchAfterUpgrade = () => true;+ env.deps.selfProtocolVersion = 999;+ env.deps.selfRuntimeVersion = '99.0.0';+ enableAttachProbe({ readServerLock: () => stableLock });++ const outcome = await openOutcome(new WindowManager(env.deps));++ expect(outcome).toEqual({+ kind: 'refused',+ errKind: 'other-channel-holder',+ holderChannel: 'stable',+ message:+ 'OpenKnowledge (Stable) is serving this project (pid 65792). Only one OpenKnowledge app can edit a project at a time.',+ });+ expect(killProbe).not.toHaveBeenCalled();+ expect(env.utilities.length).toBe(0);+ expect(env.windows.length).toBe(0);+ expect(+ env.logEntries.filter(+ (e) =>+ (e.payload as { event?: string }).event === 'desktop-server-refused-other-channel',+ ),+ ).toEqual([+ {+ payload: {+ event: 'desktop-server-refused-other-channel',+ operation: 'attach',+ lockPid: 65792,+ holderChannel: 'stable',+ selfChannel: 'beta',+ projectPath: '/tmp/dragon',+ },+ message: "[window-manager] refusing another channel's server for this project",+ },+ ]);+ });++ test("another channel's holder that is not serving gets the stale-lock recovery, not the serving refusal", async () => {+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ env.deps.selfChannel = 'beta';+ enableAttachProbe({+ readServerLock: () => stableLock,+ probeWsUpgrade: () => Promise.resolve(false),+ });+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: 22020 });+ env.deps.spawnLockPollDeadlineMs = 50;+ env.deps.spawnLockProgressDeadlineMs = 50;++ expect(await openOutcome(new WindowManager(env.deps))).toMatchObject({+ kind: 'refused',+ errKind: 'stale-lock-holder',+ });+ });++ async function stopFromDialog(+ lockOnDisk: ServerLockMetadataLike,+ expectedHolder?: { pid: number; channel: string },+ probeWsUpgrade?: WindowManagerDeps['probeWsUpgrade'],+ ) {+ const killed = new Set<number>();+ env.deps.killProbe = (pid, signal) => {+ if (signal === 'SIGTERM') killed.add(pid);+ };+ env.deps.selfChannel = 'beta';+ enableAttachProbe({+ readServerLock: () => lockOnDisk,+ isProcessAlive: (pid) => !killed.has(pid),+ probeWsUpgrade,+ });+ const projectPath = mkdtempSync(join(tmpdir(), 'ok-other-channel-stop-'));+ mkdirSync(join(projectPath, '.ok', 'local'), { recursive: true });+ writeFileSync(+ join(projectPath, '.ok', 'local', 'server.lock'),+ JSON.stringify(lockOnDisk),+ 'utf-8',+ );+ try {+ const outcome = await new WindowManager(env.deps).forceStopConflictingServer(+ projectPath,+ expectedHolder,+ );+ const stopLog = env.logEntries+ .map((e) => e.payload as Record<string, unknown>)+ .filter((p) => p.event === 'desktop-force-stop-conflicting-server')+ .map(({ projectPath: _projectPath, ...rest }) => rest);+ return { outcome, stopped: [...killed], stopLog };+ } finally {+ rmSync(projectPath, { recursive: true, force: true });+ }+ }++ test('the user-chosen stop frees a project another channel is serving', async () => {+ expect(await stopFromDialog(stableLock, { pid: 65792, channel: 'stable' })).toEqual({+ outcome: { ok: true },+ stopped: [65792],+ stopLog: [+ {+ event: 'desktop-force-stop-conflicting-server',+ pid: 65792,+ holderChannel: 'stable',+ outcome: 'stopped',+ },+ ],+ });+ });++ test('the user-chosen stop signals nothing when the holder changed after the dialog named it', async () => {+ expect(+ await stopFromDialog({ ...stableLock, pid: 70001 }, { pid: 65792, channel: 'stable' }),+ ).toEqual({+ outcome: { ok: false, reason: 'holder-changed' },+ stopped: [],+ stopLog: [+ {+ event: 'desktop-force-stop-conflicting-server',+ outcome: 'holder-changed',+ pid: 70001,+ holderChannel: 'stable',+ expectedPid: 65792,+ expectedHolderChannel: 'stable',+ },+ ],+ });+ expect(+ (await stopFromDialog(stableLock, { pid: 65792, channel: 'cloud' })).outcome,+ ).toEqual({ ok: false, reason: 'holder-changed' });+ });++ test('the generic stop, bound to no holder, signals nothing when another channel holds the project', async () => {+ expect(+ await stopFromDialog({ ...stableLock, pid: 65793 }, undefined, () =>+ Promise.resolve(false),+ ),+ ).toEqual({+ outcome: { ok: false, reason: 'holder-changed' },+ stopped: [],+ stopLog: [],+ });+ env.logEntries.length = 0;+ expect(await stopFromDialog(stableLock)).toEqual({+ outcome: { ok: false, reason: 'holder-changed' },+ stopped: [],+ stopLog: [],+ });+ expect(+ env.logEntries+ .map((e) => e.payload as Record<string, unknown>)+ .filter((p) => p.event === 'desktop-server-refused-other-channel')+ .map(({ projectPath: _projectPath, ...rest }) => rest),+ ).toEqual([+ {+ event: 'desktop-server-refused-other-channel',+ operation: 'force-stop',+ lockPid: 65792,+ holderChannel: 'stable',+ selfChannel: 'beta',+ },+ ]);+ expect(await stopFromDialog({ ...stableLock, channel: 'beta' })).toMatchObject({+ outcome: { ok: true },+ stopped: [65792],+ });+ });++ test('the generic stop still stops a lock that names no channel', async () => {+ expect(await stopFromDialog(liveLock)).toMatchObject({+ outcome: { ok: true },+ stopped: [65792],+ });+ });++ async function openThenStopStaleStableHolder(onDialog?: (projectPath: string) => void) {+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const STALE_PID = 65792;+ const signalled: Array<{ pid: number; signal: NodeJS.Signals | number }> = [];+ env.deps.killProbe = (pid, signal) => {+ signalled.push({ pid, signal });+ };+ const stopped = () => signalled.some((c) => c.pid === STALE_PID);+ const betaLock: ServerLockMetadataLike = {+ ...liveLock,+ pid: 70002,+ port: 59600,+ channel: 'beta',+ };+ env.deps.selfChannel = 'beta';+ enableAttachProbe({+ readServerLock: () => (stopped() ? betaLock : stableLock),+ isProcessAlive: (pid) => !(pid === STALE_PID && stopped()),+ probeWsUpgrade: (url) => Promise.resolve(!url.includes(String(stableLock.port))),+ });+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: 22020 });+ env.deps.spawnLockPollDeadlineMs = 50;+ env.deps.spawnLockProgressDeadlineMs = 50;+ const projectPath = mkdtempSync(join(tmpdir(), 'ok-other-channel-stale-'));+ mkdirSync(join(projectPath, '.ok', 'local'), { recursive: true });+ writeFileSync(+ join(projectPath, '.ok', 'local', 'server.lock'),+ JSON.stringify(stableLock),+ 'utf-8',+ );+ try {+ const wm = new WindowManager(env.deps);+ const err = await wm.createProjectWindow({ projectPath }).then(+ () => null,+ (e: unknown) => e as Error & { kind?: string },+ );+ let dialog: { detail: string; defaultId: number } | null = null;+ const stopTargets: unknown[] = [];+ let reopens = 0;+ const result = await promptHolderStop(+ {+ kind: err?.kind,+ errorMessage: err?.message ?? '',+ dialogTitle: 'A stopped server is still holding this project',+ dialogBody: err?.message ?? '',+ projectPath,+ otherChannelHolder: failedOpenHolder(err, projectPath, wm),+ warnsHolderMayBeLive: false,+ holderIsOwnChild: false,+ },+ {+ showMessageBox: (options) => {+ dialog = options;+ onDialog?.(projectPath);+ return Promise.resolve({ response: 0 });+ },+ forceStop: (expected) => {+ stopTargets.push(expected);+ return wm.forceStopConflictingServer(projectPath, expected);+ },+ retryOpen: () =>+ wm.createProjectWindow({ projectPath }).then(+ () => true,+ () => false,+ ),+ reopen: () => {+ reopens += 1;+ return Promise.resolve(false);+ },+ },+ );+ return {+ errKind: err?.kind,+ dialog: dialog as { detail: string; defaultId: number } | null,+ stopTargets,+ result,+ reopens,+ signalledHolders: signalled.filter((c) => c.pid !== 22020),+ };+ } finally {+ rmSync(projectPath, { recursive: true, force: true });+ }+ }++ test("Stop Server & Retry names another channel's holder that is not serving, defaults to Cancel, and stops only that holder", async () => {+ const run = await openThenStopStaleStableHolder();+ expect(run.errKind).toBe('stale-lock-holder');+ expect(+ env.logEntries+ .map((e) => e.payload as { event?: string; holderChannel?: string })+ .filter((p) => p.event === 'desktop-server-spawn-refused-stale-lock')+ .map((p) => p.holderChannel),+ ).toEqual(['stable']);+ expect(run.dialog?.detail).toContain(+ "OpenKnowledge (Stable) holds this project's server lock (pid 65792)",+ );+ expect(run.dialog?.detail).toContain('This OpenKnowledge (Stable) server keeps running');+ expect(run.dialog?.defaultId).toBe(1);+ expect(run.stopTargets).toEqual([{ pid: 65792, channel: 'stable' }]);+ expect({ result: run.result, reopens: run.reopens }).toEqual({+ result: { kind: 'retried', opened: true },+ reopens: 0,+ });+ expect(run.signalledHolders).toEqual([{ pid: 65792, signal: 'SIGTERM' }]);+ });++ test('Stop Server & Retry signals nothing when another holder took the lock while the dialog was open', async () => {+ const run = await openThenStopStaleStableHolder((projectPath) => {+ writeFileSync(+ join(projectPath, '.ok', 'local', 'server.lock'),+ JSON.stringify({ ...stableLock, pid: 70001 }),+ 'utf-8',+ );+ });+ expect(run.stopTargets).toEqual([{ pid: 65792, channel: 'stable' }]);+ expect({ result: run.result, reopens: run.reopens }).toEqual({+ result: { kind: 'reopened', opened: false },+ reopens: 1,+ });+ expect(run.signalledHolders).toEqual([]);+ });++ test("the lock on disk names another channel's holder for every failed-open dialog, and only that channel's", () => {+ env.deps.selfChannel = 'beta';+ let onDisk: ServerLockMetadataLike | null = null;+ env.deps.readServerLock = () => onDisk;+ const holderOf = (lock: ServerLockMetadataLike | null) => {+ onDisk = lock;+ return new WindowManager(env.deps).otherChannelLockHolder('/tmp/dragon');+ };+ expect(holderOf({ ...stableLock, port: 0, kind: 'mcp-spawned' })).toEqual({+ holderPid: 65792,+ holderChannel: 'stable',+ holderKind: 'mcp-spawned',+ selfChannel: 'beta',+ });+ expect(holderOf({ ...stableLock, channel: 'beta' })).toBeNull();+ expect(holderOf(liveLock)).toBeNull();+ expect(holderOf(null)).toBeNull();+ });++ test('the refusal error carries the holder it names, recoverable through one guard', async () => {+ env.deps.selfChannel = 'beta';+ enableAttachProbe({ readServerLock: () => ({ ...stableLock, kind: 'mcp-spawned' }) });+ const err = await new WindowManager(env.deps)+ .createProjectWindow({ projectPath: '/tmp/dragon' })+ .then(+ () => null,+ (e: unknown) => e,+ );+ expect(isOtherChannelHolderError(err)).toBe(true);+ expect(err).toMatchObject({+ kind: 'other-channel-holder',+ holderPid: 65792,+ holderChannel: 'stable',+ holderKind: 'mcp-spawned',+ selfChannel: 'beta',+ });+ expect(+ isOtherChannelHolderError(+ Object.assign(new Error('x'), {+ kind: 'other-channel-holder',+ holderPid: 65792,+ holderChannel: 'stable',+ }),+ ),+ ).toBe(false);+ });++ test('the stop offer names the acting app and describes who loses the connection by holder kind', () => {+ expect(+ otherChannelStopOffer({+ holderChannel: 'stable',+ holderKind: 'interactive',+ selfChannel: 'beta',+ }),+ ).toEqual({+ detail:+ 'This OpenKnowledge (Stable) server keeps running after any window showing the project closes, so the project stays busy until the server stops. OpenKnowledge Beta can stop it now and open the project here. Every window, editor, or agent connected to it loses its connection to this project.',+ button: 'Stop OpenKnowledge (Stable) Server & Open Here',+ });+ expect(+ otherChannelStopOffer({+ holderChannel: 'beta',+ holderKind: 'mcp-spawned',+ selfChannel: 'stable',+ }),+ ).toEqual({+ detail:+ 'An agent or editor started this OpenKnowledge Beta server over MCP. It 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). OpenKnowledge (Stable) can stop it now and open the project here. Whatever the agent or editor is doing right now is interrupted, and its next request reaches the server opened here.',+ button: 'Stop OpenKnowledge Beta Server & Open Here',+ });+ });++ test('a lock from the same channel, or one written before locks named a channel, still attaches', async () => {+ env.deps.selfChannel = 'stable';+ enableAttachProbe({ readServerLock: () => stableLock });+ expect(await openOutcome(new WindowManager(env.deps))).toEqual({+ kind: 'attached',+ port: 59534,+ });++ env.deps.selfChannel = 'beta';+ enableAttachProbe();+ expect(await openOutcome(new WindowManager(env.deps))).toEqual({+ kind: 'attached',+ port: 59534,+ });+ });++ test('a lock from a channel this build does not know is refused too, and named by its channel', async () => {+ env.deps.selfChannel = 'stable';+ enableAttachProbe({ readServerLock: () => ({ ...liveLock, channel: 'cloud' }) });+ expect(await openOutcome(new WindowManager(env.deps))).toMatchObject({+ kind: 'refused',+ errKind: 'other-channel-holder',+ holderChannel: 'cloud',+ message: expect.stringMatching(/^OpenKnowledge \(cloud\) is serving this project/),+ });+ });++ test("restart refuses to stop another channel's server", async () => {+ const killProbe = vi.fn(() => {});+ env.deps.killProbe = killProbe;+ env.deps.selfChannel = 'beta';+ enableAttachProbe({ readServerLock: () => stableLock });++ const outcome = await new WindowManager(env.deps).restartAttachedServer('/tmp/dragon');++ expect(outcome).toEqual({ ok: false, reason: 'other-channel', holderChannel: 'stable' });+ expect(killProbe).not.toHaveBeenCalled();+ });+ });+test('attaches to live same-host lock — no utility forked', async () => {enableAttachProbe();const runClean = vi.fn(() => Promise.resolve());@@ -2342,6 +2776,70 @@ describe('WindowManager', () => {expect(env.windows.length).toBe(1);});+ test("a spawn that finds another channel's server holding the lock refuses it and stops only its own child", async () => {+ enableSyncTimers();+ const OUR_CHILD_PID = 22019;+ const stableLock: ServerLockMetadataLike = { ...spawnedLock, pid: 871, channel: 'stable' };+ let reads = 0;+ env.deps.selfChannel = 'beta';+ env.deps.readServerLock = () => (reads++ === 0 ? null : stableLock);+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: OUR_CHILD_PID });+ const killCalls: Array<{ pid: number; signal: NodeJS.Signals | number }> = [];+ env.deps.killProbe = (pid, signal) => {+ killCalls.push({ pid, signal });+ throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' });+ };+ env.deps.spawnLockPollDeadlineMs = 50;+ env.deps.spawnLockProgressDeadlineMs = 50;++ const outcome = await new WindowManager(env.deps)+ .createProjectWindow({ projectPath: '/tmp/spawned-project' })+ .then(+ () => ({ kind: 'attached' as const }),+ (err) => ({+ kind: 'refused' as const,+ errKind: (err as Error & { kind?: string }).kind,+ holderPid: (err as Error & { holderPid?: number }).holderPid,+ }),+ );++ expect(outcome).toEqual({+ kind: 'refused',+ errKind: 'other-channel-holder',+ holderPid: 871,+ });+ expect(killCalls).toEqual([{ pid: OUR_CHILD_PID, signal: 'SIGTERM' }]);+ expect(env.windows.length).toBe(0);+ expect(+ env.logEntries+ .map((e) => e.payload as Record<string, unknown>)+ .filter(+ (p) =>+ p.event === 'desktop-spawn-orphan-sigterm-failed' ||+ p.event === 'desktop-server-refused-other-channel',+ )+ .map(({ err: _err, ...rest }) => rest),+ ).toEqual([+ {+ event: 'desktop-spawn-orphan-sigterm-failed',+ code: 'EPERM',+ pid: OUR_CHILD_PID,+ projectPath: '/tmp/spawned-project',+ },+ {+ event: 'desktop-server-refused-other-channel',+ operation: 'spawn',+ lockPid: 871,+ holderChannel: 'stable',+ selfChannel: 'beta',+ projectPath: '/tmp/spawned-project',+ },+ ]);+ });+test('a stale lock our child never replaced is NOT declared ready (dead port)', async () => {enableSyncTimers();const STALE_PID = 870;diff --git a/packages/server/src/process-lock.test.ts b/packages/server/src/process-lock.test.tsindex 34bc931d2..38678a925 100644--- a/packages/server/src/process-lock.test.ts+++ b/packages/server/src/process-lock.test.ts@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises';import { hostname, tmpdir } from 'node:os';import { resolve } from 'node:path';import { LOCAL_DIR } from '@inkeep/open-knowledge-core';-import { afterEach, beforeEach, describe, expect, test } from 'vitest';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import { getMachineId } from './machine-id';import {acquireProcessLock,@@ -711,6 +711,87 @@ describe('version metadata (protocolVersion + runtimeVersion)', () => {});});+describe('channel metadata (one writer per project across channels)', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ test('the lock names the channel that wrote it, and both readers return it', () => {+ vi.stubEnv('OK_CHANNEL', 'beta');+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 3000, worktreeRoot: '/me' },+ });+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.channel).toBe('beta');+ expect(readProcessLock({ lockName: LOCK_NAME, lockDir })?.channel).toBe('beta');+ const detailed = readProcessLockDetailed({ lockName: LOCK_NAME, lockDir });+ expect(detailed.status === 'live' ? detailed.lock.channel : null).toBe('beta');+ });++ test('a lock with no channel reads back without one, and a channel this build does not know is kept', () => {+ mkdirSync(lockDir, { recursive: true });+ for (const channel of [undefined, 'cloud']) {+ writeFileSync(+ lockPath,+ JSON.stringify({+ pid: process.pid,+ hostname: hostname(),+ port: 3000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/me',+ machineId: getMachineId(),+ protocolVersion: PROTOCOL_VERSION,+ runtimeVersion: RUNTIME_VERSION,+ ...(channel === undefined ? {} : { channel }),+ }),+ );+ const detailed = readProcessLockDetailed({ lockName: LOCK_NAME, lockDir });+ expect(detailed.status).toBe('live');+ expect(detailed.status === 'live' ? detailed.lock.channel : 'unread').toBe(channel);+ }+ });++ test('both readers treat a channel that is not a non-empty string as absent', () => {+ mkdirSync(lockDir, { recursive: true });+ for (const channel of ['', 42, null]) {+ writeFileSync(+ lockPath,+ JSON.stringify({+ pid: process.pid,+ hostname: hostname(),+ port: 3000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/me',+ machineId: getMachineId(),+ protocolVersion: PROTOCOL_VERSION,+ runtimeVersion: RUNTIME_VERSION,+ channel,+ }),+ );+ const plain = readProcessLock({ lockName: LOCK_NAME, lockDir });+ const detailed = readProcessLockDetailed({ lockName: LOCK_NAME, lockDir });+ expect({+ plain: plain === null ? 'unread' : plain.channel,+ detailed: detailed.status === 'live' ? detailed.lock.channel : 'unread',+ }).toEqual({ plain: undefined, detailed: undefined });+ }+ });++ test('an unsupported OK_CHANNEL still acquires the lock, without a channel', () => {+ vi.stubEnv('OK_CHANNEL', 'cloud');+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 3000, worktreeRoot: '/me' },+ });+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.pid).toBe(process.pid);+ expect('channel' in md).toBe(false);+ });+});+describe('readProcessLockDetailed', () => {test('returns absent when no lock file exists', () => {const result = readProcessLockDetailed({ lockName: LOCK_NAME, lockDir });diff --git a/packages/server/src/process-lock.ts b/packages/server/src/process-lock.tsindex 48548f260..95bf213c4 100644--- a/packages/server/src/process-lock.ts+++ b/packages/server/src/process-lock.ts@@ -10,6 +10,7 @@ import {} from 'node:fs';import { hostname } from 'node:os';import { resolve } from 'node:path';+import { resolveDesktopProductName } from '@inkeep/open-knowledge-core';import { errnoCode } from './http/handler-utils.ts';import { getLogger } from './logger.ts';import { getMachineId } from './machine-id.ts';@@ -36,6 +37,7 @@ export interface ProcessLockMetadata {capabilities?: string[];protocolVersion?: number;runtimeVersion?: string;+ channel?: string;}export interface ProcessLockHandle {@@ -126,6 +128,22 @@ function parseLock(lockPath: string, logPrefix: string): ProcessLockMetadata | n}}+function writerChannel(logPrefix: string): string | undefined {+ try {+ return resolveDesktopProductName();+ } catch (err) {+ log.warn(+ { err },+ `${logPrefix} Not recording a channel: ${err instanceof Error ? err.message : String(err)}`,+ );+ return undefined;+ }+}++function lockChannel(value: unknown): string | undefined {+ return typeof value === 'string' && value.length > 0 ? value : undefined;+}+export function acquireProcessLock(opts: {lockName: LockName;lockDir: string;@@ -159,6 +177,7 @@ export function acquireProcessLock(opts: {...(init.capabilities !== undefined && { capabilities: init.capabilities }),protocolVersion: init.protocolVersion ?? PROTOCOL_VERSION,runtimeVersion: init.runtimeVersion ?? RUNTIME_VERSION,+ channel: writerChannel(logPrefix),};const payload = JSON.stringify(record, null, 2);@@ -380,7 +399,7 @@ export function readProcessLock(opts: {const parsed = JSON.parse(readFileSync(lockPath, 'utf-8'));if (!parsed || typeof parsed !== 'object' || !isValidLockPid((parsed as { pid?: unknown }).pid))return null;- existing = parsed as ProcessLockMetadata;+ existing = { ...parsed, channel: lockChannel(parsed.channel) } as ProcessLockMetadata;} catch {return null;}@@ -446,6 +465,7 @@ export function readProcessLockDetailed(opts: {: undefined,protocolVersion: typeof r.protocolVersion === 'number' ? r.protocolVersion : undefined,runtimeVersion: typeof r.runtimeVersion === 'string' ? r.runtimeVersion : undefined,+ channel: lockChannel(r.channel),};if (!isSameMachine(lock)) return { status: 'stale', lock };