Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): ephemeral server keepalive + recovery (PRD-8119, PRD-8212) (#3818)

omar-inkeepf73e9644ed6a
diff --git a/.changeset/prd-8212-reauth-loop-and-honest-toast.md b/.changeset/prd-8212-reauth-loop-and-honest-toast.md
new file mode 100644
index 000000000..d6b3fe8f8
--- /dev/null
+++ b/.changeset/prd-8212-reauth-loop-and-honest-toast.md
@@ -0,0 +1,13 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Ephemeral single-file sessions (`ok <file>`, or opening a loose file in the desktop app) are now resilient when their server stops.
+
+- **Single-file servers no longer idle-die under an open editor.** A single-file window now holds its server alive for as long as the window is open, the same way a project window already did. Previously the single-file server inherited the 30-minute idle-shutdown default with nothing holding it up, so it could shut down while you were still editing.
+
+- **"Restart server" now works for a single file.** The restart action is routed to the correct server by the window that requested it, so restarting a stopped single-file session actually respawns it (before, it failed with "Couldn't restart the server"). Reopening a file whose server has stopped, or restarting it, converges to a single live window instead of leaving a dead one lingering.
+
+- **The connection notice is honest, and the editor stops retrying a dead server.** After a short grace with no reconnection the "keep this tab open, your edits will sync when reconnected" notice changes to a clear "the server stopped — restart it to reconnect," and the renderer stops re-authenticating against an unreachable server instead of looping until the tab is closed. A genuine transient blip still reconnects within the grace and shows "Reconnected." If the connection comes back but editing still doesn't resume, the notice says so ("Connected, but your edits aren't reaching the server yet") and keeps the Restart button, instead of leaving a stale claim on screen. Navigating during an outage — to another document, an image, a folder view — no longer silences the notice, and no longer restarts the grace behind it, so hopping between tabs can't win back the "will sync when reconnected" message from a server that has actually stopped. The notice updates the next time a document is in focus.
+
+**Behavior change for self-hosted deployments:** a loopback-bound server that declares itself externally reachable (`server.allowExternal` + `server.externalUrl` — the tunnel-to-loopback remote recipe) now defaults `server.idleShutdown` to `off` instead of `30m`. The idle timer only counts editor WebSocket connections and cannot see remote MCP agents, so such a server previously tore down under a remote agent mid-session unless you set `idleShutdown: off` by hand. A plain loopback server with no external URL is unchanged (`30m`).
diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdx
index 8f97c7701..7442c88f5 100644
--- a/docs/content/reference/configuration.mdx
+++ b/docs/content/reference/configuration.mdx
@@ -60,7 +60,7 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi
| `server.externalUrl` | string | (unset) | project | Canonical external origin the server is reached at, e.g. `https://kb.example.com` — its host joins the Host/Origin allowlists and issued URLs. Setting it declares external exposure, which additionally requires the `server.allowExternal` consent interlock. Env: `OK_EXTERNAL_URL`; flag: `ok start --external-url <url>`. Read at server start. |
| `server.allowExternal` | boolean | `false` | project-local | Exposure consent interlock: a non-loopback `server.bind` (or external requests behind a proxy declared via `server.externalUrl`) is refused without it. Per-machine — consent never travels via git, clone, or share; containers consent via `OK_ALLOW_EXTERNAL=1` instead. There is no server-side auth: restrict who can reach the server at the edge. |
| `server.openBrowser` | boolean | derived: `true` loopback-only, `false` otherwise | project-local | Open the editor in a browser once at start. The derived default means a laptop start pops the UI and an exposed or containerized server stays headless. Env: `OK_OPEN_BROWSER`; flag: `--no-open-browser`. |
-| `server.idleShutdown` | `"off"` or duration (`90s`, `30m`, `2h`) | derived: `30m` loopback-only, `off` otherwise | project-local | Shut the server down after this long with no connected editor (WebSocket) clients. Remote MCP sessions are plain HTTP the timer cannot see — set `off` (or `OK_IDLE_SHUTDOWN=off`) when remote agents use the server, or it tears down under them mid-session. |
+| `server.idleShutdown` | `"off"` or duration (`90s`, `30m`, `2h`) | derived: `30m` loopback-only & unexposed, `off` otherwise | project-local | Shut the server down after this long with no connected editor (WebSocket) clients. Remote MCP sessions are plain HTTP the timer cannot see, so an exposed deployment (`server.allowExternal` + `server.externalUrl`) derives `off` automatically. Set `off` manually (or `OK_IDLE_SHUTDOWN=off`) only in the residual case the derivation misses — a loopback server reached by remote agents with no `externalUrl` (e.g. behind a same-box reverse proxy) — or it tears down under them mid-session. |
| `editor.wordWrap` | boolean | `true` | user | Soft-wrap long lines in the source-mode CodeMirror editor. A personal preference, not project-shared. Toggle from the Settings pane. |
| `editor.previewTabs` | boolean | `true` | user | Reuse one replaceable preview tab for single clicks in the Files tree and Skills sidebar, so browsing does not accumulate tabs. Double-click the tab title, pin it, or choose **Keep open** from its context menu to make it permanent. Set `false` to open every click in its own tab. Rename transitions still reuse the current tab; back/forward navigation focuses the target's existing tab, or opens a permanent one when it is no longer open. A personal preference; toggle it from **Settings → Preferences → Preview tabs**. |
| `appearance.preview.autoOpen` | boolean | `true` | user | Whether the agent should open or refresh the OpenKnowledge preview when it edits a doc through the MCP. Default `true` lets the agent route the preview by host capability: the host's in-app browser (Cursor preview pane, Codex's built-in browser, Claude Code Desktop) when one exists, the system browser otherwise. Set `false` to keep the agent's hands off your preview window. This is useful when you're already viewing the doc in OK Desktop, a browser tab on a second display, a non-default browser, or any flow where your extensions / accessibility tooling only work in your own browser. The agent then surfaces the URL on request but does not navigate. The change takes effect on the next preview-related tool call. Toggle from **Settings → Preferences → "Open preview when agent edits"**. |
diff --git a/packages/app/src/editor/provider-pool.test.ts b/packages/app/src/editor/provider-pool.test.ts
index 0276df412..b78f2c263 100644
--- a/packages/app/src/editor/provider-pool.test.ts
+++ b/packages/app/src/editor/provider-pool.test.ts
@@ -2835,6 +2835,125 @@ describe('ProviderPool syncPromise lifecycle integration (F15)', () => {
// see the same .status='rejected' thenable so the boundary catches).
expect(__syncPromiseCacheSize()).toBe(1);
});
+
+ // When the ephemeral single-file server dies, the WS reconnect loop produces
+ // close after close; each server-driven close fires a fresh `sendToken()`
+ // reauth. The `serverDrivenCloseReauthInFlight` flag only
+ // dedupes CONCURRENT closes — sequential closes over time must not reauth
+ // without limit, or the renderer loops forever against a dead server.
+ test('server-driven-close reauth is bounded — sequential closes do not sendToken without limit', async () => {
+ pool = new ProviderPool(3, DUMMY_WS);
+ const entry = pool.open('doc1');
+ if (!entry) throw new Error('expected entry');
+ const sendTokenSpy = vi
+ .spyOn(entry.provider, 'sendToken')
+ .mockImplementation(() => Promise.resolve());
+
+ // Fire far more server-driven closes than any reasonable ceiling. Yield two
+ // microtasks between each so the reauth's `.finally` clears the in-flight
+ // flag before the next close (otherwise the in-flight guard, not the
+ // ceiling, would be what stops the loop — masking the bug).
+ const CLOSES = 15;
+ for (let i = 0; i < CLOSES; i++) {
+ entry.provider.emit('close', {
+ event: { code: 4205, reason: 'Reset Connection', wasClean: true },
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ }
+
+ // Exactly SERVER_DRIVEN_CLOSE_REAUTH_CEILING (5) reauths fire, then the loop
+ // terminates — the 6th close and beyond short-circuit at the ceiling.
+ expect(sendTokenSpy.mock.calls.length).toBe(5);
+ });
+
+ // A raw WS-transport drop arrives on the same `'close'` event but with an EMPTY
+ // reason (the server never sends an empty CloseMessage reason). Re-authing on it
+ // is pointless — the transport is gone — and against a dead ephemeral server it
+ // is the close-after-close that would spin, so the handler skips it at the root
+ // (the `'disconnect'` arm + the syncPromise rejection own that path).
+ test('a transport-drop close (empty reason) never triggers a reauth', async () => {
+ pool = new ProviderPool(3, DUMMY_WS);
+ const entry = pool.open('doc1');
+ if (!entry) throw new Error('expected entry');
+ const sendTokenSpy = vi
+ .spyOn(entry.provider, 'sendToken')
+ .mockImplementation(() => Promise.resolve());
+
+ for (let i = 0; i < 15; i++) {
+ // 1006 abnormal / empty reason = the raw socket dropped, not a server
+ // decision. (`reason: ''` and an absent reason both exercise the guard.)
+ entry.provider.emit('close', { event: { code: 1006, reason: '', wasClean: false } });
+ entry.provider.emit('close', { event: { code: 1006, wasClean: false } });
+ await Promise.resolve();
+ await Promise.resolve();
+ }
+
+ expect(sendTokenSpy).not.toHaveBeenCalled();
+ });
+
+ test('a successful sync resets the server-driven-close reauth ceiling', async () => {
+ pool = new ProviderPool(3, DUMMY_WS);
+ const entry = pool.open('doc1');
+ if (!entry) throw new Error('expected entry');
+ const sendTokenSpy = vi
+ .spyOn(entry.provider, 'sendToken')
+ .mockImplementation(() => Promise.resolve());
+
+ const fireClose = async () => {
+ entry.provider.emit('close', {
+ event: { code: 4205, reason: 'Reset Connection', wasClean: true },
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ };
+
+ // Exhaust the ceiling with a burst of closes.
+ for (let i = 0; i < 10; i++) await fireClose();
+ const afterCeiling = sendTokenSpy.mock.calls.length;
+ expect(afterCeiling).toBeLessThanOrEqual(6);
+
+ // A successful sync means the reauth actually worked — the ceiling must
+ // reset so a LATER server-death is recoverable again.
+ entry.provider.emit('synced', { state: true });
+ await Promise.resolve();
+
+ for (let i = 0; i < 10; i++) await fireClose();
+
+ // After the reset, more reauths were attempted than the single-burst
+ // ceiling allowed — proving the counter cleared on sync (without a reset,
+ // the count would stay pinned at the ceiling).
+ expect(sendTokenSpy.mock.calls.length).toBeGreaterThan(afterCeiling);
+ });
+
+ test('the ceiling breadcrumb is emitted exactly once no matter how many closes follow', async () => {
+ pool = new ProviderPool(3, DUMMY_WS);
+ const entry = pool.open('doc1');
+ if (!entry) throw new Error('expected entry');
+ vi.spyOn(entry.provider, 'sendToken').mockImplementation(() => Promise.resolve());
+ const warns: string[] = [];
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation((msg: unknown) => {
+ warns.push(String(msg));
+ });
+
+ try {
+ // Fire far past the ceiling so many closes land in the terminal branch.
+ for (let i = 0; i < 20; i++) {
+ entry.provider.emit('close', {
+ event: { code: 4205, reason: 'Reset Connection', wasClean: true },
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ }
+ } finally {
+ warnSpy.mockRestore();
+ }
+
+ const ceilingWarns = warns.filter((w) =>
+ w.includes('ok-provider-server-driven-close-reauth-ceiling'),
+ );
+ expect(ceilingWarns).toHaveLength(1);
+ });
});
// ---------------------------------------------------------------------------
diff --git a/packages/app/src/editor/provider-pool.ts b/packages/app/src/editor/provider-pool.ts
index 58342e5c1..b9f9383dd 100644
--- a/packages/app/src/editor/provider-pool.ts
+++ b/packages/app/src/editor/provider-pool.ts
@@ -101,6 +101,25 @@ export type ServerRestartRecoveryState =
const IDLE_SERVER_RESTART_RECOVERY: ServerRestartRecoveryState = Object.freeze({ kind: 'idle' });
+/**
+ * Ceiling on consecutive server-driven-close reauth attempts before the pool
+ * stops re-authing and emits a one-shot escalation breadcrumb (a structured
+ * `console.warn`, not a queryable state field).
+ *
+ * Division of labour, so this constant is not mistaken for the dead-server fix:
+ * a genuine server-driven close (application-level `CloseMessage`) carries a
+ * reason and normally means a rename/remove remap that a single `sendToken()`
+ * resolves. The DEAD-server reconnect loop is filtered upstream by the
+ * empty-reason guard in `onServerDrivenClose` (a dead server's raw WS drops carry
+ * no reason), so it never reaches — let alone touches — this counter. Concurrent
+ * closes are deduped by `serverDrivenCloseReauthInFlight`. This ceiling is the
+ * remaining backstop for a REASONED close that repeats with no intervening
+ * `synced` (e.g. a server bug resending 4205). The counter
+ * (`serverDrivenCloseReauthAttempts`) resets to 0 on any successful `synced`, so
+ * a genuine transient never trips it.
+ */
+const SERVER_DRIVEN_CLOSE_REAUTH_CEILING = 5;
+
/**
* Pool entries follow a two-state lifecycle modeled as a discriminated
* union: `Active` (the normal case — provider live, persistence attached)
@@ -236,6 +255,15 @@ interface ActivePoolEntry extends PoolEntryBase {
* resets when `sendToken` settles (success or failure).
*/
serverDrivenCloseReauthInFlight: boolean;
+ /**
+ * Count of consecutive reasoned server-driven-close reauth attempts since the
+ * last successful `synced`; reset to 0 in the `synced` handler. Held at most
+ * one PAST `SERVER_DRIVEN_CLOSE_REAUTH_CEILING` — the ceiling+1 value is the
+ * one-shot sentinel meaning "escalation breadcrumb already emitted". See that
+ * constant's docblock for what the bound protects against (and what it
+ * deliberately does not).
+ */
+ serverDrivenCloseReauthAttempts: number;
}
/**
@@ -251,6 +279,7 @@ interface TearingDownPoolEntry extends PoolEntryBase {
observerFireCounterCleanup: null;
pendingRecycleTimer: null;
serverDrivenCloseReauthInFlight: false;
+ serverDrivenCloseReauthAttempts: 0;
}
type PoolEntry = ActivePoolEntry | TearingDownPoolEntry;
@@ -2018,6 +2047,7 @@ export class ProviderPool {
pendingRecycleTimer: null,
bridgeSetupFailed: false,
serverDrivenCloseReauthInFlight: false,
+ serverDrivenCloseReauthAttempts: 0,
persistenceAttachOwned: false,
lineageEpochRecordAtOpen,
};
@@ -2059,6 +2089,11 @@ export class ProviderPool {
clearTimeout(entry.pendingRecycleTimer);
entry.pendingRecycleTimer = null;
}
+ // A successful sync means any prior server-driven-close reauth actually
+ // worked — clear the streak so a later REASONED close gets a fresh
+ // re-auth budget. Scope and non-scope of the bound:
+ // `SERVER_DRIVEN_CLOSE_REAUTH_CEILING`.
+ entry.serverDrivenCloseReauthAttempts = 0;
this.markServerRestartRecoverySynced(docName);
this.notify();
@@ -2342,7 +2377,44 @@ export class ProviderPool {
// exists, cache miss) and the doc resumes — safe in both directions.
const onServerDrivenClose = ({ event }: { event?: { code?: number; reason?: string } }) => {
if (entry.kind !== 'active' || this.entries.get(docName) !== entry) return;
+ // Re-auth is only meaningful for a genuine server-driven doc-level close.
+ // This same `'close'` event also fires for a raw WS-transport drop (a dead
+ // server's reconnect loop, sleep/wake, a network blip), which arrives with
+ // an EMPTY reason — the server NEVER sends an empty CloseMessage reason (its
+ // default is "Server closed the connection"; `closeConnections` sends 4205
+ // "Reset Connection"), so an empty reason is definitionally a transport
+ // drop. Those are owned by the `'disconnect'` arm and the syncPromise
+ // rejection, not a doc-level auth decision: re-authing on them is pointless
+ // (the transport is gone, the token can't send) and, against a dead server,
+ // IS the close-after-close that would otherwise spin. Skip them at the root;
+ // what the ceiling below still backstops is documented on
+ // `SERVER_DRIVEN_CLOSE_REAUTH_CEILING`.
+ if (!event?.reason) return;
if (entry.serverDrivenCloseReauthInFlight) return;
+ // Ceiling: stop re-authing once the streak of failed reauths (no
+ // intervening `synced`, which resets the counter) reaches the bound, and
+ // escalate ONCE with a structured `console.warn` breadcrumb — a log
+ // trail, not a queryable state field. What this protects against (and
+ // what the empty-reason guard above already owns instead) is documented
+ // once, on `SERVER_DRIVEN_CLOSE_REAUTH_CEILING`.
+ if (entry.serverDrivenCloseReauthAttempts >= SERVER_DRIVEN_CLOSE_REAUTH_CEILING) {
+ if (entry.serverDrivenCloseReauthAttempts === SERVER_DRIVEN_CLOSE_REAUTH_CEILING) {
+ // One-shot: bump past the ceiling so later closes short-circuit here
+ // without re-emitting the escalation.
+ entry.serverDrivenCloseReauthAttempts = SERVER_DRIVEN_CLOSE_REAUTH_CEILING + 1;
+ console.warn(
+ JSON.stringify({
+ event: 'ok-provider-server-driven-close-reauth-ceiling',
+ docName,
+ attempts: SERVER_DRIVEN_CLOSE_REAUTH_CEILING,
+ reason: event?.reason ?? '<unknown>',
+ code: event?.code ?? null,
+ }),
+ );
+ }
+ return;
+ }
+ entry.serverDrivenCloseReauthAttempts += 1;
entry.serverDrivenCloseReauthInFlight = true;
// Fire-and-forget. `sendToken` is async (the token resolver may be
// a function), but failures that surface as a permission denial route
@@ -2372,18 +2444,15 @@ export class ProviderPool {
entry.serverDrivenCloseReauthInFlight = false;
}
});
- const reason = event?.reason ?? '<unknown>';
- // `code` tells intentional closes apart from transport drops in a
- // diagnostic bundle: the server NEVER sends an empty reason (its
- // CloseMessage defaults to "Server closed the connection", and
- // closeConnections sends 4205 "Reset Connection") — so reason '' means
- // the raw WebSocket dropped (1006 abnormal, 1001 going-away) and the
- // close was never a server decision at all.
+ // Reason is guaranteed non-empty here (empty-reason transport drops
+ // returned above), so this only records genuine server-driven closes.
+ // `code` still distinguishes the server's close variants (default vs 4205
+ // "Reset Connection") in a diagnostic bundle.
console.info(
JSON.stringify({
event: 'ok-provider-server-driven-close-reauth',
docName,
- reason,
+ reason: event.reason,
code: event?.code ?? null,
}),
);
@@ -3784,6 +3853,7 @@ export class ProviderPool {
torn.observerFireCounterCleanup = null;
torn.pendingRecycleTimer = null;
torn.serverDrivenCloseReauthInFlight = false;
+ torn.serverDrivenCloseReauthAttempts = 0;
if (pendingRecycleTimer) clearTimeout(pendingRecycleTimer);
diff --git a/packages/app/src/lib/use-server-keepalive.ts b/packages/app/src/lib/use-server-keepalive.ts
index 9d7155918..22bc1dad6 100644
--- a/packages/app/src/lib/use-server-keepalive.ts
+++ b/packages/app/src/lib/use-server-keepalive.ts
@@ -74,8 +74,11 @@ export function useServerKeepalive(
useEffect(() => {
const start = optionsRef.current?.startKeepalive ?? defaultStartKeepalive;
const isElectronHost = optionsRef.current?.isElectronHost ?? defaultIsElectronHost;
- // Desktop already holds a main-process keepalive and boots its server with
- // idleShutdownMs: null, so a renderer keepalive there is redundant.
+ // Desktop already holds a main-process keepalive for every window kind, so a
+ // renderer keepalive here is redundant: both the packaged project-window
+ // attach path and ephemeral single-file windows open an explicit
+ // `createKeepalive` against the server's real idle default, and the dev-only
+ // utility-fork boot additionally passes `idleShutdownMs: null`.
if (isElectronHost()) return;
const handle = start({
resolveWsUrl: async () => keepaliveBaseFromCollabUrl(collabUrlRef.current),
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index 6bf330d3d..9f729c1f8 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -764,6 +764,7 @@
"8OxKZy": ["نجح النقل لكن الشريط الجانبي قد يكون قديمًا — حدّث لإعادة المزامنة"],
"8PifYj": ["مخطط Mermaid"],
"8PmoQF": ["افتح قائمة الإدراج في موضع نصي فارغ أو نشط."],
+ "8QLpZe": ["توقّف الخادم. أعد تشغيله لإعادة الاتصال."],
"8RtNI0": ["فشل تحميل المستندات"],
"8TvlHF": ["تفريغ الأعطال"],
"8Uv5e6": ["الوكلاء"],
@@ -2928,6 +2929,7 @@
"X3MMeA": ["لا يوجد لأي من هذه المشكلات إصلاح تلقائي."],
"X59Fx2": ["تعذّر فتح هذا المستند في Slidev."],
"X7ShnN": ["فتح لوحة الوكلاء"],
+ "X7fxS9": ["متصل، لكن تعديلاتك لا تصل إلى الخادم بعد. أعد تشغيله إذا استمر ذلك."],
"X7u0xR": [["0"], " قالب متاح"],
"X8kjQX": ["أعد المصادقة مع GitHub"],
"X9VpsP": ["يجري تحميل محتويات المجلد"],
@@ -4402,6 +4404,7 @@
"mYGY3B": ["التاريخ"],
"mYzDD_": ["يوجد بالفعل مجلد شجرة عمل لذلك الفرع."],
"mZ1r4i": ["إنشاء مستند من ", ["label"]],
+ "m_mtGl": ["توقّف الخادم."],
"maDWIB": ["مصدر المرآة <0>api-spec</0>"],
"makN88": ["لا توجد أنماط بعد. اكتب اسم مجلد أو ملف أدناه لبدء إخفاء الملفات."],
"mdKFEy": ["ألغيت تحميل «", ["docName"], "»."],
@@ -4500,6 +4503,7 @@
"n4vt3Q": ["تنزيل التطبيق"],
"n5Vy3l": ["فُتح على الفرع ", ["branch"]],
"n5n_vi": ["مستودع خاص"],
+ "n6N-xC": ["متصل، لكن تعديلاتك لا تصل إلى الخادم بعد."],
"n6hXUm": [
"تجلب المزامنة التلقائية الإيداعات وتسحبها وتدفعها دوريًا إلى مستودع git البعيد لديك لتبقى تعديلاتك متزامنة عبر أجهزتك."
],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index 87f1d3cc4..4e35a24ad 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -3213,6 +3213,14 @@ msgstr "متصل بـ"
msgid "Connected to GitHub"
msgstr "متصل بـ GitHub"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "متصل، لكن تعديلاتك لا تصل إلى الخادم بعد."
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "متصل، لكن تعديلاتك لا تصل إلى الخادم بعد. أعد تشغيله إذا استمر ذلك."
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13248,6 +13256,14 @@ msgstr "ملف المخطط غير موجود أو فشل تحميله — إض
msgid "the server responded but server.lock has no port yet"
msgstr "استجاب الخادم لكن server.lock لا يحتوي على منفذ بعد"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "توقّف الخادم."
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "توقّف الخادم. أعد تشغيله لإعادة الاتصال."
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index 72968aca2..1c6aa8a10 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -638,6 +638,7 @@
"8OxKZy": ["সরানো সফল হয়েছে কিন্তু সাইডবার পুরোনো হতে পারে — আবার সিঙ্ক করতে সতেজ করুন"],
"8PifYj": ["Mermaid চিত্র"],
"8PmoQF": ["কোনো খালি বা সক্রিয় লেখার অবস্থানে সন্নিবেশ মেনু খুলুন।"],
+ "8QLpZe": ["সার্ভার বন্ধ হয়ে গেছে। পুনরায় সংযোগের জন্য এটি পুনরায় চালু করুন।"],
"8RtNI0": ["নথি লোড করতে ব্যর্থ"],
"8TvlHF": ["ক্র্যাশ ডাম্প"],
"8Uv5e6": ["এজেন্ট"],
@@ -2481,6 +2482,7 @@
"X3MMeA": ["এই সমস্যাগুলোর কোনোটিরই স্বয়ংক্রিয় সমাধান নেই।"],
"X59Fx2": ["এই নথিটি Slidev-এ খোলা যায়নি।"],
"X7ShnN": ["এজেন্ট প্যানেল খুলুন"],
+ "X7fxS9": ["সংযোগ হয়েছে, কিন্তু আপনার সম্পাদনা এখনও সার্ভারে পৌঁছাচ্ছে না। এটি চলতে থাকলে সার্ভার পুনরায় চালু করুন।"],
"X7u0xR": [["0"], "টি টেমপ্লেট আছে"],
"X8kjQX": ["GitHub-এর সঙ্গে আবার প্রমাণীকরণ করুন"],
"X9VpsP": ["ফোল্ডারের বিষয়বস্তু লোড হচ্ছে"],
@@ -3777,6 +3779,7 @@
"mYGY3B": ["তারিখ"],
"mYzDD_": ["ওই ব্রাঞ্চের জন্য একটি ওয়ার্কট্রি ফোল্ডার আগে থেকেই আছে।"],
"mZ1r4i": [["label"], " থেকে একটি নথি তৈরি করুন"],
+ "m_mtGl": ["সার্ভার বন্ধ হয়ে গেছে।"],
"maDWIB": ["মিরর উৎস <0>api-spec</0>"],
"makN88": ["এখনও কোনো প্যাটার্ন নেই। ফাইল লুকানো শুরু করতে নিচে একটি ফোল্ডার বা ফাইলের নাম লিখুন।"],
"mdKFEy": ["আপনি \"", ["docName"], "\" লোড করা বাতিল করেছেন।"],
@@ -3845,6 +3848,7 @@
"n4vt3Q": ["অ্যাপ ডাউনলোড করুন"],
"n5Vy3l": [["branch"], " ব্রাঞ্চে খোলা হয়েছে"],
"n5n_vi": ["ব্যক্তিগত রিপোজিটরি"],
+ "n6N-xC": ["সংযোগ হয়েছে, কিন্তু আপনার সম্পাদনা এখনও সার্ভারে পৌঁছাচ্ছে না।"],
"n6hXUm": [
"স্বয়ংক্রিয় সিঙ্ক নিয়মিতভাবে আপনার রিমোট git রিপোজিটরি থেকে কমিট আনে, টানে ও পাঠায় যাতে আপনার সম্পাদনা সব মেশিনে মিলে থাকে।"
],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index fb2f444cd..2dc9f7566 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -3209,6 +3209,14 @@ msgstr "যার সঙ্গে যুক্ত"
msgid "Connected to GitHub"
msgstr "GitHub-এর সঙ্গে যুক্ত হয়েছে"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "সংযোগ হয়েছে, কিন্তু আপনার সম্পাদনা এখনও সার্ভারে পৌঁছাচ্ছে না।"
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "সংযোগ হয়েছে, কিন্তু আপনার সম্পাদনা এখনও সার্ভারে পৌঁছাচ্ছে না। এটি চলতে থাকলে সার্ভার পুনরায় চালু করুন।"
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13244,6 +13252,14 @@ msgstr "স্কিমা ফাইলটি নেই বা লোড কর
msgid "the server responded but server.lock has no port yet"
msgstr "সার্ভার সাড়া দিয়েছে কিন্তু server.lock-এ এখনো কোনো পোর্ট নেই"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "সার্ভার বন্ধ হয়ে গেছে।"
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "সার্ভার বন্ধ হয়ে গেছে। পুনরায় সংযোগের জন্য এটি পুনরায় চালু করুন।"
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index c91fb6ad9..a9092f072 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -655,6 +655,7 @@
"8OxKZy": ["Move succeeded but the sidebar may be out of date — refresh to resync"],
"8PifYj": ["Mermaid diagram"],
"8PmoQF": ["Open the insert menu in an empty or active text position."],
+ "8QLpZe": ["The server stopped. Restart it to reconnect."],
"8RtNI0": ["Failed to load documents"],
"8TvlHF": ["Crash dump"],
"8Uv5e6": ["Agents"],
@@ -2536,6 +2537,9 @@
"X3MMeA": ["None of these problems have an automatic fix."],
"X59Fx2": ["Couldn't open this document in Slidev."],
"X7ShnN": ["Open agents panel"],
+ "X7fxS9": [
+ "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+ ],
"X7u0xR": [["0"], " templates available"],
"X8kjQX": ["Re-authenticate with GitHub"],
"X9VpsP": ["Loading folder contents"],
@@ -3885,6 +3889,7 @@
"mYGY3B": ["Date"],
"mYzDD_": ["A worktree folder for that branch already exists."],
"mZ1r4i": ["Create a document from ", ["label"]],
+ "m_mtGl": ["The server stopped."],
"maDWIB": ["Mirror source <0>api-spec</0>"],
"makN88": ["No patterns yet. Type a folder or file name below to start hiding files."],
"mdKFEy": ["You cancelled loading \"", ["docName"], "\"."],
@@ -3957,6 +3962,7 @@
"n4vt3Q": ["Download app"],
"n5Vy3l": ["Opened on branch ", ["branch"]],
"n5n_vi": ["Private repository"],
+ "n6N-xC": ["Connected, but your edits aren't reaching the server yet."],
"n6hXUm": [
"Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index a14087ffa..67327a653 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -3213,6 +3213,14 @@ msgstr "Connected to"
msgid "Connected to GitHub"
msgstr "Connected to GitHub"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "Connected, but your edits aren't reaching the server yet."
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13248,6 +13256,14 @@ msgstr "The schema file does not exist or failed to load — adding a field crea
msgid "the server responded but server.lock has no port yet"
msgstr "the server responded but server.lock has no port yet"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "The server stopped."
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "The server stopped. Restart it to reconnect."
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index de8c77349..fe50232b8 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -775,6 +775,7 @@
],
"8PifYj": ["Diagrama de Mermaid"],
"8PmoQF": ["Abre el menú de inserción en una posición de texto vacía o activa."],
+ "8QLpZe": ["El servidor se detuvo. Reinícialo para volver a conectarte."],
"8RtNI0": ["No se pudieron cargar los documentos"],
"8TvlHF": ["Volcado de fallo"],
"8Uv5e6": ["Agentes"],
@@ -2961,6 +2962,9 @@
"X3MMeA": ["Ninguno de estos problemas tiene arreglo automático."],
"X59Fx2": ["No se pudo abrir este documento en Slidev."],
"X7ShnN": ["Abrir el panel de agentes"],
+ "X7fxS9": [
+ "Conectado, pero tus ediciones aún no llegan al servidor. Reinícialo si esto continúa."
+ ],
"X7u0xR": [["0"], " plantillas disponibles"],
"X8kjQX": ["Volver a autenticarse con GitHub"],
"X9VpsP": ["Cargando el contenido de la carpeta"],
@@ -4502,6 +4506,7 @@
"mYGY3B": ["Fecha"],
"mYzDD_": ["Ya existe una carpeta de worktree para esa rama."],
"mZ1r4i": ["Crear un documento a partir de ", ["label"]],
+ "m_mtGl": ["El servidor se detuvo."],
"maDWIB": ["Origen del espejo <0>api-spec</0>"],
"makN88": [
"Todavía no hay patrones. Escribe abajo el nombre de una carpeta o un archivo para empezar a ocultar archivos."
@@ -4589,6 +4594,7 @@
"n4vt3Q": ["Descargar la aplicación"],
"n5Vy3l": ["Abierto en la rama ", ["branch"]],
"n5n_vi": ["Repositorio privado"],
+ "n6N-xC": ["Conectado, pero tus ediciones aún no llegan al servidor."],
"n6hXUm": [
"La sincronización automática hace fetch, pull y push de commits a tu repositorio git remoto cada cierto tiempo para que tus ediciones sigan sincronizadas entre equipos."
],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index 83dee8591..b77de51cb 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -3213,6 +3213,14 @@ msgstr "Conectado a"
msgid "Connected to GitHub"
msgstr "Conectado a GitHub"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "Conectado, pero tus ediciones aún no llegan al servidor."
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "Conectado, pero tus ediciones aún no llegan al servidor. Reinícialo si esto continúa."
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13248,6 +13256,14 @@ msgstr "El archivo de esquema no existe o no se pudo cargar; al añadir un campo
msgid "the server responded but server.lock has no port yet"
msgstr "el servidor respondió pero server.lock aún no tiene puerto"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "El servidor se detuvo."
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "El servidor se detuvo. Reinícialo para volver a conectarte."
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index f1ae93ac1..4aec38c3c 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -797,6 +797,7 @@
],
"8PifYj": ["Diagramme Mermaid"],
"8PmoQF": ["Ouvre le menu d'insertion à une position de texte vide ou active."],
+ "8QLpZe": ["Le serveur s'est arrêté. Redémarrez-le pour vous reconnecter."],
"8RtNI0": ["Échec du chargement des documents"],
"8TvlHF": ["Vidage de plantage"],
"8Uv5e6": ["Agents"],
@@ -2993,6 +2994,9 @@
"X3MMeA": ["Aucun de ces problèmes n'a de correction automatique."],
"X59Fx2": ["Impossible d'ouvrir ce document dans Slidev."],
"X7ShnN": ["Ouvrir le panneau des agents"],
+ "X7fxS9": [
+ "Connecté, mais vos modifications n'atteignent pas encore le serveur. Redémarrez-le si cela continue."
+ ],
"X7u0xR": [["0"], " modèles disponibles"],
"X8kjQX": ["Se réauthentifier auprès de GitHub"],
"X9VpsP": ["Chargement du contenu du dossier"],
@@ -4536,6 +4540,7 @@
"mYGY3B": ["Date"],
"mYzDD_": ["Un dossier de worktree pour cette branche existe déjà."],
"mZ1r4i": ["Créer un document à partir de ", ["label"]],
+ "m_mtGl": ["Le serveur s'est arrêté."],
"maDWIB": ["Source du miroir <0>api-spec</0>"],
"makN88": [
"Pas encore de motifs. Saisissez un nom de dossier ou de fichier ci-dessous pour commencer à masquer des fichiers."
@@ -4623,6 +4628,7 @@
"n4vt3Q": ["Télécharger l’application"],
"n5Vy3l": ["Ouvert sur la branche ", ["branch"]],
"n5n_vi": ["Dépôt privé"],
+ "n6N-xC": ["Connecté, mais vos modifications n'atteignent pas encore le serveur."],
"n6hXUm": [
"La synchronisation automatique récupère, tire et pousse périodiquement les commits vers votre dépôt git distant, afin que vos modifications restent synchronisées entre vos machines."
],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 3df1c0b26..3829c6229 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -3213,6 +3213,14 @@ msgstr "Connecté à"
msgid "Connected to GitHub"
msgstr "Connecté à GitHub"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "Connecté, mais vos modifications n'atteignent pas encore le serveur."
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "Connecté, mais vos modifications n'atteignent pas encore le serveur. Redémarrez-le si cela continue."
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13248,6 +13256,14 @@ msgstr "Le fichier de schéma n'existe pas ou n'a pas pu être chargé — ajout
msgid "the server responded but server.lock has no port yet"
msgstr "le serveur a répondu mais server.lock n'a pas encore de port"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "Le serveur s'est arrêté."
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "Le serveur s'est arrêté. Redémarrez-le pour vous reconnecter."
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 6e8d74452..3162fc5b7 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -637,6 +637,7 @@
"8OxKZy": ["हिलाना सफल रहा पर साइडबार पुराना हो सकता है — फिर से सिंक करने के लिए ताज़ा करें"],
"8PifYj": ["Mermaid आरेख"],
"8PmoQF": ["किसी खाली या सक्रिय पाठ स्थिति में इन्सर्ट मेन्यू खोलें।"],
+ "8QLpZe": ["सर्वर बंद हो गया। फिर से कनेक्ट करने के लिए इसे पुनः आरंभ करें।"],
"8RtNI0": ["दस्तावेज़ लोड करने में विफल"],
"8TvlHF": ["क्रैश डंप"],
"8Uv5e6": ["एजेंट"],
@@ -2463,6 +2464,9 @@
"X3MMeA": ["इनमें से किसी भी समस्या का कोई स्वचालित समाधान नहीं है।"],
"X59Fx2": ["इस दस्तावेज़ को Slidev में नहीं खोला जा सका।"],
"X7ShnN": ["एजेंट पैनल खोलें"],
+ "X7fxS9": [
+ "कनेक्ट हो गया, लेकिन आपके संपादन अभी सर्वर तक नहीं पहुँच रहे। यदि यह जारी रहे तो इसे पुनः आरंभ करें।"
+ ],
"X7u0xR": [["0"], " टेम्पलेट उपलब्ध"],
"X8kjQX": ["GitHub के साथ फिर से प्रमाणित करें"],
"X9VpsP": ["फ़ोल्डर की सामग्री लोड हो रही है"],
@@ -3763,6 +3767,7 @@
"mYGY3B": ["तारीख़"],
"mYzDD_": ["उस ब्रांच के लिए एक वर्कट्री फ़ोल्डर पहले से मौजूद है।"],
"mZ1r4i": [["label"], " से एक दस्तावेज़ बनाएँ"],
+ "m_mtGl": ["सर्वर बंद हो गया।"],
"maDWIB": ["मिरर स्रोत <0>api-spec</0>"],
"makN88": ["अभी कोई पैटर्न नहीं। फ़ाइलें छिपाना शुरू करने के लिए नीचे कोई फ़ोल्डर या फ़ाइल नाम लिखें।"],
"mdKFEy": ["आपने \"", ["docName"], "\" लोड करना रद्द कर दिया।"],
@@ -3831,6 +3836,7 @@
"n4vt3Q": ["ऐप डाउनलोड करें"],
"n5Vy3l": ["ब्रांच ", ["branch"], " पर खोला गया"],
"n5n_vi": ["निजी रिपॉज़िटरी"],
+ "n6N-xC": ["कनेक्ट हो गया, लेकिन आपके संपादन अभी सर्वर तक नहीं पहुँच रहे।"],
"n6hXUm": [
"स्वत: सिंक समय-समय पर आपकी रिमोट git रिपॉज़िटरी से कमिट लाता, खींचता और भेजता है ताकि आपके संपादन सभी मशीनों पर तालमेल में रहें।"
],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 1ee74521b..2d7f8bf18 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -3209,6 +3209,14 @@ msgstr "इससे जुड़ा"
msgid "Connected to GitHub"
msgstr "GitHub से जुड़ गया"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "कनेक्ट हो गया, लेकिन आपके संपादन अभी सर्वर तक नहीं पहुँच रहे।"
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "कनेक्ट हो गया, लेकिन आपके संपादन अभी सर्वर तक नहीं पहुँच रहे। यदि यह जारी रहे तो इसे पुनः आरंभ करें।"
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13244,6 +13252,14 @@ msgstr "स्कीमा फ़ाइल मौजूद नहीं है
msgid "the server responded but server.lock has no port yet"
msgstr "सर्वर ने जवाब दिया लेकिन server.lock में अभी कोई पोर्ट नहीं है"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "सर्वर बंद हो गया।"
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "सर्वर बंद हो गया। फिर से कनेक्ट करने के लिए इसे पुनः आरंभ करें।"
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index f393b9a24..dd3cfdefb 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -663,6 +663,7 @@
],
"8PifYj": ["Diagram Mermaid"],
"8PmoQF": ["Membuka menu sisip pada posisi teks yang kosong atau aktif."],
+ "8QLpZe": ["Server berhenti. Mulai ulang untuk menyambung kembali."],
"8RtNI0": ["Gagal memuat dokumen"],
"8TvlHF": ["Crash dump"],
"8Uv5e6": ["Agen"],
@@ -2554,6 +2555,9 @@
"X3MMeA": ["Tidak satu pun masalah ini punya perbaikan otomatis."],
"X59Fx2": ["Tidak dapat membuka dokumen ini di Slidev."],
"X7ShnN": ["Buka panel agen"],
+ "X7fxS9": [
+ "Terhubung, tetapi suntingan Anda belum sampai ke server. Mulai ulang server jika ini terus berlanjut."
+ ],
"X7u0xR": [["0"], " templat tersedia"],
"X8kjQX": ["Autentikasi ulang dengan GitHub"],
"X9VpsP": ["Memuat isi folder"],
@@ -3914,6 +3918,7 @@
"mYGY3B": ["Tanggal"],
"mYzDD_": ["Folder worktree untuk cabang itu sudah ada."],
"mZ1r4i": ["Buat dokumen dari ", ["label"]],
+ "m_mtGl": ["Server berhenti."],
"maDWIB": ["Sumber cermin <0>api-spec</0>"],
"makN88": [
"Belum ada pola. Ketik nama folder atau berkas di bawah untuk mulai menyembunyikan berkas."
@@ -3985,6 +3990,7 @@
"n4vt3Q": ["Unduh aplikasi"],
"n5Vy3l": ["Dibuka di cabang ", ["branch"]],
"n5n_vi": ["Repositori pribadi"],
+ "n6N-xC": ["Terhubung, tetapi suntingan Anda belum sampai ke server."],
"n6hXUm": [
"Sinkronisasi otomatis secara berkala melakukan fetch, pull, dan push commit ke repositori git remote Anda agar suntingan Anda tetap selaras antarkomputer."
],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index 3c3223b99..41596914a 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -3209,6 +3209,14 @@ msgstr "Terhubung ke"
msgid "Connected to GitHub"
msgstr "Terhubung ke GitHub"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "Terhubung, tetapi suntingan Anda belum sampai ke server."
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "Terhubung, tetapi suntingan Anda belum sampai ke server. Mulai ulang server jika ini terus berlanjut."
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13244,6 +13252,14 @@ msgstr "Berkas skemanya tidak ada atau gagal dimuat — menambahkan sebuah bidan
msgid "the server responded but server.lock has no port yet"
msgstr "server merespons tetapi server.lock belum memiliki port"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "Server berhenti."
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "Server berhenti. Mulai ulang untuk menyambung kembali."
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.json
index 28fda1d65..caf4c8779 100644
--- a/packages/app/src/locales/ko/messages.json
+++ b/packages/app/src/locales/ko/messages.json
@@ -643,6 +643,7 @@
],
"8PifYj": ["Mermaid 다이어그램"],
"8PmoQF": ["비어 있거나 활성화된 텍스트 위치에서 삽입 메뉴를 엽니다."],
+ "8QLpZe": ["서버가 중지되었습니다. 다시 연결하려면 재시작하세요."],
"8RtNI0": ["문서를 불러오지 못했습니다"],
"8TvlHF": ["크래시 덤프"],
"8Uv5e6": ["에이전트"],
@@ -2455,6 +2456,9 @@
"X3MMeA": ["이 문제들에는 자동 수정이 없습니다."],
"X59Fx2": ["이 문서를 Slidev에서 열지 못했습니다."],
"X7ShnN": ["에이전트 패널 열기"],
+ "X7fxS9": [
+ "연결되었지만 편집 내용이 아직 서버에 전달되지 않고 있습니다. 계속되면 서버를 재시작하세요."
+ ],
"X7u0xR": ["템플릿 ", ["0"], "개 사용 가능"],
"X8kjQX": ["GitHub 재인증"],
"X9VpsP": ["폴더 내용 불러오는 중"],
@@ -3756,6 +3760,7 @@
"mYGY3B": ["날짜"],
"mYzDD_": ["해당 브랜치용 워크트리 폴더가 이미 있습니다."],
"mZ1r4i": [["label"], "에서 문서 만들기"],
+ "m_mtGl": ["서버가 중지되었습니다."],
"maDWIB": ["미러 소스 <0>api-spec</0>"],
"makN88": [
"아직 패턴이 없습니다. 아래에 폴더 또는 파일 이름을 입력하면 파일 숨기기를 시작합니다."
@@ -3825,6 +3830,7 @@
"n4vt3Q": ["앱 다운로드"],
"n5Vy3l": [["branch"], " 브랜치에서 열었습니다"],
"n5n_vi": ["비공개 저장소"],
+ "n6N-xC": ["연결되었지만 편집 내용이 아직 서버에 전달되지 않고 있습니다."],
"n6hXUm": [
"자동 동기화는 원격 git 저장소에서 커밋을 주기적으로 가져오고 풀하고 푸시하여 여러 컴퓨터에서 편집 내용이 동기화된 상태로 유지되도록 합니다."
],
diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.po
index 265a10497..1e2b0968a 100644
--- a/packages/app/src/locales/ko/messages.po
+++ b/packages/app/src/locales/ko/messages.po
@@ -3213,6 +3213,14 @@ msgstr "연결 대상"
msgid "Connected to GitHub"
msgstr "GitHub에 연결됨"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "연결되었지만 편집 내용이 아직 서버에 전달되지 않고 있습니다."
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "연결되었지만 편집 내용이 아직 서버에 전달되지 않고 있습니다. 계속되면 서버를 재시작하세요."
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13248,6 +13256,14 @@ msgstr "스키마 파일이 없거나 불러오지 못했습니다. 필드를
msgid "the server responded but server.lock has no port yet"
msgstr "서버 응답 완료. server.lock에 포트 없음"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "서버가 중지되었습니다."
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "서버가 중지되었습니다. 다시 연결하려면 재시작하세요."
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index f53271ca7..effcb3933 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -655,6 +655,7 @@
"8OxKZy": ["Ḿōvē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"8PifYj": ["Ḿēŕḿàĩď ďĩàĝŕàḿ"],
"8PmoQF": ["Ōƥēń ţĥē ĩńśēŕţ ḿēńũ ĩń àń ēḿƥţŷ ōŕ àćţĩvē ţēxţ ƥōśĩţĩōń."],
+ "8QLpZe": ["Ţĥē śēŕvēŕ śţōƥƥēď. Ŕēśţàŕţ ĩţ ţō ŕēćōńńēćţ."],
"8RtNI0": ["Ƒàĩĺēď ţō ĺōàď ďōćũḿēńţś"],
"8TvlHF": ["Ćŕàśĥ ďũḿƥ"],
"8Uv5e6": ["Àĝēńţś"],
@@ -2536,6 +2537,9 @@
"X3MMeA": ["Ńōńē ōƒ ţĥēśē ƥŕōƀĺēḿś ĥàvē àń àũţōḿàţĩć ƒĩx."],
"X59Fx2": ["Ćōũĺďń'ţ ōƥēń ţĥĩś ďōćũḿēńţ ĩń Śĺĩďēv."],
"X7ShnN": ["Ōƥēń àĝēńţś ƥàńēĺ"],
+ "X7fxS9": [
+ "Ćōńńēćţēď, ƀũţ ŷōũŕ ēďĩţś àŕēń'ţ ŕēàćĥĩńĝ ţĥē śēŕvēŕ ŷēţ. Ŕēśţàŕţ ĩţ ĩƒ ţĥĩś ćōńţĩńũēś."
+ ],
"X7u0xR": [["0"], " ţēḿƥĺàţēś àvàĩĺàƀĺē"],
"X8kjQX": ["Ŕē-àũţĥēńţĩćàţē ŵĩţĥ ĜĩţĤũƀ"],
"X9VpsP": ["Ĺōàďĩńĝ ƒōĺďēŕ ćōńţēńţś"],
@@ -3885,6 +3889,7 @@
"mYGY3B": ["Ďàţē"],
"mYzDD_": ["À ŵōŕķţŕēē ƒōĺďēŕ ƒōŕ ţĥàţ ƀŕàńćĥ àĺŕēàďŷ ēxĩśţś."],
"mZ1r4i": ["Ćŕēàţē à ďōćũḿēńţ ƒŕōḿ ", ["label"]],
+ "m_mtGl": ["Ţĥē śēŕvēŕ śţōƥƥēď."],
"maDWIB": ["Ḿĩŕŕōŕ śōũŕćē <0>àƥĩ-śƥēć</0>"],
"makN88": ["Ńō ƥàţţēŕńś ŷēţ. Ţŷƥē à ƒōĺďēŕ ōŕ ƒĩĺē ńàḿē ƀēĺōŵ ţō śţàŕţ ĥĩďĩńĝ ƒĩĺēś."],
"mdKFEy": ["Ŷōũ ćàńćēĺĺēď ĺōàďĩńĝ \"", ["docName"], "\"."],
@@ -3957,6 +3962,7 @@
"n4vt3Q": ["Ďōŵńĺōàď àƥƥ"],
"n5Vy3l": ["Ōƥēńēď ōń ƀŕàńćĥ ", ["branch"]],
"n5n_vi": ["Ƥŕĩvàţē ŕēƥōśĩţōŕŷ"],
+ "n6N-xC": ["Ćōńńēćţēď, ƀũţ ŷōũŕ ēďĩţś àŕēń'ţ ŕēàćĥĩńĝ ţĥē śēŕvēŕ ŷēţ."],
"n6hXUm": [
"Àũţō-śŷńć ƥēŕĩōďĩćàĺĺŷ ƒēţćĥēś, ƥũĺĺś, àńď ƥũśĥēś ćōḿḿĩţś ţō ŷōũŕ ŕēḿōţē ĝĩţ ŕēƥōśĩţōŕŷ śō ŷōũŕ ēďĩţś śţàŷ ĩń śŷńć àćŕōśś ḿàćĥĩńēś."
],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 33b13267d..3f7c0e7d3 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -3209,6 +3209,14 @@ msgstr ""
msgid "Connected to GitHub"
msgstr ""
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr ""
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr ""
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13244,6 +13252,14 @@ msgstr ""
msgid "the server responded but server.lock has no port yet"
msgstr ""
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr ""
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr ""
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 928d05980..8ade93e37 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -761,6 +761,7 @@
],
"8PifYj": ["Diagrama do Mermaid"],
"8PmoQF": ["Abre o menu de inserção em uma posição de texto vazia ou ativa."],
+ "8QLpZe": ["O servidor parou. Reinicie-o para reconectar."],
"8RtNI0": ["Falha ao carregar os documentos"],
"8TvlHF": ["Despejo de falha"],
"8Uv5e6": ["Agentes"],
@@ -2909,6 +2910,9 @@
"X3MMeA": ["Nenhum destes problemas tem correção automática."],
"X59Fx2": ["Não foi possível abrir este documento no Slidev."],
"X7ShnN": ["Abrir o painel de agentes"],
+ "X7fxS9": [
+ "Conectado, mas suas edições ainda não estão chegando ao servidor. Reinicie-o se isso continuar."
+ ],
"X7u0xR": [["0"], " modelos disponíveis"],
"X8kjQX": ["Autenticar de novo no GitHub"],
"X9VpsP": ["Carregando o conteúdo da pasta"],
@@ -4404,6 +4408,7 @@
"mYGY3B": ["Data"],
"mYzDD_": ["Já existe uma pasta de worktree para esse ramo."],
"mZ1r4i": ["Criar um documento a partir de ", ["label"]],
+ "m_mtGl": ["O servidor parou."],
"maDWIB": ["Fonte do espelho <0>api-spec</0>"],
"makN88": [
"Ainda não há padrões. Digite abaixo o nome de uma pasta ou arquivo para começar a ocultar arquivos."
@@ -4491,6 +4496,7 @@
"n4vt3Q": ["Baixar aplicativo"],
"n5Vy3l": ["Aberto no ramo ", ["branch"]],
"n5n_vi": ["Repositório privado"],
+ "n6N-xC": ["Conectado, mas suas edições ainda não estão chegando ao servidor."],
"n6hXUm": [
"A sincronização automática faz fetch, pull e push de commits para seu repositório git remoto de tempos em tempos, para que suas edições fiquem em sincronia entre computadores."
],
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index e92366140..1f6079903 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -3209,6 +3209,14 @@ msgstr "Conectado a"
msgid "Connected to GitHub"
msgstr "Conectado ao GitHub"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "Conectado, mas suas edições ainda não estão chegando ao servidor."
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "Conectado, mas suas edições ainda não estão chegando ao servidor. Reinicie-o se isso continuar."
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13244,6 +13252,14 @@ msgstr "O arquivo de esquema não existe ou falhou ao carregar — adicionar um
msgid "the server responded but server.lock has no port yet"
msgstr "o servidor respondeu, mas o server.lock ainda não tem porta"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "O servidor parou."
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "O servidor parou. Reinicie-o para reconectar."
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index d0eb585e9..aaaedd5dd 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -675,6 +675,7 @@
"8OxKZy": ["منتقلی ہو گئی مگر سائیڈ بار پرانا ہو سکتا ہے — دوبارہ مطابقت کے لیے تازہ کریں"],
"8PifYj": ["Mermaid خاکہ"],
"8PmoQF": ["خالی یا فعال متن کی جگہ پر داخل کرنے کا مینو کھولیں۔"],
+ "8QLpZe": ["سرور رک گیا۔ دوبارہ منسلک ہونے کے لیے اسے دوبارہ چلائیں۔"],
"8RtNI0": ["دستاویزات لوڈ نہیں ہو سکیں"],
"8TvlHF": ["کریش ڈمپ"],
"8Uv5e6": ["ایجنٹس"],
@@ -2602,6 +2603,9 @@
"X3MMeA": ["ان میں سے کسی مسئلے کا خودکار حل نہیں ہے۔"],
"X59Fx2": ["یہ دستاویز Slidev میں نہیں کھولی جا سکی۔"],
"X7ShnN": ["ایجنٹس کا پینل کھولیں"],
+ "X7fxS9": [
+ "منسلک ہو گیا، لیکن آپ کی ترامیم ابھی سرور تک نہیں پہنچ رہیں۔ اگر یہ جاری رہے تو اسے دوبارہ چلائیں۔"
+ ],
"X7u0xR": [["0"], " ٹیمپلیٹس دستیاب"],
"X8kjQX": ["GitHub سے دوبارہ توثیق کریں"],
"X9VpsP": ["فولڈر کا مواد لوڈ ہو رہا ہے"],
@@ -3981,6 +3985,7 @@
"mYGY3B": ["تاریخ"],
"mYzDD_": ["اس برانچ کے لیے ورک ٹری فولڈر پہلے سے موجود ہے۔"],
"mZ1r4i": [["label"], " سے دستاویز بنائیں"],
+ "m_mtGl": ["سرور رک گیا۔"],
"maDWIB": ["مرر کا ماخذ <0>api-spec</0>"],
"makN88": [
"ابھی کوئی پیٹرن نہیں۔ فائلیں چھپانا شروع کرنے کے لیے نیچے فولڈر یا فائل کا نام لکھیں۔"
@@ -4054,6 +4059,7 @@
"n4vt3Q": ["ایپ ڈاؤن لوڈ کریں"],
"n5Vy3l": ["برانچ ", ["branch"], " پر کھولا گیا"],
"n5n_vi": ["نجی ریپازٹری"],
+ "n6N-xC": ["منسلک ہو گیا، لیکن آپ کی ترامیم ابھی سرور تک نہیں پہنچ رہیں۔"],
"n6hXUm": [
"خودکار مطابقت پذیری وقتاً فوقتاً آپ کی ریموٹ git ریپازٹری سے کمٹس لاتی، کھینچتی اور بھیجتی ہے تاکہ آپ کی ترامیم مشینوں کے درمیان ہم آہنگ رہیں۔"
],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index 5fc45fc1f..8bef0a5cc 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -3213,6 +3213,14 @@ msgstr "منسلک ہے"
msgid "Connected to GitHub"
msgstr "GitHub سے منسلک"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "منسلک ہو گیا، لیکن آپ کی ترامیم ابھی سرور تک نہیں پہنچ رہیں۔"
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "منسلک ہو گیا، لیکن آپ کی ترامیم ابھی سرور تک نہیں پہنچ رہیں۔ اگر یہ جاری رہے تو اسے دوبارہ چلائیں۔"
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13248,6 +13256,14 @@ msgstr "اسکیما فائل موجود نہیں یا لوڈ نہیں ہو سک
msgid "the server responded but server.lock has no port yet"
msgstr "سرور نے جواب دیا مگر server.lock میں ابھی کوئی پورٹ نہیں"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "سرور رک گیا۔"
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "سرور رک گیا۔ دوبارہ منسلک ہونے کے لیے اسے دوبارہ چلائیں۔"
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index fea97edf7..3ba9a65bd 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -589,6 +589,7 @@
"8OxKZy": ["移动成功,但侧边栏可能不是最新的——请刷新以重新同步"],
"8PifYj": ["Mermaid 图示"],
"8PmoQF": ["在空白或活动的文本位置打开插入菜单。"],
+ "8QLpZe": ["服务器已停止。重启服务器以重新连接。"],
"8RtNI0": ["加载文档失败"],
"8TvlHF": ["崩溃转储"],
"8Uv5e6": ["智能体"],
@@ -2242,6 +2243,7 @@
"X3MMeA": ["这些问题都没有自动修复方案。"],
"X59Fx2": ["无法在 Slidev 中打开此文档。"],
"X7ShnN": ["打开智能体面板"],
+ "X7fxS9": ["已连接,但你的编辑尚未送达服务器。如果持续如此,请重启服务器。"],
"X7u0xR": ["有 ", ["0"], " 个模板可用"],
"X8kjQX": ["重新通过 GitHub 认证"],
"X9VpsP": ["正在加载文件夹内容"],
@@ -3428,6 +3430,7 @@
"mYGY3B": ["日期"],
"mYzDD_": ["该分支的 worktree 文件夹已存在。"],
"mZ1r4i": ["用 ", ["label"], " 创建文档"],
+ "m_mtGl": ["服务器已停止。"],
"maDWIB": ["镜像来源 <0>api-spec</0>"],
"makN88": ["还没有模式。在下方输入文件夹名或文件名,即可开始隐藏文件。"],
"mdKFEy": ["你取消了“", ["docName"], "”的加载。"],
@@ -3480,6 +3483,7 @@
"n4vt3Q": ["下载应用"],
"n5Vy3l": ["已在分支 ", ["branch"], " 上打开"],
"n5n_vi": ["私有仓库"],
+ "n6N-xC": ["已连接,但你的编辑尚未送达服务器。"],
"n6hXUm": [
"自动同步会定期从你的远程 git 仓库执行 fetch、pull 和 push,让你的编辑在多台电脑之间保持同步。"
],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index 08f3b568e..85ad31a6e 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -3213,6 +3213,14 @@ msgstr "已连接到"
msgid "Connected to GitHub"
msgstr "已连接到 GitHub"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "已连接,但你的编辑尚未送达服务器。"
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "已连接,但你的编辑尚未送达服务器。如果持续如此,请重启服务器。"
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13248,6 +13256,14 @@ msgstr "架构文件不存在或加载失败——添加字段会自动创建它
msgid "the server responded but server.lock has no port yet"
msgstr "服务器有响应,但 server.lock 中还没有端口"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "服务器已停止。"
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "服务器已停止。重启服务器以重新连接。"
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index 3599e45fc..87c1217ac 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -593,6 +593,7 @@
"8OxKZy": ["移動成功,但側邊欄可能不是最新的——請重新整理以重新同步"],
"8PifYj": ["Mermaid 圖表"],
"8PmoQF": ["在空白或作用中的文字位置開啟插入選單。"],
+ "8QLpZe": ["伺服器已停止。重新啟動伺服器以重新連線。"],
"8RtNI0": ["載入文件失敗"],
"8TvlHF": ["當機傾印"],
"8Uv5e6": ["代理"],
@@ -2270,6 +2271,7 @@
"X3MMeA": ["這些問題都沒有自動修正的方式。"],
"X59Fx2": ["無法在 Slidev 中開啟此文件。"],
"X7ShnN": ["開啟代理面板"],
+ "X7fxS9": ["已連線,但你的編輯尚未送達伺服器。如果持續如此,請重新啟動伺服器。"],
"X7u0xR": ["有 ", ["0"], " 個範本可用"],
"X8kjQX": ["重新用 GitHub 驗證"],
"X9VpsP": ["正在載入資料夾內容"],
@@ -3454,6 +3456,7 @@
"mYGY3B": ["日期"],
"mYzDD_": ["該分支的 worktree 資料夾已存在。"],
"mZ1r4i": ["用 ", ["label"], " 建立文件"],
+ "m_mtGl": ["伺服器已停止。"],
"maDWIB": ["鏡像來源 <0>api-spec</0>"],
"makN88": ["還沒有任何模式。在下面輸入資料夾或檔案名稱,就能開始隱藏檔案。"],
"mdKFEy": ["你取消了「", ["docName"], "」的載入。"],
@@ -3506,6 +3509,7 @@
"n4vt3Q": ["下載應用程式"],
"n5Vy3l": ["已在分支 ", ["branch"], " 上開啟"],
"n5n_vi": ["私人儲存庫"],
+ "n6N-xC": ["已連線,但你的編輯尚未送達伺服器。"],
"n6hXUm": [
"自動同步會定期對你的遠端 git 儲存庫執行 fetch、pull 和 push,讓你的編輯在多台電腦之間保持同步。"
],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index eea41ee79..a85a0495b 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -3213,6 +3213,14 @@ msgstr "已連接到"
msgid "Connected to GitHub"
msgstr "已連接到 GitHub"
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet."
+msgstr "已連線,但你的編輯尚未送達伺服器。"
+
+#: src/presence/use-sync-toasts.ts
+msgid "Connected, but your edits aren't reaching the server yet. Restart it if this continues."
+msgstr "已連線,但你的編輯尚未送達伺服器。如果持續如此,請重新啟動伺服器。"
+
#: src/components/AuthModal.tsx
#: src/components/PropertyPanel.tsx
msgid "Connecting"
@@ -13248,6 +13256,14 @@ msgstr "結構描述檔案不存在或載入失敗——新增欄位就會建立
msgid "the server responded but server.lock has no port yet"
msgstr "伺服器有回應,但 server.lock 裡還沒有連接埠"
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped."
+msgstr "伺服器已停止。"
+
+#: src/presence/use-sync-toasts.ts
+msgid "The server stopped. Restart it to reconnect."
+msgstr "伺服器已停止。重新啟動伺服器以重新連線。"
+
#. placeholder {0}: origin.trim()
#: src/components/settings/NetworkAccessSection.tsx
msgid "The server will accept requests for {0} with no built-in authentication. Anyone who can reach your tunnel will have full control of this knowledge base, including sync, GitHub credentials, and local operations. Make sure the tunnel's edge restricts who can connect."
diff --git a/packages/app/src/presence/use-sync-toasts.dom.test.tsx b/packages/app/src/presence/use-sync-toasts.dom.test.tsx
new file mode 100644
index 000000000..b57e6eab1
--- /dev/null
+++ b/packages/app/src/presence/use-sync-toasts.dom.test.tsx
@@ -0,0 +1,816 @@
+/**
+ * Hook tests for the disconnect-toast grace downgrade: the optimistic
+ * "will sync when reconnected" copy is swapped for an honest "server stopped"
+ * message only after a grace with no reconnect, and a reconnect (`synced`, or a
+ * bare `connected` socket) before the grace cancels the downgrade. Runs under
+ * jsdom (`test:dom`) so `renderHook` works; the `t` template macro resolves to
+ * its English source text (no catalog is activated, so the macro returns the
+ * source string, which the assertions match). `toast` and the relaunch store are
+ * mocked.
+ */
+
+import { renderHook } from '@testing-library/react';
+import { act } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+
+const warning = vi.fn();
+const success = vi.fn();
+const dismiss = vi.fn();
+
+vi.mock('sonner', () => ({
+ toast: {
+ warning: (...args: unknown[]) => warning(...args),
+ success: (...args: unknown[]) => success(...args),
+ dismiss: (...args: unknown[]) => dismiss(...args),
+ error: () => {},
+ },
+}));
+// Controllable so the relaunch-suppression path is reachable (a constant-false
+// mock would leave that branch untestable).
+let relaunchInFlightFlag = false;
+vi.mock('@/lib/relaunch-store', () => ({ useRelaunchInFlight: () => relaunchInFlightFlag }));
+
+import { useSyncToasts } from './use-sync-toasts';
+
+const messages = (spy: typeof warning): string[] => spy.mock.calls.map((c) => String(c[0]));
+
+// Matches the dom tier's okDesktop stub convention (configurable
+// defineProperty, reset in beforeEach) — see e.g. EditorHeader.dom.test.tsx.
+function setBridge(singleFile: boolean) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: {
+ config: { singleFile, projectPath: '/tmp/p' },
+ restartServer: vi.fn(async () => ({ ok: true })),
+ },
+ });
+}
+
+// The downgraded (server-stopped) toast is the last `warning` call after the grace.
+const lastWarning = () => warning.mock.calls.at(-1) as [string, { action?: unknown }] | undefined;
+
+describe('useSyncToasts — disconnect grace downgrade', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ warning.mockClear();
+ success.mockClear();
+ dismiss.mockClear();
+ relaunchInFlightFlag = false;
+ Object.defineProperty(window, 'okDesktop', { configurable: true, value: undefined });
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test('downgrades to the honest "server stopped" copy after the grace with no reconnect', () => {
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ {
+ initialProps: { s: 'synced' as const },
+ },
+ );
+
+ // Disconnect after having synced → optimistic copy first.
+ act(() => rerender({ s: 'disconnected' }));
+ expect(messages(warning).some((m) => m.includes('keep this tab open'))).toBe(true);
+ warning.mockClear();
+
+ // No reconnect across the grace → honest terminal copy replaces it.
+ act(() => vi.advanceTimersByTime(10_000));
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ });
+
+ test('a reconnect before the grace cancels the downgrade (no "server stopped")', () => {
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ {
+ initialProps: { s: 'synced' as const },
+ },
+ );
+
+ act(() => rerender({ s: 'disconnected' }));
+ warning.mockClear();
+ act(() => rerender({ s: 'synced' }));
+ act(() => vi.advanceTimersByTime(10_000));
+
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ expect(success).toHaveBeenCalled();
+ });
+
+ test('ephemeral single-file: honest toast offers the working Restart button (sender-routed to the ephemeral respawn)', () => {
+ // Restart is routed to the correct server by the requesting window
+ // (`ok:project:restart-server` resolves ephemeral vs project by sender), so a
+ // stopped single-file session gets a working button.
+ setBridge(true);
+ const restartSpy = (window as { okDesktop?: { restartServer: ReturnType<typeof vi.fn> } })
+ .okDesktop?.restartServer as ReturnType<typeof vi.fn>;
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(10_000));
+
+ const last = lastWarning();
+ expect(String(last?.[0])).toMatch(/restart it to reconnect/i);
+ // The terminal toast is the standing affordance for a dead server: it must
+ // replace in place (same id) and never auto-expire out from under the user.
+ expect(last?.[1]).toMatchObject({ id: 'sync-status', duration: Infinity });
+ const action = last?.[1]?.action as { onClick: () => void } | undefined;
+ expect(action).toBeDefined();
+ // The button is wired to a real restart, not decorative: clicking it invokes
+ // the bridge's restartServer.
+ act(() => action?.onClick());
+ expect(restartSpy).toHaveBeenCalledTimes(1);
+ });
+
+ test('project server: honest toast offers the working Restart button', () => {
+ setBridge(false);
+ const restartSpy = (window as { okDesktop?: { restartServer: ReturnType<typeof vi.fn> } })
+ .okDesktop?.restartServer as ReturnType<typeof vi.fn>;
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(10_000));
+
+ const last = lastWarning();
+ expect(String(last?.[0])).toMatch(/restart it to reconnect/i);
+ const action = last?.[1]?.action as { onClick: () => void } | undefined;
+ expect(action).toBeDefined();
+ act(() => action?.onClick());
+ expect(restartSpy).toHaveBeenCalledTimes(1);
+ });
+
+ test('the optimistic toast carries the Restart button too (desktop, before the grace)', () => {
+ // The button rides the optimistic toast, not just the terminal one — a server
+ // that opens but never syncs (or flaps) never reaches the downgrade, so the
+ // optimistic toast is the only surface left to carry recovery.
+ setBridge(true);
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' })); // no timer advance: pre-grace
+ const optimistic = warning.mock.calls.find((c) => String(c[0]).includes('keep this tab open'));
+ expect(optimistic).toBeDefined();
+ expect((optimistic?.[1] as { action?: unknown })?.action).toBeDefined();
+ // Same single-slot contract as the terminal toast: fixed id, never expires.
+ expect(optimistic?.[1]).toMatchObject({ id: 'sync-status', duration: Infinity });
+ });
+
+ test('a reconnected socket that never re-syncs (pre-grace) gets the accurate stalled copy AND its Restart button', () => {
+ // Wedged-but-alive after a prior sync: the socket reopens under the grace and
+ // then parks at `connected` without `synced` (auth stall / large initial sync
+ // / wedged doc). The `connected` hop replaces the now-falsified "Connection
+ // lost" claim with the accurate stalled copy — the SAME copy the post-grace
+ // route gets, so one runtime state never reads two different messages — and
+ // keeps the button. (A server that never syncs on FIRST connect is the
+ // sync-timeout error boundary's persona, not this toast's.)
+ setBridge(true);
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connected' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(5_000)); // under the grace
+ dismiss.mockClear();
+ act(() => rerender({ s: 'connected' }));
+ act(() => vi.advanceTimersByTime(30_000)); // parks at connected, well past the grace
+
+ // Replaced in place — never dismissed, never downgraded to "server stopped".
+ expect(dismiss).not.toHaveBeenCalled();
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain("aren't reaching the server");
+ expect(last?.[1]?.action).toBeDefined();
+ });
+
+ test('a socket that reopens AFTER the grace and parks at connected still has a standing toast with a Restart button', () => {
+ // The post-grace variant of the wedged persona: the terminal "server stopped"
+ // already fired, then the socket reopens and never re-syncs. The `connected`
+ // hop must REPLACE the falsified terminal claim with the accurate stalled
+ // copy + button (same toast id), never dismiss to silence — no branch
+ // re-runs while the status parks at `connected`, so whatever this hop
+ // leaves on screen is the persona's last word.
+ setBridge(true);
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connected' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(10_000)); // grace elapses → terminal toast fired
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ dismiss.mockClear();
+ warning.mockClear();
+
+ act(() => rerender({ s: 'connected' }));
+ act(() => vi.advanceTimersByTime(30_000)); // parks at connected
+
+ expect(dismiss).not.toHaveBeenCalled(); // replaced, not dismissed to silence
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain("aren't reaching the server"); // names the actual state
+ expect(String(last?.[0])).toMatch(/restart it/i); // copy points at the control
+ expect(last?.[1]?.action).toBeDefined(); // and it carries the Restart button
+ // Full option shape: same toast id (in-place replace) and a sticky duration.
+ expect(last?.[1]).toMatchObject({ id: 'sync-status', duration: Infinity });
+ });
+
+ test('a server flapping faster than the grace still carries a Restart button and never falsely reports stopped', () => {
+ setBridge(true);
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connected' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ // Each disconnect re-shows the optimistic toast; each connect cancels the
+ // grace, so the terminal downgrade never accumulates 10s and never fires.
+ for (let i = 0; i < 4; i++) {
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(3_000));
+ act(() => rerender({ s: 'connected' }));
+ act(() => vi.advanceTimersByTime(3_000));
+ }
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ const optimistics = warning.mock.calls.filter((c) =>
+ String(c[0]).includes('keep this tab open'),
+ );
+ expect(optimistics.length).toBeGreaterThan(0);
+ for (const call of optimistics) {
+ expect((call[1] as { action?: unknown })?.action).toBeDefined();
+ }
+ });
+
+ test('disconnected → connected → synced shows Reconnected with no false "server stopped" and no premature dismiss', () => {
+ // The production reconnect ordering — a reconnect cannot skip `connected`.
+ setBridge(false);
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connected' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(2_000)); // brief blip, under the grace
+ dismiss.mockClear();
+ act(() => rerender({ s: 'connected' }));
+ // The standing "Connection lost" is replaced in place with the accurate
+ // stalled intermediate — never dismissed (a dismiss-then-recreate on the
+ // same id would race the exit animation).
+ expect(dismiss).not.toHaveBeenCalled();
+ act(() => rerender({ s: 'synced' }));
+ expect(success).toHaveBeenCalledWith('Reconnected', expect.anything());
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ });
+
+ test('browser mode (no bridge): honest toast is message-only, no Restart control', () => {
+ // No `window.okDesktop` (the `ok ui` browser case) → nothing to restart, so
+ // the copy omits the "Restart it" instruction and offers no action.
+ Object.defineProperty(window, 'okDesktop', { configurable: true, value: undefined });
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(10_000));
+
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain('server stopped');
+ expect(String(last?.[0])).not.toMatch(/restart it/i);
+ expect(last?.[1]?.action).toBeUndefined();
+ });
+
+ test('a bare `connected` socket before the grace cancels the downgrade (no "server stopped")', () => {
+ // A dead server never reaches `connected` (connection refused), so a
+ // `connected` transition proves the server is reachable — the grace timer
+ // must be cancelled even though `synced` has not fired yet.
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connected' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ warning.mockClear();
+ act(() => rerender({ s: 'connected' }));
+ act(() => vi.advanceTimersByTime(10_000));
+
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ });
+
+ test('a `connected` AFTER the downgrade replaces the false "server stopped" claim (browser mode: message-only)', () => {
+ // disconnected → (grace) → "server stopped" → connected. The socket is back,
+ // so the terminal claim is false — it is REPLACED with the accurate stalled
+ // copy under the same toast id (in browser mode with no bridge, message-only
+ // and without the restart instruction), never dismissed to silence.
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connected' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(10_000));
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ dismiss.mockClear();
+ warning.mockClear();
+
+ act(() => rerender({ s: 'connected' }));
+ expect(dismiss).not.toHaveBeenCalled();
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain("aren't reaching the server");
+ expect(String(last?.[0])).not.toMatch(/restart it/i); // no absent-control pointer
+ expect(last?.[1]?.action).toBeUndefined(); // no bridge → no button, but never silence
+ });
+
+ test('switching docs mid-outage carries the terminal claim over — no fresh "will sync" promise from a dead server', () => {
+ const { rerender } = renderHook(
+ ({ s, doc }: { s: 'synced' | 'disconnected'; doc: string }) => useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' } },
+ );
+ // Reach the terminal "server stopped" state on doc a.md.
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' }));
+ act(() => vi.advanceTimersByTime(10_000));
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ dismiss.mockClear();
+ warning.mockClear();
+
+ // Still disconnected, user switches docs. ALL outage state is
+ // connection-scoped and survives, so the same effect run re-asserts the
+ // TERMINAL claim for the new doc — a dead server must never win back the
+ // optimistic "your edits will sync when reconnected" promise just because
+ // the user tried a different file.
+ act(() => rerender({ s: 'disconnected', doc: 'b.md' }));
+ expect(dismiss).not.toHaveBeenCalled(); // re-asserted in place, not blanked
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain('server stopped');
+ expect(messages(warning).some((m) => m.includes('keep this tab open'))).toBe(false);
+ });
+
+ test('switching docs as the outage ends replaces the claim with "Reconnected" — no dismiss-then-recreate', () => {
+ const { rerender } = renderHook(
+ ({ s, doc }: { s: 'synced' | 'disconnected'; doc: string }) => useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' }));
+ act(() => vi.advanceTimersByTime(10_000));
+ dismiss.mockClear();
+
+ // Healthy switch: the new doc syncs. The standing claim is replaced in
+ // place by "Reconnected" (same toast id) — because `wasDisconnectedRef`
+ // survived the switch — with no dismiss racing the replacement.
+ act(() => rerender({ s: 'synced', doc: 'b.md' }));
+ expect(dismiss).not.toHaveBeenCalled();
+ expect(success).toHaveBeenCalledWith('Reconnected', expect.anything());
+ });
+
+ test('a blip resolved by switching straight to an already-synced doc leaves no stale clock — a later outage gets a full fresh grace', () => {
+ // Switching to an already-synced pooled document derives `synced` directly
+ // on the provider swap, with no intervening `connected` render — so the
+ // `synced` arm is the only place this path can clear the outage clock. A
+ // stamp left stale here would make a later, ordinary blip compute a spent
+ // grace and fire "The server stopped." over a healthy server within a
+ // tick.
+ const { rerender } = renderHook(
+ ({ s, doc }: { s: 'synced' | 'disconnected'; doc: string }) => useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' })); // T0: blip observed
+ act(() => vi.advanceTimersByTime(3_000));
+ act(() => rerender({ s: 'synced', doc: 'b.md' })); // direct-to-synced pooled switch
+ expect(success).toHaveBeenCalledWith('Reconnected', expect.anything());
+ act(() => vi.advanceTimersByTime(30_000)); // healthy editing, well past T0 + grace
+ warning.mockClear();
+
+ act(() => rerender({ s: 'disconnected', doc: 'b.md' })); // an ordinary later blip
+ expect(messages(warning).some((m) => m.includes('keep this tab open'))).toBe(true);
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ act(() => vi.advanceTimersByTime(9_999)); // a full fresh grace, not a spent one
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ act(() => vi.advanceTimersByTime(1));
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ });
+
+ test('switching docs while the reconnect loop is at `connecting` keeps the claim — a later parked connected still has toast + button', () => {
+ // The reconnect loop spends most of its time at `connecting`, so a doc
+ // switch is likeliest to land there. The standing claim must survive it:
+ // if the socket then reaches `connected` and parks, the stalled copy (and
+ // its Restart button) must take over — never a silent, claim-less park.
+ setBridge(true);
+ const { rerender } = renderHook(
+ ({ s, doc }: { s: 'synced' | 'connecting' | 'connected' | 'disconnected'; doc: string }) =>
+ useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' }));
+ act(() => vi.advanceTimersByTime(10_000)); // terminal claim up
+ dismiss.mockClear();
+ warning.mockClear();
+
+ act(() => rerender({ s: 'connecting', doc: 'b.md' })); // switch lands at connecting
+ expect(dismiss).not.toHaveBeenCalled(); // the claim is carried, not blanked
+
+ act(() => rerender({ s: 'connected', doc: 'b.md' }));
+ act(() => vi.advanceTimersByTime(30_000)); // parks
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain("aren't reaching the server");
+ expect(last?.[1]?.action).toBeDefined();
+ });
+
+ test('focusing a non-document tab mid-grace keeps the toast and the clock — a doc reopen re-arms the REMAINDER', () => {
+ // `activeDocName === null` means the FOCUSED TAB is not a document (an
+ // image, a folder listing, the skills browser, a blank tab) — ordinary
+ // navigation with the outage still live, NOT teardown. The standing toast
+ // and its Restart button must stay up (they are the only post-sync outage
+ // surface). The timer OBJECT is cancelled (nothing doc-less could follow
+ // it up) but the outage clock keeps counting, so the reopen re-arms with
+ // the remainder — alternating tabs can neither fire the downgrade doc-less
+ // nor starve it by resetting the grace to a fresh 10s each time.
+ const { rerender } = renderHook(
+ ({ s, doc }: { s: 'synced' | 'connecting' | 'disconnected'; doc: string | null }) =>
+ useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' as string | null } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' })); // t=0: outage observed
+ act(() => vi.advanceTimersByTime(5_000)); // t=5s, mid-grace
+ dismiss.mockClear();
+ warning.mockClear();
+
+ act(() => rerender({ s: 'disconnected', doc: null })); // user clicks an image tab
+ act(() => rerender({ s: 'connecting', doc: null })); // status settles (null provider)
+ expect(dismiss).not.toHaveBeenCalled(); // the standing toast stays up
+ act(() => vi.advanceTimersByTime(3_000)); // t=8s, doc-less: no toast may fire here
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+
+ // Back on a document mid-outage: re-asserts the optimistic copy, and the
+ // grace resumes on the ORIGINAL schedule — 2s remain of the 10s, not a
+ // fresh 10s (which would let tab alternation renew the promise forever).
+ act(() => rerender({ s: 'disconnected', doc: 'b.md' }));
+ expect(messages(warning).some((m) => m.includes('keep this tab open'))).toBe(true);
+ act(() => vi.advanceTimersByTime(1_999)); // t=9.999s since the outage began
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ act(() => vi.advanceTimersByTime(1)); // t=10s exactly
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ });
+
+ test('a grace that elapses entirely on a non-document tab does not fire — the reopen delivers the honest copy', () => {
+ // The two halves of the doc-less contract in one walk. First: the timer
+ // OBJECT must be cancelled on the hop — nothing may reach the toast slot
+ // while no document is focused, even when the deadline passes there.
+ // Second: the clock kept counting, so the reopen sees a spent grace and
+ // downgrades synchronously — the honest copy lands immediately, with no
+ // optimistic replay against a server already silent past the deadline.
+ const { rerender } = renderHook(
+ ({ s, doc }: { s: 'synced' | 'connecting' | 'disconnected'; doc: string | null }) =>
+ useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' as string | null } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' })); // t=0: outage observed
+ act(() => vi.advanceTimersByTime(5_000)); // t=5s, mid-grace
+ act(() => rerender({ s: 'disconnected', doc: null })); // hop to an image tab
+ act(() => rerender({ s: 'connecting', doc: null }));
+ dismiss.mockClear();
+ warning.mockClear();
+
+ act(() => vi.advanceTimersByTime(6_000)); // t=11s: past the deadline, still doc-less
+ expect(warning).not.toHaveBeenCalled(); // nothing may fire without a document
+
+ act(() => rerender({ s: 'disconnected', doc: 'b.md' })); // reopen after the spent grace
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ expect(messages(warning).some((m) => m.includes('keep this tab open'))).toBe(false);
+ expect(dismiss).not.toHaveBeenCalled(); // replaced in place throughout
+ });
+
+ test('focusing a non-document tab AFTER the downgrade keeps the terminal claim — a doc reopen re-asserts it, not the optimistic promise', () => {
+ // The regression this pins: `downgradedRef` is connection-scoped and must
+ // survive a hop through an image/folder tab, exactly like the doc→doc
+ // path — a dead server must not win its "will sync when reconnected"
+ // promise back because the user's route back to a document passed through
+ // a non-document tab.
+ const { rerender } = renderHook(
+ ({ s, doc }: { s: 'synced' | 'connecting' | 'disconnected'; doc: string | null }) =>
+ useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' as string | null } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' }));
+ act(() => vi.advanceTimersByTime(10_000)); // full downgrade — terminal claim up
+ dismiss.mockClear();
+ warning.mockClear();
+
+ act(() => rerender({ s: 'disconnected', doc: null }));
+ act(() => rerender({ s: 'connecting', doc: null }));
+ expect(dismiss).not.toHaveBeenCalled(); // the standing claim survives the hop
+
+ act(() => rerender({ s: 'disconnected', doc: 'b.md' })); // back on a document
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain('server stopped'); // honest copy, immediately
+ expect(messages(warning).some((m) => m.includes('keep this tab open'))).toBe(false);
+ });
+
+ test('reopening a document directly at `connected` after a non-document hop replaces the standing claim with the stalled copy', () => {
+ // The claim stood the whole time (never dismissed on the hop), so the
+ // `connected` branch replaces it — accurate at that instant; `synced`
+ // resolves it moments later on the common path.
+ setBridge(true);
+ const { rerender } = renderHook(
+ ({
+ s,
+ doc,
+ }: {
+ s: 'synced' | 'connecting' | 'connected' | 'disconnected';
+ doc: string | null;
+ }) => useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' as string | null } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' }));
+ act(() => vi.advanceTimersByTime(10_000));
+ act(() => rerender({ s: 'connecting', doc: null })); // hop through a non-document tab
+ dismiss.mockClear();
+ warning.mockClear();
+
+ act(() => rerender({ s: 'connected', doc: 'b.md' })); // reopen lands on a live socket
+ expect(dismiss).not.toHaveBeenCalled();
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain("aren't reaching the server");
+ expect(last?.[1]?.action).toBeDefined();
+ });
+
+ test('a doc reopen at `synced` after a non-document hop resolves the carried claim with "Reconnected"', () => {
+ // The resolve leg of the hop matrix: a terminal claim survives the hop
+ // (nothing can falsify it doc-less), and the reopen walks the real
+ // recovery sequence — `connecting` (no branch runs), `connected`
+ // (replaces the falsified terminal claim with the stalled copy), then
+ // `synced` (resolves that with the success) — never a stranded Infinity
+ // "server stopped" over a healthy server, never a dismiss racing the
+ // replacement.
+ const { rerender } = renderHook(
+ ({
+ s,
+ doc,
+ }: {
+ s: 'synced' | 'connecting' | 'connected' | 'disconnected';
+ doc: string | null;
+ }) => useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' as string | null } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' }));
+ act(() => vi.advanceTimersByTime(10_000)); // terminal claim up
+ act(() => rerender({ s: 'connecting', doc: null })); // hop; server recovers meanwhile
+ dismiss.mockClear();
+ success.mockClear();
+
+ act(() => rerender({ s: 'connecting', doc: 'b.md' })); // reopen walks the real sequence
+ act(() => rerender({ s: 'connected', doc: 'b.md' }));
+ act(() => rerender({ s: 'synced', doc: 'b.md' }));
+
+ expect(success).toHaveBeenCalledWith('Reconnected', expect.anything());
+ expect(dismiss).not.toHaveBeenCalled(); // replaced in place, never dismissed
+ });
+
+ test('a relaunch flag flip while a non-document tab is focused still silences the standing claim', () => {
+ // The relaunch guard sits ABOVE the doc-less return, so "silent during a
+ // relaunch" holds even when the flip lands on an image/folder tab with a
+ // terminal claim (and its live Restart button, aimed at a server the
+ // updater is sweeping) still on screen.
+ const { rerender } = renderHook(
+ ({ s, doc }: { s: 'synced' | 'connecting' | 'disconnected'; doc: string | null }) =>
+ useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' as string | null } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' }));
+ act(() => vi.advanceTimersByTime(10_000)); // terminal claim up
+ act(() => rerender({ s: 'connecting', doc: null })); // hop to a non-document tab
+ dismiss.mockClear();
+
+ relaunchInFlightFlag = true;
+ act(() => rerender({ s: 'connecting', doc: null })); // flag flips while doc-less
+ expect(dismiss).toHaveBeenCalledWith('sync-status');
+ });
+
+ test('switching docs right after a healthy reconnect leaves the expiring "Reconnected" toast alone', () => {
+ // With no outage claim standing, a doc switch does nothing to the slot:
+ // a "Reconnected" success self-expires, and a stranded restart-failure
+ // error (which the user still needs) must not silently vanish.
+ const { rerender } = renderHook(
+ ({ s, doc }: { s: 'synced' | 'disconnected'; doc: string }) => useSyncToasts(s, doc),
+ { initialProps: { s: 'synced' as const, doc: 'a.md' } },
+ );
+ act(() => rerender({ s: 'disconnected', doc: 'a.md' }));
+ act(() => rerender({ s: 'synced', doc: 'a.md' })); // "Reconnected" fires, claim clears
+ dismiss.mockClear();
+ warning.mockClear();
+
+ act(() => rerender({ s: 'synced', doc: 'b.md' }));
+ // "Left alone" proven in full: nothing dismissed AND nothing re-emitted
+ // into the slot — the success from the reconnect is the only one ever.
+ expect(dismiss).not.toHaveBeenCalled();
+ expect(warning).not.toHaveBeenCalled();
+ expect(success).toHaveBeenCalledTimes(1);
+ });
+
+ test('a clean first connect is silent (no prior outage, no stalled toast)', () => {
+ // The happy path the hook's docstring promises: connecting → connected →
+ // synced with no prior outage emits nothing. Without the standing-claim
+ // guard on the `connected` branch, a cold start would show a permanent
+ // false "aren't reaching the server" warning that nothing ever replaces
+ // (the "Reconnected" arm needs a prior disconnect).
+ const { rerender } = renderHook(
+ ({ s }: { s: 'connecting' | 'connected' | 'synced' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'connecting' as const } },
+ );
+ act(() => rerender({ s: 'connected' })); // first-ever connect, nothing disconnected before it
+ expect(warning).not.toHaveBeenCalled();
+ act(() => rerender({ s: 'synced' }));
+ expect(warning).not.toHaveBeenCalled();
+ expect(success).not.toHaveBeenCalled(); // and no "Reconnected" for an outage that never happened
+ });
+
+ test('the grace survives a disconnected→connecting churn cycle (timer is not per-branch)', () => {
+ // `connecting` runs NO branch in this hook — the reconnect loop spends most
+ // of its time there. The grace armed on the first disconnect must keep
+ // running across those hops (the unmount-only cleanup exists precisely so
+ // status churn cannot clear it), reaching the terminal copy on schedule.
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connecting' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(4_000));
+ act(() => rerender({ s: 'connecting' })); // no branch runs; timer keeps counting
+ act(() => vi.advanceTimersByTime(4_000));
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(2_000)); // 10s cumulative across the churn
+
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ });
+
+ test('after the downgrade, a connecting→disconnected churn re-asserts the terminal copy, not the optimistic one', () => {
+ // The sticky `downgradedRef`: once the server is presumed stopped, status
+ // churn that revisits `disconnected` must keep the honest message rather
+ // than reverting to the optimistic promise.
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connecting' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(10_000));
+ warning.mockClear();
+
+ act(() => rerender({ s: 'connecting' }));
+ act(() => rerender({ s: 'disconnected' }));
+
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain('server stopped');
+ expect(messages(warning).some((m) => m.includes('keep this tab open'))).toBe(false);
+ });
+
+ test('the grace boundary is exact: no downgrade at 9,999ms, downgrade at 10,000ms', () => {
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(9_999));
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ act(() => vi.advanceTimersByTime(1));
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ });
+
+ test('unmounting mid-grace cancels the pending downgrade (no toast from a dead hook)', () => {
+ const { rerender, unmount } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(5_000));
+ unmount();
+ act(() => vi.advanceTimersByTime(10_000));
+
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ });
+
+ test('a relaunch mid-outage silences the hook: standing toast dismissed, grace cancelled, connected re-issues nothing', () => {
+ // "Silent during a relaunch" holds by construction — the suppression is
+ // hoisted above every emitter, so it also covers the post-downgrade
+ // `connected` replace path and a flag flip that lands while the reconnect
+ // loop parks at `connecting`.
+ setBridge(false);
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connecting' | 'connected' | 'disconnected' }) =>
+ useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(10_000)); // terminal toast up
+ relaunchInFlightFlag = true;
+ dismiss.mockClear();
+ warning.mockClear();
+
+ act(() => rerender({ s: 'connecting' })); // flag flip lands at connecting
+ expect(dismiss).toHaveBeenCalledWith('sync-status');
+
+ act(() => rerender({ s: 'connected' })); // server back while flag still set
+ act(() => vi.advanceTimersByTime(30_000));
+ expect(warning).not.toHaveBeenCalled(); // no re-issue on top of the relaunch notice
+ });
+
+ test('a relaunch flag flip mid-grace cancels the pending downgrade (not just the standing toast)', () => {
+ // The guard's clearDowngradeTimer must fire while a grace is actually
+ // pending — a suppressed teardown must not later produce a false
+ // "server stopped" from a timer armed before the flag flipped.
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connecting' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' }));
+ act(() => vi.advanceTimersByTime(5_000)); // mid-grace
+ relaunchInFlightFlag = true;
+ warning.mockClear();
+
+ act(() => rerender({ s: 'connecting' })); // flag flip lands mid-grace
+ act(() => vi.advanceTimersByTime(30_000)); // well past where the grace would fire
+
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ });
+
+ test('an aborted relaunch re-asserts the now-genuine outage (relaunchInFlight is a live dep)', () => {
+ // The docblock's promise: "if the relaunch aborts while still disconnected,
+ // this re-runs and the warning fires for the now-genuine outage." The flag
+ // flips true → false with the STATUS unchanged, so only the dep in the
+ // effect array can re-run the hook — dropping it ships a user disconnected
+ // from a torn-down server with no toast and no Restart button.
+ setBridge(false);
+ relaunchInFlightFlag = true;
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' })); // suppressed
+ expect(warning).not.toHaveBeenCalled();
+
+ relaunchInFlightFlag = false; // relaunch aborts; status unchanged
+ act(() => rerender({ s: 'disconnected' }));
+ const last = lastWarning();
+ expect(String(last?.[0])).toContain('keep this tab open');
+ expect(last?.[1]?.action).toBeDefined(); // and the Restart button is back
+ });
+
+ test('a relaunch that interrupts a mid-grace outage resets the clock — the post-abort outage gets a full fresh grace', () => {
+ // The relaunch guard clears the outage clock along with the claim: the
+ // teardown it suppresses is intentional, so time accrued before (and
+ // during) the relaunch must not count against the NEXT outage. A stamp
+ // left stale here would make the aborted relaunch's re-assert compute a
+ // spent grace and jump straight to the terminal copy instead of the
+ // optimistic one.
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' })); // t=0: genuine outage, grace arms
+ act(() => vi.advanceTimersByTime(5_000)); // mid-grace
+ relaunchInFlightFlag = true;
+ act(() => rerender({ s: 'disconnected' })); // guard silences + resets the outage state
+ act(() => vi.advanceTimersByTime(30_000)); // a long relaunch
+ warning.mockClear();
+
+ relaunchInFlightFlag = false; // relaunch aborts; still disconnected
+ act(() => rerender({ s: 'disconnected' }));
+ expect(messages(warning).some((m) => m.includes('keep this tab open'))).toBe(true); // optimistic, not terminal
+ act(() => vi.advanceTimersByTime(9_999)); // a full fresh grace for the new outage
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ act(() => vi.advanceTimersByTime(1));
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(true);
+ });
+
+ test('a clean relaunch leaves no outage residue: no spurious "Reconnected" after it completes', () => {
+ // The suppressed disconnect must not set wasDisconnectedRef — otherwise the
+ // post-relaunch sync would announce a reconnection for an outage the user
+ // never saw.
+ relaunchInFlightFlag = true;
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'disconnected' }) => useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' })); // the intentional teardown, suppressed
+ relaunchInFlightFlag = false;
+ success.mockClear();
+ act(() => rerender({ s: 'synced' })); // fresh server back up
+
+ expect(success).not.toHaveBeenCalled();
+ });
+
+ test('churn cannot orphan a second grace timer — cancel kills the ONLY pending downgrade', () => {
+ // If a re-entry into `disconnected` armed a SECOND timer (instead of the
+ // arm-once guard keeping the original), the `connected` cancel would clear
+ // only the tracked one and the orphan would later fire a false
+ // "server stopped" over a live socket.
+ const { rerender } = renderHook(
+ ({ s }: { s: 'synced' | 'connecting' | 'connected' | 'disconnected' }) =>
+ useSyncToasts(s, 'doc.md'),
+ { initialProps: { s: 'synced' as const } },
+ );
+ act(() => rerender({ s: 'disconnected' })); // t=0: arms the grace
+ act(() => vi.advanceTimersByTime(4_000));
+ act(() => rerender({ s: 'connecting' }));
+ act(() => rerender({ s: 'disconnected' })); // re-entry must NOT arm a second timer
+ act(() => vi.advanceTimersByTime(4_000)); // t=8s
+ act(() => rerender({ s: 'connected' })); // cancels the (single) pending grace
+ act(() => vi.advanceTimersByTime(30_000)); // any orphan would fire in here
+
+ expect(messages(warning).some((m) => m.includes('server stopped'))).toBe(false);
+ });
+});
diff --git a/packages/app/src/presence/use-sync-toasts.ts b/packages/app/src/presence/use-sync-toasts.ts
index 469e128d6..9272f8e90 100644
--- a/packages/app/src/presence/use-sync-toasts.ts
+++ b/packages/app/src/presence/use-sync-toasts.ts
@@ -8,6 +8,31 @@ import type { SyncStatus } from './use-sync-status';
const TOAST_ID = 'sync-status';
+/**
+ * How long a disconnect may persist before we treat the server as *stopped*
+ * (not a transient blip) and downgrade the toast copy. A network hiccup or
+ * transient socket drop reconnects well under this and the `connected`/`synced`
+ * branches cancel the downgrade; a server whose process actually stopped never
+ * reconnects, so after the grace the optimistic "your edits will sync when
+ * reconnected" promise (a dead end once the process is gone) is replaced with
+ * an honest "server stopped" message. The grace is a wall-clock measure of the
+ * whole outage, not of time on the current document (see
+ * `disconnectedSinceRef` for the hop semantics).
+ *
+ * Sleep/wake is the one case a `setTimeout` grace cannot time correctly: the
+ * timer is suspended with the process, so on wake it can fire (elapsed wall
+ * time > grace) before the socket has re-established, briefly showing the
+ * terminal copy for a healthy server. Self-correcting — the `connected` hop
+ * replaces the false claim and `synced` shows "Reconnected" moments later.
+ *
+ * Deliberately shorter than the app's 30s "give up" thresholds (e.g. the
+ * sync-timeout deadline): this is only a COPY downgrade, not an abandonment —
+ * the toast and its Restart button stay up, and nothing stops trying to
+ * reconnect. 10s is long enough to ride out an ordinary blip and short enough
+ * that a genuinely dead server does not sit under a false "will sync" promise.
+ */
+const DISCONNECT_PRESUMED_DEAD_MS = 10_000;
+
/**
* onClick for the disconnect toast's "Restart server" action. When a project's
* server has actually stopped (`ok stop`, an idle-shutdown that fired while the
@@ -45,56 +70,250 @@ export function useSyncToasts(status: SyncStatus, activeDocName: string | null)
const relaunchInFlight = useRelaunchInFlight();
const hasConnectedRef = useRef(false);
const wasDisconnectedRef = useRef(false);
+ // Pending grace timer that downgrades the optimistic toast to the honest
+ // "server stopped" copy, plus a sticky flag so once we've downgraded a
+ // re-render while still disconnected does not revert to the optimistic copy.
+ const downgradeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const downgradedRef = useRef(false);
+ // True from the first outage toast until a dismiss or "Reconnected" clears
+ // it (set by every emitter at `showToast`). The `connected` branch keys its
+ // replace on this — an outage claim of EITHER kind is falsified by a live
+ // socket, so the accurate connected-but-stalled copy must take over whether
+ // the standing toast was the optimistic one (sub-grace reconnect) or the
+ // terminal one (post-grace). Not a strict "an outage toast is on screen"
+ // invariant: `runDisconnectRestart`'s failed-restart branch overwrites the
+ // same TOAST_ID slot with an error toast without clearing this, so it can
+ // read true while that error is what's showing. Deliberate — a live socket
+ // obsoletes a restart-failure headline too.
+ //
+ // Outage state is server-scoped — each doc holds its own provider, but a
+ // real server outage drops every socket together — so no outage STATE
+ // resets when `activeDocName` changes: the refs, the terminal
+ // `downgradedRef` claim, the outage clock, and the standing toast all carry
+ // (the timer OBJECT alone is doc-scoped — see the doc-less branch). While a
+ // claim stands, whichever branch next runs re-asserts, replaces, or
+ // resolves it — a dead server never wins its "will sync when reconnected"
+ // promise back just because the user tried a different file. With no claim
+ // standing, a doc change touches nothing: the slot then holds either a
+ // self-expiring "Reconnected" or a restart-failure error the user still
+ // needs, and neither should vanish because a tab changed.
+ const outageToastStandingRef = useRef(false);
+ // Wall-clock stamp of when the current outage's grace first armed — the
+ // canonical statement of the hop semantics. The grace measures TOTAL time
+ // across the outage, not time on the current document: a hop through a
+ // non-document tab cancels the timer object (nothing doc-less could follow
+ // it up) but keeps this stamp, so a document reopen re-arms with the
+ // REMAINDER — or downgrades on the spot if the deadline passed during the
+ // hop. Alternating between an editor pane and an image pane can therefore
+ // neither fire a toast doc-less nor starve the downgrade by resetting the
+ // clock. Set when the grace first arms; stays set after the downgrade fires
+ // (the outage is still live); cleared only where the outage claim itself
+ // resolves: a live socket (`connected`/`synced`) or the relaunch guard.
+ // Wall-clock (`Date.now()`) over a monotonic clock is deliberate:
+ // `setTimeout` is itself suspended with the process, so the sleep/wake
+ // reasoning on `DISCONNECT_PRESUMED_DEAD_MS` is wall-clock either way. A
+ // backwards clock step (NTP correction) between arm and re-arm is bounded
+ // by the re-arm's upper clamp to at most one fresh grace.
+ const disconnectedSinceRef = useRef<number | null>(null);
- const prevDocRef = useRef(activeDocName);
+ // Clear the grace timer on unmount only. Empty deps so it does NOT run on
+ // every status flip — the timer must survive the connecting/disconnected
+ // churn of a reconnect loop to actually reach the grace. Refs are stable, so
+ // no dependency is needed.
+ useEffect(
+ () => () => {
+ if (downgradeTimerRef.current !== null) {
+ clearTimeout(downgradeTimerRef.current);
+ downgradeTimerRef.current = null;
+ }
+ },
+ [],
+ );
useEffect(() => {
- if (prevDocRef.current !== activeDocName) {
- prevDocRef.current = activeDocName;
- hasConnectedRef.current = false;
- wasDisconnectedRef.current = false;
- }
-
- if (!activeDocName) return;
+ const clearDowngradeTimer = () => {
+ if (downgradeTimerRef.current !== null) {
+ clearTimeout(downgradeTimerRef.current);
+ downgradeTimerRef.current = null;
+ }
+ };
if (status === 'synced') {
hasConnectedRef.current = true;
}
+ // Relaunch suppression, above BOTH the doc-less return and every toast
+ // emitter, so "this hook is silent during a relaunch" holds on every path
+ // — including a flag flip that lands while a non-document tab is focused
+ // with a claim standing (the guard reads no document context, so there is
+ // no reason to let the doc-less return shadow it). An outage toast (with
+ // a live Restart button aimed at a server the updater is sweeping) would
+ // contradict the sidebar's calm "Relaunching…" notice (rationale at
+ // `relaunchInFlight` above). `hasConnectedRef` is recorded above this
+ // guard so an aborted relaunch at `synced` still knows the window once
+ // connected;
+ // `wasDisconnectedRef` is left untouched, so an aborted relaunch that
+ // later syncs shows "Reconnected" only if a real outage preceded it.
+ if (relaunchInFlight) {
+ clearDowngradeTimer();
+ downgradedRef.current = false;
+ disconnectedSinceRef.current = null;
+ toast.dismiss(TOAST_ID);
+ outageToastStandingRef.current = false;
+ return;
+ }
+
+ if (!activeDocName) {
+ // The focused tab is not a DOCUMENT — an image/PDF, a folder listing,
+ // the skills browser, an over-limit file, a blank tab, or no pane target
+ // at all. That is ordinary navigation, not teardown: the standing outage
+ // claim and its Restart button stay up (they are the only post-sync
+ // outage surface), and `downgradedRef` + the outage clock survive. A
+ // document reopen then resumes on the ORIGINAL deadline: mid-grace it
+ // re-shows the optimistic copy for the remainder only; once the grace is
+ // spent (downgraded before the hop, or elapsed during it) it shows the
+ // honest copy immediately. What can never happen is a fresh 10s promise
+ // against a server already silent that long. Only the timer OBJECT is
+ // cancelled: no branch below runs while doc-less, so a timer firing here
+ // could neither be cancelled by the reconnect it raced nor followed by
+ // the replace/resolve arms — the reopen re-arms from the surviving stamp
+ // (see `disconnectedSinceRef`). Accepted residual: nothing can falsify a
+ // claim while doc-less either, so if the server recovers during the hop
+ // the claim stands stale until a document regains focus (same staleness
+ // already accepted at `connecting`; a doc-independent health signal
+ // would be a design change, not a gap here).
+ clearDowngradeTimer();
+ return;
+ }
+
+ // Desktop only: offer a working recovery on the outage toasts. Both desktop
+ // server kinds restart from here: a project server via
+ // `restartAttachedServer`, and an ephemeral single-file server via the
+ // sender-routed `restartEphemeralServer` (the `ok:project:restart-server` IPC
+ // picks the path from the requesting window), so single-file is not gated
+ // off. In `ok ui` (browser) mode there is no bridge, so the toasts stay
+ // message-only. (No `typeof window` guard — this runs inside useEffect,
+ // always client-side.)
+ const bridge = window.okDesktop;
+ const hasRestartButton = bridge !== undefined;
+ const restartAction =
+ bridge !== undefined
+ ? {
+ action: {
+ label: t`Restart server`,
+ onClick: () => {
+ void runDisconnectRestart(bridge);
+ },
+ },
+ }
+ : {};
+ // The three outage messages, each factored once so the copy and its options
+ // cannot drift between call sites (all share TOAST_ID, so the latest call
+ // replaces the previous message in place; each records itself standing):
+ // - optimistic: a fresh disconnect — reconnect + delivery are expected.
+ // - connected-but-stalled: the socket is proven live but edits are not
+ // landing — replaces whichever outage claim a live socket falsified.
+ // Names delivery rather than sync: "Sync" is the Git-integration label
+ // elsewhere in the product (`SyncStatusBadge`, settings `SyncSection`),
+ // so a bare "not syncing" status claim reads as a Git problem. The
+ // optimistic copy below predates this and still says "will sync".
+ // - terminal: the grace elapsed with no reconnect — the server is presumed
+ // stopped. Only browser (`ok ui`) mode has no Restart button; there the
+ // copy omits the restart instruction so it never points at an absent
+ // control.
+ const showToast = (message: string) => {
+ outageToastStandingRef.current = true;
+ toast.warning(message, { id: TOAST_ID, duration: Infinity, ...restartAction });
+ };
+ const showConnectionLost = () =>
+ showToast(t`Connection lost — keep this tab open, your edits will sync when reconnected`);
+ const showConnectedStalled = () =>
+ showToast(
+ hasRestartButton
+ ? t`Connected, but your edits aren't reaching the server yet. Restart it if this continues.`
+ : t`Connected, but your edits aren't reaching the server yet.`,
+ );
+ const showServerStopped = () =>
+ showToast(
+ hasRestartButton ? t`The server stopped. Restart it to reconnect.` : t`The server stopped.`,
+ );
+
+ if (status === 'connected') {
+ // The socket reopened, so the server is reachable — a stopped server never
+ // reaches `connected` (its process is gone, the connection is refused).
+ // Cancel a pending downgrade so the grace can't fire "The server stopped."
+ // over a live socket, and drop the sticky flag so a later re-disconnect
+ // arms a fresh grace. A live socket falsifies WHICHEVER claim is standing
+ // — "Connection lost", "The server stopped.", or a stranded
+ // restart-failure error (see `outageToastStandingRef`'s docblock) — so if
+ // one is up, REPLACE it (same toast id) with copy that names this exact
+ // state, keeping the Restart button: a socket that parks here without
+ // ever syncing (auth stall, wedged doc) gets no further transition to
+ // hand it one, whether it reopened before the grace or after. On the
+ // common recovery path `synced` lands moments later and swaps in
+ // "Reconnected"; the brief accurate intermediate is the cost of never
+ // showing a falsified headline.
+ clearDowngradeTimer();
+ downgradedRef.current = false;
+ disconnectedSinceRef.current = null;
+ if (outageToastStandingRef.current) showConnectedStalled();
+ }
+
if (status === 'disconnected' && hasConnectedRef.current) {
- if (relaunchInFlight) {
- // Intentional teardown — clear any warning already showing (covers the
- // disconnect-then-relaunch ordering) and stay silent. Don't set
- // `wasDisconnectedRef`, so no spurious "Reconnected" fires afterward.
- toast.dismiss(TOAST_ID);
+ wasDisconnectedRef.current = true;
+ // The action rides BOTH the optimistic and the terminal toast. A
+ // reconnected socket that never re-syncs, or one that flaps faster than
+ // the grace, never reaches the terminal downgrade (the `connected` hop
+ // cancels it), so the optimistic toast is the only surface left to carry
+ // recovery. (A server that never syncs on FIRST connect is not this hook's
+ // case — `hasConnectedRef` gates on a prior `synced`, and the sync-timeout
+ // error boundary owns that persona with its own Restart action.)
+ if (downgradedRef.current) {
+ // Already presumed stopped — keep the honest message across re-renders.
+ showServerStopped();
return;
}
- wasDisconnectedRef.current = true;
- // Desktop only: offer a working recovery. "keep this tab open\u2026 will sync
- // when reconnected" is true for a transient blip but a dead end once the
- // server has actually stopped \u2014 Restart spawns a fresh one. In `ok ui`
- // (browser) mode there is no bridge, so the toast stays message-only.
- // (No `typeof window` guard \u2014 this runs inside useEffect, always client-side.)
- const bridge = window.okDesktop;
- toast.warning(
- t`Connection lost \u2014 keep this tab open, your edits will sync when reconnected`,
- {
- id: TOAST_ID,
- duration: Infinity,
- ...(bridge
- ? {
- action: {
- label: t`Restart server`,
- onClick: () => {
- void runDisconnectRestart(bridge);
- },
- },
- }
- : {}),
- },
- );
+ // Arm the downgrade for the REMAINDER of the grace — the clock survives
+ // non-document hops (see `disconnectedSinceRef`), so tab alternation
+ // cannot renew the optimistic promise. A transient disconnect reconnects
+ // under the grace and the `connected`/`synced` branches cancel this; a
+ // stopped server never reconnects, so at the deadline we swap in the
+ // honest copy. A grace already spent (the deadline passed while no
+ // document was focused) downgrades right here, synchronously — a
+ // zero-delay timer would only write the optimistic copy over the honest
+ // one for a tick.
+ if (downgradeTimerRef.current === null) {
+ const now = Date.now();
+ if (disconnectedSinceRef.current === null) {
+ disconnectedSinceRef.current = now;
+ }
+ // Clamped above by the full grace so a backwards wall-clock step
+ // (NTP correction between arm and re-arm) stretches the wait by at
+ // most one fresh grace instead of the size of the step.
+ const remainingMs = Math.min(
+ DISCONNECT_PRESUMED_DEAD_MS,
+ DISCONNECT_PRESUMED_DEAD_MS - (now - disconnectedSinceRef.current),
+ );
+ if (remainingMs <= 0) {
+ downgradedRef.current = true;
+ showServerStopped();
+ return;
+ }
+ downgradeTimerRef.current = setTimeout(() => {
+ downgradeTimerRef.current = null;
+ downgradedRef.current = true;
+ showServerStopped();
+ }, remainingMs);
+ }
+ showConnectionLost();
} else if (wasDisconnectedRef.current && status === 'synced') {
wasDisconnectedRef.current = false;
+ clearDowngradeTimer();
+ downgradedRef.current = false;
+ disconnectedSinceRef.current = null;
+ // The outage is over — the success replaces the outage toast in place
+ // (same id) and auto-expires, so no outage toast is standing anymore.
+ outageToastStandingRef.current = false;
toast.success(t`Reconnected`, { id: TOAST_ID, duration: 3000 });
}
}, [status, activeDocName, t, relaunchInFlight]);
diff --git a/packages/core/src/config/resolve-server-config.test.ts b/packages/core/src/config/resolve-server-config.test.ts
index 352a2f109..64ad1e7c4 100644
--- a/packages/core/src/config/resolve-server-config.test.ts
+++ b/packages/core/src/config/resolve-server-config.test.ts
@@ -92,6 +92,45 @@ describe('resolveServerRuntimeConfig — defaults', () => {
expect(eagerContainer.openBrowser).toBe(true);
expect(eagerContainer.idleShutdown).toBe('2h');
});
+
+ test('an exposed loopback deployment (allowExternal + externalUrl) does NOT idle-die', () => {
+ // The tunnel-to-loopback remote recipe: bound to 127.0.0.1 but declared
+ // reachable. The idle timer is blind to the `/mcp` agent keeping it busy, so
+ // exposure must derive `off` (like a 0.0.0.0 bind already does).
+ const resolved = resolveServerRuntimeConfig(
+ parse({ server: { externalUrl: 'https://kb.example.ts.net', allowExternal: true } }),
+ );
+ expect(resolved.loopbackOnly).toBe(true);
+ expect(resolved.idleShutdown).toBe('off');
+ });
+
+ test('an unexposed loopback deployment still idles out', () => {
+ // allowExternal without an externalUrl is not "exposed" — keep the default.
+ const resolved = resolveServerRuntimeConfig(parse({ server: { allowExternal: true } }));
+ expect(resolved.loopbackOnly).toBe(true);
+ expect(resolved.idleShutdown).toBe(DEFAULT_LOOPBACK_IDLE_SHUTDOWN);
+ });
+
+ test('externalUrl without allowExternal is not exposed — idle default kept', () => {
+ const resolved = resolveServerRuntimeConfig(
+ parse({ server: { externalUrl: 'https://kb.example.ts.net' } }),
+ );
+ expect(resolved.loopbackOnly).toBe(true);
+ expect(resolved.idleShutdown).toBe(DEFAULT_LOOPBACK_IDLE_SHUTDOWN);
+ });
+
+ test('an explicit idleShutdown wins even when exposed', () => {
+ const resolved = resolveServerRuntimeConfig(
+ parse({
+ server: {
+ externalUrl: 'https://kb.example.ts.net',
+ allowExternal: true,
+ idleShutdown: '45m',
+ },
+ }),
+ );
+ expect(resolved.idleShutdown).toBe('45m');
+ });
});
describe('resolveServerRuntimeConfig — externalUrl', () => {
diff --git a/packages/core/src/config/resolve-server-config.ts b/packages/core/src/config/resolve-server-config.ts
index 1fcbc3b47..189799d8b 100644
--- a/packages/core/src/config/resolve-server-config.ts
+++ b/packages/core/src/config/resolve-server-config.ts
@@ -2,9 +2,12 @@
* Resolve the effective `server.*` runtime settings from a merged `Config`.
*
* The one job no zod `.default()` can do: **derived defaults.** `openBrowser`
- * and `idleShutdown` default off the resolved bind: a loopback-only server pops
- * the UI and idles out after {@link DEFAULT_LOOPBACK_IDLE_SHUTDOWN}; an exposed
- * or containerized server is headless and stays up. The local/hosted split is
+ * derives off the resolved bind alone: a loopback-only server pops the UI, an
+ * exposed or containerized one is headless. `idleShutdown` derives three ways:
+ * loopback-and-unexposed idles out after {@link DEFAULT_LOOPBACK_IDLE_SHUTDOWN};
+ * a non-loopback bind stays up; and a loopback bind declared externally reachable
+ * (`allowExternal` + `externalUrl`) also stays up, since its remote agents keep
+ * it busy over `/mcp`, which the idle timer cannot see. The local/hosted split is
* emergent from these values — there is deliberately no mode key to branch on.
*
* Enforcing the exposure interlock (refusing to boot when
@@ -16,7 +19,11 @@
import type { Config } from './schema.ts';
import { DEFAULT_SERVER_BIND, IDLE_SHUTDOWN_DURATION_RE } from './schema.ts';
-/** Derived `idleShutdown` for a loopback-only server; exposed binds derive `'off'`. */
+/**
+ * Derived `idleShutdown` for a loopback-only, UNEXPOSED server. A non-loopback
+ * bind, or a loopback bind declared externally reachable (`allowExternal` +
+ * `externalUrl`), derives `'off'` instead.
+ */
export const DEFAULT_LOOPBACK_IDLE_SHUTDOWN = '30m';
export interface ServerRuntimeConfig {
@@ -126,13 +133,22 @@ export function resolveServerRuntimeConfig(config: Config | undefined): ServerRu
const port = server?.port;
const externalUrl = server?.externalUrl;
+ // "Exposed" = the operator declared this deployment reachable from outside
+ // (allowExternal + an explicit externalUrl). The idle timer counts only
+ // `/collab` editor WebSockets and is blind to `/mcp`, so a tunnel-to-loopback
+ // server serving a remote agent would idle-shut-down mid-session. Keying the
+ // idle default off exposure, not the raw bind, keeps an exposed loopback
+ // server alive like a `0.0.0.0` bind already is.
+ const exposed = (server?.allowExternal ?? false) && externalUrl !== undefined;
+
return {
port,
bind,
externalUrl,
allowExternal: server?.allowExternal ?? false,
openBrowser: server?.openBrowser ?? loopbackOnly,
- idleShutdown: server?.idleShutdown ?? (loopbackOnly ? DEFAULT_LOOPBACK_IDLE_SHUTDOWN : 'off'),
+ idleShutdown:
+ server?.idleShutdown ?? (loopbackOnly && !exposed ? DEFAULT_LOOPBACK_IDLE_SHUTDOWN : 'off'),
loopbackOnly,
};
}
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index 5c0753615..2e51e6357 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -1393,11 +1393,12 @@ export const ConfigSchema = z.looseObject({
// `agentSettable: false` on every leaf: an agent must never widen its own
// network exposure.
//
- // `openBrowser` and `idleShutdown` have DERIVED defaults (they depend on
- // whether the resolved `bind` is loopback-only), so those leaves stay
- // optional here — a schema-time `.default()` cannot see `bind`. The
- // derivation lives in `resolveServerRuntimeConfig`
- // (`resolve-server-config.ts`).
+ // `openBrowser` and `idleShutdown` have DERIVED defaults, so those leaves stay
+ // optional here — a schema-time `.default()` cannot see the other fields.
+ // `openBrowser` keys off whether the resolved `bind` is loopback-only;
+ // `idleShutdown` additionally keys off exposure (a loopback bind declared
+ // externally reachable via `allowExternal` + `externalUrl` stays up too). The
+ // derivation lives in `resolveServerRuntimeConfig` (`resolve-server-config.ts`).
server: z
.looseObject({
port: z
@@ -1471,7 +1472,7 @@ export const ConfigSchema = z.looseObject({
reload: 'live',
defaultScope: 'project-local',
description:
- "Shut the server down after this long with no activity: a duration like '30m' (positive integer with unit s, m, or h), or 'off'. Default derived: '30m' when every bind address is loopback, 'off' otherwise (an exposed or containerized server stays up). Reloadable — a valid change applies without a restart. Per-machine (project-local) — not shared.",
+ "Shut the server down after this long with no activity: a duration like '30m' (positive integer with unit s, m, or h), or 'off'. Default derived: '30m' for a loopback-only, unexposed server; 'off' otherwise — a non-loopback bind, or a loopback bind declared externally reachable (server.allowExternal + server.externalUrl), stays up, because a remote agent keeps it busy over /mcp, which the idle timer does not count. Residual case the derivation cannot see: a loopback server reached by remote agents with no server.externalUrl (e.g. behind a same-box reverse proxy) still idles at 30m — set 'off' by hand. Reloadable — a valid change applies without a restart. Per-machine (project-local) — not shared.",
})
.optional(),
})
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index b179eb8ef..1031210a9 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -6748,13 +6748,13 @@ function registerIpcHandlers() {
return undefined;
});
- handle('ok:project:restart-server', async (_event, projectPath) => {
- // Renderer-initiated from the version-drift notification. Terminates the
- // attached (not-owned) server and recreates the window against a fresh
- // own-version spawn. The returned outcome only reaches the renderer on
- // failure (a surviving window) — success recreates the originating window.
- // The try/catch makes the contract uniform: every path resolves with an
- // outcome rather than rejecting on a destroyed renderer.
+ handle('ok:project:restart-server', async (event, projectPath) => {
+ // Renderer-initiated from the version-drift notification or the "server
+ // gone" error affordance. Terminates the server and recreates/retires the
+ // originating window against a fresh spawn. The returned outcome only reaches
+ // the renderer on failure (a surviving window). The try/catch makes the
+ // contract uniform: every path resolves with an outcome rather than rejecting
+ // on a destroyed renderer.
if (!wm) {
logIpcError({
event: 'ipc.error',
@@ -6765,7 +6765,14 @@ function registerIpcHandlers() {
return { ok: false, reason: 'other' };
}
try {
- const outcome = await wm.restartAttachedServer(projectPath, {
+ // Route by the REQUESTING window, not the `projectPath` arg — an ephemeral
+ // single-file window's server is file-keyed under a throwaway temp dir the
+ // directory-keyed `restartAttachedServer` can't reach. The decision lives in
+ // `restartServerForWindow` (on the class that owns the identity map) so it is
+ // unit-testable through the DI harness; this handler only adapts the sender
+ // webContents to a window and threads the CLI args.
+ const senderWindow = BrowserWindow.fromWebContents(event.sender);
+ const outcome = await wm.restartServerForWindow(senderWindow, projectPath, {
localOpCliArgs: resolveLocalOpCliArgs(),
});
if (outcome.ok === false) {
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index be9e77eb0..5d4a6b19a 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -534,6 +534,17 @@ interface ProjectContext {
};
}
+/**
+ * The `createEphemeralWindow` inputs retained per-window so a later "Restart
+ * server" can replay the exact open — even for a dead window a re-open has
+ * already orphaned from `windowsByPath`. See `ephemeralWindowIdentity`.
+ */
+export interface EphemeralOpenIdentity {
+ canonicalFilePath: string;
+ contentDir: string;
+ docName: string;
+}
+
interface CreateProjectWindowOpts {
projectPath: string;
/**
@@ -1160,6 +1171,18 @@ export class WindowManager {
*/
private readonly windowsByPath = new Map<string, ProjectContext>();
+ /**
+ * BrowserWindow → the original `createEphemeralWindow` inputs, for every
+ * ephemeral single-file window, cleared only when that window actually closes.
+ * Distinct from `windowsByPath`: a re-open after the server died replaces the
+ * slot with the fresh window, orphaning the still-open dead window from that
+ * map — but a "Restart server" click can still come from the dead window, and
+ * it must route to the ephemeral respawn (not the directory-keyed project
+ * restart, which fails with a toast loop). Also the source for
+ * `retireStaleWindowsForFile` (find every window for a file to converge on one).
+ */
+ private readonly ephemeralWindowIdentity = new Map<BrowserWindowLike, EphemeralOpenIdentity>();
+
/**
* BrowserWindow → its ProjectContext for two of the spans in which no
* authoritative `windowsByPath` entry answers for a window the user can see
@@ -2140,6 +2163,211 @@ export class WindowManager {
}
}
+ /**
+ * The restart identity for a window, if it is an ephemeral single-file window.
+ * Looks up the durable `ephemeralWindowIdentity` map (NOT `windowsByPath`), so
+ * it still resolves a dead window that a re-open has orphaned from the slot
+ * map — the case where routing a restart to the project path produced the
+ * error-toast loop. Returns `undefined` for project windows.
+ *
+ * Public for the DI test harness (which resolves the identity the IPC would
+ * hand `restartEphemeralServer`); production routes through the sibling
+ * `restartServerForWindow`, which calls this internally.
+ */
+ getEphemeralIdentityForWindow(win: BrowserWindowLike): EphemeralOpenIdentity | undefined {
+ return this.ephemeralWindowIdentity.get(win);
+ }
+
+ /**
+ * Restart the server for an ephemeral single-file window (the "server gone"
+ * affordance's action). `restartAttachedServer` is directory-keyed and cannot
+ * reach a file-keyed ephemeral session (its lock lives under a throwaway
+ * `$TMPDIR/ok-ephemeral-*` dir, keyed by the canonical FILE path) — routing a
+ * single-file restart there failed with a retry-toast loop. Instead respawn
+ * through `createEphemeralWindow`, which then retires every other window for the
+ * file, converging to a single live window. Routed here from the IPC by the
+ * durable `ephemeralWindowIdentity` lookup, so it works even for a dead window a
+ * re-open already orphaned from `windowsByPath`.
+ *
+ * A restart must *actually restart*: `createEphemeralWindow` normally DEDUPS
+ * onto a live server (correct for `ok open <file>`, wrong here — it would focus
+ * the window, spawn nothing, and resolve `{ ok: true }` having restarted
+ * nothing, which the renderer reads as "torn down and recreated" and shows no
+ * feedback). So when a live session for this file still exists — e.g. the
+ * DocumentErrorBoundary reach-error path fires while the process is alive but
+ * sync is wedged — terminate it and evict its slot FIRST, forcing the recreate
+ * to spawn a fresh server. A dead session needs no pre-teardown; the recreate's
+ * own stale-entry path reaps it. The fresh window IS the success signal (the
+ * old originating window is closed by the recreate's `retireStaleWindowsForFile`
+ * sweep, so the caller's invoke rejects and stops — the contract
+ * `restartCollabServer` already expects), so there is no separate
+ * `ok:server-restarted` toast to thread as `restartAttachedServer` does.
+ *
+ * No `onProjectServerRestarted` (the sibling's note-window recreate): an
+ * ephemeral single-file session structurally cannot pop out note windows
+ * (`open-in-new-window` is `singleFileHidden`), so there is nothing to recreate.
+ *
+ * `requestingWindow` gates the live-terminate to slot OWNERSHIP: the live server
+ * is torn down only when the window that asked is the one currently holding the
+ * file's slot (the wedged-but-alive case it is written for). A superseded window
+ * that a re-open orphaned from the slot (its live sibling now owns it) must NOT
+ * terminate that healthy sibling — it falls through to `createEphemeralWindow`,
+ * which dedups onto the live sibling and retires the orphan. Convergence
+ * normally closes such orphans first, so this is a guard on the narrow
+ * `closeAndAwait` grace window. Required rather than optional so a caller cannot
+ * omit it and silently fall into the dedup-only path — that returns
+ * `{ ok: true }` having spawned nothing, the outcome this method exists to
+ * prevent.
+ */
+ async restartEphemeralServer(
+ identity: EphemeralOpenIdentity,
+ requestingWindow: BrowserWindowLike,
+ ): Promise<OkServerRestartOutcome> {
+ this.deps.log?.info(
+ {
+ event: 'desktop-ephemeral-restart',
+ outcome: 'requested',
+ file: identity.canonicalFilePath,
+ },
+ '[window-manager] ephemeral server restart requested',
+ );
+ try {
+ const canonicalKey = this.canonicalizeKey(identity.canonicalFilePath);
+ const current = this.windowsByPath.get(canonicalKey);
+ if (
+ current &&
+ current.window === requestingWindow &&
+ current.window.isDestroyed?.() !== true &&
+ this.isEphemeralServerAlive(current)
+ ) {
+ // Live server + open window + the requester owns the slot: this is the
+ // "restart raced a healthy (but wedged) server" case. Evict the slot,
+ // close its keepalive, and terminate the server so the recreate below
+ // cannot dedup back onto it.
+ this.deps.log?.info(
+ {
+ event: 'desktop-ephemeral-restart',
+ outcome: 'terminated-live',
+ file: identity.canonicalFilePath,
+ },
+ '[window-manager] terminating the live ephemeral server before respawn',
+ );
+ this.windowsByPath.delete(canonicalKey);
+ this.closeKeepalive(canonicalKey);
+ if (current.ephemeral) await this.teardownEphemeralSession(current.ephemeral);
+ }
+ const recreated = await this.createEphemeralWindow({
+ canonicalFilePath: identity.canonicalFilePath,
+ contentDir: identity.contentDir,
+ docName: identity.docName,
+ });
+ this.deps.log?.info(
+ {
+ event: 'desktop-ephemeral-restart',
+ outcome: 'respawned',
+ file: identity.canonicalFilePath,
+ apiOrigin: recreated.apiOrigin,
+ },
+ '[window-manager] ephemeral server restart respawned',
+ );
+ return { ok: true };
+ } catch (err) {
+ this.deps.log?.warn(
+ {
+ event: 'desktop-ephemeral-restart',
+ outcome: 'recreate-failed',
+ err: err instanceof Error ? (err.stack ?? err.message) : String(err),
+ file: identity.canonicalFilePath,
+ },
+ '[window-manager] ephemeral server restart could not respawn',
+ );
+ // The dead originating window stays open so its renderer surfaces failure.
+ return { ok: false, reason: 'other' };
+ }
+ }
+
+ /**
+ * Route a renderer-initiated `ok:project:restart-server` to the correct restart
+ * by the REQUESTING window, not the `projectPath` arg. An ephemeral single-file
+ * window's server is file-keyed under a throwaway temp dir, so the
+ * directory-keyed `restartAttachedServer` can't reach it and drops the user into
+ * a retry-toast loop; the durable window→identity map resolves the ephemeral
+ * case (and still resolves a dead window a re-open has orphaned from
+ * `windowsByPath`). Kept here — a testable method on the class that owns the
+ * maps — rather than as an inline ternary in the IPC handler, which no test tier
+ * can reach.
+ */
+ async restartServerForWindow(
+ sender: BrowserWindowLike | null,
+ projectPath: string,
+ opts: { localOpCliArgs?: string[] },
+ ): Promise<OkServerRestartOutcome> {
+ if (sender !== null) {
+ const ephemeralIdentity = this.getEphemeralIdentityForWindow(sender);
+ if (ephemeralIdentity !== undefined) {
+ // `sender` is the window whose identity we just resolved; pass it so the
+ // live-terminate is gated on that window still owning the file's slot.
+ return this.restartEphemeralServer(ephemeralIdentity, sender);
+ }
+ }
+ return this.restartAttachedServer(projectPath, opts);
+ }
+
+ /**
+ * Retire (close) every OTHER open ephemeral window for `canonicalKey` besides
+ * `keepWindow`. Called once `createEphemeralWindow` has landed on the live
+ * window for a file, so a (re)open or restart converges to exactly one window
+ * and no dead window dangles. Safe because at most one live server exists per
+ * file — the one behind `keepWindow` — so every sibling window's server is
+ * already dead. Each retired window's own `'closed'` handler clears its identity;
+ * its teardown branch short-circuits (the ownership guard fails, since the live
+ * `keepWindow` now owns the slot), which is correct — a retired window's server
+ * was already reaped by the stale-entry path, the exit-watch, or the restart
+ * pre-terminate before it got here. Snapshots the targets first so the
+ * `'closed'`-driven map mutation cannot perturb the iteration.
+ *
+ * Routes through `closeAndAwait` (not a bare `close()`), so a window that never
+ * emits `'closed'` — a `beforeunload` veto, a native wedge — is force-destroyed
+ * rather than left open with its `ephemeralWindowIdentity` entry leaked, which
+ * would defeat the "converges to exactly one window" guarantee. Fire-and-forget
+ * at the call sites (they don't await convergence), so the sweep runs its
+ * closes concurrently.
+ */
+ private retireStaleWindowsForFile(canonicalKey: string, keepWindow: BrowserWindowLike): void {
+ const stale: BrowserWindowLike[] = [];
+ for (const [win, identity] of this.ephemeralWindowIdentity) {
+ if (win === keepWindow) continue;
+ if (this.canonicalizeKey(identity.canonicalFilePath) !== canonicalKey) continue;
+ stale.push(win);
+ }
+ if (stale.length === 0) return;
+ this.deps.log?.info(
+ { event: 'desktop-ephemeral-retire-stale', canonicalKey, retired: stale.length },
+ '[window-manager] retiring stale ephemeral window(s) for the file',
+ );
+ for (const win of stale) void this.closeAndAwait(win);
+ }
+
+ /**
+ * Close and drop the ephemeral keepalive for `canonicalKey`, if one is open.
+ * The keepalive re-reads `<lockDir>/server.lock` every attempt, so once a
+ * session's server is gone (its lockDir removed by `teardownEphemeralSession`)
+ * an un-closed keepalive reconnect-loops against a path that no longer exists
+ * for the window's remaining lifetime. Every PER-WINDOW teardown site — normal
+ * close, exit-watch reap, stale-entry re-spawn, the restart pre-terminate — must
+ * call this so the keepalive dies with the server it was holding up.
+ * `stopAllOwnedServers` (relaunch/quit) does not: it runs immediately before the
+ * process exits, so any surviving keepalive is bounded by that exit, not a
+ * window's lifetime.
+ */
+ private closeKeepalive(canonicalKey: string): void {
+ const keepalive = this.keepalives.get(canonicalKey);
+ if (keepalive) {
+ keepalive.close();
+ this.keepalives.delete(canonicalKey);
+ }
+ }
+
/**
* Close a window and resolve once its `'closed'` event fires (the existing
* attach `'closed'` handler runs alongside, clearing its own map/keepalive
@@ -2942,6 +3170,9 @@ export class WindowManager {
// `apiOrigin`, so `ok open <file>` "succeeded" with no live session.
if (windowAlive && this.isEphemeralServerAlive(existing)) {
this.bringToFront(existing.window);
+ // Converge: retire any other (dead-server) window left open for this
+ // file; keep the live `existing` one.
+ this.retireStaleWindowsForFile(canonicalKey, existing.window);
return existing;
}
this.deps.log?.warn(
@@ -2958,17 +3189,25 @@ export class WindowManager {
: '[window-manager] stale destroyed ephemeral entry — clearing and re-creating',
);
this.windowsByPath.delete(canonicalKey);
+ // The stale session's keepalive (if any) is now pointing at a lockDir the
+ // teardown below removes — close it here so it does not reconnect-loop for
+ // the stale window's remaining lifetime (its guarded `'closed'` teardown
+ // won't run once this re-open takes the slot). No-op when none was opened.
+ this.closeKeepalive(canonicalKey);
// Reap the dead session's temp dir + (already-dead) pid only when the
// window is still open here. A destroyed window already ran its `'closed'`
// teardown; teardown is idempotent, but skipping the redundant SIGTERM/rm
// keeps the destroyed-window path single-pass, as before.
//
- // The stale window itself is left open, not closed — deliberately, unlike
- // `restartAttachedServer` (which closes the old window once the replacement
- // exists). That path has a synchronous in-place replacement; here the user
- // explicitly re-opened, and gracefully retiring the dead-server window is
- // the renderer "server gone" affordance's job, not main's. Closing it here
- // would preempt that and yank a window the user may still be reading.
+ // This branch only reaps the dead SERVER + temp dir; the stale WINDOW is
+ // not closed here. Convergence to a single window happens later in this same
+ // flow: once the fresh server is live, `retireStaleWindowsForFile` (at the
+ // end of `spawnEphemeralWindow`) closes every other window for the file,
+ // including this one. Splitting it that way keeps the "close the old window"
+ // step behind a live replacement (recreate-then-close, no flash), matching
+ // `restartAttachedServer`'s ordering — closing here, before the replacement
+ // exists, would flash an empty gap and yank a window the user may still be
+ // reading with nothing yet to replace it.
if (windowAlive && existing.ephemeral) {
void this.teardownEphemeralSession(existing.ephemeral);
}
@@ -3204,6 +3443,11 @@ export class WindowManager {
// teardown path; a straggling poll must not fire a second teardown.
stopExitWatch();
disposeShowGate();
+ // Drop this window's restart identity UNCONDITIONALLY — ahead of the
+ // ownership guard. The identity is per-window, so it must clear whenever
+ // THIS window closes, including the orphaned dead-window case where the
+ // guard short-circuits (a re-open already took the slot).
+ this.ephemeralWindowIdentity.delete(window);
// Ownership guard — only tear down if THIS window still owns the slot. A
// focus-dedup re-open or `stopAllOwnedServers` could have replaced/cleared
// the entry; without the guard we'd terminate a sibling's server or double
@@ -3211,6 +3455,9 @@ export class WindowManager {
// keeps the common path single-pass.)
if (this.windowsByPath.get(canonicalKey) !== context) return;
this.windowsByPath.delete(canonicalKey);
+ // Close the ephemeral keepalive before the server teardown — mirrors the
+ // project-window close. No-op when none was opened (unwired harness).
+ this.closeKeepalive(canonicalKey);
// Fire-and-forget: the `'closed'` event handler is synchronous. Terminate
// the server THEN remove the temp dir (sequential — see
// `teardownEphemeralSession`).
@@ -3220,6 +3467,30 @@ export class WindowManager {
});
this.windowsByPath.set(canonicalKey, context);
+ // Hold the ephemeral server against its own idle-shutdown for as long as
+ // this window is open. The single-file server inherits the 30-min idle
+ // default but, unlike a project window, had no keepalive — so with no
+ // editor WebSocket to reset the idle timer (the timer counts only /collab
+ // connections) it could idle-shut-down underneath the open editor. Mirrors
+ // the project-window keepalive: keyed by canonicalKey, the pre-set close
+ // guards a re-open replacing the slot, and the `'closed'` handler above
+ // tears it down.
+ if (this.deps.createKeepalive) {
+ const existingKeepalive = this.keepalives.get(canonicalKey);
+ if (existingKeepalive) existingKeepalive.close();
+ this.keepalives.set(canonicalKey, this.deps.createKeepalive({ lockDir }));
+ }
+ // Durable window→identity record for the restart affordance (survives a
+ // re-open replacing the slot; cleared on real window close).
+ this.ephemeralWindowIdentity.set(window, {
+ canonicalFilePath: opts.canonicalFilePath,
+ contentDir: opts.contentDir,
+ docName: opts.docName,
+ });
+ // Converge to one window per file: a fresh spawn happens because the
+ // file's prior server(s) died; retire any windows still open for those
+ // dead sessions now that a live replacement exists.
+ this.retireStaleWindowsForFile(canonicalKey, window);
} finally {
releaseLoadingContext();
}
@@ -3271,6 +3542,15 @@ export class WindowManager {
// ephemeral lockDir lives inside the throwaway temp projectDir that this
// teardown removes — a persistent project lock is re-attached and read
// by a later bug-report bundle, but a throwaway one never is.
+ //
+ // Close the keepalive too: the server it was holding up is gone, and it
+ // re-reads the lockDir this teardown removes on every attempt, so
+ // leaving it open reconnect-loops against a deleted path for the
+ // window's remaining lifetime — the same failure shape as an unbounded
+ // renderer reauth loop, just in the main process. windowsByPath keeps
+ // its entry (for session-restore), so the guarded `'closed'` teardown
+ // still runs on a real close; `closeKeepalive` is idempotent.
+ this.closeKeepalive(canonicalKey);
void this.teardownEphemeralSession(eph);
} catch (err) {
this.deps.log?.warn(
diff --git a/packages/desktop/tests/main/window-manager-ephemeral.test.ts b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
index 35ff9a2a2..8e5a02986 100644
--- a/packages/desktop/tests/main/window-manager-ephemeral.test.ts
+++ b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
import {
type BrowserWindowLike,
+ type EphemeralOpenIdentity,
type ServerLockMetadataLike,
WindowManager,
type WindowManagerDeps,
@@ -202,6 +203,34 @@ function buildEphemeralEnv(): EphemeralEnv {
const FILE = '/Users/me/notes/todo.md';
const PARENT = '/Users/me/notes';
+/** Controllable `setInterval`/`clearInterval` stubs for the exit-watch. Each
+ * interval is a record whose `cb` fires on `tick()` until cleared. Module-scoped
+ * so both the createEphemeralWindow and keepalive describes share one impl. */
+interface FakeInterval {
+ cb: () => void;
+ cleared: boolean;
+}
+function wireIntervalTimers(deps: WindowManagerDeps): FakeInterval[] {
+ const intervals: FakeInterval[] = [];
+ deps.setInterval = (cb: () => void) => {
+ const rec: FakeInterval = { cb, cleared: false };
+ intervals.push(rec);
+ return rec;
+ };
+ deps.clearInterval = (handle: unknown) => {
+ (handle as FakeInterval).cleared = true;
+ };
+ return intervals;
+}
+/** Advance every live interval `rounds` times (a cleared interval is inert). */
+function tick(intervals: FakeInterval[], rounds: number): void {
+ for (let r = 0; r < rounds; r++) {
+ for (const rec of intervals) {
+ if (!rec.cleared) rec.cb();
+ }
+ }
+}
+
describe('createEphemeralWindow', () => {
let env: EphemeralEnv;
beforeEach(() => {
@@ -347,8 +376,8 @@ describe('createEphemeralWindow', () => {
// Same two-tier wait as the project-open path, second call site. Without
// this, dropping the progress-deadline argument here would regress the
- // ephemeral path to the original bug while the project-open coverage stayed
- // green. The base env's `setTimeout` is a no-op that never invokes its
+ // ephemeral path's spawn-lock progress-deadline handling while the project-open
+ // coverage stayed green. The base env's `setTimeout` is a no-op that never invokes its
// callback — fine for the `deadlineMs = 0` tests, which return before any
// sleep is attempted — so this test supplies one that fires immediately.
test('a live child that binds after the startup deadline is not SIGTERMd', async () => {
@@ -584,33 +613,8 @@ describe('createEphemeralWindow', () => {
// shutdown) while its BrowserWindow stays open. The pre-fix dedup returned the
// cached ProjectContext whenever the window was alive, handing the renderer a
// dead `apiOrigin` — `ok open <file>` "succeeded" but started no session.
-
- /** Controllable `setInterval`/`clearInterval` stubs for the exit-watch. Each
- * interval is a record whose `cb` fires on `tick()` until cleared. */
- interface FakeInterval {
- cb: () => void;
- cleared: boolean;
- }
- function wireIntervalTimers(deps: WindowManagerDeps): FakeInterval[] {
- const intervals: FakeInterval[] = [];
- deps.setInterval = (cb: () => void) => {
- const rec: FakeInterval = { cb, cleared: false };
- intervals.push(rec);
- return rec;
- };
- deps.clearInterval = (handle: unknown) => {
- (handle as FakeInterval).cleared = true;
- };
- return intervals;
- }
- /** Advance every live interval `rounds` times (a cleared interval is inert). */
- function tick(intervals: FakeInterval[], rounds: number): void {
- for (let r = 0; r < rounds; r++) {
- for (const rec of intervals) {
- if (!rec.cleared) rec.cb();
- }
- }
- }
+ // (`wireIntervalTimers` / `tick` are module-scoped, shared with the keepalive
+ // describe below.)
test('re-open after the ephemeral server dies spawns a FRESH live session, not the dead one', async () => {
const wm = new WindowManager(env.deps);
@@ -844,3 +848,515 @@ describe('createEphemeralWindow', () => {
expect(env.killCalls.filter((k) => k.pid === second.ephemeral?.pid)).toEqual([]);
});
});
+
+// An ephemeral single-file server inherits the 30-min idle-shutdown default, and
+// the idle timer counts only /collab connections. These pin that an ephemeral
+// window opens a keepalive against its own (temp) lock and tears it down on close,
+// mirroring the project-window keepalive, so the server is held up for as long as
+// the editor window is open.
+describe('ephemeral keepalive lifecycle', () => {
+ let env: EphemeralEnv;
+ beforeEach(() => {
+ env = buildEphemeralEnv();
+ });
+
+ function makeKeepaliveMock() {
+ const calls: Array<{ lockDir: string }> = [];
+ const handles: Array<{ closed: boolean }> = [];
+ const create = vi.fn((opts: { lockDir: string }) => {
+ calls.push(opts);
+ const handle = { closed: false };
+ handles.push(handle);
+ return {
+ close: () => {
+ handle.closed = true;
+ },
+ isConnected: () => !handle.closed,
+ };
+ });
+ return { create, calls, handles };
+ }
+
+ test('opens a keepalive against the ephemeral lock when the window mounts', async () => {
+ const ka = makeKeepaliveMock();
+ env.deps.createKeepalive = ka.create as unknown as WindowManagerDeps['createKeepalive'];
+ const wm = new WindowManager(env.deps);
+ const ctx = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+
+ expect(ka.calls).toHaveLength(1);
+ // Keyed to the throwaway temp lock, NOT the file's parent dir.
+ expect(ka.calls[0]?.lockDir).toBe(getLocalDir('/tmp/ok-ephemeral-1'));
+ expect(ka.calls[0]?.lockDir).toBe(ctx.ephemeral?.lockDir);
+ expect(ka.handles[0]?.closed).toBe(false);
+ });
+
+ test('closes the keepalive when the window closes', async () => {
+ const ka = makeKeepaliveMock();
+ env.deps.createKeepalive = ka.create as unknown as WindowManagerDeps['createKeepalive'];
+ const wm = new WindowManager(env.deps);
+ await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ expect(ka.handles[0]?.closed).toBe(false);
+
+ env.windows[0]?.fireClose();
+ await wait(20);
+ expect(ka.handles[0]?.closed).toBe(true);
+ });
+
+ test('re-open after the server died replaces the keepalive (old closed, fresh open)', async () => {
+ const ka = makeKeepaliveMock();
+ env.deps.createKeepalive = ka.create as unknown as WindowManagerDeps['createKeepalive'];
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ env.killServer(first.ephemeral?.pid as number);
+ await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ await wait(20);
+
+ expect(ka.calls).toHaveLength(2); // fresh session opened its own keepalive
+ expect(ka.handles[0]?.closed).toBe(true); // the dead session's keepalive was retired
+ expect(ka.handles[1]?.closed).toBe(false);
+ });
+
+ test('no createKeepalive dep → no keepalive opened (back-compat)', async () => {
+ const wm = new WindowManager(env.deps);
+ await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ expect(env.windows).toHaveLength(1);
+ });
+
+ test('exit-watch closes the keepalive when the server dies out-of-band', async () => {
+ const ka = makeKeepaliveMock();
+ env.deps.createKeepalive = ka.create as unknown as WindowManagerDeps['createKeepalive'];
+ const intervals = wireIntervalTimers(env.deps);
+
+ const wm = new WindowManager(env.deps);
+ const ctx = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ expect(ka.handles[0]?.closed).toBe(false);
+
+ // The detached server dies while the window stays open; the next exit-watch
+ // poll reaps the session AND must close the keepalive — otherwise it
+ // reconnect-loops against the removed lockDir for the window's whole
+ // remaining lifetime.
+ env.killServer(ctx.ephemeral?.pid as number);
+ tick(intervals, 1);
+ await wait(20);
+
+ expect(ka.handles[0]?.closed).toBe(true);
+ // The map entry is deliberately KEPT for session-restore; a later real close
+ // is then a no-op on the already-closed keepalive.
+ expect(wm.getWindowFor(FILE)).toBe(ctx);
+ });
+
+ test('a re-open whose respawn fails still closes the dead session keepalive (no orphan loop)', async () => {
+ const ka = makeKeepaliveMock();
+ env.deps.createKeepalive = ka.create as unknown as WindowManagerDeps['createKeepalive'];
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ expect(ka.handles[0]?.closed).toBe(false);
+
+ env.killServer(first.ephemeral?.pid as number);
+ // The re-open's respawn throws AFTER the stale-entry branch has evicted the
+ // slot but BEFORE a fresh keepalive is installed: the stale-entry
+ // `closeKeepalive` must have already closed the dead session's keepalive,
+ // because the old window's `'closed'` teardown can no longer run (the slot is
+ // gone), so this is the only path that would clean it up.
+ env.deps.spawnDetachedServer = async () => {
+ throw Object.assign(new Error('spawn boom'), { kind: 'spawn-error' });
+ };
+ await expect(
+ wm.createEphemeralWindow({ canonicalFilePath: FILE, contentDir: PARENT, docName: 'todo' }),
+ ).rejects.toThrow('spawn boom');
+
+ // The dead session's keepalive was closed by the stale-entry teardown, not
+ // left pointing at the removed lock; the failed respawn opened no new one.
+ expect(ka.handles[0]?.closed).toBe(true);
+ expect(ka.calls).toHaveLength(1);
+ });
+});
+
+// --- restartEphemeralServer: the in-window "Restart server" affordance for a
+// single-file session. The project restart path is directory-keyed and cannot
+// reach a file-keyed ephemeral session; this replays the open through
+// `createEphemeralWindow` (dead → reap + respawn; live → dedup) and retires the
+// dead window once a live replacement exists (recreate-then-close). Same DI
+// harness as createEphemeralWindow above.
+describe('restartEphemeralServer', () => {
+ let env: EphemeralEnv;
+ beforeEach(() => {
+ env = buildEphemeralEnv();
+ });
+
+ // Resolve the restart identity the IPC router would hand this method — the
+ // durable window→identity lookup, NOT `windowsByPath` (which a re-open evicts).
+ const identityOf = (wm: WindowManager, win: BrowserWindowLike): EphemeralOpenIdentity => {
+ const id = wm.getEphemeralIdentityForWindow(win);
+ if (!id) throw new Error('expected an ephemeral identity for the window');
+ return id;
+ };
+
+ test('dead server (no re-open): restart respawns a fresh session and retires the dead window', async () => {
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ const deadPid = first.ephemeral?.pid as number;
+ const deadOrigin = first.apiOrigin;
+ const deadTempDir = first.ephemeral?.projectDir as string;
+
+ // The detached server dies while its window stays open — the exact state the
+ // "server gone" affordance renders against.
+ env.killServer(deadPid);
+
+ const outcome = await wm.restartEphemeralServer(identityOf(wm, first.window), first.window);
+ await wait(20);
+
+ expect(outcome).toEqual({ ok: true });
+ // A fresh server was spawned; the map now resolves the file to the live one.
+ expect(env.spawnCalls).toHaveLength(2);
+ const live = wm.getWindowFor(FILE);
+ expect(live).toBeDefined();
+ expect(live).not.toBe(first);
+ expect(live?.apiOrigin).not.toBe(deadOrigin);
+ // The dead window was retired, and the dead session's throwaway temp dir was
+ // reaped — converged to one window, no zombie, no leak.
+ expect(env.windows[0]?.isDestroyed()).toBe(true);
+ expect(env.removedDirs).toContain(deadTempDir);
+ expect(live?.window.isDestroyed()).toBe(false);
+ });
+
+ test('live session (restart raced a healthy server): terminates it and respawns fresh — a restart must restart', async () => {
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ const livePid = first.ephemeral?.pid as number;
+ const liveTempDir = first.ephemeral?.projectDir as string;
+ const liveOrigin = first.apiOrigin;
+
+ // The server is alive but the user explicitly asked to restart (e.g. sync is
+ // wedged and the reach-error affordance fired). An explicit restart must
+ // ACTUALLY restart: `createEphemeralWindow` would otherwise focus-dedup onto
+ // the live server and report success having done nothing (the renderer reads
+ // that as "torn down and recreated" and shows no feedback). So the live
+ // server is terminated and a fresh one spawned.
+ const outcome = await wm.restartEphemeralServer(identityOf(wm, first.window), first.window);
+ await wait(20);
+
+ expect(outcome).toEqual({ ok: true });
+ expect(env.spawnCalls).toHaveLength(2); // a real respawn, not a no-op dedup
+ // The previously-live server was terminated and its throwaway temp dir reaped.
+ expect(env.killCalls.some((k) => k.pid === livePid && k.signal === 'SIGTERM')).toBe(true);
+ expect(env.removedDirs).toContain(liveTempDir);
+ // Converged to one fresh live window; the originating one was retired.
+ expect(env.windows[0]?.isDestroyed()).toBe(true);
+ const live = wm.getWindowFor(FILE);
+ expect(live).not.toBe(first);
+ expect(live?.apiOrigin).not.toBe(liveOrigin);
+ expect(live?.window.isDestroyed()).toBe(false);
+ });
+
+ test("ownership gate: a genuine orphan's restart converges onto the live sibling without killing it", async () => {
+ const wm = new WindowManager(env.deps);
+ const orphan = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ // Neuter the orphan's close so the re-open's retire sweep can't actually
+ // destroy it — leaving a REAL orphan: still open, still in the identity map,
+ // but no longer the slot owner. Production reaches this state only inside
+ // the <=2s `closeAndAwait` grace; the harness's synchronous close would
+ // otherwise collapse it instantly, making the retire-the-orphan path the
+ // gate's docblock promises unreachable.
+ const orphanClose = vi.fn();
+ (env.windows[0] as FakeWindow).close = orphanClose as unknown as FakeWindow['close'];
+
+ env.killServer(orphan.ephemeral?.pid as number);
+ // Re-open spawns the live sibling and tries (via retire) to close the orphan.
+ const live = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ await wait(20);
+ const livePid = live.ephemeral?.pid as number;
+ expect(wm.getWindowFor(FILE)).toBe(live);
+ expect(orphanClose).toHaveBeenCalled(); // the re-open's retire swept the orphan
+ expect(wm.getEphemeralIdentityForWindow(orphan.window)).toBeDefined(); // still an orphan
+
+ // The orphan (not the slot owner) fires Restart. The gate must decline to
+ // terminate the LIVE sibling's server and instead dedup onto it, retiring the
+ // orphan again — converge, don't kill a healthy session.
+ orphanClose.mockClear();
+ const spawnsBefore = env.spawnCalls.length;
+ const outcome = await wm.restartEphemeralServer(identityOf(wm, orphan.window), orphan.window);
+ await wait(20);
+
+ expect(outcome).toEqual({ ok: true });
+ // The two assertions that discriminate the gate's arms: a wrongly-terminating
+ // branch would add a spawn AND a SIGTERM against the live pid.
+ expect(env.spawnCalls).toHaveLength(spawnsBefore); // dedup onto the sibling; no third spawn
+ expect(env.killCalls.some((k) => k.pid === livePid)).toBe(false); // sibling's server untouched
+ expect(wm.getWindowFor(FILE)).toBe(live);
+ // Sanity, not discrimination: the retire sweep targets the orphan under
+ // EITHER arm (a wrong terminate also ends in a fresh spawn whose sweep runs).
+ expect(orphanClose).toHaveBeenCalled();
+ });
+
+ test('the retire sweep closes EVERY stale window in one pass (stale.length > 1)', async () => {
+ // Two orphans for the same file (each with a neutered close so the sweep
+ // cannot collapse them) plus a fresh live spawn — the docblock's plural
+ // ("every OTHER open ephemeral window") exercised with a stale set larger
+ // than one, which a `break` after the first target would fail.
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ const firstClose = vi.fn();
+ (env.windows[0] as FakeWindow).close = firstClose as unknown as FakeWindow['close'];
+ env.killServer(first.ephemeral?.pid as number);
+
+ const second = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ await wait(20);
+ const secondClose = vi.fn();
+ (env.windows[1] as FakeWindow).close = secondClose as unknown as FakeWindow['close'];
+ env.killServer(second.ephemeral?.pid as number);
+ // Both prior windows are now stale identity-map entries; both survived their
+ // sweeps (neutered close), so the next spawn's sweep sees stale.length === 2.
+ firstClose.mockClear();
+ secondClose.mockClear();
+
+ const third = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ await wait(20);
+
+ expect(wm.getWindowFor(FILE)).toBe(third);
+ expect(firstClose).toHaveBeenCalled(); // both stale windows swept, not just
+ expect(secondClose).toHaveBeenCalled(); // the most recent one
+ expect(third.window.isDestroyed()).toBe(false);
+ });
+
+ // Re-opening `ok open <file>` after the server died must not leave the dead
+ // window dangling beside the fresh one: the re-open retires the dead window
+ // itself, with no manual "Restart server" click needed.
+ test('re-open after server death auto-retires the dead window (converges to one)', async () => {
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ env.killServer(first.ephemeral?.pid as number);
+
+ const reopened = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ await wait(20);
+
+ expect(reopened).not.toBe(first);
+ expect(env.spawnCalls).toHaveLength(2);
+ // The dead window is retired by the re-open — not left dangling.
+ expect(env.windows[0]?.isDestroyed()).toBe(true);
+ expect(reopened.window.isDestroyed()).toBe(false);
+ expect(wm.getWindowFor(FILE)).toBe(reopened);
+ // Only the live window's identity survives.
+ expect(wm.getEphemeralIdentityForWindow(first.window)).toBeUndefined();
+ expect(wm.getEphemeralIdentityForWindow(reopened.window)).toBeDefined();
+ });
+
+ // Re-open, then EVERY server for the file dies at once (e.g. `pkill -f
+ // ok-ephemeral` hits them all). Restart from the surviving window must respawn
+ // ONE fresh session and retire every stale window — converge to one, never
+ // accumulate a third window.
+ test('re-open then all servers die: restart respawns once and retires every stale window', async () => {
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ env.killServer(first.ephemeral?.pid as number);
+ const reopened = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ await wait(20);
+ // The re-open already retired the first window; the second is live.
+ expect(env.windows[0]?.isDestroyed()).toBe(true);
+
+ // Now the second server dies too.
+ env.killServer(reopened.ephemeral?.pid as number);
+
+ const outcome = await wm.restartEphemeralServer(
+ identityOf(wm, reopened.window),
+ reopened.window,
+ );
+ await wait(20);
+
+ expect(outcome).toEqual({ ok: true });
+ expect(env.spawnCalls).toHaveLength(3); // second was dead → one fresh spawn (no accumulation)
+ expect(env.windows[1]?.isDestroyed()).toBe(true); // the now-dead reopened window retired
+ const live = wm.getWindowFor(FILE);
+ expect(live?.window.isDestroyed()).toBe(false);
+ // Exactly one live identity remains for the file.
+ expect(wm.getEphemeralIdentityForWindow(reopened.window)).toBeUndefined();
+ expect(live && wm.getEphemeralIdentityForWindow(live.window)).toBeDefined();
+ });
+
+ test('respawn failure: returns {ok:false} and leaves the originating window open', async () => {
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ const identity = identityOf(wm, first.window);
+ env.killServer(first.ephemeral?.pid as number);
+ // The respawn throws (spawn failure) — the affordance must surface a failure
+ // the renderer can act on, not tear down the window the user is still reading.
+ env.deps.spawnDetachedServer = async () => {
+ throw Object.assign(new Error('spawn boom'), { kind: 'spawn-error' });
+ };
+
+ const outcome = await wm.restartEphemeralServer(identity, first.window);
+
+ expect(outcome).toEqual({ ok: false, reason: 'other' });
+ expect(env.windows[0]?.isDestroyed()).toBe(false); // originating window kept
+ });
+
+ test('getEphemeralIdentityForWindow: present for an ephemeral window, absent for others, cleared on close', async () => {
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+
+ // Present + carries the exact replay inputs.
+ expect(wm.getEphemeralIdentityForWindow(first.window)).toEqual({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ // A window this manager never created (a project window, in practice) has no
+ // ephemeral identity → the IPC routes it to the project restart path.
+ const strangerWindow = makeWindow();
+ expect(wm.getEphemeralIdentityForWindow(strangerWindow)).toBeUndefined();
+
+ // Cleared when the window actually closes.
+ first.window.fireClose();
+ await wait(20);
+ expect(wm.getEphemeralIdentityForWindow(first.window)).toBeUndefined();
+ });
+});
+
+// The `ok:project:restart-server` IPC picks the restart path from the REQUESTING
+// window, not the `projectPath` arg. Keeping that decision on the class that owns
+// the identity map (rather than as a ternary in the IPC handler, which no test
+// tier can reach — the bootstrap suite stubs `registerIpcHandlers` out) makes each
+// branch reachable here: ephemeral window, plain project window, null/destroyed
+// sender. Deleting or inverting the branch would restore the directory-keyed
+// misroute for ephemeral single-file sessions, and now fails a test.
+describe('restartServerForWindow (IPC routing seam)', () => {
+ let env: EphemeralEnv;
+ beforeEach(() => {
+ env = buildEphemeralEnv();
+ });
+
+ test('an ephemeral sender routes to the ephemeral respawn (observable), ignoring the projectPath arg', async () => {
+ const wm = new WindowManager(env.deps);
+ const first = await wm.createEphemeralWindow({
+ canonicalFilePath: FILE,
+ contentDir: PARENT,
+ docName: 'todo',
+ });
+ env.killServer(first.ephemeral?.pid as number);
+
+ // A deliberately-wrong projectPath: if routing fell through to the
+ // directory-keyed `restartAttachedServer` (the misroute this chain removes),
+ // it would drive that bogus dir and never touch the file.
+ const outcome = await wm.restartServerForWindow(first.window, '/some/unrelated/project', {});
+ await wait(20);
+
+ // Observable proof of the ephemeral path: a fresh single-file server spawned
+ // and the file converged to a live window. `restartAttachedServer` would have
+ // found no lock at the bogus dir and spawned nothing for this file.
+ expect(outcome).toEqual({ ok: true });
+ expect(env.spawnCalls).toHaveLength(2);
+ expect(wm.getWindowFor(FILE)?.window.isDestroyed()).toBe(false);
+ });
+
+ test('a plain project sender window routes to restartAttachedServer with the projectPath + args', async () => {
+ const wm = new WindowManager(env.deps);
+ // A window this manager never registered as ephemeral (a project window).
+ const projectWindow = makeWindow();
+ // `restartAttachedServer`'s real path can't run in this ephemeral harness
+ // (its `forkUtility` dep deliberately throws), so spy on it — with a
+ // distinctive outcome, so the pass-through assertion below discriminates
+ // this branch from anything the ephemeral path could produce.
+ const attached = vi
+ .spyOn(wm, 'restartAttachedServer')
+ .mockResolvedValue({ ok: false, reason: 'eperm' });
+
+ const outcome = await wm.restartServerForWindow(projectWindow, '/some/project', {
+ localOpCliArgs: ['--y'],
+ });
+
+ expect(attached).toHaveBeenCalledWith('/some/project', { localOpCliArgs: ['--y'] });
+ expect(outcome).toEqual({ ok: false, reason: 'eperm' }); // the attached outcome, verbatim
+ });
+
+ test('a null sender (destroyed webContents) routes to restartAttachedServer', async () => {
+ const wm = new WindowManager(env.deps);
+ const attached = vi
+ .spyOn(wm, 'restartAttachedServer')
+ .mockResolvedValue({ ok: false, reason: 'eperm' });
+
+ const outcome = await wm.restartServerForWindow(null, '/some/project', {});
+
+ expect(attached).toHaveBeenCalledWith('/some/project', {});
+ expect(outcome).toEqual({ ok: false, reason: 'eperm' }); // the attached outcome, verbatim
+ });
+});