Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

PRD-7987 Add pop-out note windows (#3509)

serafin-garciaae4c3a3f171b
diff --git a/.changeset/pop-out-note-window.md b/.changeset/pop-out-note-window.md
new file mode 100644
index 000000000..7277bf86b
--- /dev/null
+++ b/.changeset/pop-out-note-window.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Open a document in its own window (desktop). Right-click a document tab and choose "Open in New Window", run it from the command palette, or pick it from the Window menu to pop the current document out into a dedicated window you can park on another monitor.
+
+- Edits sync live between the pop-out and the main window through the project's existing collaboration server, with no extra setup.
+- Opening the same document again focuses the window you already have rather than stacking duplicates. Any number of pop-outs can coexist across and within projects.
+- Following a wiki link navigates the pop-out in place and updates its title.
+- A pop-out closes with its project's main window. If its document is deleted, it shows an explicit "document deleted" state with a close button rather than closing out from under you.
+- Your pop-out layout comes back on relaunch, each window reattached to its project and restored to its own position.
diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsx
index 734c15acb..ce9120e56 100644
--- a/packages/app/src/App.dom.test.tsx
+++ b/packages/app/src/App.dom.test.tsx
@@ -285,6 +285,11 @@ function createBridge() {
};
}
+/** A popped-out note window: same bridge shape, `note` mode. */
+function createNoteWindowBridge() {
+ return { ...createBridge(), config: { mode: 'note' as const, ptyAvailable: true } };
+}
+
function renderApp({ bridge = null }: { bridge?: ReturnType<typeof createBridge> | null } = {}) {
if (bridge) {
Object.defineProperty(window, 'okDesktop', {
@@ -352,6 +357,34 @@ describe('App runtime wiring', () => {
vi.restoreAllMocks();
});
+ describe('note window chrome reduction', () => {
+ test('drops the sidebar, the palette, and agent-driven navigation', () => {
+ renderApp({ bridge: createNoteWindowBridge() as ReturnType<typeof createBridge> });
+
+ expect(screen.queryByTestId('file-sidebar')).toBeNull();
+ expect(screen.queryByTestId('command-palette')).toBeNull();
+ // SystemDocSubscriber retargets the window to whatever doc an agent is
+ // writing — right for the workspace window, wrong for a parked pop-out.
+ expect(screen.queryByTestId('system-doc-subscriber')).toBeNull();
+ });
+
+ test('keeps the editor and the connecting banner', () => {
+ renderApp({ bridge: createNoteWindowBridge() as ReturnType<typeof createBridge> });
+
+ expect(screen.getByTestId('editor-pane')).not.toBeNull();
+ expect(screen.getByTestId('connecting-banner')).not.toBeNull();
+ });
+
+ test('an ordinary editor window keeps all of it', () => {
+ renderApp({ bridge: createBridge() });
+
+ expect(screen.getByTestId('file-sidebar')).not.toBeNull();
+ expect(screen.getByTestId('command-palette')).not.toBeNull();
+ expect(screen.getByTestId('system-doc-subscriber')).not.toBeNull();
+ expect(screen.getByTestId('editor-pane')).not.toBeNull();
+ });
+ });
+
test('imports and mounts the app shell providers and core surfaces', () => {
renderApp();
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 5c8346365..45c39dd60 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -17,6 +17,7 @@ import { composeTerminalLaunchPrompt } from '@/components/handoff/useHandoffDisp
import { InstallInClaudeDesktopDialog } from '@/components/InstallInClaudeDesktopDialog';
import { McpConsentDialog } from '@/components/McpConsentDialog';
import { isNewItemShortcut, NewItemDialog } from '@/components/NewItemDialog';
+import { NoteWindowMainActionReceiver } from '@/components/NoteWindowMainActionReceiver';
import {
downgradeFolderIndexForHashNav,
type ResolvedNavigationTarget,
@@ -53,6 +54,7 @@ import {
skillsFromHash,
} from '@/lib/doc-hash';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import { isNoteWindow } from '@/lib/note-window-mode';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { mark, ProfilerBoundary } from '@/lib/perf';
import { SingleFileModeProvider, useSingleFileMode } from '@/lib/single-file-mode';
@@ -482,12 +484,15 @@ function SettingsShortcutHandler() {
* state-aware enable/disable for items like Rename / Move to Trash / Send
* to AI. Web-host short-circuits when the desktop bridge is absent.
*
- * Lives at the App-tier where `useDocumentContext()` is already mounted —
- * exactly one push site keeps the last-write-wins semantics main relies on
- * (`editorActiveTarget` is module-scope, singleton across windows). Effect
- * deps are narrowed to the discriminator + identifier so a render that
- * re-creates an equal `activeTarget` reference doesn't re-fire the push —
- * the snapshot main consumes is normalized to the same four shapes.
+ * Lives at the App-tier where `useDocumentContext()` is already mounted — one
+ * push site per window. Main keys the snapshot by SENDING window and reads the
+ * focused one, so two windows on one project (a pop-out beside its editor
+ * window) no longer fight over the menu's scope. Effect deps are narrowed to
+ * the discriminator + identifier so a render that re-creates an equal
+ * `activeTarget` reference doesn't re-fire the push — the snapshot main
+ * consumes is normalized to the same four shapes. A rename changes the
+ * identifier, so the push re-fires, which is what lets a popped-out window's
+ * title follow a rename.
*
* Snapshot shape mirrors `EditorActiveTargetSnapshot`'s discriminated union
* (doc / folder / asset / null). `folder-index` and `missing` collapse to
@@ -639,6 +644,9 @@ function AppBody() {
const isElectronHost = typeof window !== 'undefined' && window.okDesktop != null;
const [commandPaletteOpen, setCommandPaletteOpen] = useState(false);
const singleFile = useSingleFileMode();
+ // A popped-out note window shows one document full-window: no workspace
+ // chrome, and none of the app-root singletons that assume the main window.
+ const noteWindow = isNoteWindow();
// "Open in terminal" launcher — desktop-only. Routes a scope-derived prompt
// to the docked terminal in EditorPane. `composeTerminalLaunchPrompt` drops
@@ -670,7 +678,12 @@ function AppBody() {
<>
<ConnectingBanner />
<PageListProvider>
- <SystemDocSubscriber />
+ <NoteWindowMainActionReceiver />
+ {/* Agent-driven hash navigation retargets the window to whatever doc an
+ agent is writing. That is right for the main workspace window and
+ wrong for a pop-out, which the user parked on one specific document
+ on purpose. */}
+ {!noteWindow && <SystemDocSubscriber />}
<ValidationFreshness />
{/* Explains a skill that lists but can't open (gitignored bundle) and
offers the one-line fix. Mounted here because the guard fires from
@@ -681,7 +694,7 @@ function AppBody() {
<NewItemShortcutHandler />
{/* Settings is unavailable in single-file mode (config editing is
inert), so the Cmd-, route handler isn't mounted. */}
- {!singleFile && <SettingsShortcutHandler />}
+ {!singleFile && !noteWindow && <SettingsShortcutHandler />}
{SHOW_INSTALL_SKILL && <InstallInClaudeDesktopTrigger />}
{/* File → New project… opens CreateProjectDialog here.
Desktop-only — the `new-project` menu action never fires in
@@ -710,11 +723,15 @@ function AppBody() {
<ShareReceiveMissDialog />
</Suspense>
) : null}
- <CommandPalette
- bridge={desktopBridge}
- open={commandPaletteOpen}
- onOpenChange={setCommandPaletteOpen}
- />
+ {/* The palette is a workspace navigator; a single-document window has
+ nowhere to navigate to. Deferred, not refused (§15 Future Work). */}
+ {!noteWindow && (
+ <CommandPalette
+ bridge={desktopBridge}
+ open={commandPaletteOpen}
+ onOpenChange={setCommandPaletteOpen}
+ />
+ )}
{/* Electron BrowserWindow renders with `titleBarStyle: 'hiddenInset'` +
`transparent: true` + `vibrancy: 'sidebar'`, so the renderer owns
window-drag affordance. Existing chrome rows (EditorHeader,
@@ -741,7 +758,9 @@ function AppBody() {
<SidebarProvider className="h-screen overflow-hidden">
{/* No-project single-file mode drops the file sidebar (file tree +
project switcher); the editor inset takes the full width. */}
- {!singleFile && <FileSidebar onOpenSearch={() => setCommandPaletteOpen(true)} />}
+ {!singleFile && !noteWindow && (
+ <FileSidebar onOpenSearch={() => setCommandPaletteOpen(true)} />
+ )}
<SidebarInset className="overflow-hidden h-[calc(100vh-var(--layout-inset-offset))]">
<EditorPane onOpenSearch={() => setCommandPaletteOpen(true)} />
</SidebarInset>
diff --git a/packages/app/src/comments/CommentSelectionAffordance.tsx b/packages/app/src/comments/CommentSelectionAffordance.tsx
index ce27bcd35..0b92a5df1 100644
--- a/packages/app/src/comments/CommentSelectionAffordance.tsx
+++ b/packages/app/src/comments/CommentSelectionAffordance.tsx
@@ -27,7 +27,6 @@ import { posToDOMRect } from '@tiptap/core';
import type { Editor } from '@tiptap/react';
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
-import { requestDocPanelTab } from '@/components/doc-panel-events';
import { Button } from '@/components/ui/button';
import {
ComposerMentionInput,
@@ -39,6 +38,7 @@ import { cn } from '@/lib/utils';
import { setCommentDraftRange } from './anchor-decorations';
import { captureSelectionContext } from './anchor-search';
import { useCommentsPanelOnScreen } from './comments-panel-visibility';
+import { revealComments } from './reveal-queue';
import { selectedSpan } from './selected-span';
import { createThread, emitStartComment, subscribeStartComment } from './store';
@@ -286,7 +286,7 @@ export function CommentSelectionAffordance({
<Button
size="sm"
variant="ghost"
- onClick={() => requestDocPanelTab('comments')}
+ onClick={() => revealComments('doc', docName)}
className="px-2 text-muted-foreground hover:text-foreground"
>
<Trans>View comments</Trans>
diff --git a/packages/app/src/comments/reveal-queue.ts b/packages/app/src/comments/reveal-queue.ts
index aa956ef39..6335cd68b 100644
--- a/packages/app/src/comments/reveal-queue.ts
+++ b/packages/app/src/comments/reveal-queue.ts
@@ -21,6 +21,7 @@
import { requestDocPanelTab } from '@/components/doc-panel-events';
import type { PanelScope } from '@/components/PanelScopeHeader';
+import { routeNoteWindowActionToMain } from '@/lib/note-window-main-actions';
const COMMENT_SCOPE_EVENT = 'open-knowledge:comments-scope';
@@ -60,13 +61,22 @@ export function subscribeCommentScopeRequests(onRequest: (scope: PanelScope) =>
}
/** Open the doc panel on the Comments tab, set to `scope`. */
-export function revealComments(scope: PanelScope): void {
+export function revealComments(scope: PanelScope, docName?: string): void {
+ if (
+ docName !== undefined &&
+ typeof window !== 'undefined' &&
+ routeNoteWindowActionToMain(
+ { kind: 'reveal-comments', docName, scope: scope === 'project' ? 'queue' : 'doc' },
+ window,
+ )
+ )
+ return;
pendingScope = scope;
requestDocPanelTab('comments');
bus.dispatchEvent(new CustomEvent<PanelScope>(COMMENT_SCOPE_EVENT, { detail: scope }));
}
/** The project-wide queue — what the composer chip counts, spanning documents. */
-export function revealQueue(): void {
- revealComments('project');
+export function revealQueue(docName?: string): void {
+ revealComments('project', docName);
}
diff --git a/packages/app/src/comments/store.ts b/packages/app/src/comments/store.ts
index 8b002761c..db26af2e5 100644
--- a/packages/app/src/comments/store.ts
+++ b/packages/app/src/comments/store.ts
@@ -319,7 +319,7 @@ export function createThread(args: {
// Only after the server accepted it. Revealing optimistically would open
// the panel on a comment that then failed to anchor. Doc scope: the thing
// to show is the comment just made, beside the passage it is on.
- revealComments('doc');
+ revealComments('doc', args.docName);
emitCommentPosted();
})
.catch((err: unknown) => {
@@ -363,7 +363,7 @@ export function createPropertyThread(args: {
// Same as the passage path above: not chained into the outer `.catch`, so
// it has to carry its own.
void refresh(args.docName).catch(() => undefined);
- revealComments('doc');
+ revealComments('doc', args.docName);
emitCommentPosted();
})
.catch((err: unknown) => {
diff --git a/packages/app/src/components/AppMenubar.dom.test.tsx b/packages/app/src/components/AppMenubar.dom.test.tsx
index 3ab9ed7b8..282df6209 100644
--- a/packages/app/src/components/AppMenubar.dom.test.tsx
+++ b/packages/app/src/components/AppMenubar.dom.test.tsx
@@ -2,9 +2,10 @@
* DOM tests for AppMenubar's custom Windows/Linux menus.
*
* AppMenubar is the custom-drawn Windows/Linux menu bar; it self-gates on
- * `window.okDesktop` and returns null on darwin. These pin the Help entries
- * that route to in-app dialogs and the View history rows, including their
- * ordering, shortcut hints, and `bridge.menu.dispatch` payloads.
+ * `window.okDesktop` and returns null on darwin and in focused note windows.
+ * These pin the Help entries that route to in-app dialogs and the View history
+ * rows, including their ordering, shortcut hints, and
+ * `bridge.menu.dispatch` payloads.
*
* Invocation: `pnpm exec vitest run --config vitest.dom.config.ts
* src/components/AppMenubar.dom.test.tsx` from `packages/app/`.
@@ -22,12 +23,13 @@ vi.doMock('@lingui/react/macro', () => ({
type DispatchMock = ReturnType<typeof vi.fn>;
-function installBridge(platform: string): DispatchMock {
+function installBridge(platform: string, mode: 'editor' | 'note' = 'editor'): DispatchMock {
// `query` resolves null so the snapshot-gated rows stay hidden; the two
// rows under test are unconditional.
const dispatch = vi.fn(() => Promise.resolve(null));
(window as unknown as { okDesktop?: unknown }).okDesktop = {
platform,
+ config: { mode },
menu: { dispatch },
};
return dispatch;
@@ -66,6 +68,16 @@ describe('AppMenubar Help menu', () => {
expect(container.firstChild).toBeNull();
});
+ test.each([
+ 'win32',
+ 'linux',
+ ] as const)('returns null in a %s note window, where app-wide menu chrome is intentionally absent', async (platform) => {
+ installBridge(platform, 'note');
+ const { AppMenubar } = await import('./AppMenubar');
+ const { container } = render(<AppMenubar />);
+ expect(container.firstChild).toBeNull();
+ });
+
test('Send feedback dispatches the send-feedback menu action', async () => {
const dispatch = installBridge('win32');
await openHelpMenu();
diff --git a/packages/app/src/components/AppMenubar.tsx b/packages/app/src/components/AppMenubar.tsx
index 14c2096cb..3eb7da836 100644
--- a/packages/app/src/components/AppMenubar.tsx
+++ b/packages/app/src/components/AppMenubar.tsx
@@ -25,6 +25,7 @@
import { useLingui } from '@lingui/react/macro';
import { useState } from 'react';
+import { shouldShowAppMenubar } from '@/components/app-menubar-gate';
import {
Menubar,
MenubarCheckboxItem,
@@ -50,7 +51,7 @@ export function AppMenubar() {
const bridge = typeof window !== 'undefined' ? (window.okDesktop ?? null) : null;
const [snapshot, setSnapshot] = useState<OkMenuRendererSnapshot | null>(null);
- if (bridge == null || bridge.menu == null || bridge.platform === 'darwin') return null;
+ if (!shouldShowAppMenubar() || bridge == null || bridge.menu == null) return null;
const menu: NonNullable<OkDesktopBridge['menu']> = bridge.menu;
const dispatch = (request: OkMenuDispatchRequest): void => {
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsx
index 3294f5c98..5fe7e6e2a 100644
--- a/packages/app/src/components/EditorActivityPool.tsx
+++ b/packages/app/src/components/EditorActivityPool.tsx
@@ -72,8 +72,10 @@ import { TiptapEditor } from '@/editor/TiptapEditor';
import type { EditorModeValue } from '@/editor/use-editor-mode';
import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
+import { isNoteWindow } from '@/lib/note-window-mode';
import { mark, ProfilerBoundary } from '@/lib/perf';
import { readNumericOverride } from '@/lib/perf/env-override';
+import { cn } from '@/lib/utils';
import { DiffViewBoundary } from './DiffViewBoundary';
import { DocumentBoundary } from './DocumentBoundary';
import { DocumentErrorBoundary } from './DocumentErrorBoundary';
@@ -1032,7 +1034,7 @@ export function ScrollPreservingContainer({
// - TOOLBAR_HEIGHT in editor/extensions/frozen-table-headers.ts: the
// plane frozen table header rows pin to (and the occluder block in
// globals.css must stay at least this tall).
- // - TOOLBAR_OVERLAP_PX in editor/SourceEditor.tsx: CM6 ignores ancestor
+ // - editorToolbarOverlapPx in editor/SourceEditor.tsx: CM6 ignores ancestor
// scroll-padding-top, so full-page source mode restates the inset via
// EditorView.scrollMargins. Deliberately scope-limited to source-mode —
// nested CM consumers of `createNestedCMExtensions` (e.g.,
@@ -1040,11 +1042,14 @@ export function ScrollPreservingContainer({
// and have no programmatic scroll-into-view call sites today; adding
// a `scrollMargins` contribution in the shared factory would mis-align
// nested CM scrolls if they ever become scrollable.
- // - TOOLBAR_OVERLAP_PX in editor/mode-switch-landing.ts: the mode-switch
+ // - editorToolbarOverlapPx in editor/mode-switch-landing.ts: the mode-switch
// capture probes step in from this inset, and the landing hands it to
// the controller as the target's resting offset below the toolbar.
// The toolbar itself: components/EditorToolbar.tsx.
- className="editor-doc-scroll subtle-scrollbar h-full overflow-y-auto pt-14 scroll-pt-14"
+ className={cn(
+ 'editor-doc-scroll subtle-scrollbar h-full overflow-y-auto',
+ isNoteWindow() ? 'pt-0 scroll-pt-0' : 'pt-14 scroll-pt-14',
+ )}
style={{ overflowAnchor: 'auto' }}
>
{children}
diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsx
index 645c3b390..2e4e0e456 100644
--- a/packages/app/src/components/EditorArea.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.dom.test.tsx
@@ -995,6 +995,22 @@ describe('EditorArea session-panel edge reveal tabs', () => {
expect(panels?.contains(agentMount)).toBe(true);
expect(header?.contains(agentMount)).toBe(false);
});
+
+ test('a note window never renders the agents reveal tab', () => {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: {
+ config: { mode: 'note' },
+ editor: { notifyViewMenuStateChanged: () => {} },
+ },
+ });
+ try {
+ renderArea({ agentsVisible: false });
+ expect(screen.queryByRole('button', { name: 'Open agents panel' })).toBeNull();
+ } finally {
+ Reflect.deleteProperty(window, 'okDesktop');
+ }
+ });
});
describe('EditorArea terminal placement', () => {
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index 54ac920c6..07db5cc41 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -71,6 +71,7 @@ import { docNameFromHash, hashFromDocName, isSameHash } from '@/lib/doc-hash';
import { getInitialDocPanelWidth, writeDocPanelWidth } from '@/lib/doc-panel-width-store';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import { isNoteWindow } from '@/lib/note-window-mode';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { ProfilerBoundary } from '@/lib/perf';
import {
@@ -365,6 +366,7 @@ function EditorAreaInner({
renderWorkspaceHeader = renderTabsWithoutHeader,
}: EditorAreaProps) {
const { t } = useLingui();
+ const noteWindow = isNoteWindow();
const {
activeDocName,
activeProvider,
@@ -529,8 +531,8 @@ function EditorAreaInner({
// doc-panel neutralization — compute it up here so effects can depend on it.
// Keyed off visibility rather than has-tabs so the panel's feedback is
// immediate during the seconds-long agent spawn.
- const agentsColumnPresent = agentsVisible;
- const terminalColumnPresent = terminalVisible && terminalPlacement === 'right';
+ const agentsColumnPresent = !noteWindow && agentsVisible;
+ const terminalColumnPresent = !noteWindow && terminalVisible && terminalPlacement === 'right';
const resizableRailColumnPresent = terminalColumnPresent || agentsColumnPresent;
// The agents panel is the one surface with a persistent edge affordance: it is
// discoverable in a way a chord is not, and an agent conversation is the thing a
@@ -540,11 +542,11 @@ function EditorAreaInner({
// The terminal has NO reveal tab. It is a developer surface reached by ⌘J (and
// the View menu), and a second permanent tab hovering over the editor footer's
// bottom-right was clutter competing with the Ask AI composer for that corner.
- const rightRevealTabPresent = !agentsVisible && onRevealAgents != null;
+ const rightRevealTabPresent = !noteWindow && !agentsVisible && onRevealAgents != null;
const terminalContainer =
terminalPlacement === 'right' ? rightTerminalContainer : bottomTerminalContainer;
const terminalShowing = terminalVisible && terminalContainer != null;
- const agentsShowing = agentsVisible && agentsContainer != null;
+ const agentsShowing = agentsColumnPresent && agentsContainer != null;
// Report the attach points up to EditorPane (which owns the long-lived session
// hosts). EditorArea only says where to attach — the VS Code / Zed pattern of
// owning the terminal above the layout that changes.
@@ -1878,17 +1880,19 @@ function EditorAreaInner({
visibleDocNames={renderableVisibleDocNames}
activityHosts={activityHosts}
parkingHost={parkingHost}
- renderToolbar={(docName, provider) => (
- <PaneDocumentToolbar
- docName={docName}
- provider={provider}
- isSourceMode={isSourceMode}
- onModeChange={onModeChange}
- isPanelCollapsed={isCollapsed}
- onTogglePanel={togglePanel}
- reserveRightGutter={docName === activeDocName && rightRevealTabPresent && isCollapsed}
- />
- )}
+ renderToolbar={(docName, provider) =>
+ noteWindow ? null : (
+ <PaneDocumentToolbar
+ docName={docName}
+ provider={provider}
+ isSourceMode={isSourceMode}
+ onModeChange={onModeChange}
+ isPanelCollapsed={isCollapsed}
+ onTogglePanel={togglePanel}
+ reserveRightGutter={docName === activeDocName && rightRevealTabPresent && isCollapsed}
+ />
+ )
+ }
isSourceMode={isSourceMode}
editorPlaceholder={poolActiveDocName === activeDocName ? editorPlaceholder : undefined}
previousDocName={previousDocName ?? undefined}
@@ -2043,6 +2047,13 @@ function EditorAreaInner({
</>
);
+ // A popped-out note window carries no doc-panel rail, so the editor takes the
+ // window's full width. Cleared after the branches above rather than guarding
+ // each one: every branch that builds a rail is equally out of scope here, and
+ // one exit keeps the layout arithmetic below honest (`rightPanel == null`
+ // feeds `editorAbsorbsResidual`).
+ if (noteWindow) rightPanel = null;
+
// The editor absorbs the residual width whenever something on the right claims
// space — the doc panel (when present and not collapsed) or a resizable rail.
const editorAbsorbsResidual =
diff --git a/packages/app/src/components/EditorBreadcrumb.dom.test.tsx b/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
index 445a27ed0..c60be47bd 100644
--- a/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
+++ b/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
@@ -31,6 +31,31 @@ describe('EditorBreadcrumb (Tier-3 mount)', () => {
expect(container.firstChild).toBeNull();
});
+ test('optionally renders the active document as the current breadcrumb page', () => {
+ render(<EditorBreadcrumb docName="meetings/2026/notes" includeCurrentPage />);
+
+ const nav = screen.getByRole('navigation', { name: /breadcrumb/i });
+ const pages = [...nav.querySelectorAll('[data-slot="breadcrumb-page"]')];
+ expect(pages.map((page) => page.textContent)).toEqual(['meetings', '2026', 'notes']);
+ expect(pages[0]?.getAttribute('aria-current')).toBeNull();
+ expect(pages[1]?.getAttribute('aria-current')).toBeNull();
+ expect(pages[2]?.getAttribute('aria-current')).toBe('page');
+ expectVisualClassTokens(nav.querySelector('[data-slot="breadcrumb-list"]')?.className, [
+ 'text-sm',
+ ]);
+ expectVisualClassTokens(pages[2]?.className, ['font-medium', 'text-foreground']);
+ });
+
+ test('renders a root-level document when the current page is requested', () => {
+ render(<EditorBreadcrumb docName="notes" includeCurrentPage />);
+
+ const currentPage = screen
+ .getByRole('navigation', { name: /breadcrumb/i })
+ .querySelector('[data-slot="breadcrumb-page"]');
+ expect(currentPage?.textContent).toBe('notes');
+ expect(currentPage?.getAttribute('aria-current')).toBe('page');
+ });
+
test('renders folder segments with chevron separators for a nested docName', () => {
render(<EditorBreadcrumb docName="meetings/2026/q1/notes" />);
diff --git a/packages/app/src/components/EditorBreadcrumb.tsx b/packages/app/src/components/EditorBreadcrumb.tsx
index 6e2724d5b..806fee5f4 100644
--- a/packages/app/src/components/EditorBreadcrumb.tsx
+++ b/packages/app/src/components/EditorBreadcrumb.tsx
@@ -14,6 +14,8 @@ import { cn } from '@/lib/utils';
interface EditorBreadcrumbProps {
docName: string | null;
+ /** Include the active document as the final, current-page breadcrumb item. */
+ includeCurrentPage?: boolean;
/** Optional extra classes for the outer breadcrumb nav (e.g. layout overrides). */
className?: string;
}
@@ -33,7 +35,9 @@ type BreadcrumbNode =
| { kind: 'ellipsis'; hidden: readonly string[] };
/**
- * Folder-path breadcrumb for the active doc — renders nothing at project root.
+ * Folder-path breadcrumb for the active doc. By default it renders nothing at
+ * project root; titlebar callers can include the active document as the final
+ * current-page item.
*
* Pure display: no click / hover navigation behavior. Every segment renders
* as a non-link `BreadcrumbPage`. Folder segments derive from
@@ -47,11 +51,10 @@ type BreadcrumbNode =
* item, so a screen reader still announces the full hierarchy while sighted
* users get the compact `root › … › leaf` form.
*
- * Mounted in EditorToolbar's left grid cell. The mount point scopes its own
- * `pointer-events-auto` so it doesn't get swallowed by the parent grid's
- * `pointer-events-none` overlay; this component itself does NOT need
- * pointer-events scoping because it is display-only — the mount-side scoping
- * is what surfaces the truncation-tooltip `title` to the pointer.
+ * EditorToolbar's mount point scopes its own `pointer-events-auto` so it
+ * doesn't get swallowed by the parent grid's `pointer-events-none` overlay;
+ * this component itself does NOT need pointer-events scoping because it is
+ * display-only. It is also mounted directly in the draggable note titlebar.
*
* The full `min-w-0` chain (nav → list → item → page) plus `overflow-hidden`
* on the list is load-bearing: the toolbar mounts this in a `grid-cols-3`
@@ -62,7 +65,11 @@ type BreadcrumbNode =
* spread-props (BreadcrumbPage forwards every attr to its inner span), so the
* native truncation tooltip continues to reveal the full segment on hover.
*/
-export function EditorBreadcrumb({ docName, className }: EditorBreadcrumbProps) {
+export function EditorBreadcrumb({
+ docName,
+ includeCurrentPage = false,
+ className,
+}: EditorBreadcrumbProps) {
if (!docName) return null;
// A template shows its owning folder path, derived from the content shape and
// hiding the `.ok/templates/` segment (matching the name-only tab label); a
@@ -71,12 +78,16 @@ export function EditorBreadcrumb({ docName, className }: EditorBreadcrumbProps)
// so the breadcrumb and tab label split the path through one primitive.
const template = parseTemplateContentDocName(docName);
const managed = template ? null : parseManagedArtifactName(docName);
- const segments = template
+ const folderSegments = template
? template.folder.split('/').filter(Boolean)
: managed
? []
: tabParts(docName, '').prefix.replace(/\/$/, '').split('/').filter(Boolean);
+ const segments = includeCurrentPage
+ ? [...folderSegments, tabParts(docName, '').label]
+ : folderSegments;
if (segments.length === 0) return null;
+ const currentPageKey = includeCurrentPage ? segments.join('/') : null;
// Stable per-segment key: full prefix slice up to that segment.
// Disambiguates identical names at different depths (e.g. `notes/notes`).
@@ -99,9 +110,15 @@ export function EditorBreadcrumb({ docName, className }: EditorBreadcrumbProps)
return (
<Breadcrumb className={cn('flex min-w-0 items-center', className)}>
- <BreadcrumbList className="min-w-0 flex-nowrap gap-1 overflow-hidden text-muted-foreground/70 text-xs">
+ <BreadcrumbList
+ className={cn(
+ 'min-w-0 flex-nowrap gap-1 overflow-hidden text-muted-foreground/70',
+ includeCurrentPage ? 'text-sm' : 'text-xs',
+ )}
+ >
{nodes.map((node, index) => {
const key = node.kind === 'segment' ? node.key : 'ellipsis';
+ const isCurrentPage = node.kind === 'segment' && node.key === currentPageKey;
return (
<Fragment key={key}>
{/* Separator is a SIBLING of the item — shadcn renders both as
@@ -134,8 +151,11 @@ export function EditorBreadcrumb({ docName, className }: EditorBreadcrumbProps)
) : (
<BreadcrumbItem className="min-w-0">
<BreadcrumbPage
- current={false}
- className="min-w-0 truncate font-normal text-muted-foreground/70"
+ current={isCurrentPage}
+ className={cn(
+ 'min-w-0 truncate font-normal',
+ isCurrentPage ? 'font-medium text-foreground' : 'text-muted-foreground/70',
+ )}
title={node.value}
>
<UserText>{node.value}</UserText>
diff --git a/packages/app/src/components/EditorHeader.dom.test.tsx b/packages/app/src/components/EditorHeader.dom.test.tsx
index 91f5a920c..d922b92ac 100644
--- a/packages/app/src/components/EditorHeader.dom.test.tsx
+++ b/packages/app/src/components/EditorHeader.dom.test.tsx
@@ -109,6 +109,13 @@ function setWindowsHost() {
});
}
+function setNoteHost() {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { config: { mode: 'note' }, menu: {}, platform: 'win32' },
+ });
+}
+
async function renderHeader(tabs?: ReactNode) {
const { EditorHeader } = await import('./EditorHeader');
render(
@@ -449,6 +456,46 @@ describe('EditorHeader runtime behavior', () => {
expect(screen.queryByTestId('navigation-history-controls')).toBeNull();
});
+ test('note windows put document context in the titlebar without Resources or sync chrome', async () => {
+ setNoteHost();
+ sidebarState = 'expanded';
+ const { EditorHeader } = await import('./EditorHeader');
+ render(
+ <TooltipProvider delayDuration={0}>
+ <EditorHeader noteModeToggle={<button type="button">mode switch</button>} />
+ </TooltipProvider>,
+ );
+
+ const leadingZone = document.querySelector(
+ '[data-editor-header-leading-actions]',
+ ) as HTMLElement;
+ const header = document.querySelector('header') as HTMLElement;
+ expect(leadingZone.textContent).toContain('docs');
+ expect(leadingZone.textContent).toContain('notes');
+ expect(
+ leadingZone.querySelector('[data-slot="breadcrumb-page"][aria-current="page"]')?.textContent,
+ ).toBe('notes');
+ expectVisualClassTokens(header.className, ['bg-background']);
+ expectVisualClassTokensAbsent(header.className, [
+ 'bg-muted/35',
+ 'shadow-[inset_0_-1px_0_var(--border)]',
+ ]);
+ expectVisualClassTokens(leadingZone.className, ['left-[var(--ok-titlebar-reserve-left,1rem)]']);
+ expect(screen.getByRole('button', { name: 'mode switch' })).toBeTruthy();
+ const modeToggle = document.querySelector('[data-note-window-mode-toggle]') as HTMLElement;
+ expectVisualClassTokens(modeToggle.className, [
+ '[&_[data-slot=toggle-group]]:bg-transparent',
+ '[&_[data-slot=toggle-group]]:p-0',
+ '[&_[data-slot=toggle-group-item]]:size-8',
+ '[&_[data-slot=toggle-group-item]]:shadow-none',
+ ]);
+ expect(screen.queryByRole('button', { name: 'Resources' })).toBeNull();
+ expect(screen.queryByTestId('sync-status-badge')).toBeNull();
+ expect(screen.queryByTestId('presence-bar')).toBeNull();
+ expect(screen.queryByTestId('beta-badge')).toBeNull();
+ expect(screen.queryByTestId('app-menubar')).toBeNull();
+ });
+
test('renders workspace tabs between the global action zones', async () => {
await renderHeader(<div data-testid="editor-tabs">tabs</div>);
diff --git a/packages/app/src/components/EditorHeader.tsx b/packages/app/src/components/EditorHeader.tsx
index 0c8a3f818..6a407778b 100644
--- a/packages/app/src/components/EditorHeader.tsx
+++ b/packages/app/src/components/EditorHeader.tsx
@@ -13,6 +13,7 @@ import { SidebarTrigger, useSidebar } from '@/components/ui/sidebar';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useDocumentContext } from '@/editor/DocumentContext';
import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
+import { isNoteWindow } from '@/lib/note-window-mode';
import {
buildDocShareInput,
buildFolderShareInput,
@@ -22,6 +23,7 @@ import { useSingleFileMode } from '@/lib/single-file-mode';
import { cn } from '@/lib/utils';
import { PresenceBar } from '@/presence/PresenceBar';
import { BetaBadge } from './BetaBadge';
+import { EditorBreadcrumb } from './EditorBreadcrumb';
import { HelpPopover } from './HelpPopover';
import { InstanceBadge } from './InstanceBadge';
import { NavigationHistoryControls } from './NavigationHistoryControls';
@@ -38,6 +40,8 @@ const AppMenubar = lazy(() =>
interface EditorHeaderProps {
children?: ReactNode;
+ /** Editor-mode switch promoted into the titlebar in a popped-out note. */
+ noteModeToggle?: ReactNode;
onSignIn?: () => void;
onSetIdentity?: () => void;
onOpenSearch?: () => void;
@@ -45,6 +49,7 @@ interface EditorHeaderProps {
export function EditorHeader({
children,
+ noteModeToggle,
onSignIn,
onSetIdentity,
onOpenSearch,
@@ -63,6 +68,13 @@ export function EditorHeader({
// (sidebar toggle, tab strip, Settings) while leaving the editor + the
// doc-scoped actions (Share / sync / agent handoff) intact.
const singleFile = useSingleFileMode();
+ // A popped-out note window reduces the header the same way a single-file
+ // session does, and for the same reason: neither has a file sidebar, a
+ // project switcher, or anywhere for project chrome to act. Gating only on
+ // `singleFile` left a pop-out showing a Files toggle for a sidebar that is
+ // not there — caught by the two-window smoke, invisible to the dom tier.
+ const noteWindow = isNoteWindow();
+ const reducedChrome = singleFile || noteWindow;
const sidebarShortcut = formatShortcut('toggle-files-sidebar');
const sidebarShortcutLabel = formatShortcutLabel('toggle-files-sidebar');
const searchShortcut = formatShortcut('command-palette');
@@ -109,6 +121,7 @@ export function EditorHeader({
// token (defined under `html.electron-mode`) so the magic 78px lives in one
// place; the `,1rem` fallback is the precedent-#49 safe form.
const isCollapsed = sidebarState === 'collapsed';
+ const reserveTrafficLights = isElectronHost && (isCollapsed || noteWindow);
const appMenubar = shouldShowAppMenubar() ? (
<Suspense fallback={null}>
<AppMenubar />
@@ -166,17 +179,17 @@ export function EditorHeader({
off and on a throwaway server, so a share link would point at a
session that's gone on close. Hidden here (mirrors the
sidebar/Settings gates) rather than rendered disabled. */}
- {!singleFile && (
+ {!reducedChrome && (
<ShareButton input={shareInput} onClickWhenNoRemote={() => setPublishOpen(true)} />
)}
- <SyncStatusBadge onSignIn={onSignIn} onSetIdentity={onSetIdentity} />
+ {!noteWindow && <SyncStatusBadge onSignIn={onSignIn} onSetIdentity={onSetIdentity} />}
<PresenceBar />
<Separator orientation="vertical" className="h-4 shrink-0 data-vertical:self-center" />
<InstanceBadge />
<BetaBadge />
{/* Settings is unavailable in single-file mode (config editing is inert). */}
- {!singleFile && <SettingsButton />}
- <HelpPopover />
+ {!reducedChrome && <SettingsButton />}
+ {!noteWindow && <HelpPopover />}
</>
);
@@ -185,11 +198,13 @@ export function EditorHeader({
ref={headerRef}
data-electron-drag={isElectronHost ? '' : undefined}
style={{
- ['--editor-header-leading-offset' as string]:
- isElectronHost && isCollapsed ? 'var(--ok-titlebar-reserve-left, 1rem)' : '0px',
+ ['--editor-header-leading-offset' as string]: reserveTrafficLights
+ ? 'var(--ok-titlebar-reserve-left, 1rem)'
+ : '0px',
}}
className={cn(
- 'group/editor-header relative flex h-12 shrink-0 items-center bg-muted/35 shadow-[inset_0_-1px_0_var(--border)]',
+ 'group/editor-header relative flex h-12 shrink-0 items-center',
+ noteWindow ? 'bg-background' : 'bg-muted/35 shadow-[inset_0_-1px_0_var(--border)]',
isElectronHost && '[-webkit-app-region:drag]',
)}
>
@@ -219,14 +234,18 @@ export function EditorHeader({
className={cn(
'absolute inset-y-0 left-0 z-20 flex items-center gap-1 px-3',
isElectronHost && '[-webkit-app-region:drag]',
- isElectronHost && isCollapsed && 'left-[var(--ok-titlebar-reserve-left,1rem)]',
+ reserveTrafficLights && 'left-[var(--ok-titlebar-reserve-left,1rem)]',
+ noteWindow && 'max-w-[calc(50%-4rem)] overflow-hidden',
)}
>
{/* The menubar renders in single-file windows too: the project-chrome
group below is absent there, so without this slot Window / Help /
- Exit would have no reachable surface at all. */}
+ Exit would have no reachable surface at all. A focused note window
+ deliberately omits app-wide menu chrome, matching auxiliary editor
+ windows on Windows/Linux. */}
{singleFile && appMenubar}
- {!singleFile && (
+ {noteWindow && <EditorBreadcrumb docName={activeDocName} includeCurrentPage />}
+ {!reducedChrome && (
<>
<ButtonGroup
aria-label={t`Workspace navigation`}
@@ -282,6 +301,15 @@ export function EditorHeader({
)}
</div>
+ {noteWindow && noteModeToggle ? (
+ <div
+ data-note-window-mode-toggle=""
+ className="absolute inset-y-0 left-1/2 z-30 flex -translate-x-1/2 items-center [-webkit-app-region:no-drag] [&_[data-slot=toggle-group]]:bg-transparent [&_[data-slot=toggle-group]]:p-0 [&_[data-slot=toggle-group-item]]:size-8 [&_[data-slot=toggle-group-item]]:shadow-none"
+ >
+ {noteModeToggle}
+ </div>
+ ) : null}
+
<div
ref={trailingActionsRef}
data-electron-drag={isElectronHost ? '' : undefined}
@@ -301,8 +329,10 @@ export function EditorHeader({
isElectronHost && 'mr-[var(--ok-titlebar-reserve-right,0px)]',
)}
>
- {headerActions}
- {!singleFile && <PublishToGitHubDialog open={publishOpen} onOpenChange={setPublishOpen} />}
+ {!noteWindow && headerActions}
+ {!reducedChrome && (
+ <PublishToGitHubDialog open={publishOpen} onOpenChange={setPublishOpen} />
+ )}
</div>
</header>
);
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index 27907bca6..924f26a28 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -1,4 +1,9 @@
-import type { TerminalCli, TerminalPlacement } from '@inkeep/open-knowledge-core';
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import {
+ isEditableTextDocFile,
+ type TerminalCli,
+ type TerminalPlacement,
+} from '@inkeep/open-knowledge-core';
import {
lazy,
Suspense,
@@ -27,17 +32,20 @@ import { authPromptStore } from '@/lib/auth-prompt-store';
import { useConfigContext } from '@/lib/config-provider';
import { matchesKeyboardShortcut, matchesRendererShortcut } from '@/lib/keyboard-shortcuts';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import { isNoteWindow } from '@/lib/note-window-mode';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { readTerminalPlacement, writeTerminalPlacement } from '@/lib/terminal-placement-store';
import { readTerminalRightWidth, writeTerminalRightWidth } from '@/lib/terminal-right-width-store';
import { recordTerminalOpened } from '@/lib/terminal-telemetry';
import { setViewMenuState } from '@/lib/view-menu-state-store';
+import { useSyncStatus } from '@/presence/use-sync-status';
import { AuthModal } from './AuthModal';
import { AutoSyncOnboardingDialog } from './AutoSyncOnboardingDialog';
import { resolveAutoSyncOnboarding } from './auto-sync-onboarding-gate';
import { type PanelTab, TABS } from './DocPanel';
import { EditorArea, type SessionPlacements } from './EditorArea';
import { EditorHeader } from './EditorHeader';
+import { EditorModeToggle } from './EditorModeToggle';
import { composeTerminalSelectionPaste } from './handoff/compose-terminal-selection';
import { requestPreferredSession } from './handoff/preferred-session-events';
import {
@@ -105,6 +113,25 @@ export interface ThreadLaunchIntent {
export type EditorMode = EditorModeValue;
+function NoteWindowModeToggle({
+ provider,
+ editorMode,
+ onModeChange,
+}: {
+ provider: HocuspocusProvider | null;
+ editorMode: EditorModeValue;
+ onModeChange: (mode: EditorModeValue) => void;
+}) {
+ const syncStatus = useSyncStatus(provider);
+ return (
+ <EditorModeToggle
+ isSourceMode={editorMode === 'source'}
+ onModeChange={onModeChange}
+ sourceDisabled={syncStatus !== 'connected' && syncStatus !== 'synced'}
+ />
+ );
+}
+
interface EditorPaneProps {
onOpenSearch?: () => void;
}
@@ -149,7 +176,12 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
// (node-pty is not bundled there; terminal dock dark off-mac), where a
// rendered affordance would only surface a spawn failure. Gate every
// terminal affordance on both so a control that can't launch never renders.
+ // A popped-out note window is a reading/writing surface for one document, so
+ // it carries no docked terminal. Deferred rather than refused: the surface is
+ // structurally the heaviest of the deferred chrome, not ruled out forever.
+ const noteWindow = isNoteWindow();
const terminalAvailable =
+ !noteWindow &&
desktopBridge != null &&
desktopBridge.terminal != null &&
desktopBridge.config.ptyAvailable === true;
@@ -319,6 +351,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
// chord per destination is the point, and two would put the same intent behind
// a key that says "terminal".
useEffect(() => {
+ if (noteWindow) return;
return subscribeLocalMenuAction((action) => {
if (action === 'toggle-terminal') {
setTerminalVisible((visible) => !visible);
@@ -336,7 +369,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
setAgentsVisible((visible) => !visible);
}
});
- }, []);
+ }, [noteWindow]);
// Unlike the ⌘L listener below, this one stays mounted on desktop: ⌃` carries
// no native accelerator, so the renderer is its only delivery path. ⌘J is
@@ -550,6 +583,10 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
// (always, even on a read failure) releases the deferred pushes so the View
// menu converges. Desktop-only.
useEffect(() => {
+ if (noteWindow) {
+ setDockRestoreSettled(true);
+ return;
+ }
const bridge = window.okDesktop;
if (bridge == null) return;
// Capability-guard like TerminalDock's list(): a desktop bridge without a
@@ -587,7 +624,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
return () => {
cancelled = true;
};
- }, []);
+ }, [noteWindow]);
// Adoption telemetry: count each open (the false→true transition). Starts
// hidden, so the mount run is a no-op; desktop-only (the dock is too). The
@@ -736,17 +773,26 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
activeTab={activeTab}
onActiveTabChange={setActiveTab}
terminalBridge={terminalAvailable ? desktopBridge : null}
- terminalVisible={terminalVisible}
+ terminalVisible={noteWindow ? false : terminalVisible}
terminalPlacement={terminalPlacement}
terminalRightWidth={terminalRightWidth}
onTerminalVisibleChange={setTerminalVisible}
onTerminalRightWidthChange={setTerminalRightWidth}
- agentsVisible={agentsVisible}
+ agentsVisible={noteWindow ? false : agentsVisible}
onAgentsVisibleChange={setAgentsVisible}
onSessionPlacements={setPlacements}
- onRevealAgents={revealAgents}
+ onRevealAgents={noteWindow ? undefined : revealAgents}
renderWorkspaceHeader={(tabs) => (
<EditorHeader
+ noteModeToggle={
+ noteWindow && activeDocName !== null && !isEditableTextDocFile(activeDocName) ? (
+ <NoteWindowModeToggle
+ provider={activeProvider}
+ editorMode={editorMode}
+ onModeChange={handleModeChange}
+ />
+ ) : null
+ }
onSignIn={() => {
setAuthInitialStep('auth');
setAuthModalOpen(true);
@@ -768,20 +814,22 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
unavailable. The terminal host mounts only where a shell can actually
spawn (`terminalAvailable` folds in `ptyAvailable`); an empty terminal
dock on those hosts would be a control that can never do anything. */}
- <Suspense fallback={null}>
- <SessionsHost
- surface="agents-panel"
- bridge={desktopBridge}
- terminalCapable={terminalAvailable}
- visible={agentsVisible}
- onVisibleChange={setAgentsVisible}
- threadLaunch={threadLaunch}
- installedClis={installedClis}
- container={placements.agents.container}
- isShowing={placements.agents.isShowing}
- onRequestEditorFocus={() => placements.editorRegion?.focus()}
- />
- </Suspense>
+ {noteWindow ? null : (
+ <Suspense fallback={null}>
+ <SessionsHost
+ surface="agents-panel"
+ bridge={desktopBridge}
+ terminalCapable={terminalAvailable}
+ visible={agentsVisible}
+ onVisibleChange={setAgentsVisible}
+ threadLaunch={threadLaunch}
+ installedClis={installedClis}
+ container={placements.agents.container}
+ isShowing={placements.agents.isShowing}
+ onRequestEditorFocus={() => placements.editorRegion?.focus()}
+ />
+ </Suspense>
+ )}
{terminalAvailable ? (
<Suspense fallback={null}>
<SessionsHost
diff --git a/packages/app/src/components/EditorTabs.dom.test.tsx b/packages/app/src/components/EditorTabs.dom.test.tsx
index 1588c9556..3dc7b7fbf 100644
--- a/packages/app/src/components/EditorTabs.dom.test.tsx
+++ b/packages/app/src/components/EditorTabs.dom.test.tsx
@@ -1288,6 +1288,53 @@ describe('EditorTabs runtime behavior', () => {
expect(moveTabToNewPane).toHaveBeenCalledWith(newId, 'right');
});
+ test('offers Open in New Window on document tabs only, and never on the web host', async () => {
+ const { folderId, assetId, newId } = defaultTabs();
+
+ // Web host: no desktop bridge, so the pop-out entry point does not exist.
+ await renderEditorTabs();
+ expect(screen.queryAllByTestId('editor-tab-context-open-in-new-window')).toHaveLength(0);
+
+ cleanup();
+ const openNoteWindow = vi.fn(async () => ({ ok: true as const, outcome: 'created' as const }));
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { noteWindow: { open: openNoteWindow } },
+ });
+ await renderEditorTabs();
+
+ // One per file-backed DOCUMENT tab. A folder and an asset carry their own
+ // id prefixes; a blank "New tab" has no prefix and so parses as a doc, but
+ // is backed by no file — all three are excluded.
+ const items = screen.getAllByTestId('editor-tab-context-open-in-new-window');
+ const docTabCount = visibleTabIds.filter(
+ (id) => id !== folderId && id !== assetId && id !== newId,
+ ).length;
+ expect(items).toHaveLength(docTabCount);
+ expect(docTabCount).toBe(3);
+
+ fireEvent.click(items[0] as HTMLElement);
+ expect(openNoteWindow).toHaveBeenCalledWith('docs/team/notes', 'tab-menu');
+ });
+
+ test('popping a tab out leaves the origin tab list untouched', async () => {
+ const openNoteWindow = vi.fn(async () => ({ ok: true as const, outcome: 'created' as const }));
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { noteWindow: { open: openNoteWindow } },
+ });
+ await renderEditorTabs();
+
+ fireEvent.click(
+ screen.getAllByTestId('editor-tab-context-open-in-new-window')[0] as HTMLElement,
+ );
+
+ // Keep-both: the origin tab stays open, so nothing on the origin side moves.
+ expect(closeTab).not.toHaveBeenCalled();
+ expect(closeTabs).not.toHaveBeenCalled();
+ expect(moveTabToNewPane).not.toHaveBeenCalled();
+ });
+
test('disables move-to-pane actions when the pane has only one tab', async () => {
activeDocName = 'docs/team/notes';
activeTabId = 'docs/team/notes';
diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsx
index 56853f0e7..71c7bfefa 100644
--- a/packages/app/src/components/EditorTabs.tsx
+++ b/packages/app/src/components/EditorTabs.tsx
@@ -12,6 +12,7 @@ import {
PanelRight,
PinIcon,
PlusIcon,
+ SquareArrowOutUpRight,
Trash2,
XIcon,
} from 'lucide-react';
@@ -60,6 +61,7 @@ import { useSkills } from '@/hooks/use-skills';
import { emitFileTreeMenuActionRename } from '@/lib/file-tree-menu-action-events';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { skillEntryLiveDocName } from '@/lib/managed-artifact-doc-name';
+import { openDocInNoteWindow } from '@/lib/open-note-window';
import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { cn } from '@/lib/utils';
import {
@@ -321,6 +323,17 @@ function EditorTabContextMenu({
);
const closableTabIds = filterClosableTabIds(openTabs, pinnedTabIds);
const canMoveToNewPane = canSplit && openTabs.length > 1;
+ // Pop-out is desktop-only and document-only. Two conditions, because neither
+ // alone is enough: the parsed kind rules out folder / asset / skill tabs,
+ // which carry their own id prefixes, while `target` rules out a blank "New
+ // tab" — its id has no prefix, so it parses AS a doc, but it is backed by no
+ // file and there would be nothing for the new window to show. Already inside a
+ // note window there is no tab strip, so this menu never renders there.
+ const parsedTab = parseEditorTabId(tabId);
+ const popOutDocName =
+ parsedTab.kind === 'doc' && target && typeof window !== 'undefined' && window.okDesktop
+ ? parsedTab.docName
+ : null;
return (
<>
@@ -407,6 +420,17 @@ function EditorTabContextMenu({
<PanelRight aria-hidden="true" />
<Trans>Move to new pane right</Trans>
</ContextMenuItem>
+ {popOutDocName ? (
+ <ContextMenuItem
+ data-testid="editor-tab-context-open-in-new-window"
+ onSelect={() => {
+ void openDocInNoteWindow(popOutDocName, 'tab-menu');
+ }}
+ >
+ <SquareArrowOutUpRight aria-hidden="true" />
+ <Trans>Open in New Window</Trans>
+ </ContextMenuItem>
+ ) : null}
</ContextMenuGroup>
</ContextMenuContent>
</ContextMenu>
diff --git a/packages/app/src/components/EditorToolbar.dom.test.tsx b/packages/app/src/components/EditorToolbar.dom.test.tsx
index 17f4f290e..287f825da 100644
--- a/packages/app/src/components/EditorToolbar.dom.test.tsx
+++ b/packages/app/src/components/EditorToolbar.dom.test.tsx
@@ -77,7 +77,10 @@ function missing(property: string): LintDiagnostic {
}
describe('EditorToolbar runtime layout', () => {
- afterEach(() => cleanup());
+ afterEach(() => {
+ cleanup();
+ Reflect.deleteProperty(window, 'okDesktop');
+ });
async function renderToolbar(
activeDocName = 'docs/Page.md',
@@ -163,6 +166,17 @@ describe('EditorToolbar runtime layout', () => {
);
});
+ test('hides the document-panel toggle in a note window', async () => {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { config: { mode: 'note' } },
+ });
+
+ await renderToolbar();
+
+ expect(document.querySelector('[data-doc-panel-toggle]')).toBeNull();
+ });
+
test('a tree-hidden doc gets the not-in-sidebar indicator beside the breadcrumb', async () => {
await renderToolbar('.scratch/hidden-note');
diff --git a/packages/app/src/components/EditorToolbar.tsx b/packages/app/src/components/EditorToolbar.tsx
index cf2f27659..5b6943492 100644
--- a/packages/app/src/components/EditorToolbar.tsx
+++ b/packages/app/src/components/EditorToolbar.tsx
@@ -19,6 +19,7 @@ import type { EditorModeValue } from '@/editor/use-editor-mode.ts';
import { useConfigContextOptional } from '@/lib/config-context';
import { formatShortcut, formatShortcutLabel } from '@/lib/keyboard-shortcuts';
import { parseProjectSkillContentDocName } from '@/lib/managed-artifact-doc-name';
+import { isNoteWindow } from '@/lib/note-window-mode';
import {
NO_RESERVED_KEYS,
SKILL_RESERVED_KEYS,
@@ -105,6 +106,7 @@ export function EditorToolbar({
const slidesPluginEnabled = useConfigContextOptional()?.merged?.slides?.enabled === true;
const panelShortcut = formatShortcut('toggle-document-panel');
const panelShortcutLabel = formatShortcutLabel('toggle-document-panel');
+ const showPanelToggle = !isNoteWindow();
// Skills carry install/uninstall + history chrome in this per-doc toolbar
// (templates + documents don't — only skills are installed). Install is a
// live symlink, so there's no reinstall step.
@@ -245,30 +247,32 @@ export function EditorToolbar({
<SlidesToolbarControls provider={activeProvider} docName={activeDocName} />
</Suspense>
) : null}
- <Tooltip>
- <Button
- data-doc-panel-toggle=""
- variant="ghost"
- size="icon"
- onClick={onTogglePanel}
- aria-expanded={!isPanelCollapsed}
- aria-controls="doc-panel"
- aria-label={
- isPanelCollapsed
- ? t`Show panel (${panelShortcutLabel})`
- : t`Hide panel (${panelShortcutLabel})`
- }
- asChild
- >
- <TooltipTrigger>
- {isPanelCollapsed ? <PanelRightOpen /> : <PanelRightClose />}
- </TooltipTrigger>
- </Button>
- <TooltipContent side="bottom">
- <span>{isPanelCollapsed ? t`Show panel` : t`Hide panel`}</span>{' '}
- <Kbd aria-label={panelShortcutLabel}>{panelShortcut}</Kbd>
- </TooltipContent>
- </Tooltip>
+ {showPanelToggle ? (
+ <Tooltip>
+ <Button
+ data-doc-panel-toggle=""
+ variant="ghost"
+ size="icon"
+ onClick={onTogglePanel}
+ aria-expanded={!isPanelCollapsed}
+ aria-controls="doc-panel"
+ aria-label={
+ isPanelCollapsed
+ ? t`Show panel (${panelShortcutLabel})`
+ : t`Hide panel (${panelShortcutLabel})`
+ }
+ asChild
+ >
+ <TooltipTrigger>
+ {isPanelCollapsed ? <PanelRightOpen /> : <PanelRightClose />}
+ </TooltipTrigger>
+ </Button>
+ <TooltipContent side="bottom">
+ <span>{isPanelCollapsed ? t`Show panel` : t`Hide panel`}</span>{' '}
+ <Kbd aria-label={panelShortcutLabel}>{panelShortcut}</Kbd>
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
</div>
<div
aria-hidden
diff --git a/packages/app/src/components/EditorWorkspace.tsx b/packages/app/src/components/EditorWorkspace.tsx
index 8183d0a2c..32bb30a0b 100644
--- a/packages/app/src/components/EditorWorkspace.tsx
+++ b/packages/app/src/components/EditorWorkspace.tsx
@@ -21,12 +21,18 @@ import {
useLayoutEffect,
useRef,
useState,
+ useSyncExternalStore,
} from 'react';
import { docNameForNavigationTarget } from '@/components/navigation-targets';
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
import { useDocumentContext } from '@/editor/DocumentContext';
import type { EditorPaneState, PaneSide } from '@/editor/editor-panes';
import { openSidebarDropPayload } from '@/editor/sidebar-drop';
+import {
+ getNoteWindowDeletedDoc,
+ subscribeNoteWindowDeleted,
+} from '@/lib/note-window-deleted-store';
+import { isNoteWindow } from '@/lib/note-window-mode';
import { hasSidebarDragType, parseSidebarDragPayload } from '@/lib/sidebar-drag';
import { useSingleFileMode } from '@/lib/single-file-mode';
import { cn } from '@/lib/utils';
@@ -39,6 +45,7 @@ import {
isEditorTabDropData,
TAB_KEYBOARD_DRAG_CODES,
} from './editor-tabs-chrome';
+import { NoteWindowDeletedState } from './NoteWindowDeletedState';
const MIN_EDITOR_PANE_WIDTH = 300;
@@ -360,6 +367,15 @@ export function EditorWorkspace({
visibleTabIdsByPane,
} = useDocumentContext();
const singleFile = useSingleFileMode();
+ // Two surfaces show exactly one document with no tab strip and no split: an
+ // ephemeral single-file session (`ok <file>`) and a popped-out note window.
+ // They reach it for different reasons but render the same reduced workspace.
+ const singleDocumentSurface = singleFile || isNoteWindow();
+ const deletedDocName = useSyncExternalStore(
+ subscribeNoteWindowDeleted,
+ getNoteWindowDeletedDoc,
+ () => null,
+ );
const desktopSessionRestorePending =
!singleFile &&
!tabSessionLoaded &&
@@ -686,8 +702,20 @@ export function EditorWorkspace({
</div>
);
- if (singleFile) {
+ if (singleDocumentSurface) {
const pane = panes.find((candidate) => candidate.id === focusedPaneId) ?? panes[0];
+ // A deleted document replaces the editor outright. The header stays so the
+ // window keeps its chrome and drag region while the user reads and closes.
+ if (deletedDocName !== null) {
+ return (
+ <>
+ {renderHeader(null)}
+ <div data-editor-workspace="" className="relative min-h-0 flex-1 overflow-hidden">
+ <NoteWindowDeletedState docName={deletedDocName} />
+ </div>
+ </>
+ );
+ }
return (
<>
{renderHeader(null)}
diff --git a/packages/app/src/components/NoteWindowDeletedState.dom.test.tsx b/packages/app/src/components/NoteWindowDeletedState.dom.test.tsx
new file mode 100644
index 000000000..98516af5a
--- /dev/null
+++ b/packages/app/src/components/NoteWindowDeletedState.dom.test.tsx
@@ -0,0 +1,116 @@
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { useSyncExternalStore } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import {
+ __resetNoteWindowDeletedForTests,
+ getNoteWindowDeletedDoc,
+ markNoteWindowDocDeleted,
+ subscribeNoteWindowDeleted,
+} from '@/lib/note-window-deleted-store';
+import { NoteWindowDeletedState } from './NoteWindowDeletedState';
+
+afterEach(() => {
+ cleanup();
+ __resetNoteWindowDeletedForTests();
+ vi.restoreAllMocks();
+});
+
+describe('NoteWindowDeletedState', () => {
+ test('names the deleted document and offers a way out', () => {
+ render(<NoteWindowDeletedState docName="notes/alpha" />);
+
+ expect(screen.getByTestId('note-window-deleted-state')).not.toBeNull();
+ expect(screen.getByText('notes/alpha')).not.toBeNull();
+ expect(screen.getByRole('button', { name: 'Close window' })).not.toBeNull();
+ });
+
+ test('the close affordance is a real button, so it is keyboard reachable', () => {
+ render(<NoteWindowDeletedState docName="notes/alpha" />);
+ const button = screen.getByRole('button', { name: 'Close window' });
+
+ // Reachable by Tab and activatable by Enter/Space purely by being a button
+ // that is not disabled and not removed from the tab order.
+ expect(button.tagName).toBe('BUTTON');
+ expect((button as HTMLButtonElement).disabled).toBe(false);
+ expect(button.getAttribute('tabindex')).not.toBe('-1');
+ });
+
+ test('moves focus to the close button on mount, so a keyboard user is not stranded', () => {
+ render(<NoteWindowDeletedState docName="notes/alpha" />);
+
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Close window' }));
+ });
+
+ test('closes the window when activated, rather than navigating anywhere', () => {
+ const close = vi.spyOn(window, 'close').mockImplementation(() => {});
+ render(<NoteWindowDeletedState docName="notes/alpha" />);
+
+ screen.getByRole('button', { name: 'Close window' }).click();
+
+ expect(close).toHaveBeenCalledOnce();
+ });
+});
+
+describe('note-window deleted store', () => {
+ test('starts healthy', () => {
+ expect(getNoteWindowDeletedDoc()).toBeNull();
+ });
+
+ test('records the deleted document and reports it handled', () => {
+ // Returning true is what tells the removal reconciler to skip navigate-home.
+ expect(markNoteWindowDocDeleted('notes/alpha')).toBe(true);
+ expect(getNoteWindowDeletedDoc()).toBe('notes/alpha');
+ });
+
+ test('a repeat mark for the same document stays handled', () => {
+ markNoteWindowDocDeleted('notes/alpha');
+ expect(markNoteWindowDocDeleted('notes/alpha')).toBe(true);
+ expect(getNoteWindowDeletedDoc()).toBe('notes/alpha');
+ });
+
+ test('notifies a subscriber on mark, and its cleanup stops further notifications', () => {
+ // This subscribe→emit→cleanup contract is what drives the window's ONLY
+ // recovery surface (the deleted state) via `useSyncExternalStore`; a
+ // regression in `emit()`/subscription would silently strand the user.
+ const listener = vi.fn();
+ const unsubscribe = subscribeNoteWindowDeleted(listener);
+
+ markNoteWindowDocDeleted('notes/alpha');
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+ // A different doc emits again; the unsubscribed listener must not fire.
+ markNoteWindowDocDeleted('notes/beta');
+ expect(listener).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('note-window deleted store — subscriber re-render', () => {
+ // The exact consumer shape `EditorWorkspace` uses, isolated to a probe so the
+ // recovery path is provable without mounting the full editor surface.
+ function DeletedProbe() {
+ const deletedDocName = useSyncExternalStore(
+ subscribeNoteWindowDeleted,
+ getNoteWindowDeletedDoc,
+ );
+ return deletedDocName ? (
+ <NoteWindowDeletedState docName={deletedDocName} />
+ ) : (
+ <div data-testid="healthy-editor" />
+ );
+ }
+
+ test('a mark after mount re-renders the subscriber into the deleted state', () => {
+ render(<DeletedProbe />);
+ expect(screen.queryByTestId('note-window-deleted-state')).toBeNull();
+ expect(screen.getByTestId('healthy-editor')).not.toBeNull();
+
+ act(() => {
+ markNoteWindowDocDeleted('notes/alpha');
+ });
+
+ expect(screen.getByTestId('note-window-deleted-state')).not.toBeNull();
+ expect(screen.getByText('notes/alpha')).not.toBeNull();
+ expect(screen.queryByTestId('healthy-editor')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/NoteWindowDeletedState.tsx b/packages/app/src/components/NoteWindowDeletedState.tsx
new file mode 100644
index 000000000..0f7caab64
--- /dev/null
+++ b/packages/app/src/components/NoteWindowDeletedState.tsx
@@ -0,0 +1,53 @@
+/**
+ * What a popped-out note window shows once its document is deleted.
+ *
+ * Deliberately a terminal state rather than a redirect or an auto-close. The
+ * window is a place the user parked a specific document, often on another
+ * monitor: closing it out from under them loses the position they chose, and
+ * navigating it somewhere else turns a one-document window into a surface it was
+ * never meant to be. Saying plainly that the document is gone, and letting them
+ * close the window themselves, is the only option that does not act on their
+ * behalf.
+ */
+
+import { Trans } from '@lingui/react/macro';
+import { useEffect, useRef } from 'react';
+import { UserText } from '@/components/UserText';
+import { Button } from '@/components/ui/button';
+
+export function NoteWindowDeletedState({ docName }: { docName: string }) {
+ const closeButtonRef = useRef<HTMLButtonElement>(null);
+ // This replaces the editor surface, so move focus to the one actionable
+ // control. A keyboard user who was editing when the document was deleted would
+ // otherwise be stranded on `document.body` with no reachable affordance.
+ useEffect(() => {
+ closeButtonRef.current?.focus();
+ }, []);
+
+ return (
+ <div
+ data-testid="note-window-deleted-state"
+ className="flex h-full flex-1 flex-col items-center justify-center gap-3 p-8 text-center"
+ >
+ <h2 className="font-medium text-base text-foreground">
+ <Trans>This document was deleted</Trans>
+ </h2>
+ {/* The name is user content, so it renders as data rather than being
+ folded into the sentence above — no interpolation to mis-translate —
+ and through `UserText` so its writing direction comes from the name
+ itself rather than the interface language. */}
+ <p className="max-w-md break-all text-muted-foreground text-sm">
+ <UserText>{docName}</UserText>
+ </p>
+ <Button
+ ref={closeButtonRef}
+ variant="secondary"
+ onClick={() => {
+ window.close();
+ }}
+ >
+ <Trans>Close window</Trans>
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/NoteWindowMainActionReceiver.dom.test.ts b/packages/app/src/components/NoteWindowMainActionReceiver.dom.test.ts
new file mode 100644
index 000000000..37e1c8525
--- /dev/null
+++ b/packages/app/src/components/NoteWindowMainActionReceiver.dom.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, test } from 'vitest';
+import { subscribeToActiveTerminalInput } from '@/components/handoff/terminal-input-events';
+import { subscribeToTerminalLaunchRequests } from '@/components/handoff/terminal-launch-events';
+import { subscribeToAgentThreadLaunchRequests } from '@/components/handoff/thread-launch-events';
+import { dispatchNoteWindowMainAction } from './NoteWindowMainActionReceiver';
+
+describe('dispatchNoteWindowMainAction', () => {
+ test('re-enters the owning renderer conversation buses', () => {
+ const target = new EventTarget();
+ const received: unknown[] = [];
+ const unsubscribe = [
+ subscribeToActiveTerminalInput((detail) => received.push(detail), target),
+ subscribeToAgentThreadLaunchRequests((detail) => received.push(detail), target),
+ subscribeToTerminalLaunchRequests(
+ (prompt, cli, options) => received.push({ prompt, cli, ...options }),
+ target,
+ ),
+ ];
+
+ dispatchNoteWindowMainAction(
+ { kind: 'active-input', text: 'Explain', newTab: true, submit: true },
+ target,
+ );
+ dispatchNoteWindowMainAction(
+ {
+ kind: 'agent-thread',
+ agentSource: 'custom',
+ agentId: 'reviewer',
+ prompt: 'Review',
+ docName: 'notes/alpha',
+ titleHint: 'Review',
+ },
+ target,
+ );
+ dispatchNoteWindowMainAction(
+ { kind: 'terminal-launch', prompt: 'Review', cli: 'codex', stage: false },
+ target,
+ );
+
+ expect(received).toEqual([
+ { text: 'Explain', newTab: true, submit: true },
+ {
+ agentSource: 'custom',
+ agentId: 'reviewer',
+ prompt: 'Review',
+ docName: 'notes/alpha',
+ titleHint: 'Review',
+ },
+ { prompt: 'Review', cli: 'codex', stage: false },
+ ]);
+ for (const stop of unsubscribe) stop();
+ });
+});
diff --git a/packages/app/src/components/NoteWindowMainActionReceiver.tsx b/packages/app/src/components/NoteWindowMainActionReceiver.tsx
new file mode 100644
index 000000000..e6306328a
--- /dev/null
+++ b/packages/app/src/components/NoteWindowMainActionReceiver.tsx
@@ -0,0 +1,69 @@
+import type { OkNoteWindowMainAction } from '@inkeep/open-knowledge-core/desktop-bridge';
+import { useEffect } from 'react';
+import { revealQueue } from '@/comments/reveal-queue';
+import { requestDocPanelTab } from '@/components/doc-panel-events';
+import { requestActiveTerminalInput } from '@/components/handoff/terminal-input-events';
+import { requestTerminalLaunch } from '@/components/handoff/terminal-launch-events';
+import { requestAgentThreadLaunch } from '@/components/handoff/thread-launch-events';
+import { hashFromDocName, isSameHash } from '@/lib/doc-hash';
+import { isNoteWindow } from '@/lib/note-window-mode';
+
+export function dispatchNoteWindowMainAction(
+ action: OkNoteWindowMainAction,
+ target: Window | EventTarget,
+): void {
+ switch (action.kind) {
+ case 'active-input':
+ requestActiveTerminalInput(
+ action.text,
+ {
+ newTab: action.newTab,
+ submit: action.submit,
+ target: action.target,
+ },
+ target,
+ );
+ return;
+ case 'agent-thread':
+ requestAgentThreadLaunch(
+ {
+ agentSource: action.agentSource,
+ agentId: action.agentId,
+ prompt: action.prompt,
+ docName: action.docName,
+ titleHint: action.titleHint,
+ },
+ target,
+ );
+ return;
+ case 'terminal-launch':
+ requestTerminalLaunch(action.prompt, action.cli, { stage: action.stage }, target);
+ return;
+ case 'reveal-comments': {
+ if (action.scope === 'queue') {
+ revealQueue();
+ return;
+ }
+ requestDocPanelTab('comments', target);
+ if (typeof window === 'undefined' || target !== window) return;
+ const nextHash = hashFromDocName(action.docName);
+ if (!isSameHash(window.location.hash, nextHash)) window.location.hash = nextHash;
+ return;
+ }
+ }
+}
+
+/**
+ * Receives actions that a popped-out note handed to this owning project
+ * window, then re-enters the same renderer-local buses as a direct click.
+ */
+export function NoteWindowMainActionReceiver() {
+ useEffect(() => {
+ if (isNoteWindow()) return;
+ const subscribe = window.okDesktop?.noteWindow?.onMainAction;
+ if (typeof subscribe !== 'function') return;
+ return subscribe((action) => dispatchNoteWindowMainAction(action, window));
+ }, []);
+
+ return null;
+}
diff --git a/packages/app/src/components/app-menubar-gate.ts b/packages/app/src/components/app-menubar-gate.ts
index c2bce1c43..1ccc13b5c 100644
--- a/packages/app/src/components/app-menubar-gate.ts
+++ b/packages/app/src/components/app-menubar-gate.ts
@@ -3,11 +3,16 @@
* `AppMenubar.tsx` so the mount sites (EditorHeader, NavigatorApp) can
* decide WHETHER to render without pulling the menubar component — and its
* radix Menubar primitive — into the eager bundle: `AppMenubar` is
- * lazy-loaded, and on web + macOS (where this predicate is false) its chunk
- * never downloads at all.
+ * lazy-loaded, and on web, macOS, and focused note windows (where this
+ * predicate is false) its chunk never downloads at all.
*/
export function shouldShowAppMenubar(): boolean {
if (typeof window === 'undefined') return false;
const bridge = window.okDesktop;
- return bridge != null && bridge.menu != null && bridge.platform !== 'darwin';
+ return (
+ bridge != null &&
+ bridge.menu != null &&
+ bridge.platform !== 'darwin' &&
+ bridge.config?.mode !== 'note'
+ );
}
diff --git a/packages/app/src/components/command-palette-commands.ts b/packages/app/src/components/command-palette-commands.ts
index 1b62f888f..83f941540 100644
--- a/packages/app/src/components/command-palette-commands.ts
+++ b/packages/app/src/components/command-palette-commands.ts
@@ -37,6 +37,7 @@ import {
Settings,
Sparkles,
SpellCheck,
+ SquareArrowOutUpRight,
SquareTerminal,
Trash2,
UnfoldVertical,
@@ -50,6 +51,7 @@ import type { OkDesktopBridge, OkMenuAction } from '@/lib/desktop-bridge-types';
import { hashFromSkills } from '@/lib/doc-hash';
import { i18n } from '@/lib/i18n';
import type { KeyboardShortcutId } from '@/lib/keyboard-shortcuts';
+import { openDocInNoteWindow } from '@/lib/open-note-window';
import { SETTINGS_OPEN_HASH } from '@/lib/use-settings-route';
import type { ViewMenuState } from '@/lib/view-menu-state-store';
@@ -181,6 +183,7 @@ const PALETTE_COMMAND_LABELS = {
newFile: msg`New file`,
newFolder: msg`New folder`,
openGraph: msg`Open graph`,
+ openInNewWindow: msg`Open in New Window`,
initializeStarterPack: msg`Initialize starter pack`,
newSkill: msg`New skill`,
newProject: msg`New project`,
@@ -275,6 +278,7 @@ const COMMAND_ICONS: Record<string, ComponentType<{ className?: string }>> = {
'new-file': FilePlus2,
'new-folder': FolderPlus,
'open-graph': Network,
+ 'open-in-new-window': SquareArrowOutUpRight,
'initialize-starter-pack': Package,
'new-skill': Sparkles,
'new-project': Plus,
@@ -335,6 +339,12 @@ const COMMAND_DISPATCH: Record<string, (ctx: PaletteCommandContext) => void> = {
ctx.closePalette();
requestDocPanelTab('graph');
},
+ 'open-in-new-window': (ctx) => {
+ ctx.closePalette();
+ // `requiresActiveDoc` already gated the row, so a null here would mean the
+ // availability evaluation and the dispatch disagreed.
+ if (ctx.activeDocName) void openDocInNoteWindow(ctx.activeDocName, 'palette');
+ },
'initialize-starter-pack': (ctx) => {
ctx.closePalette();
ctx.openSeedDialog();
diff --git a/packages/app/src/components/command-palette-open-in-new-window.test.ts b/packages/app/src/components/command-palette-open-in-new-window.test.ts
new file mode 100644
index 000000000..a6370734d
--- /dev/null
+++ b/packages/app/src/components/command-palette-open-in-new-window.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, test, vi } from 'vitest';
+import { PALETTE_COMMANDS, type PaletteCommandContext } from './command-palette-commands';
+
+const openDocInNoteWindow = vi.hoisted(() => vi.fn(async () => {}));
+vi.mock('@/lib/open-note-window', () => ({ openDocInNoteWindow }));
+
+/**
+ * The palette's half of "Open in New Window". The row must disappear rather
+ * than grey out when there is nothing to pop: the palette's availability
+ * mechanism only hides, so a row that survives with no active document would be
+ * a dead click.
+ */
+function ctx(over: Partial<PaletteCommandContext>): PaletteCommandContext {
+ return {
+ bridge: {} as PaletteCommandContext['bridge'],
+ singleFile: false,
+ activeDocName: 'notes/alpha',
+ contextualTargetKind: 'doc',
+ viewMenuState: {},
+ ...over,
+ } as unknown as PaletteCommandContext;
+}
+
+describe('open-in-new-window palette command', () => {
+ const cmd = PALETTE_COMMANDS.find((c) => c.id === 'open-in-new-window');
+
+ test('is registered in the commands group', () => {
+ expect(cmd).toBeDefined();
+ expect(cmd?.group).toBe('commands');
+ });
+
+ test('is listed when a document is active on the desktop host', () => {
+ expect(cmd?.available(ctx({}))).toBe(true);
+ });
+
+ test('is hidden when no document is active', () => {
+ expect(cmd?.available(ctx({ activeDocName: null }))).toBe(false);
+ });
+
+ test('is hidden on the web host, which cannot spawn a window', () => {
+ expect(cmd?.available(ctx({ bridge: null }))).toBe(false);
+ });
+
+ test('is hidden in a single-file session, which is already one document', () => {
+ expect(cmd?.available(ctx({ singleFile: true }))).toBe(false);
+ });
+
+ test('closes the palette and pops the active document out, tagged as palette', () => {
+ const closePalette = vi.fn();
+ cmd?.dispatch(ctx({ closePalette }));
+
+ expect(closePalette).toHaveBeenCalledOnce();
+ expect(openDocInNoteWindow).toHaveBeenCalledWith('notes/alpha', 'palette');
+ });
+});
diff --git a/packages/app/src/components/desktop-root-app.tsx b/packages/app/src/components/desktop-root-app.tsx
index 555316c90..78181b742 100644
--- a/packages/app/src/components/desktop-root-app.tsx
+++ b/packages/app/src/components/desktop-root-app.tsx
@@ -13,8 +13,15 @@ const TerminalWindowApp = lazy(() =>
/**
* Pick the root surface for the current window from the desktop bridge's mode.
* `terminal` and `navigator` are dedicated Electron window types; everything
- * else — editor windows, and the web / CLI distribution where `bridge` is
- * undefined — renders the full editor shell.
+ * else — editor windows, popped-out `note` windows, and the web / CLI
+ * distribution where `bridge` is undefined — renders the full editor shell.
+ *
+ * `note` deliberately shares the editor root rather than getting a dedicated
+ * one. Its reduced chrome comes from a flag read inside the tree
+ * (`isNoteWindow`), the same shape single-file mode uses, which keeps the
+ * pooled hybrid render tree and the DocumentContext machinery (tab remap,
+ * rename following, delete reconciliation) intact instead of hand-composing
+ * around them.
*/
export function selectDesktopRootApp(bridge: OkDesktopBridge | undefined): ReactElement {
if (bridge?.config.mode === 'terminal') {
diff --git a/packages/app/src/components/handoff/terminal-input-events.ts b/packages/app/src/components/handoff/terminal-input-events.ts
index 3ffeabdf5..da937f129 100644
--- a/packages/app/src/components/handoff/terminal-input-events.ts
+++ b/packages/app/src/components/handoff/terminal-input-events.ts
@@ -17,6 +17,8 @@
* degrades per what is enabled and available.
*/
+import { routeNoteWindowActionToMain } from '@/lib/note-window-main-actions';
+
const ACTIVE_TERMINAL_INPUT_EVENT = 'open-knowledge:active-terminal-input';
export interface ActiveTerminalInputDetail {
@@ -56,14 +58,16 @@ export function requestActiveTerminalInput(
? new EventTarget()
: window,
): void {
+ const detail: ActiveTerminalInputDetail = {
+ text,
+ newTab: options?.newTab === true,
+ submit: options?.submit === true,
+ ...(options?.target === 'agents' ? { target: 'agents' as const } : {}),
+ };
+ if (routeNoteWindowActionToMain({ kind: 'active-input', ...detail }, target)) return;
target.dispatchEvent(
new CustomEvent<ActiveTerminalInputDetail>(ACTIVE_TERMINAL_INPUT_EVENT, {
- detail: {
- text,
- newTab: options?.newTab === true,
- submit: options?.submit === true,
- ...(options?.target === 'agents' ? { target: 'agents' as const } : {}),
- },
+ detail,
}),
);
}
diff --git a/packages/app/src/components/handoff/terminal-launch-events.ts b/packages/app/src/components/handoff/terminal-launch-events.ts
index 7e1587674..dedb3eb14 100644
--- a/packages/app/src/components/handoff/terminal-launch-events.ts
+++ b/packages/app/src/components/handoff/terminal-launch-events.ts
@@ -15,6 +15,7 @@
*/
import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import { routeNoteWindowActionToMain } from '@/lib/note-window-main-actions';
const TERMINAL_LAUNCH_EVENT = 'open-knowledge:terminal-launch';
@@ -44,6 +45,18 @@ export function requestTerminalLaunch(
? new EventTarget()
: window,
): void {
+ if (
+ routeNoteWindowActionToMain(
+ {
+ kind: 'terminal-launch',
+ prompt,
+ cli,
+ stage: options?.stage === true,
+ },
+ target,
+ )
+ )
+ return;
target.dispatchEvent(
new CustomEvent<TerminalLaunchDetail>(TERMINAL_LAUNCH_EVENT, {
detail: { prompt, cli, stage: options?.stage === true },
diff --git a/packages/app/src/components/handoff/thread-launch-events.ts b/packages/app/src/components/handoff/thread-launch-events.ts
index 9d7c8cdc4..9bd64ed19 100644
--- a/packages/app/src/components/handoff/thread-launch-events.ts
+++ b/packages/app/src/components/handoff/thread-launch-events.ts
@@ -9,6 +9,8 @@
* desktop gate.
*/
+import { routeNoteWindowActionToMain } from '@/lib/note-window-main-actions';
+
const THREAD_LAUNCH_EVENT = 'open-knowledge:agent-thread-launch';
export interface AgentThreadLaunchDetail {
@@ -32,6 +34,7 @@ export function requestAgentThreadLaunch(
? new EventTarget()
: window,
): void {
+ if (routeNoteWindowActionToMain({ kind: 'agent-thread', ...detail }, target)) return;
target.dispatchEvent(new CustomEvent<AgentThreadLaunchDetail>(THREAD_LAUNCH_EVENT, { detail }));
}
diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsx
index 965a9763c..2e9169472 100644
--- a/packages/app/src/editor/DocumentContext.tsx
+++ b/packages/app/src/editor/DocumentContext.tsx
@@ -23,6 +23,8 @@ import {
} from '@/lib/doc-hash';
import { emitBranchChanged, emitDocumentsChanged } from '@/lib/documents-events';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import { markNoteWindowDocDeleted } from '@/lib/note-window-deleted-store';
+import { isNoteWindow } from '@/lib/note-window-mode';
import { mark } from '@/lib/perf';
import { refreshServerInfo } from '@/lib/server-info-refresh';
import { useCollabUrl } from '@/lib/use-collab-url';
@@ -65,7 +67,7 @@ import {
filterOpenTabsForKnownTargets,
folderTabId,
isSkillTabId,
- localTabSessionStorageKey,
+ localTabSessionKeyForMode,
parseEditorTabId,
parseEditorTabSessionState,
readLocalTabSessionState,
@@ -502,8 +504,7 @@ function getDesktopBridge() {
function getLocalTabSessionKey(): string | null {
if (typeof window === 'undefined') return null;
- if (window.okDesktop?.config.mode === 'editor') return null;
- return localTabSessionStorageKey(window.location.origin);
+ return localTabSessionKeyForMode(window.okDesktop?.config.mode, window.location.origin);
}
function readInitialLocalTabSession() {
@@ -1346,6 +1347,11 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
const focused = focusedPane(workspaceRef.current);
navigateToHash(focused.activeTabId ? hashFromTabId(focused.activeTabId) : '');
},
+ // A popped-out window has one document and no home surface to land on, so
+ // it shows an explicit deleted state rather than navigating. Declining in
+ // every other window keeps the workspace behavior untouched.
+ showDocumentDeletedState: (docName) =>
+ isNoteWindow() ? markNoteWindowDocDeleted(docName) : false,
});
}
diff --git a/packages/app/src/editor/SourceEditor.tsx b/packages/app/src/editor/SourceEditor.tsx
index 80af004dc..17d8becdf 100644
--- a/packages/app/src/editor/SourceEditor.tsx
+++ b/packages/app/src/editor/SourceEditor.tsx
@@ -21,6 +21,8 @@ import {
} from '@/editor/extensions/nested-cm-extensions';
import type { RawMdxNavDetail } from '@/editor/extensions/raw-mdx-nav-event';
import { useConfigContext } from '@/lib/config-provider';
+import { editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';
+import { claimNoteWindowInitialFocus } from '@/lib/note-window-focus';
import { registerSourceView, unregisterSourceView } from './active-source-view';
import { createSourceClipboardExtension } from './clipboard/index.ts';
import { type CmCacheEntry, mountCmEditor, parkCmEditor } from './editor-cache';
@@ -56,11 +58,8 @@ import { attachTypingBurstDetector } from './typing-burst-detector';
// bounding rect and does NOT read `scroll-padding-top` from the scroll ancestor,
// so the `scroll-pt-14` on ScrollPreservingContainer in
// components/EditorActivityPool.tsx does not reach source mode. EditorView.scrollMargins
-// is CM6's native equivalent — restate the inset here. Keep in sync with `pt-14`
-// / `scroll-pt-14` in components/EditorActivityPool.tsx; rendered height from
-// components/EditorToolbar.tsx.
-const TOOLBAR_OVERLAP_PX = 56;
-
+// is CM6's native equivalent — derive the inset from the same note-window-aware
+// helper as the shared scroll container.
// CodeMirror's search config asks for a scroll EFFECT rather than performing
// the scroll, so standing a match-scroll down means handing back an effect no
// extension reads.
@@ -349,7 +348,7 @@ export function SourceEditor({
height: '100%',
},
}),
- EditorView.scrollMargins.of(() => ({ top: TOOLBAR_OVERLAP_PX })),
+ EditorView.scrollMargins.of(() => ({ top: editorToolbarOverlapPx() })),
],
});
const view = new EditorView({ state, parent: el });
@@ -387,6 +386,10 @@ export function SourceEditor({
// synchronously at flip time, before this editor is hidden, and so outline
// active-heading tracking can measure this document's line geometry.
registerSourceView(docName, entry.view);
+ // A popped-out note window has nothing else to focus, so the first editor
+ // surface to mount takes the caret. One-shot per window: later mounts
+ // (Activity reveal, mode flip) must not yank focus back mid-session.
+ if (claimNoteWindowInitialFocus()) entry.view.focus();
} catch (err) {
// Surface mount failures through DocumentErrorBoundary.
console.error('[SourceEditor] mountCmEditor failed', err);
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index 69a95df1b..c0065f9cd 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -38,6 +38,7 @@ import { CommentsBoundary } from '@/comments/CommentsBoundary';
import { loadFollowFilePref } from '@/components/acp/follow-file';
import { OUTLINE_NAV_EVENT, type OutlineNavDetail } from '@/components/OutlinePanel';
import { anchorFromHash } from '@/lib/doc-hash';
+import { claimNoteWindowInitialFocus } from '@/lib/note-window-focus';
import { mark } from '@/lib/perf';
import { wrapExtensionsWithTiming } from '@/lib/perf/cold-mount-instrumentation';
import { useIdentity } from '../presence/identity';
@@ -1049,6 +1050,26 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
};
}, [editor, provider]);
+ // A popped-out note window has nothing else to focus, so the first editor
+ // surface to mount takes the caret. The claim is one-shot per window, so an
+ // Activity reveal or a mode flip later in the session cannot yank focus back.
+ // View-guarded like this file's other `'create'` effects: `editor.view` is a
+ // throwing proxy until ProseMirror mounts.
+ useEffect(() => {
+ const focusIfClaimed = () => {
+ if (editor.isDestroyed || !getEditorView(editor)) return;
+ if (claimNoteWindowInitialFocus()) editor.commands.focus();
+ };
+ if (getEditorView(editor)) {
+ focusIfClaimed();
+ } else {
+ editor.on('create', focusIfClaimed);
+ }
+ return () => {
+ editor.off('create', focusIfClaimed);
+ };
+ }, [editor]);
+
// Rename-snapshot consumption — one-shot, on the editor's first `'create'`.
// The rename snapshot (HTML + scrollTop + selection, see editor-cache.ts)
// is keyed by docName; this effect consumes it in two steps:
diff --git a/packages/app/src/editor/bubble-menu/bubble-menu-clip.ts b/packages/app/src/editor/bubble-menu/bubble-menu-clip.ts
index ef866dab6..b65fbad4d 100644
--- a/packages/app/src/editor/bubble-menu/bubble-menu-clip.ts
+++ b/packages/app/src/editor/bubble-menu/bubble-menu-clip.ts
@@ -1,5 +1,5 @@
import type { Editor } from '@tiptap/react';
-import { TOOLBAR_HEIGHT } from '../extensions/frozen-table-headers';
+import { editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';
/**
* Floating-UI clipping options that keep selection-anchored menus inside the
@@ -34,7 +34,7 @@ export function deriveEditorClipOptions(editor: Editor) {
// (recycle/remount race) — fall back to the default boundary this pass.
}
const padding = {
- top: TOOLBAR_HEIGHT,
+ top: editorToolbarOverlapPx(),
bottom:
readRootInlinePxVar('--ask-composer-height') +
readRootInlinePxVar('--conflict-footer-height'),
diff --git a/packages/app/src/editor/client-removal-reconciliation.test.ts b/packages/app/src/editor/client-removal-reconciliation.test.ts
index 5ea54b9a7..76623d79e 100644
--- a/packages/app/src/editor/client-removal-reconciliation.test.ts
+++ b/packages/app/src/editor/client-removal-reconciliation.test.ts
@@ -21,6 +21,8 @@ function createPorts(
deferredClears?: boolean;
remapActiveTarget?: boolean;
clearRejects?: boolean;
+ /** Present = a surface that handles active-doc deletion itself (note window). */
+ deletedStateHandled?: boolean;
} = {},
) {
const log: string[] = [];
@@ -66,6 +68,14 @@ function createPorts(
clearActiveTargetForRemoval: (docName) => log.push(`clear-target:${docName}`),
navigateToDocument: (docName) => log.push(`navigate:${docName}`),
navigateHome: () => log.push('navigate:home'),
+ ...(options.deletedStateHandled === undefined
+ ? {}
+ : {
+ showDocumentDeletedState: (docName: string) => {
+ log.push(`deleted-state:${docName}`);
+ return options.deletedStateHandled === true;
+ },
+ }),
};
return { clearDeferred, log, reconciler: createClientRemovalReconciler(ports) };
}
@@ -210,6 +220,44 @@ describe('ClientRemovalReconciler', () => {
]);
});
+ test('a surface that shows its own deleted state suppresses navigate-home', async () => {
+ // The note window has exactly one document and no home surface to navigate
+ // to, so it takes over and shows an explicit deleted state instead.
+ const { log, reconciler } = createPorts({
+ activePoolDocName: 'deleted',
+ deletedStateHandled: true,
+ });
+ await reconciler.reconcileAuthRemoval({ docName: 'deleted' });
+
+ expect(log).toContain('deleted-state:deleted');
+ expect(log).not.toContain('navigate:home');
+ // Cleanup still runs — the window stops showing a document that is gone.
+ expect(log).toContain('remove-tab:deleted');
+ expect(log).toContain('clear-target:deleted');
+ });
+
+ test('a surface that declines still navigates home', async () => {
+ const { log, reconciler } = createPorts({
+ activePoolDocName: 'deleted',
+ deletedStateHandled: false,
+ });
+ await reconciler.reconcileAuthRemoval({ docName: 'deleted' });
+
+ expect(log).toContain('deleted-state:deleted');
+ expect(log).toContain('navigate:home');
+ });
+
+ test('an inactive document never offers the deleted state', async () => {
+ const { log, reconciler } = createPorts({
+ activePoolDocName: 'other',
+ deletedStateHandled: true,
+ });
+ await reconciler.reconcileAuthRemoval({ docName: 'deleted' });
+
+ expect(log).not.toContain('deleted-state:deleted');
+ expect(log).not.toContain('navigate:home');
+ });
+
test('auth removal of an inactive document leaves unrelated navigation intact', async () => {
const { log, reconciler } = createPorts({ activePoolDocName: 'other' });
await reconciler.reconcileAuthRemoval({ docName: 'deleted' });
diff --git a/packages/app/src/editor/client-removal-reconciliation.ts b/packages/app/src/editor/client-removal-reconciliation.ts
index a3b36a4b1..0ae1e5cb1 100644
--- a/packages/app/src/editor/client-removal-reconciliation.ts
+++ b/packages/app/src/editor/client-removal-reconciliation.ts
@@ -47,6 +47,17 @@ export interface ClientRemovalReconciliationPorts {
clearActiveTargetForRemoval(docName: string): void;
navigateToDocument(docName: string): void;
navigateHome(): void;
+ /**
+ * Offer the surface a chance to handle the deletion of the ACTIVE document
+ * itself, returning true when it did.
+ *
+ * Exists for the popped-out note window, which shows exactly one document and
+ * so has nowhere to navigate home TO — the home surface is a workspace view it
+ * deliberately does not have. It shows an explicit deleted state instead.
+ * Absent (or returning false) keeps the workspace window's navigate-home
+ * behavior unchanged.
+ */
+ showDocumentDeletedState?(docName: string): boolean;
}
function uniqueDocNames(docNames: readonly string[]): string[] {
@@ -102,7 +113,7 @@ export function createClientRemovalReconciler(
await ports.closeAndClear(docName);
ports.removeDocumentTab(docName);
ports.clearActiveTargetForRemoval(docName);
- if (wasActive) ports.navigateHome();
+ if (wasActive && ports.showDocumentDeletedState?.(docName) !== true) ports.navigateHome();
},
};
}
diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.ts
index 2e72e3ec6..f08755ce7 100644
--- a/packages/app/src/editor/editor-tabs.test.ts
+++ b/packages/app/src/editor/editor-tabs.test.ts
@@ -13,6 +13,7 @@ import {
isSkillBundleShapedPath,
isSkillDocName,
isSkillTabId,
+ localTabSessionKeyForMode,
localTabSessionStorageKey,
nextActiveTabAfterClose,
nextActiveTabAfterCloseMany,
@@ -624,6 +625,23 @@ describe('editor tab state', () => {
});
});
+ test('a note window gets no local tab-session key, so it cannot clobber the editor window', () => {
+ // Every desktop window shares one `file://` origin, so a popped-out note
+ // window writing the origin-derived key would overwrite the main editor
+ // window's tabs. Single-document windows persist nothing at all.
+ expect(localTabSessionKeyForMode('note', 'file://')).toBeNull();
+ });
+
+ test('a desktop editor window gets no local key either (it persists via the bridge)', () => {
+ expect(localTabSessionKeyForMode('editor', 'file://')).toBeNull();
+ });
+
+ test('the browser host still gets the origin-derived key', () => {
+ expect(localTabSessionKeyForMode(undefined, 'http://localhost:5173')).toBe(
+ localTabSessionStorageKey('http://localhost:5173'),
+ );
+ });
+
test('local tab session storage round-trips serializable state', () => {
const storage = createMemoryStorage();
const key = localTabSessionStorageKey('http://localhost:5173');
diff --git a/packages/app/src/editor/editor-tabs.ts b/packages/app/src/editor/editor-tabs.ts
index d4b2ead09..c4f90bd1a 100644
--- a/packages/app/src/editor/editor-tabs.ts
+++ b/packages/app/src/editor/editor-tabs.ts
@@ -819,6 +819,25 @@ export function localTabSessionStorageKey(projectKey: string): string {
return `${LOCAL_TAB_SESSION_PREFIX}${projectKey}`;
}
+/**
+ * The localStorage tab-session key for a desktop window mode, or null when that
+ * mode must not use localStorage at all.
+ *
+ * Two modes opt out, for different reasons:
+ * - `editor` persists through the desktop bridge instead, keyed per project.
+ * - `note` persists nothing. A popped-out window shows a single document, so
+ * there is no tab session worth saving, and every desktop window shares one
+ * `file://` origin — a note window writing this key would clobber the main
+ * editor window's tabs.
+ *
+ * Every other caller (the browser host, where the origin really is per-project)
+ * gets the origin-derived key.
+ */
+export function localTabSessionKeyForMode(mode: string | undefined, origin: string): string | null {
+ if (mode === 'editor' || mode === 'note') return null;
+ return localTabSessionStorageKey(origin);
+}
+
export function readLocalTabSessionState(
storage: Pick<Storage, 'getItem'> | null,
key: string,
diff --git a/packages/app/src/editor/extensions/frozen-table-headers.ts b/packages/app/src/editor/extensions/frozen-table-headers.ts
index 690827fec..39e43862b 100644
--- a/packages/app/src/editor/extensions/frozen-table-headers.ts
+++ b/packages/app/src/editor/extensions/frozen-table-headers.ts
@@ -53,6 +53,7 @@
import { Extension } from '@tiptap/core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { EDITOR_TOOLBAR_HEIGHT, editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';
// EditorToolbar is absolutely positioned at the top of the scroll container,
// 3.5rem tall. Frozen headers must clear it. One of the four load-bearing
@@ -60,7 +61,7 @@ import { Plugin, PluginKey } from '@tiptap/pm/state';
// move them together. Exported so selection-anchored floating menus can treat
// the toolbar band as occluded (editor/bubble-menu/bubble-menu-clip.ts)
// instead of keeping a fifth drifting copy of the value.
-export const TOOLBAR_HEIGHT = 56;
+export const TOOLBAR_HEIGHT = EDITOR_TOOLBAR_HEIGHT;
// Subtle shadow to indicate the frozen row overlaps the table body.
const FROZEN_SHADOW = '0 2px 4px rgba(0, 0, 0, 0.08)';
@@ -107,7 +108,7 @@ export function computeFreezeRange(
const maxShift = tableHeight - headerHeight;
if (maxShift <= 0) return null;
// The scroll offset at which the table's top crosses the toolbar boundary.
- const startOffset = scrollTop + tableTop - (containerTop + TOOLBAR_HEIGHT);
+ const startOffset = scrollTop + tableTop - (containerTop + editorToolbarOverlapPx());
return { startOffset, endOffset: startOffset + maxShift, maxShift };
}
@@ -336,7 +337,7 @@ function computeAndApplyFrozenHeaders(
// Fallback: compute the instantaneous shift and apply it directly.
const shift = Math.max(0, Math.min(scrollTop - range.startOffset, range.maxShift));
- if (shift <= 0 || tableRect.bottom <= containerTop + TOOLBAR_HEIGHT) {
+ if (shift <= 0 || tableRect.bottom <= containerTop + editorToolbarOverlapPx()) {
resetHeaderCells(firstRow);
continue;
}
diff --git a/packages/app/src/editor/mode-switch-landing.ts b/packages/app/src/editor/mode-switch-landing.ts
index 7f73afed1..b3d26b5f3 100644
--- a/packages/app/src/editor/mode-switch-landing.ts
+++ b/packages/app/src/editor/mode-switch-landing.ts
@@ -25,6 +25,7 @@ import type { Editor } from '@tiptap/core';
import type { Node as PmNode } from '@tiptap/pm/model';
import type { EditorView as ProseMirrorView } from '@tiptap/pm/view';
import type * as Y from 'yjs';
+import { editorToolbarOverlapPx } from '@/lib/editor-toolbar-overlap';
import { getEditorForDoc } from './active-editor';
import { getSourceViewForDoc } from './active-source-view';
import { visibleEditorScrollContainer } from './editor-cache';
@@ -54,11 +55,8 @@ import { VIEW_IN_SOURCE_EVENT, type ViewInSourceDetail } from './view-in-source-
// Toolbar exclusion zone in px (= EditorToolbar's rendered 3.5rem height). The
// toolbar overlays the top of the shared scroller, so both the capture probe
// (below the toolbar) and the landing offset (target sits just under it) start
-// here. Restated rather than shared to keep this leaf free of a React-component
-// import cycle; keep in sync with TOOLBAR_OVERLAP_PX in SourceEditor.tsx and the
-// scroll-pt-14 in components/EditorActivityPool.tsx.
-const TOOLBAR_OVERLAP_PX = 56;
-
+// here. The shared helper keeps this leaf free of a React-component import cycle
+// while returning zero when the note titlebar owns the controls.
let sharedResolver: ModeSwitchPositionResolver | null = null;
function getSharedResolver(): ModeSwitchPositionResolver {
sharedResolver ??= createApproxResolver(getSharedMarkdownManager());
@@ -310,7 +308,8 @@ function findScrollContainer(): HTMLElement | null {
function topmostVisiblePos(view: ProseMirrorView, container: HTMLElement): number | null {
const rect = container.getBoundingClientRect();
const x = rect.left + rect.width / 2;
- for (const dy of [TOOLBAR_OVERLAP_PX + 1, TOOLBAR_OVERLAP_PX + 12, TOOLBAR_OVERLAP_PX + 40]) {
+ const toolbarOverlap = editorToolbarOverlapPx();
+ for (const dy of [toolbarOverlap + 1, toolbarOverlap + 12, toolbarOverlap + 40]) {
const found = view.posAtCoords({ left: x, top: rect.top + dy });
if (found) return found.pos;
}
@@ -326,7 +325,8 @@ function topmostVisiblePos(view: ProseMirrorView, container: HTMLElement): numbe
function topmostVisibleSourceOffset(view: EditorView, container: HTMLElement): number | null {
const rect = container.getBoundingClientRect();
const x = rect.left + rect.width / 2;
- for (const dy of [TOOLBAR_OVERLAP_PX + 1, TOOLBAR_OVERLAP_PX + 12, TOOLBAR_OVERLAP_PX + 40]) {
+ const toolbarOverlap = editorToolbarOverlapPx();
+ for (const dy of [toolbarOverlap + 1, toolbarOverlap + 12, toolbarOverlap + 40]) {
const pos = view.posAtCoords({ x, y: rect.top + dy });
if (pos !== null) return pos;
}
@@ -476,7 +476,7 @@ export function startSourceLanding(params: {
grade: target.confidence,
landedMode: 'source',
transition,
- toolbarOffset: TOOLBAR_OVERLAP_PX,
+ toolbarOffset: editorToolbarOverlapPx(),
onOutcome: isJump
? (outcome) => {
// Flash the whole block once it is genuinely on screen (the controller
@@ -542,7 +542,7 @@ export function startWysiwygLanding(params: {
grade: target.confidence,
landedMode: 'wysiwyg',
transition,
- toolbarOffset: TOOLBAR_OVERLAP_PX,
+ toolbarOffset: editorToolbarOverlapPx(),
onDiscardQueuedTarget: () => clearPendingWysiwygNavigation(docName),
});
}
diff --git a/packages/app/src/lib/command-menu-parity.test.ts b/packages/app/src/lib/command-menu-parity.test.ts
index 7ec925f9e..8ec19fc91 100644
--- a/packages/app/src/lib/command-menu-parity.test.ts
+++ b/packages/app/src/lib/command-menu-parity.test.ts
@@ -549,6 +549,9 @@ describe('command identity registry (Phase 2b)', () => {
'new-file',
'new-folder',
'open-graph',
+ // Invokes the note-window bridge channel directly. The menu-action bus is
+ // renderer-local, and this has to reach main to spawn a BrowserWindow.
+ 'open-in-new-window',
'initialize-starter-pack',
'new-project',
'open-folder',
diff --git a/packages/app/src/lib/editor-toolbar-overlap.dom.test.ts b/packages/app/src/lib/editor-toolbar-overlap.dom.test.ts
new file mode 100644
index 000000000..b34e30355
--- /dev/null
+++ b/packages/app/src/lib/editor-toolbar-overlap.dom.test.ts
@@ -0,0 +1,19 @@
+import { afterEach, describe, expect, test } from 'vitest';
+import { editorToolbarOverlapPx } from './editor-toolbar-overlap';
+
+afterEach(() => {
+ Reflect.deleteProperty(window, 'okDesktop');
+});
+
+describe('editorToolbarOverlapPx', () => {
+ test('reclaims the overlay band only when its controls moved into the note titlebar', () => {
+ expect(editorToolbarOverlapPx()).toBe(56);
+
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: { config: { mode: 'note' } },
+ });
+
+ expect(editorToolbarOverlapPx()).toBe(0);
+ });
+});
diff --git a/packages/app/src/lib/editor-toolbar-overlap.ts b/packages/app/src/lib/editor-toolbar-overlap.ts
new file mode 100644
index 000000000..30cc16beb
--- /dev/null
+++ b/packages/app/src/lib/editor-toolbar-overlap.ts
@@ -0,0 +1,12 @@
+import { isNoteWindow } from '@/lib/note-window-mode';
+
+/** Height of the document overlay toolbar on ordinary editor surfaces. */
+export const EDITOR_TOOLBAR_HEIGHT = 56;
+
+/**
+ * The note window promotes the breadcrumb and mode switch into its titlebar,
+ * so document content has no overlay to clear.
+ */
+export function editorToolbarOverlapPx(): number {
+ return isNoteWindow() ? 0 : EDITOR_TOOLBAR_HEIGHT;
+}
diff --git a/packages/app/src/lib/note-window-deleted-store.ts b/packages/app/src/lib/note-window-deleted-store.ts
new file mode 100644
index 000000000..7a2f3ae04
--- /dev/null
+++ b/packages/app/src/lib/note-window-deleted-store.ts
@@ -0,0 +1,49 @@
+/**
+ * Terminal state for a popped-out note window whose document was deleted.
+ *
+ * A workspace window navigates home when its active document disappears. A note
+ * window cannot: it shows exactly one document and deliberately has no home
+ * surface to land on, so navigating there would strand the user in an empty
+ * shell with no explanation. It shows an explicit deleted state instead and
+ * lets the user close the window.
+ *
+ * Module-level rather than context state because the trigger arrives from the
+ * provider pool's auth-rejection path, outside React's render tree, and the one
+ * consumer is the window's own editor surface.
+ */
+
+const listeners = new Set<() => void>();
+let deletedDocName: string | null = null;
+
+function emit(): void {
+ for (const listener of listeners) listener();
+}
+
+/**
+ * Record that this window's document is gone. Returns true so the removal
+ * reconciler can treat it as "handled" and skip its navigate-home.
+ */
+export function markNoteWindowDocDeleted(docName: string): boolean {
+ if (deletedDocName === docName) return true;
+ deletedDocName = docName;
+ emit();
+ return true;
+}
+
+/** The deleted document's name, or null while the window is healthy. */
+export function getNoteWindowDeletedDoc(): string | null {
+ return deletedDocName;
+}
+
+export function subscribeNoteWindowDeleted(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** Test-only: return the window to its healthy state. */
+export function __resetNoteWindowDeletedForTests(): void {
+ deletedDocName = null;
+ emit();
+}
diff --git a/packages/app/src/lib/note-window-focus.dom.test.ts b/packages/app/src/lib/note-window-focus.dom.test.ts
new file mode 100644
index 000000000..dde997081
--- /dev/null
+++ b/packages/app/src/lib/note-window-focus.dom.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import {
+ __resetNoteWindowFocusClaimForTests,
+ claimNoteWindowInitialFocus,
+} from './note-window-focus.ts';
+
+type OkDesktopStub = { config: { mode: string } };
+
+function stubMode(mode: string | null): void {
+ if (mode === null) {
+ (window as unknown as { okDesktop?: OkDesktopStub }).okDesktop = undefined;
+ return;
+ }
+ (window as unknown as { okDesktop?: OkDesktopStub }).okDesktop = { config: { mode } };
+}
+
+beforeEach(() => {
+ __resetNoteWindowFocusClaimForTests();
+});
+
+afterEach(() => {
+ stubMode(null);
+ __resetNoteWindowFocusClaimForTests();
+});
+
+describe('claimNoteWindowInitialFocus', () => {
+ test('the first editor surface in a note window takes the caret', () => {
+ stubMode('note');
+ expect(claimNoteWindowInitialFocus()).toBe(true);
+ });
+
+ test('a later mount finds the claim spent, so focus is never yanked back', () => {
+ stubMode('note');
+ claimNoteWindowInitialFocus();
+
+ // An Activity reveal, a mode flip, a remount: all of these re-run the
+ // editor mount path within one window.
+ expect(claimNoteWindowInitialFocus()).toBe(false);
+ expect(claimNoteWindowInitialFocus()).toBe(false);
+ });
+
+ test.each(['editor', 'navigator', 'terminal'])('the %s window mode never autofocuses', (mode) => {
+ stubMode(mode);
+ expect(claimNoteWindowInitialFocus()).toBe(false);
+ });
+
+ test('the web host never autofocuses', () => {
+ stubMode(null);
+ expect(claimNoteWindowInitialFocus()).toBe(false);
+ });
+
+ test('a non-note window does not spend the claim a later note window would need', () => {
+ stubMode('editor');
+ expect(claimNoteWindowInitialFocus()).toBe(false);
+
+ stubMode('note');
+ expect(claimNoteWindowInitialFocus()).toBe(true);
+ });
+});
diff --git a/packages/app/src/lib/note-window-focus.ts b/packages/app/src/lib/note-window-focus.ts
new file mode 100644
index 000000000..98745e3a8
--- /dev/null
+++ b/packages/app/src/lib/note-window-focus.ts
@@ -0,0 +1,35 @@
+/**
+ * Initial keyboard focus for a popped-out note window.
+ *
+ * A note window opens showing one document and nothing else focusable, so
+ * without this the caret lands on `document.body` and the first keystroke goes
+ * nowhere. The workspace window has a sidebar and a tab strip to focus into and
+ * deliberately does NOT autofocus the editor, so this is note-only.
+ *
+ * The claim is one-shot per WINDOW, not per editor mount. Editors mount and
+ * remount constantly here — the Activity pool hides and reveals entries, and a
+ * mode switch tears down one editor surface and builds the other — and focusing
+ * on every mount would yank the caret back mid-session, including out of the
+ * property panel the user just clicked into. Whichever surface mounts first
+ * (WYSIWYG or source, per the persisted editor mode) takes the claim; the other
+ * finds it spent.
+ */
+
+import { isNoteWindow } from '@/lib/note-window-mode';
+
+let claimed = false;
+
+/**
+ * `true` at most once per note window, for the caller that should take focus.
+ * Always `false` in every other window mode.
+ */
+export function claimNoteWindowInitialFocus(): boolean {
+ if (claimed || !isNoteWindow()) return false;
+ claimed = true;
+ return true;
+}
+
+/** Test-only: forget the claim so each case starts from a fresh window. */
+export function __resetNoteWindowFocusClaimForTests(): void {
+ claimed = false;
+}
diff --git a/packages/app/src/lib/note-window-main-actions.dom.test.ts b/packages/app/src/lib/note-window-main-actions.dom.test.ts
new file mode 100644
index 000000000..c986b4b8d
--- /dev/null
+++ b/packages/app/src/lib/note-window-main-actions.dom.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { revealComments, revealQueue } from '@/comments/reveal-queue';
+import { requestActiveTerminalInput } from '@/components/handoff/terminal-input-events';
+import { requestTerminalLaunch } from '@/components/handoff/terminal-launch-events';
+import { requestAgentThreadLaunch } from '@/components/handoff/thread-launch-events';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+function installNoteBridge() {
+ const dispatchToMain = vi.fn(async () => ({ ok: true as const }));
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: {
+ config: { mode: 'note' },
+ noteWindow: { dispatchToMain },
+ } as unknown as OkDesktopBridge,
+ });
+ return dispatchToMain;
+}
+
+afterEach(() => {
+ Reflect.deleteProperty(window, 'okDesktop');
+});
+
+describe('note-window main action routing', () => {
+ test('Ask AI input is handed to the owning project window', () => {
+ const dispatch = installNoteBridge();
+
+ requestActiveTerminalInput('Review this passage', { newTab: true, submit: true });
+
+ expect(dispatch).toHaveBeenCalledWith({
+ kind: 'active-input',
+ text: 'Review this passage',
+ newTab: true,
+ submit: true,
+ });
+ });
+
+ test('agent and terminal launches are handed to the owning project window', () => {
+ const dispatch = installNoteBridge();
+
+ requestAgentThreadLaunch({
+ agentSource: 'registry',
+ agentId: 'claude',
+ prompt: 'Review this note',
+ docName: 'notes/alpha',
+ titleHint: 'Review',
+ });
+ requestTerminalLaunch('Review this note', 'codex', { stage: false });
+
+ expect(dispatch.mock.calls.map(([action]) => action)).toEqual([
+ {
+ kind: 'agent-thread',
+ agentSource: 'registry',
+ agentId: 'claude',
+ prompt: 'Review this note',
+ docName: 'notes/alpha',
+ titleHint: 'Review',
+ },
+ {
+ kind: 'terminal-launch',
+ prompt: 'Review this note',
+ cli: 'codex',
+ stage: false,
+ },
+ ]);
+ });
+
+ test('posting a comment opens its document scope in the owning project window', () => {
+ const dispatch = installNoteBridge();
+
+ revealComments('doc', 'notes/alpha');
+
+ expect(dispatch).toHaveBeenCalledWith({
+ kind: 'reveal-comments',
+ docName: 'notes/alpha',
+ scope: 'doc',
+ });
+ });
+
+ test('opening the project queue stays project-scoped in the owning project window', () => {
+ const dispatch = installNoteBridge();
+
+ revealQueue('notes/alpha');
+
+ expect(dispatch).toHaveBeenCalledWith({
+ kind: 'reveal-comments',
+ docName: 'notes/alpha',
+ scope: 'queue',
+ });
+ });
+
+ test('a main-side refusal that RESOLVES { ok: false } is logged, not silently dropped', async () => {
+ // The invoke resolves (not rejects) with `{ ok: false, reason }` when the
+ // project window has closed in the cascade-close gap, so a `.catch`-only
+ // handler would drop it with no diagnostic signal.
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const dispatchToMain = vi.fn(async () => ({
+ ok: false as const,
+ reason: 'project-not-open' as const,
+ }));
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: {
+ config: { mode: 'note' },
+ noteWindow: { dispatchToMain },
+ } as unknown as OkDesktopBridge,
+ });
+
+ requestActiveTerminalInput('Review this passage', { newTab: true, submit: true });
+
+ await vi.waitFor(() =>
+ expect(warn).toHaveBeenCalledWith(
+ '[note-window] main-window action dispatch declined',
+ expect.objectContaining({ reason: 'project-not-open', kind: 'active-input' }),
+ ),
+ );
+ warn.mockRestore();
+ });
+});
diff --git a/packages/app/src/lib/note-window-main-actions.ts b/packages/app/src/lib/note-window-main-actions.ts
new file mode 100644
index 000000000..20d9413a9
--- /dev/null
+++ b/packages/app/src/lib/note-window-main-actions.ts
@@ -0,0 +1,35 @@
+import type { OkNoteWindowMainAction } from '@inkeep/open-knowledge-core/desktop-bridge';
+import { isNoteWindow } from '@/lib/note-window-mode';
+
+/**
+ * Hand one action from the reduced note renderer to its owning project window.
+ *
+ * Custom EventTargets are test seams and must stay window-local. Production
+ * callers pass the default `window`; only that path is eligible for IPC.
+ */
+export function routeNoteWindowActionToMain(
+ action: OkNoteWindowMainAction,
+ target: Pick<Window, 'dispatchEvent'> | EventTarget,
+): boolean {
+ if (typeof window === 'undefined' || target !== window || !isNoteWindow()) return false;
+ const dispatch = window.okDesktop?.noteWindow?.dispatchToMain;
+ if (typeof dispatch !== 'function') return false;
+
+ // The invoke RESOLVES with `{ ok: false, reason }` on a main-side refusal (the
+ // project window closed in the cascade-close gap, say) — a `.catch` alone
+ // would drop that silently, leaving no signal for diagnosis. Inspect the
+ // resolved value the way `open-note-window.ts` does, and log both arms.
+ void dispatch(action)
+ .then((result) => {
+ if (!result.ok) {
+ console.warn('[note-window] main-window action dispatch declined', {
+ reason: result.reason,
+ kind: action.kind,
+ });
+ }
+ })
+ .catch((error: unknown) => {
+ console.warn('[note-window] main-window action dispatch failed', error);
+ });
+ return true;
+}
diff --git a/packages/app/src/lib/note-window-mode.dom.test.ts b/packages/app/src/lib/note-window-mode.dom.test.ts
new file mode 100644
index 000000000..cb180967f
--- /dev/null
+++ b/packages/app/src/lib/note-window-mode.dom.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, describe, expect, test } from 'vitest';
+import { isNoteWindow } from './note-window-mode.ts';
+
+type OkDesktopStub = { config: { mode: string } };
+
+function stubMode(mode: string | null): void {
+ if (mode === null) {
+ (window as unknown as { okDesktop?: OkDesktopStub }).okDesktop = undefined;
+ return;
+ }
+ (window as unknown as { okDesktop?: OkDesktopStub }).okDesktop = { config: { mode } };
+}
+
+afterEach(() => {
+ stubMode(null);
+});
+
+describe('isNoteWindow', () => {
+ test('is true for a popped-out note window', () => {
+ stubMode('note');
+ expect(isNoteWindow()).toBe(true);
+ });
+
+ test.each(['editor', 'navigator', 'terminal'])('is false for the %s window mode', (mode) => {
+ stubMode(mode);
+ expect(isNoteWindow()).toBe(false);
+ });
+
+ test('is false on the web host, which has no desktop bridge', () => {
+ stubMode(null);
+ expect(isNoteWindow()).toBe(false);
+ });
+
+ test('a partial bridge with no config resolves false instead of throwing', () => {
+ // Session-only E2E hosts expose a bridge without the full surface. This is
+ // read during render, so a throw takes the whole header down.
+ (window as unknown as { okDesktop?: unknown }).okDesktop = {};
+ expect(isNoteWindow()).toBe(false);
+ });
+});
diff --git a/packages/app/src/lib/note-window-mode.ts b/packages/app/src/lib/note-window-mode.ts
new file mode 100644
index 000000000..a154d35a6
--- /dev/null
+++ b/packages/app/src/lib/note-window-mode.ts
@@ -0,0 +1,30 @@
+/**
+ * Note-window mode — is this renderer a popped-out single-document window
+ * (`--ok-mode=note`)? When true the App drops workspace chrome (file sidebar,
+ * tab strip, command palette, doc panel, agent panel, docked terminal) and
+ * renders one document full-window, keeping the editor, its toolbar, the
+ * property panel, the footer, and the connecting banner.
+ *
+ * Single-channel, unlike `useSingleFileMode`'s dual-channel resolution. The
+ * flag rides `window.okDesktop.config.mode`, which is a frozen argv-derived
+ * snapshot resolved before first render, so this answers synchronously and
+ * there is no chrome flash and no `/api/config` fallback to write. The web host
+ * cannot reach note mode at all: it has no desktop bridge, so this is always
+ * false there.
+ */
+
+// Loads the `Window.okDesktop?` global augmentation (side-effect import).
+import '@/lib/desktop-bridge-types';
+
+/**
+ * `true` when this window is a popped-out single-document note window.
+ *
+ * `config` is optional-chained even though the bridge type declares it
+ * required: partial bridges are real at runtime. Session-only E2E hosts expose
+ * a bridge without the full surface, and this is read during render, so a throw
+ * here takes the whole header down rather than degrading.
+ */
+export function isNoteWindow(): boolean {
+ if (typeof window === 'undefined') return false;
+ return window.okDesktop?.config?.mode === 'note';
+}
diff --git a/packages/app/src/lib/open-note-window.ts b/packages/app/src/lib/open-note-window.ts
new file mode 100644
index 000000000..8e0a5fba9
--- /dev/null
+++ b/packages/app/src/lib/open-note-window.ts
@@ -0,0 +1,51 @@
+/**
+ * Renderer entry point for "Open in New Window" — the doc-tab context menu and
+ * the command palette both call this.
+ *
+ * Desktop-only by construction: it invokes the `ok:window:open-note` bridge
+ * channel, and the web host has no bridge. Both callers already gate on the
+ * bridge existing, so a missing bridge here means a programming error rather
+ * than a user-facing state, and it resolves without a toast.
+ *
+ * The spawn is keep-both (the origin tab stays open) and nothing on the origin
+ * side mutates, so there is nothing to roll back on failure — a failed open is
+ * one dead action, reported and dropped.
+ */
+
+import { t } from '@lingui/core/macro';
+import { toast } from 'sonner';
+// Loads the `Window.okDesktop?` global augmentation (side-effect import).
+import '@/lib/desktop-bridge-types';
+
+/**
+ * The renderer-originated entry points only. The canonical union lives in the
+ * main process (`note-window-registry.ts`) and also carries `'window-menu'`,
+ * which is main-originated and never reaches this renderer surface. `packages/app`
+ * cannot import the main-process type, so this strict subset is declared
+ * separately on purpose — do not "sync" it by adding `'window-menu'`.
+ */
+export type RendererNoteWindowEntryPoint = 'tab-menu' | 'palette';
+
+/**
+ * Pop `docName` into its own window, or focus the window already showing it.
+ * Reports failure as a toast in the invoking window; never throws at the
+ * call site, so a menu handler can fire-and-forget it.
+ */
+export async function openDocInNoteWindow(
+ docName: string,
+ entryPoint: RendererNoteWindowEntryPoint,
+): Promise<void> {
+ const bridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
+ if (!bridge) return;
+
+ try {
+ const result = await bridge.noteWindow.open(docName, entryPoint);
+ if (result.ok) return;
+ // `no-project` means the invoking window has no project context, which a
+ // user cannot act on directly — say what failed, not which internal lookup
+ // missed.
+ toast.error(t`Could not open this document in a new window.`);
+ } catch {
+ toast.error(t`Could not open this document in a new window.`);
+ }
+}
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index dea9679ff..91f55948a 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -183,6 +183,7 @@
"1di5fu": ["المستند غير موجود"],
"1hvhf0": ["المجلد على القرص والمعرّف الذي يستخدمه الوكلاء لاستدعاء هذه المهارة."],
"1jym2J": ["لا ترسل هذا التعليق"],
+ "1lFNz3": ["تم حذف هذا المستند"],
"1njn7W": ["فاتح"],
"1nke1r": ["فتح ", ["0"], " على GitHub (يفتح في تبويب جديد)"],
"1oSHI0": ["تعذّر تثبيت ", ["skillName"], ": ", ["0"]],
@@ -1195,6 +1196,7 @@
"E5WeIy": ["أعد فتح آخر تبويب محرر مغلق."],
"E6lrpp": ["أدِر حساب GitHub الذي يستخدمه OpenKnowledge لاستعراض مستودعاتك ومزامنتها."],
"E7BhZn": ["ملاحظة فارغة"],
+ "E91VZY": ["فتح في نافذة جديدة"],
"E9bKSA": ["يجري الإنشاء"],
"E9gh86": ["يمكنك إرفاق ما يصل إلى ", ["MAX_ATTACHMENTS"], " صور."],
"EARn6h": ["تعذّرت مشاركة المهارات — ", ["detail"], "."],
@@ -4194,6 +4196,7 @@
"nzHlj8": ["إغلاق ", ["0"]],
"nzaV6Q": ["الصور المصغّرة للصفحات"],
"o0bHtA": ["من OpenKnowledge"],
+ "o1veZ6": ["تعذر فتح هذا المستند في نافذة جديدة."],
"o49mDZ": ["يجري تحميل سجل الخط الزمني"],
"o7AkQ0": ["إظهار المحلولة"],
"o9CrsQ": ["research-note"],
@@ -4472,6 +4475,7 @@
"rbrHTd": ["موافق عليه — ", ["optionName"]],
"rcJmK8": ["تحويل المواقع إلى نسخ"],
"rdU729": ["التخطيط"],
+ "rf8fiC": ["إغلاق النافذة"],
"rfFpcF": ["إزالة ", ["chip"]],
"rg7hNd": ["قيّم تجربتك"],
"rgPqOw": ["حوّل الكتلة الحالية إلى فقرة."],
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index 2490cb5b3..edbe1a296 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -2604,6 +2604,10 @@ msgstr "إغلاق الطرفية"
msgid "Close this chat's tab to delete it"
msgstr "أغلق علامة تبويب هذه المحادثة لحذفها"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "إغلاق النافذة"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3294,6 +3298,10 @@ msgstr "تعذّر فتح منتقي المجلدات"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "تعذّر فتح تسجيل الدخول إلى GitHub. يرجى المحاولة مرة أخرى."
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "تعذر فتح هذا المستند في نافذة جديدة."
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "تعذّر الوصول إلى الخادم"
@@ -8618,6 +8626,11 @@ msgstr "فتح في التطبيق الافتراضي"
msgid "Open in file manager"
msgstr "فتح في مدير الملفات"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "فتح في نافذة جديدة"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "فتح في Slidev"
@@ -12655,6 +12668,10 @@ msgstr "هذا المستند نشط بالفعل في المحرر. استخد
msgid "This document is missing required properties"
msgstr "ينقص هذا المستند خصائص مطلوبة"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "تم حذف هذا المستند"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "تجاهلت نقطة النهاية هذه حجم المتجه الذي ضبطته. أزل <0>search.semantic.dimensions</0> لاستخدام حجم النموذج نفسه."
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index a784bf700..ec879468b 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -160,6 +160,7 @@
"1di5fu": ["নথি পাওয়া যায়নি"],
"1hvhf0": ["ডিস্কের ফোল্ডার এবং এজেন্টরা এই স্কিলটি ডাকতে যে id ব্যবহার করে।"],
"1jym2J": ["এই মন্তব্যটি পাঠাবেন না"],
+ "1lFNz3": ["এই নথিটি মুছে ফেলা হয়েছে"],
"1njn7W": ["হালকা"],
"1nke1r": [["0"], " GitHub-এ খুলুন (নতুন ট্যাবে খোলে)"],
"1oSHI0": [["skillName"], " ইনস্টল করা যায়নি: ", ["0"]],
@@ -974,6 +975,7 @@
"E5WeIy": ["সবচেয়ে সম্প্রতি বন্ধ করা সম্পাদক ট্যাবটি আবার খুলুন।"],
"E6lrpp": ["আপনার রিপোজিটরি ব্রাউজ ও সিঙ্ক করতে OpenKnowledge যে GitHub অ্যাকাউন্ট ব্যবহার করে তা সামলান।"],
"E7BhZn": ["খালি নোট"],
+ "E91VZY": ["নতুন উইন্ডোতে খুলুন"],
"E9bKSA": ["তৈরি করা হচ্ছে"],
"E9gh86": ["আপনি সর্বোচ্চ ", ["MAX_ATTACHMENTS"], "টি ছবি সংযুক্ত করতে পারেন।"],
"EARn6h": ["স্কিল ভাগ করা যায়নি — ", ["detail"], "।"],
@@ -3584,6 +3586,7 @@
"nzHlj8": [["0"], " বন্ধ করুন"],
"nzaV6Q": ["পাতার থাম্বনেইল"],
"o0bHtA": ["OpenKnowledge-এর তৈরি"],
+ "o1veZ6": ["এই নথিটি নতুন উইন্ডোতে খোলা যায়নি।"],
"o49mDZ": ["কালানুক্রমের ইতিহাস লোড হচ্ছে"],
"o7AkQ0": ["সমাধান হওয়াগুলি দেখান"],
"o9CrsQ": ["research-note"],
@@ -3807,6 +3810,7 @@
"rbrHTd": ["অনুমোদিত — ", ["optionName"]],
"rcJmK8": ["জায়গাগুলোকে অনুলিপিতে রূপান্তর করুন"],
"rdU729": ["বিন্যাস"],
+ "rf8fiC": ["উইন্ডো বন্ধ করুন"],
"rfFpcF": [["chip"], " সরান"],
"rg7hNd": ["আপনার অভিজ্ঞতা মূল্যায়ন করুন"],
"rgPqOw": ["বর্তমান ব্লকটিকে অনুচ্ছেদে রূপান্তর করুন।"],
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index 016930048..8cbcb9a9e 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -2600,6 +2600,10 @@ msgstr "টার্মিনাল বন্ধ করুন"
msgid "Close this chat's tab to delete it"
msgstr "এটি মুছতে এই চ্যাটের ট্যাব বন্ধ করুন"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "উইন্ডো বন্ধ করুন"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3290,6 +3294,10 @@ msgstr "ফোল্ডার নির্বাচক খোলা যায়
msgid "Could not open GitHub sign-in. Please try again."
msgstr "GitHub সাইন-ইন খোলা যায়নি। অনুগ্রহ করে আবার চেষ্টা করুন।"
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "এই নথিটি নতুন উইন্ডোতে খোলা যায়নি।"
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "সার্ভারের নাগাল পাওয়া যায়নি"
@@ -8614,6 +8622,11 @@ msgstr "ডিফল্ট অ্যাপে খুলুন"
msgid "Open in file manager"
msgstr "ফাইল ম্যানেজারে খুলুন"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "নতুন উইন্ডোতে খুলুন"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "Slidev-এ খুলুন"
@@ -12651,6 +12664,10 @@ msgstr "এই নথিটি সম্পাদকে আগে থেকে
msgid "This document is missing required properties"
msgstr "এই নথিতে আবশ্যক প্রপার্টি অনুপস্থিত"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "এই নথিটি মুছে ফেলা হয়েছে"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "এই এন্ডপয়েন্ট আপনার কনফিগার করা ভেক্টরের আকার উপেক্ষা করেছে। মডেলের নিজের আকার ব্যবহার করতে <0>search.semantic.dimensions</0> সরিয়ে দিন।"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index adf5748e6..25bef4641 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -164,6 +164,7 @@
"1di5fu": ["Document not found"],
"1hvhf0": ["The folder on disk and the id agents use to invoke this skill."],
"1jym2J": ["Don't send this comment"],
+ "1lFNz3": ["This document was deleted"],
"1njn7W": ["Light"],
"1nke1r": ["Open ", ["0"], " on GitHub (opens in a new tab)"],
"1oSHI0": ["Couldn't install ", ["skillName"], ": ", ["0"]],
@@ -1008,6 +1009,7 @@
"Manage the GitHub account OpenKnowledge uses to browse and sync your repositories."
],
"E7BhZn": ["Blank note"],
+ "E91VZY": ["Open in New Window"],
"E9bKSA": ["Creating"],
"E9gh86": ["You can attach up to ", ["MAX_ATTACHMENTS"], " images."],
"EARn6h": ["Couldn't share skills — ", ["detail"], "."],
@@ -3692,6 +3694,7 @@
"nzHlj8": ["Close ", ["0"]],
"nzaV6Q": ["Page thumbnails"],
"o0bHtA": ["By OpenKnowledge"],
+ "o1veZ6": ["Could not open this document in a new window."],
"o49mDZ": ["Loading timeline history"],
"o7AkQ0": ["Show resolved"],
"o9CrsQ": ["research-note"],
@@ -3934,6 +3937,7 @@
"rbrHTd": ["Approved — ", ["optionName"]],
"rcJmK8": ["Convert locations to copies"],
"rdU729": ["Layout"],
+ "rf8fiC": ["Close window"],
"rfFpcF": ["Remove ", ["chip"]],
"rg7hNd": ["Rate your experience"],
"rgPqOw": ["Convert the current block to a paragraph."],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index a6dbdb5f9..bc33e901d 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -2604,6 +2604,10 @@ msgstr "Close terminal"
msgid "Close this chat's tab to delete it"
msgstr "Close this chat's tab to delete it"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "Close window"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3294,6 +3298,10 @@ msgstr "Could not open folder picker"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "Could not open GitHub sign-in. Please try again."
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "Could not open this document in a new window."
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "Could not reach server"
@@ -8618,6 +8626,11 @@ msgstr "Open in default app"
msgid "Open in file manager"
msgstr "Open in file manager"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "Open in New Window"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "Open in Slidev"
@@ -12655,6 +12668,10 @@ msgstr "This document is already active in the editor. Use Open to collapse the
msgid "This document is missing required properties"
msgstr "This document is missing required properties"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "This document was deleted"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index 4687ea437..564ec42a5 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -186,6 +186,7 @@
"1di5fu": ["No se encontró el documento"],
"1hvhf0": ["La carpeta en el disco y el id con el que los agentes invocan esta habilidad."],
"1jym2J": ["No enviar este comentario"],
+ "1lFNz3": ["Este documento se eliminó"],
"1njn7W": ["Claro"],
"1nke1r": ["Abrir ", ["0"], " en GitHub (se abre en una pestaña nueva)"],
"1oSHI0": ["No se pudo instalar ", ["skillName"], ": ", ["0"]],
@@ -1185,6 +1186,7 @@
"Gestiona la cuenta de GitHub que usa OpenKnowledge para explorar y sincronizar tus repositorios."
],
"E7BhZn": ["Nota en blanco"],
+ "E91VZY": ["Abrir en una ventana nueva"],
"E9bKSA": ["Creando"],
"E9gh86": ["Puedes adjuntar hasta ", ["MAX_ATTACHMENTS"], " imágenes."],
"EARn6h": ["No se pudieron compartir las habilidades: ", ["detail"], "."],
@@ -4280,6 +4282,7 @@
"nzHlj8": ["Cerrar ", ["0"]],
"nzaV6Q": ["Miniaturas de página"],
"o0bHtA": ["Por OpenKnowledge"],
+ "o1veZ6": ["No se pudo abrir este documento en una ventana nueva."],
"o49mDZ": ["Cargando el historial de la cronología"],
"o7AkQ0": ["Mostrar resueltos"],
"o9CrsQ": ["nota-de-investigacion"],
@@ -4549,6 +4552,7 @@
"rbrHTd": ["Aprobado — ", ["optionName"]],
"rcJmK8": ["Convertir las ubicaciones en copias"],
"rdU729": ["Diseño"],
+ "rf8fiC": ["Cerrar ventana"],
"rfFpcF": ["Quitar ", ["chip"]],
"rg7hNd": ["Valora tu experiencia"],
"rgPqOw": ["Convierte el bloque actual en un párrafo."],
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index c0ee20182..93db4933c 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -2604,6 +2604,10 @@ msgstr "Cerrar terminal"
msgid "Close this chat's tab to delete it"
msgstr "Cierra la pestaña de este chat para eliminarlo"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "Cerrar ventana"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3294,6 +3298,10 @@ msgstr "No se pudo abrir el selector de carpetas"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "No se pudo abrir el inicio de sesión de GitHub. Inténtalo de nuevo."
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "No se pudo abrir este documento en una ventana nueva."
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "No se pudo contactar con el servidor"
@@ -8618,6 +8626,11 @@ msgstr "Abrir en la aplicación predeterminada"
msgid "Open in file manager"
msgstr "Abrir en el gestor de archivos"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "Abrir en una ventana nueva"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "Abrir en Slidev"
@@ -12655,6 +12668,10 @@ msgstr "Este documento ya está activo en el editor. Usa Abrir para contraer el
msgid "This document is missing required properties"
msgstr "A este documento le faltan propiedades obligatorias"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "Este documento se eliminó"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "Este endpoint ignoró el tamaño de vector que configuraste. Quita <0>search.semantic.dimensions</0> para usar el tamaño propio del modelo."
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index e371afba4..770ebe6e0 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -194,6 +194,7 @@
"Le dossier sur le disque et l'id que les agents utilisent pour invoquer cette compétence."
],
"1jym2J": ["Ne pas envoyer ce commentaire"],
+ "1lFNz3": ["Ce document a été supprimé"],
"1njn7W": ["Clair"],
"1nke1r": ["Ouvrir ", ["0"], " sur GitHub (s'ouvre dans un nouvel onglet)"],
"1oSHI0": ["Impossible d'installer ", ["skillName"], " : ", ["0"]],
@@ -1213,6 +1214,7 @@
"Gérez le compte GitHub qu'OpenKnowledge utilise pour parcourir et synchroniser vos dépôts."
],
"E7BhZn": ["Note vierge"],
+ "E91VZY": ["Ouvrir dans une nouvelle fenêtre"],
"E9bKSA": ["Création"],
"E9gh86": ["Vous pouvez joindre jusqu'à ", ["MAX_ATTACHMENTS"], " images."],
"EARn6h": ["Impossible de partager les compétences — ", ["detail"], "."],
@@ -4313,6 +4315,7 @@
"nzHlj8": ["Fermer ", ["0"]],
"nzaV6Q": ["Miniatures des pages"],
"o0bHtA": ["Par OpenKnowledge"],
+ "o1veZ6": ["Impossible d'ouvrir ce document dans une nouvelle fenêtre."],
"o49mDZ": ["Chargement de l'historique de la chronologie"],
"o7AkQ0": ["Afficher les résolus"],
"o9CrsQ": ["research-note"],
@@ -4602,6 +4605,7 @@
"rbrHTd": ["Approuvé — ", ["optionName"]],
"rcJmK8": ["Convertir les emplacements en copies"],
"rdU729": ["Mise en page"],
+ "rf8fiC": ["Fermer la fenêtre"],
"rfFpcF": ["Retirer ", ["chip"]],
"rg7hNd": ["Évaluez votre expérience"],
"rgPqOw": ["Convertit le bloc actuel en paragraphe."],
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 04c89073f..161eead8e 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -2604,6 +2604,10 @@ msgstr "Fermer le terminal"
msgid "Close this chat's tab to delete it"
msgstr "Fermez l'onglet de ce chat pour le supprimer"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "Fermer la fenêtre"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3294,6 +3298,10 @@ msgstr "Impossible d'ouvrir le sélecteur de dossier"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "Impossible d'ouvrir la connexion GitHub. Veuillez réessayer."
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "Impossible d'ouvrir ce document dans une nouvelle fenêtre."
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "Impossible de joindre le serveur"
@@ -8618,6 +8626,11 @@ msgstr "Ouvrir dans l'application par défaut"
msgid "Open in file manager"
msgstr "Ouvrir dans le gestionnaire de fichiers"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "Ouvrir dans une nouvelle fenêtre"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "Ouvrir dans Slidev"
@@ -12655,6 +12668,10 @@ msgstr "Ce document est déjà actif dans l'éditeur. Utilisez Ouvrir pour rédu
msgid "This document is missing required properties"
msgstr "Il manque des propriétés obligatoires à ce document"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "Ce document a été supprimé"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "Ce point de terminaison a ignoré la taille de vecteur que vous avez configurée. Supprimez <0>search.semantic.dimensions</0> pour utiliser la taille propre au modèle."
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 4241d1e1f..4879470dc 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -162,6 +162,7 @@
"1di5fu": ["दस्तावेज़ नहीं मिला"],
"1hvhf0": ["डिस्क का फ़ोल्डर और वह id जिससे एजेंट इस स्किल को बुलाते हैं।"],
"1jym2J": ["यह टिप्पणी न भेजें"],
+ "1lFNz3": ["यह दस्तावेज़ हटा दिया गया था"],
"1njn7W": ["हल्का"],
"1nke1r": [["0"], " को GitHub पर खोलें (नए टैब में खुलता है)"],
"1oSHI0": [["skillName"], " इंस्टॉल नहीं की जा सकी: ", ["0"]],
@@ -976,6 +977,7 @@
"आपकी रिपॉज़िटरी ब्राउज़ और सिंक करने के लिए OpenKnowledge जिस GitHub खाते का उपयोग करता है उसे सँभालें।"
],
"E7BhZn": ["खाली नोट"],
+ "E91VZY": ["नई विंडो में खोलें"],
"E9bKSA": ["बनाया जा रहा है"],
"E9gh86": ["आप ", ["MAX_ATTACHMENTS"], " तक छवियाँ संलग्न कर सकते हैं।"],
"EARn6h": ["स्किल साझा नहीं की जा सकीं — ", ["detail"], "."],
@@ -3575,6 +3577,7 @@
"nzHlj8": [["0"], " बंद करें"],
"nzaV6Q": ["पेज थंबनेल"],
"o0bHtA": ["OpenKnowledge द्वारा"],
+ "o1veZ6": ["इस दस्तावेज़ को नई विंडो में नहीं खोला जा सका।"],
"o49mDZ": ["समयरेखा का इतिहास लोड हो रहा है"],
"o7AkQ0": ["हल की गई दिखाएँ"],
"o9CrsQ": ["research-note"],
@@ -3800,6 +3803,7 @@
"rbrHTd": ["स्वीकृत — ", ["optionName"]],
"rcJmK8": ["स्थानों को प्रतियों में बदलें"],
"rdU729": ["लेआउट"],
+ "rf8fiC": ["विंडो बंद करें"],
"rfFpcF": [["chip"], " हटाएँ"],
"rg7hNd": ["अपने अनुभव को आँकें"],
"rgPqOw": ["मौजूदा ब्लॉक को पैराग्राफ़ में बदलें।"],
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 394a75677..cfbba7d77 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -2600,6 +2600,10 @@ msgstr "टर्मिनल बंद करें"
msgid "Close this chat's tab to delete it"
msgstr "इसे हटाने के लिए इस चैट का टैब बंद करें"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "विंडो बंद करें"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3290,6 +3294,10 @@ msgstr "फ़ोल्डर चयनकर्ता नहीं खोला
msgid "Could not open GitHub sign-in. Please try again."
msgstr "GitHub साइन-इन नहीं खोला जा सका। कृपया फिर कोशिश करें।"
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "इस दस्तावेज़ को नई विंडो में नहीं खोला जा सका।"
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "सर्वर तक नहीं पहुँचा जा सका"
@@ -8614,6 +8622,11 @@ msgstr "डिफ़ॉल्ट ऐप में खोलें"
msgid "Open in file manager"
msgstr "फ़ाइल प्रबंधक में खोलें"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "नई विंडो में खोलें"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "Slidev में खोलें"
@@ -12651,6 +12664,10 @@ msgstr "यह दस्तावेज़ पहले से ही संप
msgid "This document is missing required properties"
msgstr "इस दस्तावेज़ में आवश्यक प्रॉपर्टी अनुपस्थित हैं"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "यह दस्तावेज़ हटा दिया गया था"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "इस एंडपॉइंट ने आपके कॉन्फ़िगर किए गए वेक्टर आकार को अनदेखा कर दिया। मॉडल का अपना आकार उपयोग करने के लिए <0>search.semantic.dimensions</0> हटा दें।"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index 04aea90c4..9e0f29ac0 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -164,6 +164,7 @@
"1di5fu": ["Dokumen tidak ditemukan"],
"1hvhf0": ["Folder di disk dan id yang dipakai agen untuk memanggil keterampilan ini."],
"1jym2J": ["Jangan kirim komentar ini"],
+ "1lFNz3": ["Dokumen ini telah dihapus"],
"1njn7W": ["Terang"],
"1nke1r": ["Buka ", ["0"], " di GitHub (terbuka di tab baru)"],
"1oSHI0": [["skillName"], " tidak bisa dipasang: ", ["0"]],
@@ -992,6 +993,7 @@
"Kelola akun GitHub yang dipakai OpenKnowledge untuk menelusuri dan menyinkronkan repositori Anda."
],
"E7BhZn": ["Catatan kosong"],
+ "E91VZY": ["Buka di Jendela Baru"],
"E9bKSA": ["Membuat"],
"E9gh86": ["Anda bisa melampirkan hingga ", ["MAX_ATTACHMENTS"], " gambar."],
"EARn6h": ["Keterampilan tidak bisa dibagikan — ", ["detail"], "."],
@@ -3725,6 +3727,7 @@
"nzHlj8": ["Tutup ", ["0"]],
"nzaV6Q": ["Gambar mini halaman"],
"o0bHtA": ["Oleh OpenKnowledge"],
+ "o1veZ6": ["Tidak dapat membuka dokumen ini di jendela baru."],
"o49mDZ": ["Memuat riwayat lini masa"],
"o7AkQ0": ["Tampilkan yang selesai"],
"o9CrsQ": ["catatan-riset"],
@@ -3958,6 +3961,7 @@
"rbrHTd": ["Disetujui — ", ["optionName"]],
"rcJmK8": ["Ubah lokasi menjadi salinan"],
"rdU729": ["Tata letak"],
+ "rf8fiC": ["Tutup jendela"],
"rfFpcF": ["Hapus ", ["chip"]],
"rg7hNd": ["Nilai pengalaman Anda"],
"rgPqOw": ["Mengubah blok saat ini menjadi paragraf."],
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index c478d32bb..e91895f6b 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -2600,6 +2600,10 @@ msgstr "Tutup terminal"
msgid "Close this chat's tab to delete it"
msgstr "Tutup tab obrolan ini untuk menghapusnya"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "Tutup jendela"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3290,6 +3294,10 @@ msgstr "Pemilih folder tidak dapat dibuka"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "Halaman masuk GitHub tidak dapat dibuka. Silakan coba lagi."
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "Tidak dapat membuka dokumen ini di jendela baru."
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "Server tidak dapat dihubungi"
@@ -8614,6 +8622,11 @@ msgstr "Buka di aplikasi bawaan"
msgid "Open in file manager"
msgstr "Buka di pengelola berkas"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "Buka di Jendela Baru"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "Buka di Slidev"
@@ -12651,6 +12664,10 @@ msgstr "Dokumen ini sudah aktif di penyunting. Gunakan Buka untuk menciutkan gra
msgid "This document is missing required properties"
msgstr "Dokumen ini kehilangan properti yang wajib"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "Dokumen ini telah dihapus"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "Endpoint ini mengabaikan ukuran vektor yang Anda atur. Hapus <0>search.semantic.dimensions</0> untuk memakai ukuran milik modelnya sendiri."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 5b37ac14b..598902fc3 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -164,6 +164,7 @@
"1di5fu": ["Ďōćũḿēńţ ńōţ ƒōũńď"],
"1hvhf0": ["Ţĥē ƒōĺďēŕ ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ĩńvōķē ţĥĩś śķĩĺĺ."],
"1jym2J": ["Ďōń'ţ śēńď ţĥĩś ćōḿḿēńţ"],
+ "1lFNz3": ["Ţĥĩś ďōćũḿēńţ ŵàś ďēĺēţēď"],
"1njn7W": ["Ĺĩĝĥţ"],
"1nke1r": ["Ōƥēń ", ["0"], " ōń ĜĩţĤũƀ (ōƥēńś ĩń à ńēŵ ţàƀ)"],
"1oSHI0": ["Ćōũĺďń'ţ ĩńśţàĺĺ ", ["skillName"], ": ", ["0"]],
@@ -1008,6 +1009,7 @@
"Ḿàńàĝē ţĥē ĜĩţĤũƀ àććōũńţ ŌƥēńĶńōŵĺēďĝē ũśēś ţō ƀŕōŵśē àńď śŷńć ŷōũŕ ŕēƥōśĩţōŕĩēś."
],
"E7BhZn": ["ßĺàńķ ńōţē"],
+ "E91VZY": ["Ōƥēń ĩń Ńēŵ Ŵĩńďōŵ"],
"E9bKSA": ["Ćŕēàţĩńĝ"],
"E9gh86": ["Ŷōũ ćàń àţţàćĥ ũƥ ţō ", ["MAX_ATTACHMENTS"], " ĩḿàĝēś."],
"EARn6h": ["Ćōũĺďń'ţ śĥàŕē śķĩĺĺś — ", ["detail"], "."],
@@ -3692,6 +3694,7 @@
"nzHlj8": ["Ćĺōśē ", ["0"]],
"nzaV6Q": ["Ƥàĝē ţĥũḿƀńàĩĺś"],
"o0bHtA": ["ßŷ ŌƥēńĶńōŵĺēďĝē"],
+ "o1veZ6": ["Ćōũĺď ńōţ ōƥēń ţĥĩś ďōćũḿēńţ ĩń à ńēŵ ŵĩńďōŵ."],
"o49mDZ": ["Ĺōàďĩńĝ ţĩḿēĺĩńē ĥĩśţōŕŷ"],
"o7AkQ0": ["Śĥōŵ ŕēśōĺvēď"],
"o9CrsQ": ["ŕēśēàŕćĥ-ńōţē"],
@@ -3934,6 +3937,7 @@
"rbrHTd": ["Àƥƥŕōvēď — ", ["optionName"]],
"rcJmK8": ["Ćōńvēŕţ ĺōćàţĩōńś ţō ćōƥĩēś"],
"rdU729": ["Ĺàŷōũţ"],
+ "rf8fiC": ["Ćĺōśē ŵĩńďōŵ"],
"rfFpcF": ["Ŕēḿōvē ", ["chip"]],
"rg7hNd": ["Ŕàţē ŷōũŕ ēxƥēŕĩēńćē"],
"rgPqOw": ["Ćōńvēŕţ ţĥē ćũŕŕēńţ ƀĺōćķ ţō à ƥàŕàĝŕàƥĥ."],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 6784a509d..ab9a63731 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -2600,6 +2600,10 @@ msgstr ""
msgid "Close this chat's tab to delete it"
msgstr ""
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr ""
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3290,6 +3294,10 @@ msgstr ""
msgid "Could not open GitHub sign-in. Please try again."
msgstr ""
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr ""
@@ -8614,6 +8622,11 @@ msgstr ""
msgid "Open in file manager"
msgstr ""
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr ""
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr ""
@@ -12651,6 +12664,10 @@ msgstr ""
msgid "This document is missing required properties"
msgstr ""
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 2ca41562b..80213f969 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -182,6 +182,7 @@
"1di5fu": ["Documento não encontrado"],
"1hvhf0": ["A pasta no disco e o id que os agentes usam para invocar esta habilidade."],
"1jym2J": ["Não enviar este comentário"],
+ "1lFNz3": ["Este documento foi excluído"],
"1njn7W": ["Claro"],
"1nke1r": ["Abrir ", ["0"], " no GitHub (abre em uma nova aba)"],
"1oSHI0": ["Não deu para instalar ", ["skillName"], ": ", ["0"]],
@@ -1167,6 +1168,7 @@
"Gerencie a conta do GitHub que o OpenKnowledge usa para explorar e sincronizar seus repositórios."
],
"E7BhZn": ["Nota em branco"],
+ "E91VZY": ["Abrir em nova janela"],
"E9bKSA": ["Criando"],
"E9gh86": ["Você pode anexar até ", ["MAX_ATTACHMENTS"], " imagens."],
"EARn6h": ["Não deu para compartilhar as habilidades — ", ["detail"], "."],
@@ -4196,6 +4198,7 @@
"nzHlj8": ["Fechar ", ["0"]],
"nzaV6Q": ["Miniaturas das páginas"],
"o0bHtA": ["Pelo OpenKnowledge"],
+ "o1veZ6": ["Não foi possível abrir este documento em uma nova janela."],
"o49mDZ": ["Carregando o histórico da linha do tempo"],
"o7AkQ0": ["Mostrar resolvidos"],
"o9CrsQ": ["nota-de-pesquisa"],
@@ -4455,6 +4458,7 @@
"rbrHTd": ["Aprovado — ", ["optionName"]],
"rcJmK8": ["Converter os locais em cópias"],
"rdU729": ["Layout"],
+ "rf8fiC": ["Fechar janela"],
"rfFpcF": ["Remover ", ["chip"]],
"rg7hNd": ["Avalie sua experiência"],
"rgPqOw": ["Converte o bloco atual em um parágrafo."],
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 3ebe2f708..1a2af58d8 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -2600,6 +2600,10 @@ msgstr "Fechar terminal"
msgid "Close this chat's tab to delete it"
msgstr "Feche a aba deste chat para excluí-lo"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "Fechar janela"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3290,6 +3294,10 @@ msgstr "Não foi possível abrir o seletor de pastas"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "Não foi possível abrir o login do GitHub. Tente de novo."
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "Não foi possível abrir este documento em uma nova janela."
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "Não foi possível contatar o servidor"
@@ -8614,6 +8622,11 @@ msgstr "Abrir no aplicativo padrão"
msgid "Open in file manager"
msgstr "Abrir no gerenciador de arquivos"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "Abrir em nova janela"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "Abrir no Slidev"
@@ -12651,6 +12664,10 @@ msgstr "Este documento já está ativo no editor. Use Abrir para recolher o graf
msgid "This document is missing required properties"
msgstr "Faltam propriedades obrigatórias neste documento"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "Este documento foi excluído"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "Este endpoint ignorou o tamanho de vector que você configurou. Remova <0>search.semantic.dimensions</0> para usar o tamanho próprio do modelo."
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index 558313926..32ac761fc 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -164,6 +164,7 @@
"ڈسک پر موجود فولڈر اور وہ شناخت جو ایجنٹس اس مہارت کو بلانے کے لیے استعمال کرتے ہیں۔"
],
"1jym2J": ["یہ تبصرہ نہ بھیجیں"],
+ "1lFNz3": ["یہ دستاویز حذف کر دی گئی تھی"],
"1njn7W": ["روشن"],
"1nke1r": [["0"], " کو GitHub پر کھولیں (نئے ٹیب میں کھلتا ہے)"],
"1oSHI0": [["skillName"], " نصب نہیں ہو سکی: ", ["0"]],
@@ -1014,6 +1015,7 @@
"وہ GitHub اکاؤنٹ سنبھالیں جو OpenKnowledge آپ کی ریپازٹریز براؤز اور مطابق کرنے کے لیے استعمال کرتا ہے۔"
],
"E7BhZn": ["خالی نوٹ"],
+ "E91VZY": ["نئی ونڈو میں کھولیں"],
"E9bKSA": ["بنایا جا رہا ہے"],
"E9gh86": ["آپ زیادہ سے زیادہ ", ["MAX_ATTACHMENTS"], " تصاویر منسلک کر سکتے ہیں۔"],
"EARn6h": ["مہارتیں شیئر نہیں ہو سکیں — ", ["detail"], "۔"],
@@ -3781,6 +3783,7 @@
"nzHlj8": [["0"], " بند کریں"],
"nzaV6Q": ["صفحات کے تھمب نیلز"],
"o0bHtA": ["بذریعہ OpenKnowledge"],
+ "o1veZ6": ["اس دستاویز کو نئی ونڈو میں نہیں کھولا جا سکا۔"],
"o49mDZ": ["ٹائم لائن کی تاریخ لوڈ ہو رہی ہے"],
"o7AkQ0": ["حل شدہ دکھائیں"],
"o9CrsQ": ["research-note"],
@@ -4006,6 +4009,7 @@
"rbrHTd": ["منظور شدہ — ", ["optionName"]],
"rcJmK8": ["مقامات کو نقول میں بدلیں"],
"rdU729": ["خاکہ بندی"],
+ "rf8fiC": ["ونڈو بند کریں"],
"rfFpcF": [["chip"], " ہٹائیں"],
"rg7hNd": ["اپنے تجربے کی درجہ بندی کریں"],
"rgPqOw": ["موجودہ بلاک کو پیراگراف میں بدلیں۔"],
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index 7ca2b7745..86e84f5a1 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -2604,6 +2604,10 @@ msgstr "ٹرمینل بند کریں"
msgid "Close this chat's tab to delete it"
msgstr "اسے حذف کرنے کے لیے اس چیٹ کا ٹیب بند کریں"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "ونڈو بند کریں"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3294,6 +3298,10 @@ msgstr "فولڈر منتخب کنندہ نہیں کھل سکا"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "GitHub سائن اِن نہیں کھل سکا۔ براہِ کرم دوبارہ کوشش کریں۔"
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "اس دستاویز کو نئی ونڈو میں نہیں کھولا جا سکا۔"
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "سرور تک رسائی نہیں ہو سکی"
@@ -8618,6 +8626,11 @@ msgstr "ڈیفالٹ ایپ میں کھولیں"
msgid "Open in file manager"
msgstr "فائل مینیجر میں کھولیں"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "نئی ونڈو میں کھولیں"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "Slidev میں کھولیں"
@@ -12655,6 +12668,10 @@ msgstr "یہ دستاویز ایڈیٹر میں پہلے ہی فعال ہے۔ گ
msgid "This document is missing required properties"
msgstr "اس دستاویز میں مطلوبہ خصوصیات غائب ہیں"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "یہ دستاویز حذف کر دی گئی تھی"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "اس اینڈ پوائنٹ نے آپ کا مقرر کردہ ویکٹر حجم نظر انداز کر دیا۔ ماڈل کا اپنا حجم استعمال کرنے کے لیے <0>search.semantic.dimensions</0> ہٹا دیں۔"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index 8e3a41ba8..59ca5922d 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -147,6 +147,7 @@
"1di5fu": ["找不到文档"],
"1hvhf0": ["磁盘上的文件夹,以及智能体调用这个技能时使用的 id。"],
"1jym2J": ["不要发送这条评论"],
+ "1lFNz3": ["此文档已被删除"],
"1njn7W": ["浅色"],
"1nke1r": ["在 GitHub 上打开 ", ["0"], "(在新标签页中打开)"],
"1oSHI0": ["无法安装 ", ["skillName"], ":", ["0"]],
@@ -889,6 +890,7 @@
"E5WeIy": ["重新打开最近关闭的那个编辑器标签页。"],
"E6lrpp": ["管理 OpenKnowledge 用来浏览和同步你的仓库的 GitHub 账户。"],
"E7BhZn": ["空白笔记"],
+ "E91VZY": ["在新窗口中打开"],
"E9bKSA": ["正在创建"],
"E9gh86": ["你最多可以附加 ", ["MAX_ATTACHMENTS"], " 张图片。"],
"EARn6h": ["无法共享技能——", ["detail"], "。"],
@@ -3267,6 +3269,7 @@
"nzHlj8": ["关闭 ", ["0"]],
"nzaV6Q": ["页面缩略图"],
"o0bHtA": ["来自 OpenKnowledge"],
+ "o1veZ6": ["无法在新窗口中打开此文档。"],
"o49mDZ": ["正在加载时间线历史"],
"o7AkQ0": ["显示已解决"],
"o9CrsQ": ["research-note"],
@@ -3478,6 +3481,7 @@
"rbrHTd": ["已批准 — ", ["optionName"]],
"rcJmK8": ["把这些位置改为副本"],
"rdU729": ["布局"],
+ "rf8fiC": ["关闭窗口"],
"rfFpcF": ["移除 ", ["chip"]],
"rg7hNd": ["为你的体验打分"],
"rgPqOw": ["把当前块转换为段落。"],
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index e38c50a89..aa4a998cc 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -2604,6 +2604,10 @@ msgstr "关闭终端"
msgid "Close this chat's tab to delete it"
msgstr "关闭此对话的标签页后才能删除"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "关闭窗口"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3294,6 +3298,10 @@ msgstr "无法打开文件夹选择器"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "无法打开 GitHub 登录页。请重试。"
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "无法在新窗口中打开此文档。"
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "无法连接到服务器"
@@ -8618,6 +8626,11 @@ msgstr "用默认应用打开"
msgid "Open in file manager"
msgstr "在文件管理器中打开"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "在新窗口中打开"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "在 Slidev 中打开"
@@ -12655,6 +12668,10 @@ msgstr "这个文档已经在编辑器中打开了。请用「打开」来折叠
msgid "This document is missing required properties"
msgstr "这个文档缺少必需的属性"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "此文档已被删除"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "这个端点忽略了你配置的向量维度。移除 <0>search.semantic.dimensions</0> 即可使用模型自己的维度。"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index abad18430..c03b6a85d 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -147,6 +147,7 @@
"1di5fu": ["找不到文件"],
"1hvhf0": ["磁碟上的資料夾,以及代理呼叫這個技能時使用的 id。"],
"1jym2J": ["不要傳送這則註解"],
+ "1lFNz3": ["此文件已被刪除"],
"1njn7W": ["淺色"],
"1nke1r": ["在 GitHub 上開啟 ", ["0"], "(在新分頁中開啟)"],
"1oSHI0": ["無法安裝 ", ["skillName"], ":", ["0"]],
@@ -895,6 +896,7 @@
"E5WeIy": ["重新開啟最近關閉的那個編輯器分頁。"],
"E6lrpp": ["管理 OpenKnowledge 用來瀏覽和同步你的儲存庫的那個 GitHub 帳戶。"],
"E7BhZn": ["空白筆記"],
+ "E91VZY": ["在新視窗中開啟"],
"E9bKSA": ["正在建立"],
"E9gh86": ["你最多可以附加 ", ["MAX_ATTACHMENTS"], " 張圖片。"],
"EARn6h": ["無法分享技能——", ["detail"], "。"],
@@ -3293,6 +3295,7 @@
"nzHlj8": ["關閉 ", ["0"]],
"nzaV6Q": ["頁面縮圖"],
"o0bHtA": ["由 OpenKnowledge 提供"],
+ "o1veZ6": ["無法在新視窗中開啟此文件。"],
"o49mDZ": ["正在載入時間軸記錄"],
"o7AkQ0": ["顯示已解決"],
"o9CrsQ": ["research-note"],
@@ -3504,6 +3507,7 @@
"rbrHTd": ["已核准 — ", ["optionName"]],
"rcJmK8": ["把這些位置改成副本"],
"rdU729": ["版面配置"],
+ "rf8fiC": ["關閉視窗"],
"rfFpcF": ["移除 ", ["chip"]],
"rg7hNd": ["為你的體驗評分"],
"rgPqOw": ["把目前的區塊轉換成段落。"],
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index 38c41e7ee..69c7f3ded 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -2604,6 +2604,10 @@ msgstr "關閉終端機"
msgid "Close this chat's tab to delete it"
msgstr "關閉此對話的分頁後才能刪除"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "Close window"
+msgstr "關閉視窗"
+
#: src/components/AppMenubar.tsx
#: src/lib/native-menu-catalog.ts
msgid "Close Window"
@@ -3294,6 +3298,10 @@ msgstr "無法開啟資料夾選擇器"
msgid "Could not open GitHub sign-in. Please try again."
msgstr "無法開啟 GitHub 登入頁。請再試一次。"
+#: src/lib/open-note-window.ts
+msgid "Could not open this document in a new window."
+msgstr "無法在新視窗中開啟此文件。"
+
#: src/components/FileTree.tsx
msgid "Could not reach server"
msgstr "無法連上伺服器"
@@ -8618,6 +8626,11 @@ msgstr "用預設應用程式打開"
msgid "Open in file manager"
msgstr "在檔案管理程式中打開"
+#: src/components/command-palette-commands.ts
+#: src/components/EditorTabs.tsx
+msgid "Open in New Window"
+msgstr "在新視窗中開啟"
+
#: src/components/SlidesToolbarControls.tsx
msgid "Open in Slidev"
msgstr "在 Slidev 中開啟"
@@ -12655,6 +12668,10 @@ msgstr "這份文件已經在編輯器中開啟了。請用「開啟」來摺疊
msgid "This document is missing required properties"
msgstr "這份文件缺少必要的屬性"
+#: src/components/NoteWindowDeletedState.tsx
+msgid "This document was deleted"
+msgstr "此文件已被刪除"
+
#: src/components/settings/SearchSection.tsx
msgid "This endpoint ignored the vector size you configured. Remove <0>search.semantic.dimensions</0> to use the model's own size."
msgstr "這個端點忽略了你設定的向量維度。移除 <0>search.semantic.dimensions</0> 就會改用模型自己的維度。"
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 7a2eb1001..ef2b71eb7 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -486,6 +486,11 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
navigator: {
open: async () => {},
},
+ noteWindow: {
+ open: async () => ({ ok: true as const, outcome: 'created' as const }),
+ dispatchToMain: async () => ({ ok: true as const }),
+ onMainAction: () => () => {},
+ },
seed: {
plan: async () => ({ ok: false, error: { kind: 'no-project', message: 'test mock' } }),
apply: async () => ({ ok: false, error: { kind: 'no-project', message: 'test mock' } }),
diff --git a/packages/core/src/commands/command-identity.ts b/packages/core/src/commands/command-identity.ts
index 795cedb73..aac18b010 100644
--- a/packages/core/src/commands/command-identity.ts
+++ b/packages/core/src/commands/command-identity.ts
@@ -132,6 +132,7 @@ export type MenuSection =
| 'view-tree'
| 'view-history'
| 'terminal'
+ | 'window'
| 'help-install'
| 'help-links'
| 'help-updates';
@@ -318,6 +319,22 @@ export const COMMAND_IDENTITIES: readonly CommandIdentity[] = [
availability: { requiresActiveDoc: true },
palette: { group: 'commands', visibility: 'always' },
},
+ {
+ // Pops the active document into its own window. Desktop-only (it spawns a
+ // BrowserWindow) and needs a document to pop, so with neither the palette
+ // simply omits the row — the palette's availability mechanism hides, it has
+ // no disabled state. Hidden in a single-file session too: that window is
+ // already one document, so a second one adds nothing.
+ id: 'open-in-new-window',
+ labelKey: 'openInNewWindow',
+ keywords: ['pop out', 'detach', 'separate window', 'second monitor'],
+ availability: { host: 'desktop', requiresActiveDoc: true, singleFileHidden: true },
+ palette: { group: 'commands', visibility: 'always' },
+ // The Window menu is where every incumbent puts this, and unlike the
+ // palette a menu leaf DISABLES rather than hides, which is the right
+ // affordance for a menu the user opened deliberately.
+ menu: [{ section: 'window', order: 0 }],
+ },
{
id: 'initialize-starter-pack',
labelKey: 'initializeStarterPack',
diff --git a/packages/core/src/constants/menu-labels.ts b/packages/core/src/constants/menu-labels.ts
index f0df36c72..6e39d7ddb 100644
--- a/packages/core/src/constants/menu-labels.ts
+++ b/packages/core/src/constants/menu-labels.ts
@@ -89,6 +89,7 @@ export const MENU_LABELS = {
// Palette-only commands (no native-menu leaf); shared here so the label-parity
// test guards them and the registry keeps a single label source.
openGraph: 'Open graph',
+ openInNewWindow: 'Open in New Window',
blobRun: 'Blob Run',
initializeStarterPack: 'Initialize starter pack',
newSkill: 'New skill',
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index f452628c7..3d8d7b72c 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -64,6 +64,47 @@ export interface OkTerminalDockState {
agents?: { order: string[]; activeKey: string | null };
}
+/**
+ * A conversation or comments action started in a popped-out note window and
+ * handed back to the owning project window. The note renderer composes the
+ * same bounded prompt it would use locally; main only resolves/focuses the
+ * project window and forwards this typed intent.
+ */
+export type OkNoteWindowMainAction =
+ | {
+ readonly kind: 'active-input';
+ readonly text: string;
+ readonly newTab: boolean;
+ readonly submit: boolean;
+ readonly target?: 'agents';
+ }
+ | {
+ readonly kind: 'agent-thread';
+ readonly agentSource: 'registry' | 'custom';
+ readonly agentId: string;
+ readonly prompt: string | null;
+ readonly docName: string | null;
+ readonly titleHint: string | null;
+ }
+ | {
+ readonly kind: 'terminal-launch';
+ readonly prompt: string;
+ readonly cli: TerminalCli;
+ readonly stage: boolean;
+ }
+ | {
+ readonly kind: 'reveal-comments';
+ readonly docName: string;
+ readonly scope: 'doc' | 'queue';
+ };
+
+export type OkNoteWindowMainActionResult =
+ | { readonly ok: true }
+ | {
+ readonly ok: false;
+ readonly reason: 'invalid-action' | 'not-note-window' | 'project-not-open';
+ };
+
export type OkTerminalDockStateUpdate =
| {
surface: 'terminal';
@@ -85,7 +126,7 @@ export type OkTerminalDockStateWriteResult =
};
/** Render mode picked by the main process when creating a BrowserWindow. */
-export type OkDesktopMode = 'editor' | 'navigator' | 'terminal';
+export type OkDesktopMode = 'editor' | 'navigator' | 'terminal' | 'note';
/**
* Config values injected at preload-exposure time. A frozen snapshot, not a
@@ -103,7 +144,7 @@ export interface OkDesktopConfig {
readonly projectPath: string;
/** Display name for the project (usually basename of projectPath). */
readonly projectName: string;
- /** Render mode — `navigator` renders the Project Navigator, `editor` renders the doc editor, `terminal` renders the standalone terminal window. */
+ /** Render mode — `navigator` renders the Project Navigator, `editor` renders the doc editor, `terminal` renders the standalone terminal window, `note` renders a single popped-out document full-window. */
readonly mode: OkDesktopMode;
readonly e2eSmoke: boolean;
readonly singleFile: boolean;
@@ -1635,6 +1676,29 @@ export interface OkDesktopBridge {
open(): Promise<void>;
};
+ /** Popped-out single-document windows (`--ok-mode=note`). */
+ noteWindow: {
+ /**
+ * Pop `docName` out into its own window, or focus the window already
+ * showing it. `no-project` when the calling window has no project context.
+ */
+ open(
+ docName: string,
+ entryPoint: 'tab-menu' | 'palette',
+ ): Promise<
+ | { ok: true; outcome: 'created' | 'focused' }
+ | { ok: false; reason: 'no-project' | 'invalid-request' }
+ >;
+ /**
+ * Focus the owning project window and deliver a conversation/comments
+ * action there. Note-window renderers call this instead of opening chrome
+ * that deliberately does not exist in their reduced surface.
+ */
+ dispatchToMain(action: OkNoteWindowMainAction): Promise<OkNoteWindowMainActionResult>;
+ /** Receive a note-window action in the owning project renderer. */
+ onMainAction(cb: (action: OkNoteWindowMainAction) => void): OkUnsubscribe;
+ };
+
/**
* `ok seed` scaffolder surface consumed by the FileSidebar + menu.
* `plan()` is read-only and returns what the scaffolder would write;
diff --git a/packages/desktop/package.json b/packages/desktop/package.json
index 69b113417..81c36c0ce 100644
--- a/packages/desktop/package.json
+++ b/packages/desktop/package.json
@@ -29,6 +29,7 @@
"rebuild:native": "electron-builder install-app-deps",
"smoke:mock-update": "OK_UPDATER_FORCE_DEV=1 node scripts/smoke-mock-update.mjs",
"instances": "node scripts/launch-instances.mjs",
+ "lint": "biome check . && oxlint --max-warnings 0 .",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
diff --git a/packages/desktop/src/main/active-target-registry.test.ts b/packages/desktop/src/main/active-target-registry.test.ts
new file mode 100644
index 000000000..dcc22cac5
--- /dev/null
+++ b/packages/desktop/src/main/active-target-registry.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, test } from 'vitest';
+import {
+ createEmptyActiveTarget,
+ docNameFromActiveTarget,
+ EditorActiveTargetRegistry,
+} from './active-target-registry.ts';
+
+const WIN_A = 1;
+const WIN_B = 2;
+
+function doc(identifier: string) {
+ return { kind: 'doc' as const, identifier };
+}
+
+describe('EditorActiveTargetRegistry', () => {
+ test('an unknown window reads as no target', () => {
+ const registry = new EditorActiveTargetRegistry();
+ expect(registry.get(WIN_A)).toEqual(createEmptyActiveTarget());
+ });
+
+ test('two windows retain their own targets with no cross-clobber', () => {
+ // The regression this class exists for: one module-scope snapshot meant the
+ // last window to push owned the File menu's scope for every window.
+ const registry = new EditorActiveTargetRegistry();
+ registry.update(WIN_A, doc('notes/alpha'));
+ registry.update(WIN_B, doc('notes/beta'));
+
+ expect(registry.get(WIN_A)).toEqual(doc('notes/alpha'));
+ expect(registry.get(WIN_B)).toEqual(doc('notes/beta'));
+ });
+
+ test('current() follows the focused window, not the last pusher', () => {
+ const registry = new EditorActiveTargetRegistry();
+ registry.update(WIN_A, doc('notes/alpha'));
+ registry.update(WIN_B, doc('notes/beta'));
+
+ expect(registry.current(WIN_A)).toEqual(doc('notes/alpha'));
+ expect(registry.current(WIN_B)).toEqual(doc('notes/beta'));
+ });
+
+ test('current() falls back to the most recent pusher when nothing is focused', () => {
+ // A menu rebuild can land while the app is briefly unfocused; falling back
+ // to "no target" would flicker every scoped item to disabled.
+ const registry = new EditorActiveTargetRegistry();
+ registry.update(WIN_A, doc('notes/alpha'));
+ registry.update(WIN_B, doc('notes/beta'));
+
+ expect(registry.current(null)).toEqual(doc('notes/beta'));
+ });
+
+ test('an empty registry reads as no target even unfocused', () => {
+ expect(new EditorActiveTargetRegistry().current(null)).toEqual(createEmptyActiveTarget());
+ });
+
+ test('a later push replaces that window own target only', () => {
+ const registry = new EditorActiveTargetRegistry();
+ registry.update(WIN_A, doc('notes/alpha'));
+ registry.update(WIN_B, doc('notes/beta'));
+ registry.update(WIN_A, doc('notes/gamma'));
+
+ expect(registry.get(WIN_A)).toEqual(doc('notes/gamma'));
+ expect(registry.get(WIN_B)).toEqual(doc('notes/beta'));
+ });
+
+ test('deleting a window drops its target and its fallback claim', () => {
+ const registry = new EditorActiveTargetRegistry();
+ registry.update(WIN_A, doc('notes/alpha'));
+ registry.delete(WIN_A);
+
+ expect(registry.get(WIN_A)).toEqual(createEmptyActiveTarget());
+ expect(registry.current(null)).toEqual(createEmptyActiveTarget());
+ });
+
+ test('deleting one window leaves another window fallback intact', () => {
+ const registry = new EditorActiveTargetRegistry();
+ registry.update(WIN_A, doc('notes/alpha'));
+ registry.update(WIN_B, doc('notes/beta'));
+ registry.delete(WIN_A);
+
+ expect(registry.current(null)).toEqual(doc('notes/beta'));
+ });
+});
+
+describe('docNameFromActiveTarget', () => {
+ test('reads the document out of a doc target', () => {
+ expect(docNameFromActiveTarget(doc('notes/alpha'))).toBe('notes/alpha');
+ });
+
+ test('is null for a non-doc target', () => {
+ expect(docNameFromActiveTarget({ kind: 'folder', identifier: 'notes' })).toBeNull();
+ expect(docNameFromActiveTarget(createEmptyActiveTarget())).toBeNull();
+ });
+
+ test('is null for an empty identifier, which names no document', () => {
+ expect(docNameFromActiveTarget(doc(''))).toBeNull();
+ });
+});
diff --git a/packages/desktop/src/main/active-target-registry.ts b/packages/desktop/src/main/active-target-registry.ts
new file mode 100644
index 000000000..16b2ae06f
--- /dev/null
+++ b/packages/desktop/src/main/active-target-registry.ts
@@ -0,0 +1,64 @@
+/**
+ * Per-window store for the active-editor target the renderer pushes over
+ * `ok:editor:active-target-changed`.
+ *
+ * Keyed per window rather than a single module-scope snapshot because two
+ * windows on one project both push (popped-out note windows make this routine),
+ * and a last-write-wins snapshot would let whichever pushed last own the File
+ * menu's Rename / Duplicate / Move to Trash scope regardless of which window the
+ * user is looking at. Reading the FOCUSED window's target makes the menu track
+ * the window the user is in, and gives a note window a place to read its own
+ * current document from for its title.
+ *
+ * The application menu is a singleton (`Menu.setApplicationMenu` replaces the
+ * global menu), so it reflects exactly one window — which is why reading the
+ * focused window is the right resolution.
+ *
+ * Mirrors `EditorViewMenuStateRegistry`, which solves the same problem for
+ * view-menu state.
+ */
+
+import type { EditorActiveTargetSnapshot } from '../shared/ipc-channels.ts';
+
+/** What main assumes before any renderer push lands: no target, no scope. */
+export function createEmptyActiveTarget(): EditorActiveTargetSnapshot {
+ return { kind: null };
+}
+
+export class EditorActiveTargetRegistry {
+ readonly #targets = new Map<number, EditorActiveTargetSnapshot>();
+ /**
+ * Fallback for menu reads with no focused window — a menu can be rebuilt
+ * while the app is briefly unfocused (a dialog, a Space switch), and falling
+ * back to "no target" there would flicker every scoped item to disabled.
+ */
+ #selectedWindowId: number | null = null;
+
+ update(windowId: number, target: EditorActiveTargetSnapshot): void {
+ this.#targets.set(windowId, target);
+ this.#selectedWindowId = windowId;
+ }
+
+ get(windowId: number): EditorActiveTargetSnapshot {
+ return this.#targets.get(windowId) ?? createEmptyActiveTarget();
+ }
+
+ /** The focused window's target, else the most recent pusher's. */
+ current(focusedWindowId: number | null = null): EditorActiveTargetSnapshot {
+ const windowId = focusedWindowId ?? this.#selectedWindowId;
+ return windowId === null ? createEmptyActiveTarget() : this.get(windowId);
+ }
+
+ delete(windowId: number): void {
+ this.#targets.delete(windowId);
+ if (this.#selectedWindowId === windowId) this.#selectedWindowId = null;
+ }
+}
+
+/**
+ * The document a target snapshot points at, or null for any non-doc target.
+ * A note window's title and its registry identity both track this.
+ */
+export function docNameFromActiveTarget(target: EditorActiveTargetSnapshot): string | null {
+ return target.kind === 'doc' && target.identifier.length > 0 ? target.identifier : null;
+}
diff --git a/packages/desktop/src/main/boot-restore-decision.test.ts b/packages/desktop/src/main/boot-restore-decision.test.ts
index 4051d27cc..59ea348fe 100644
--- a/packages/desktop/src/main/boot-restore-decision.test.ts
+++ b/packages/desktop/src/main/boot-restore-decision.test.ts
@@ -264,3 +264,58 @@ describe('resolveRestoreActions (file→project collapse + dedup ordering)', ()
expect(actionByKey.size).toBe(0);
});
});
+
+describe('resolveRestoreActions (popped-out note windows)', () => {
+ const identity = (filePath: string): RestoredWindow => ({ kind: 'file', filePath });
+ const PROJECT: RestoredWindow = { kind: 'project', projectPath: '/tmp/a' };
+ const DOC: RestoredWindow = { kind: 'doc', projectPath: '/tmp/a', docName: 'notes/alpha' };
+
+ test('a pop-out opens after its project, whatever the focus order said', () => {
+ // The open loop is sequential, so this ordering is what gives the pop-out a
+ // server to attach to. Focus recency put the pop-out first here.
+ const { orderedKeys } = resolveRestoreActions([DOC, PROJECT], identity);
+
+ expect(orderedKeys).toHaveLength(2);
+ expect(orderedKeys[0]).toBe('/tmp/a');
+ expect(orderedKeys[1]).toContain('notes/alpha');
+ });
+
+ test('a pop-out whose project is absent is dropped silently', () => {
+ // The project was removed, or its window did not survive. A lone pop-out
+ // has nothing to attach to, and an error window for a document the user
+ // did not ask to reopen is worse than its absence.
+ const { orderedKeys, actionByKey } = resolveRestoreActions([DOC], identity);
+
+ expect(orderedKeys).toEqual([]);
+ expect(actionByKey.size).toBe(0);
+ });
+
+ test('a pop-out of another project is dropped while its sibling survives', () => {
+ const other: RestoredWindow = { kind: 'doc', projectPath: '/tmp/gone', docName: 'notes/x' };
+ const { orderedKeys } = resolveRestoreActions([PROJECT, DOC, other], identity);
+
+ expect(orderedKeys).toHaveLength(2);
+ expect(orderedKeys.some((k) => k.includes('notes/x'))).toBe(false);
+ });
+
+ test('several pop-outs of one project keep their relative focus order', () => {
+ const beta: RestoredWindow = { kind: 'doc', projectPath: '/tmp/a', docName: 'notes/beta' };
+ const { orderedKeys } = resolveRestoreActions([beta, PROJECT, DOC], identity);
+
+ expect(orderedKeys[0]).toBe('/tmp/a');
+ expect(orderedKeys[1]).toContain('notes/beta');
+ expect(orderedKeys[2]).toContain('notes/alpha');
+ });
+
+ test('two pop-outs of one project both restore', () => {
+ const beta: RestoredWindow = { kind: 'doc', projectPath: '/tmp/a', docName: 'notes/beta' };
+ const { actionByKey } = resolveRestoreActions([PROJECT, DOC, beta], identity);
+
+ expect(actionByKey.size).toBe(3);
+ });
+
+ test('a project with no pop-outs is untouched', () => {
+ const { orderedKeys } = resolveRestoreActions([PROJECT], identity);
+ expect(orderedKeys).toEqual(['/tmp/a']);
+ });
+});
diff --git a/packages/desktop/src/main/boot-restore-decision.ts b/packages/desktop/src/main/boot-restore-decision.ts
index 08bf12e4d..1130c3ac1 100644
--- a/packages/desktop/src/main/boot-restore-decision.ts
+++ b/packages/desktop/src/main/boot-restore-decision.ts
@@ -1,4 +1,4 @@
-import { type RestoredWindow, windowRestoreKey } from './state-store.ts';
+import { type RestoredWindow, restoreSurvivorPath, windowRestoreKey } from './state-store.ts';
export interface BootRestoreInput {
pendingRestore: RestoredWindow[] | null;
@@ -45,7 +45,7 @@ export function bootRestoreDecision(input: BootRestoreInput): BootRestoreDecisio
// decision only survivor-filters.
const restorable =
pendingRestore !== null && !optionHeld
- ? pendingRestore.filter((w) => pathExists(windowRestoreKey(w)))
+ ? pendingRestore.filter((w) => pathExists(restoreSurvivorPath(w)))
: [];
if (restorable.length > 0) {
@@ -103,7 +103,37 @@ export function resolveRestoreActions(
orderedKeys.push(key);
actionByKey.set(key, action);
}
- return { orderedKeys, actionByKey };
+
+ // A pop-out attaches to its project's server, so it can only restore if that
+ // project restores too. An orphan is dropped SILENTLY: the user removed the
+ // project or its window did not survive, and an error window for a document
+ // they did not ask to reopen would be worse than its absence.
+ //
+ // Surviving pop-outs then sort after every project window. The open loop is
+ // sequential, so this is what makes "project first" true rather than
+ // incidental — a pop-out opened before its project would have no server to
+ // attach to. Within each group the focus order above is preserved, so the
+ // final key is still the raise target.
+ const restoredProjects = new Set(
+ [...actionByKey.values()]
+ .filter(
+ (action): action is Extract<RestoredWindow, { kind: 'project' }> =>
+ action.kind === 'project',
+ )
+ .map((action) => action.projectPath),
+ );
+ const projectKeys: string[] = [];
+ const docKeys: string[] = [];
+ for (const key of orderedKeys) {
+ const action = actionByKey.get(key);
+ if (action?.kind !== 'doc') {
+ projectKeys.push(key);
+ continue;
+ }
+ if (restoredProjects.has(action.projectPath)) docKeys.push(key);
+ else actionByKey.delete(key);
+ }
+ return { orderedKeys: [...projectKeys, ...docKeys], actionByKey };
}
/**
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 5eb4fd4ae..8f2f0e73c 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -163,10 +163,12 @@ import { registerPendingDelivery, sendToRenderer } from '../shared/ipc-send.ts';
import { UNINSTALL_PRELOAD_ARG } from '../shared/uninstall-preload-arg.ts';
import { resolveShell } from '../utility/pty-host.ts';
import { buildAboutPanelOptions } from './about-panel.ts';
+import { docNameFromActiveTarget, EditorActiveTargetRegistry } from './active-target-registry.ts';
import { appendOkIgnoreSync } from './append-okignore.ts';
import { registerAppImageDeepLinks } from './appimage-integration.ts';
import { openAssetSafely, revealAssetSafely } from './asset-allowlist.ts';
import { popAssetMenu, revealMenuLabel } from './asset-menu.ts';
+import { attachAssetSafetyNet } from './asset-safety-net.ts';
import { resolveEffectiveInstanceName } from './auto-instance.ts';
import {
bootAutoUpdater,
@@ -297,7 +299,7 @@ import {
spawnCursor as spawnCursorImpl,
trashItem as trashItemImpl,
} from './ipc-handlers.ts';
-import { logIpcError } from './ipc-log.ts';
+import { logIpcError, withIpcErrorLogging } from './ipc-log.ts';
import { createDesktopKeepaliveFactory, toKeepaliveLogger } from './keepalive.ts';
import {
detectGraphicalAuthCommand,
@@ -315,6 +317,25 @@ import {
import { installApplicationMenu } from './menu.ts';
import type { MenuTranslator } from './menu-translator.ts';
import { beginNavigatorHandoff, createNavigatorWindow } from './navigator-window.ts';
+import {
+ closeNoteWindowsForProject,
+ dispatchNoteWindowMainActionToProject,
+ type NoteBrowserWindow,
+ type NoteWindowProject,
+ noteWindowNativeChromeOptions,
+ noteWindowTitle,
+ openNoteWindow,
+ resolveNoteWindowProject,
+ resolveWindowProjectScope,
+} from './note-window.ts';
+import {
+ getNoteWindowContext,
+ listNoteWindows,
+ listNoteWindowsForProject,
+ type NoteWindowEntryPoint,
+ setNoteWindowDoc,
+ touchNoteWindow,
+} from './note-window-registry.ts';
import { runOkInit } from './ok-init.ts';
import {
type OnboardingFlowKind,
@@ -344,6 +365,7 @@ import {
applyReducedTransparency,
type BrowserWindowVibrancyTarget,
type ReducedTransparencyDeps,
+ setPreferredWindowVibrancy,
type VibrancyMaterial,
} from './reduced-transparency-handler.ts';
import { removeGitFolder } from './remove-git-folder.ts';
@@ -390,14 +412,17 @@ import {
normalizeTerminalRestartSnapshot,
type PersistedWindowBounds,
parseAppState,
+ type RestoredWindow,
removeRecentProject,
type SchemaIncompatibilityDiagnostic,
saveAppStateToDir,
setLastUsedProjectParent,
+ setNoteWindowBounds,
setProjectSessionState,
setProjectWindowBounds,
setSpellCheckEnabled as setSpellCheckEnabledState,
type UpdateChannel,
+ windowRestoreKey,
} from './state-store.ts';
import { isTerminalConsented, isTerminalConsentedWithGrace } from './terminal-consent.ts';
import { commitTerminalDockState } from './terminal-dock-persistence.ts';
@@ -492,9 +517,7 @@ import {
// Default vibrancy material — `VibrancyMaterial` is the canonical narrow
// union from `reduced-transparency-handler.ts`. Pinning here lets the
// prefers-reduced-transparency restore path re-enable to the same material
-// without a wider cast. `'sidebar'` is the chosen material; `'window'` is
-// the documented fallback if the Electron #27882 border quirk recurs on a
-// future Electron upgrade.
+// without a wider cast.
const VIBRANCY_DEFAULT: VibrancyMaterial = 'sidebar';
const AGENTS_HUB_DIR = AGENTS_SKILLS_ROOT.split('/')[0] ?? '.agents';
@@ -635,6 +658,89 @@ function applyProjectWindowPlacement(win: BrowserWindow, projectPath: string | u
registerCascadeAnchor(win);
}
+/**
+ * Place a note window at its project's remembered frame, or cascade.
+ *
+ * Cascades rather than reusing the frame when another note window for the same
+ * project is already sitting there — stacking a second pop-out exactly on top of
+ * the first reads as nothing having happened. The remembered frame also goes
+ * through the same display-intersection gate as project windows, so a frame
+ * saved on a monitor that is no longer connected falls back to cascade instead
+ * of opening off-screen.
+ */
+function applyNoteWindowPlacement(
+ win: BrowserWindow,
+ projectRoot: string,
+ restoredBounds?: PersistedWindowBounds,
+): void {
+ // A restored window owns its recorded frame outright: it was positioned
+ // individually, and the collision check below is about NEW pop-outs stacking,
+ // which does not apply to putting a saved layout back.
+ const saved = restoredBounds ?? appState.noteWindowBounds[projectRoot];
+ const occupied =
+ restoredBounds === undefined &&
+ listNoteWindowsForProject(projectRoot).some((windowId) => {
+ if (windowId === win.id) return false;
+ return BrowserWindow.fromId(windowId)?.isDestroyed() === false;
+ });
+ const placement = occupied
+ ? null
+ : resolveRestoredPlacement({
+ saved,
+ workAreas: screen.getAllDisplays().map((d) => d.workArea),
+ minSize: WINDOW_MIN_SIZE.EDITOR,
+ });
+ if (!placement) {
+ applyCascadePosition(win);
+ return;
+ }
+ win.setBounds(placement.bounds);
+ registerCascadeAnchor(win);
+}
+
+/**
+ * Track a note window's focus, for two consumers that both need "most recently
+ * used": the restore snapshot's ordering, and the registry's tiebreak when
+ * in-place navigation lands two windows on one (project, document) identity.
+ *
+ * Keyed on the window's CURRENT document, read at focus time rather than
+ * captured at creation, so a window that navigated is ordered under the
+ * identity it actually has.
+ */
+function trackNoteWindowFocus(win: BrowserWindow): void {
+ win.on('focus', () => {
+ if (win.isDestroyed()) return;
+ touchNoteWindow(win.id);
+ editorViewMenuStates.select(win.id);
+ refreshApplicationMenu();
+ const context = getNoteWindowContext(win.id);
+ if (!context) return;
+ recordWindowFocusSeq(
+ windowRestoreKey({
+ kind: 'doc',
+ projectPath: context.projectRoot,
+ docName: context.currentDocName,
+ }),
+ );
+ });
+}
+
+/** Persist a note window's frame as its project's remembered pop-out slot. */
+function trackNoteWindowBounds(win: BrowserWindow, projectRoot: string): void {
+ const persist = () => {
+ if (win.isDestroyed()) return;
+ appState = setNoteWindowBounds(appState, projectRoot, {
+ ...win.getNormalBounds(),
+ isMaximized: win.isMaximized(),
+ isFullScreen: win.isFullScreen(),
+ });
+ saveAppState(appState);
+ };
+ win.on('moved', persist);
+ win.on('resized', persist);
+ win.on('close', persist);
+}
+
/**
* Persist a project window's frame so the next open of the same project
* restores it. macOS emits `'moved'` / `'resized'` once per completed drag
@@ -734,7 +840,32 @@ let windowRestoreSnapshotWritten = false;
function captureWindowRestoreSnapshot(reason: string): void {
if (windowRestoreSnapshotWritten) return;
windowRestoreSnapshotWritten = true;
- const windows = sortWindowsByFocusSequence(wm?.getOpenWindows() ?? [], projectFocusSeq);
+ // Note windows live outside `windowsByPath`, so `getOpenWindows()` cannot see
+ // them — they come from their own registry. Each carries the document it is
+ // showing NOW (in-place navigation may have moved it off the one it opened
+ // with) and its own frame. Both sets sort together, so focus recency is
+ // global; the boot filter re-groups projects ahead of pop-outs at open time
+ // while preserving that order within each group.
+ const noteWindows: RestoredWindow[] = listNoteWindows().flatMap(({ windowId, context }) => {
+ const win = BrowserWindow.fromId(windowId);
+ if (!win || win.isDestroyed()) return [];
+ return [
+ {
+ kind: 'doc' as const,
+ projectPath: context.projectRoot,
+ docName: context.currentDocName,
+ bounds: {
+ ...win.getNormalBounds(),
+ isMaximized: win.isMaximized(),
+ isFullScreen: win.isFullScreen(),
+ },
+ },
+ ];
+ });
+ const windows = sortWindowsByFocusSequence(
+ [...(wm?.getOpenWindows() ?? []), ...noteWindows],
+ projectFocusSeq,
+ );
appState = { ...appState, pendingWindowRestore: windows };
if (!saveAppState(appState)) {
// Persist failed — the next boot may not reopen everything that was open.
@@ -1305,12 +1436,19 @@ const bugReportSidecar = createBugReportSidecarStore({
* folder / asset / null state, main rebuilds the menu so Rename /
* Duplicate / Move to Trash flip enabled/disabled per scope.
*
- * Module-scope rather than per-window because the menu is a singleton
- * (`Menu.setApplicationMenu` replaces the global menu). Last-write-wins
- * across multiple project windows — matches the existing recent-projects
- * pattern at `appState.recentProjects`.
+ * Keyed per window even though the menu is a singleton
+ * (`Menu.setApplicationMenu` replaces the global menu), because reads take the
+ * FOCUSED window's target. One shared snapshot was survivable while every
+ * editor window was its own project, but popped-out note windows put two
+ * windows on one project: whichever pushed last would own the File menu's scope
+ * regardless of which window the user was looking at.
*/
-let editorActiveTarget: EditorActiveTargetSnapshot = { kind: null };
+const editorActiveTargets = new EditorActiveTargetRegistry();
+
+/** The active target the application menu should reflect right now. */
+function currentActiveTarget(): EditorActiveTargetSnapshot {
+ return editorActiveTargets.current(BrowserWindow.getFocusedWindow()?.id ?? null);
+}
/**
* View-menu state pushed by the renderer via
@@ -1482,7 +1620,36 @@ function ensureWindowManager() {
trackEphemeralWindowFocus(win, opts.focusKey);
}
attachSpellcheckMenuToWindow(win);
- win.on('closed', () => editorViewMenuStates.delete(win.id));
+ win.on('closed', () => {
+ editorViewMenuStates.delete(win.id);
+ // Drop the window's active target too, so a closed window cannot keep
+ // supplying the menu's fallback scope after it is gone.
+ editorActiveTargets.delete(win.id);
+ });
+ // A project's popped-out note windows close with its main window: they
+ // never survive as independents. In dev the project's forked server dies
+ // with this window, so a surviving pop-out's argv-frozen collab URL could
+ // never reach a respawned server — an unrecoverable orphan.
+ //
+ // `windowRestoreSnapshotWritten` is the quit discriminator. Every clean-
+ // exit path captures the restore snapshot at its earliest teardown hook,
+ // which precedes this cascade, so on quit the note windows are already
+ // recorded and come back next launch. A mid-session project close finds
+ // the flag false and they are gone for good.
+ if (opts.projectPath !== undefined) {
+ const noteProjectRoot = opts.projectPath;
+ win.on('closed', () => {
+ closeNoteWindowsForProject({
+ projectRoot: noteProjectRoot,
+ reason: windowRestoreSnapshotWritten ? 'quit' : 'project-close',
+ closingProjectWindow: win as unknown as BrowserWindowLike,
+ activeProjectWindow: wm?.getWindowFor(noteProjectRoot)?.window,
+ closeWindowById: (windowId) => {
+ BrowserWindow.fromId(windowId)?.close();
+ },
+ });
+ });
+ }
// Per-window PTY reap: closing the window kills its shell (no orphan).
// Idempotent — the manager no-ops for a window that never opened one. The
// onReap clears the window's retained dock-visibility so it can't restore
@@ -1760,6 +1927,9 @@ function ensureWindowManager() {
onUtilityMessage: (msg) => {
ensureDebugIpc().handleUtilityMessage(msg);
},
+ onProjectServerRestarted: ({ projectPath, apiOrigin }) => {
+ recreateNoteWindowsForProject(projectPath, apiOrigin);
+ },
onUtilityExit: (utility) => {
ensureDebugIpc().cancelPendingForUtility(utility);
},
@@ -2855,7 +3025,8 @@ function applyMenuDispatchRole(role: MenuDispatchRole, sender: Electron.WebConte
}
async function runApplicationMenuRefresh(): Promise<void> {
- const focusedWindowId = BrowserWindow.getFocusedWindow()?.id ?? null;
+ const focusedWindow = BrowserWindow.getFocusedWindow();
+ const focusedWindowId = focusedWindow?.id ?? null;
const editorViewMenuState = editorViewMenuStates.current(focusedWindowId);
// installApplicationMenu is async because it dynamically imports
// `electron.Menu` (see menu.ts header — keeps `buildMenuTemplate`
@@ -2968,6 +3139,7 @@ async function runApplicationMenuRefresh(): Promise<void> {
// View menu history traversal uses the same focused-renderer action channel.
onNavigateBack: () => sendMenuActionToFocused('navigate-back'),
onNavigateForward: () => sendMenuActionToFocused('navigate-forward'),
+ noteWindow: focusedWindow !== null && getNoteWindowContext(focusedWindow.id) !== undefined,
// File menu state-aware items. activeTarget drives enable/disable;
// per-item handlers fire `ok:menu-action` to the focused renderer which
// already knows the current scope (sidebar selection + editor
@@ -2975,7 +3147,16 @@ async function runApplicationMenuRefresh(): Promise<void> {
// primitives the sidebar context menus invoke). Routes through the
// existing `onMenuAction` channel so there's no new IPC surface for the
// renderer to subscribe to.
- activeTarget: editorActiveTarget,
+ activeTarget: currentActiveTarget(),
+ // Main-originated, unlike the tab menu and the palette: main already knows
+ // the focused window and its active document, so there is nothing to ask
+ // the renderer for and no channel to add.
+ onOpenInNewWindow: () => {
+ const focused = BrowserWindow.getFocusedWindow();
+ const docName = docNameFromActiveTarget(editorActiveTargets.current(focused?.id ?? null));
+ if (!docName) return;
+ openNoteWindowForDoc({ origin: focused, docName, entryPoint: 'window-menu' });
+ },
onNewFile: () => sendMenuActionToFocused('new-doc'),
onNewFolder: () => sendMenuActionToFocused('new-folder'),
onNewFromTemplate: () => sendMenuActionToFocused('new-from-template'),
@@ -3771,6 +3952,7 @@ function openTerminalWindow(): void {
const project = resolveTerminalWindowProject({
editor: editorCtx ?? null,
terminal: focused ? getTerminalWindowContext(focused.id) : undefined,
+ note: focused ? getNoteWindowContext(focused.id) : undefined,
});
const rendererEntryPath = app.isPackaged
? join(process.resourcesPath, 'app', 'index.html')
@@ -3807,6 +3989,242 @@ function openTerminalWindow(): void {
recordTerminalWindowOpened();
}
+/**
+ * Reopen one popped-out window from a relaunch snapshot, after its project's
+ * window and server are up.
+ *
+ * Declines silently when the project did not come up after all — the boot
+ * filter already dropped entries whose project was absent from the snapshot,
+ * but a project window can still fail to open, and a lone pop-out with nothing
+ * to attach to is worse than a missing one. A document deleted while the app
+ * was closed still opens: the window shows the deleted state, which tells the
+ * user what happened instead of quietly dropping a window they left open.
+ */
+function restoreNoteWindow(entry: {
+ readonly projectPath: string;
+ readonly docName: string;
+ readonly bounds?: PersistedWindowBounds;
+}): void {
+ const ctx = wm?.getWindowFor(entry.projectPath);
+ if (!ctx) return;
+ openNoteWindowForDoc({
+ origin: null,
+ docName: entry.docName,
+ // No entryPoint: a restore is not an adoption.
+ project: {
+ projectPath: ctx.projectPath,
+ projectName: ctx.projectName,
+ collabUrl: collabUrlFromApiOrigin(ctx.apiOrigin),
+ apiOrigin: ctx.apiOrigin,
+ },
+ restoredBounds: entry.bounds,
+ });
+}
+
+/**
+ * Recreate a project's note windows against its freshly restarted server.
+ *
+ * A note window's attach argv is a frozen snapshot taken at creation, so after
+ * a restart it still points at the terminated server — and the replacement
+ * usually binds a different port, so the old window could never reconnect on
+ * its own. Closing and reopening on the current scope is the whole fix; the
+ * documents come back because each window's CURRENT document is read from the
+ * registry, not its birth document.
+ */
+function recreateNoteWindowsForProject(projectRoot: string, apiOrigin: string): void {
+ const docNames = listNoteWindowsForProject(projectRoot)
+ .map((windowId) => getNoteWindowContext(windowId)?.currentDocName)
+ .filter((docName): docName is string => docName !== undefined);
+ if (docNames.length === 0) return;
+
+ closeNoteWindowsForProject({
+ projectRoot,
+ // Not a quit and not a user closing the project: the windows are coming
+ // straight back, so neither the restore snapshot nor a teardown applies.
+ reason: 'project-close',
+ closeWindowById: (windowId) => {
+ BrowserWindow.fromId(windowId)?.close();
+ },
+ });
+
+ const project: NoteWindowProject = {
+ projectPath: projectRoot,
+ projectName: basename(projectRoot),
+ collabUrl: collabUrlFromApiOrigin(apiOrigin),
+ apiOrigin,
+ };
+ for (const docName of docNames) {
+ // Isolate each recreate: the windows were already closed above, so a throw
+ // on one (a `BrowserWindow` constructor failure, say) would otherwise lose
+ // every pop-out after it. No entryPoint: the app is putting back what was
+ // already open, so this must not count as an adoption.
+ try {
+ openNoteWindowForDoc({ origin: null, docName, project });
+ } catch (err) {
+ getLogger('note-window').warn(
+ { err, projectRoot, docName },
+ 'failed to recreate a note window after server restart',
+ );
+ }
+ }
+}
+
+/**
+ * The project scope a window's main-side actions operate against, resolving an
+ * editor window through `windowsByPath` and a note window through the note
+ * registry. See `resolveWindowProjectScope` for why the fallback exists.
+ */
+function windowProjectScope(win: BrowserWindow | null): {
+ projectPath: string | undefined;
+ apiOrigin: string | undefined;
+} {
+ if (!win) return { projectPath: undefined, apiOrigin: undefined };
+ return resolveWindowProjectScope({
+ editor: wm?.getContextForBrowserWindow(win as unknown as BrowserWindowLike),
+ note: getNoteWindowContext(win.id),
+ });
+}
+
+/** The project path for a window, for the containment-gated shell handlers. */
+function windowProjectPath(win: BrowserWindow | null): string | undefined {
+ return windowProjectScope(win).projectPath;
+}
+
+/**
+ * Keep a note window's title and its dedup identity on the document it is
+ * actually showing.
+ *
+ * A note window is single-document, but not fixed to the document it was born
+ * with: wiki links navigate it in place, and a rename retargets it. Both arrive
+ * here as an active-target push, which is why the title rides this existing
+ * channel instead of a new one.
+ *
+ * No-ops for every other window kind. A non-doc target (the window is showing a
+ * folder or an asset, reachable through in-place navigation) leaves the title
+ * alone rather than blanking it — a stale-but-real name beats an empty title
+ * bar.
+ */
+function applyNoteWindowTargetChange(win: BrowserWindow, target: EditorActiveTargetSnapshot): void {
+ if (getNoteWindowContext(win.id) === undefined) return;
+ const docName = docNameFromActiveTarget(target);
+ if (!docName) return;
+ setNoteWindowDoc(win.id, docName);
+ if (!win.isDestroyed()) win.setTitle(noteWindowTitle(docName));
+}
+
+/**
+ * Pop a document into its own `--ok-mode=note` window, or focus the window
+ * already showing it.
+ *
+ * One helper behind all three entry points: the doc-tab context menu and the
+ * palette reach it through `ok:window:open-note`, the Window menu calls it
+ * directly in main. `origin` is the invoking window, which supplies the project
+ * — an editor window through `windowsByPath`, or another note window through
+ * the registry so popping out from inside a pop-out works.
+ */
+function openNoteWindowForDoc(args: {
+ readonly origin: BrowserWindow | null;
+ readonly docName: string;
+ /** Undefined for opens the user did not initiate (a restart recreate). */
+ readonly entryPoint?: NoteWindowEntryPoint;
+ /** An explicit project, for callers with no origin window to resolve from. */
+ readonly project?: NoteWindowProject;
+ /** This window's OWN frame from a relaunch snapshot, which beats the
+ * per-project slot: each pop-out was positioned individually. */
+ readonly restoredBounds?: PersistedWindowBounds;
+}): { ok: true; outcome: 'created' | 'focused' } | { ok: false; reason: 'no-project' } {
+ const { origin, docName, entryPoint } = args;
+ const editorCtx =
+ origin && wm ? wm.getContextForBrowserWindow(origin as unknown as BrowserWindowLike) : null;
+ const project =
+ args.project ??
+ resolveNoteWindowProject({
+ editor: editorCtx ?? null,
+ note: origin ? getNoteWindowContext(origin.id) : undefined,
+ collabUrlFromApiOrigin,
+ projectNameFromPath: (projectPath) => basename(projectPath),
+ });
+ if (!project) return { ok: false, reason: 'no-project' };
+
+ const rendererEntryPath = app.isPackaged
+ ? join(process.resourcesPath, 'app', 'index.html')
+ : join(__dirname, '../renderer/index.html');
+ const nativeChrome = noteWindowNativeChromeOptions(process.platform);
+
+ const result = openNoteWindow({
+ createWindow: (opts) => {
+ const win = new BrowserWindow({
+ ...DEFAULT_WIN_OPTS,
+ ...nativeChrome,
+ minWidth: WINDOW_MIN_SIZE.EDITOR.width,
+ minHeight: WINDOW_MIN_SIZE.EDITOR.height,
+ title: opts.title,
+ webPreferences: {
+ ...DEFAULT_WIN_OPTS.webPreferences,
+ additionalArguments: withDebugFlagIfAllowed(opts.additionalArguments),
+ preload: join(__dirname, '../preload/index.js'),
+ },
+ });
+ // Main owns the title so it can track the displayed document; the
+ // renderer's static <title> must not overwrite it (same as every other
+ // window factory).
+ win.on('page-title-updated', (e) => {
+ e.preventDefault();
+ });
+ if (nativeChrome.vibrancy !== undefined) {
+ setPreferredWindowVibrancy(win, nativeChrome.vibrancy);
+ }
+ attachSpellcheckMenuToWindow(win);
+ return win as unknown as NoteBrowserWindow;
+ },
+ rendererEntryPath,
+ rendererDevUrl,
+ appVersion: app.getVersion(),
+ showGate,
+ project,
+ docName,
+ entryPoint,
+ // Same external-link net every editor window gets from
+ // `WindowManager.attachSafetyNet`, wired here because a note window is
+ // created outside the window manager. `openExternal` is window-independent;
+ // `openAsset` is scoped to this window's project so containment resolves
+ // against the right root.
+ attachSafetyNet: (win) =>
+ attachAssetSafetyNet(win.webContents, {
+ editorOrigin: project.apiOrigin,
+ openExternal: handleShellOpenExternal({
+ openExternal: (url) => shell.openExternal(url),
+ }),
+ openAsset: (relPath) =>
+ openAssetSafely(
+ {
+ projectPath: project.projectPath,
+ platform: process.platform,
+ openPath: (canonical) => shell.openPath(canonical),
+ },
+ relPath,
+ ),
+ }),
+ placeWindow: (win) => {
+ const browserWindow = win as unknown as BrowserWindow;
+ applyNoteWindowPlacement(browserWindow, project.projectPath, args.restoredBounds);
+ trackNoteWindowBounds(browserWindow, project.projectPath);
+ trackNoteWindowFocus(browserWindow);
+ },
+ onClosed: (windowId) => {
+ editorActiveTargets.delete(windowId);
+ },
+ focusWindowById: (windowId) => {
+ const win = BrowserWindow.fromId(windowId);
+ if (!win || win.isDestroyed()) return false;
+ if (win.isMinimized()) win.restore();
+ win.focus();
+ return true;
+ },
+ });
+ return { ok: true, outcome: result.outcome };
+}
+
/**
* Arm first-launch MCP consent. Extracted as a helper so both the
* `app.whenReady()` path (once-per-boot marker-respecting) AND the
@@ -4685,10 +5103,7 @@ function registerIpcHandlers() {
// validateSpawnPath + isPathWithinProject checks inside the impl refuse
// any out-of-scope path when a project IS bound.
const callerWin = BrowserWindow.fromWebContents(event.sender);
- const callerProjectPath =
- callerWin && wm
- ? wm.getContextForBrowserWindow(callerWin as unknown as BrowserWindowLike)?.projectPath
- : undefined;
+ const callerProjectPath = windowProjectPath(callerWin);
const outcome = await spawnCursorImpl(
{
platform: process.platform,
@@ -4749,10 +5164,7 @@ function registerIpcHandlers() {
// asset scope.
handle('ok:shell:open-asset', async (event, relPath) => {
const callerWin = BrowserWindow.fromWebContents(event.sender);
- const callerProjectPath =
- callerWin && wm
- ? wm.getContextForBrowserWindow(callerWin as unknown as BrowserWindowLike)?.projectPath
- : undefined;
+ const callerProjectPath = windowProjectPath(callerWin);
if (!callerProjectPath) {
logIpcError({
event: 'ipc.error',
@@ -4783,10 +5195,7 @@ function registerIpcHandlers() {
handle('ok:shell:reveal-asset', async (event, relPath) => {
const callerWin = BrowserWindow.fromWebContents(event.sender);
- const callerProjectPath =
- callerWin && wm
- ? wm.getContextForBrowserWindow(callerWin as unknown as BrowserWindowLike)?.projectPath
- : undefined;
+ const callerProjectPath = windowProjectPath(callerWin);
if (!callerProjectPath) {
logIpcError({
event: 'ipc.error',
@@ -4826,9 +5235,7 @@ function registerIpcHandlers() {
handle('ok:shell:show-asset-menu', async (event, params) => {
const callerWin = BrowserWindow.fromWebContents(event.sender);
if (!callerWin || !wm) return undefined;
- const projectPath = wm.getContextForBrowserWindow(
- callerWin as unknown as BrowserWindowLike,
- )?.projectPath;
+ const projectPath = windowProjectPath(callerWin);
if (!projectPath) return undefined;
popAssetMenu(
{
@@ -4873,10 +5280,7 @@ function registerIpcHandlers() {
// Resolve caller window's project directory (undefined for Navigator).
// Validation, refusal, and security rationale live in `showItemInFolderImpl`.
const callerWin = BrowserWindow.fromWebContents(event.sender);
- const callerProjectPath =
- callerWin && wm
- ? wm.getContextForBrowserWindow(callerWin as unknown as BrowserWindowLike)?.projectPath
- : undefined;
+ const callerProjectPath = windowProjectPath(callerWin);
const result = showItemInFolderImpl(
{
platform: process.platform,
@@ -4941,10 +5345,7 @@ function registerIpcHandlers() {
handle('ok:shell:trash-item', async (event, absPath) => {
const callerWin = BrowserWindow.fromWebContents(event.sender);
- const callerProjectPath =
- callerWin && wm
- ? wm.getContextForBrowserWindow(callerWin as unknown as BrowserWindowLike)?.projectPath
- : undefined;
+ const callerProjectPath = windowProjectPath(callerWin);
// Path normalization happens at span-creation time using the renderer
// input (pre-realpath). The post-realpath canonical path is what we'd
// emit to logs/index — but it may include the user home prefix, so we
@@ -4994,13 +5395,17 @@ function registerIpcHandlers() {
return result;
});
- handle('ok:editor:active-target-changed', async (_event, target) => {
- // Last-write-wins across windows — see `editorActiveTarget` declaration.
- // The renderer pushes after each navigation; main rebuilds the menu so
- // Rename / Duplicate / Move to Trash flip enabled/disabled per the new
- // scope. No attempt to dedupe identical successive pushes — the rebuild
- // is cheap and the renderer dedupes upstream where it matters.
- editorActiveTarget = target;
+ handle('ok:editor:active-target-changed', async (event, target) => {
+ // The renderer pushes after each navigation; main records it against the
+ // SENDING window and rebuilds the menu so Rename / Duplicate / Move to
+ // Trash flip enabled/disabled per the focused window's scope. No attempt to
+ // dedupe identical successive pushes — the rebuild is cheap and the
+ // renderer dedupes upstream where it matters.
+ const win = BrowserWindow.fromWebContents(event.sender);
+ if (win) {
+ editorActiveTargets.update(win.id, target);
+ applyNoteWindowTargetChange(win, target);
+ }
refreshApplicationMenu();
return undefined;
});
@@ -5052,15 +5457,15 @@ function registerIpcHandlers() {
if (!callerWin || !wm) {
return { ok: false as const, reason: 'read-error' as const, detail: 'no window context' };
}
- const ctx = wm.getContextForBrowserWindow(callerWin as unknown as BrowserWindowLike);
- if (!ctx?.projectPath || !ctx.apiOrigin) {
+ const { projectPath, apiOrigin } = windowProjectScope(callerWin);
+ if (!projectPath || !apiOrigin) {
return { ok: false as const, reason: 'read-error' as const, detail: 'no project context' };
}
return copyImageToClipboard(
{
- projectPath: ctx.projectPath,
+ projectPath,
platform: process.platform,
- assetOrigin: ctx.apiOrigin,
+ assetOrigin: apiOrigin,
clipboard,
nativeImage,
},
@@ -5145,7 +5550,7 @@ function registerIpcHandlers() {
showDevToolsMenu: !app.isPackaged || channelFromVersion(app.getVersion()) === 'beta',
canCheckForUpdates: autoUpdaterHandle != null,
canReconfigureMcpWiring: app.isPackaged && supportedPackagedInstall(),
- activeTarget: editorActiveTarget ?? { kind: null },
+ activeTarget: currentActiveTarget(),
viewMenuState: (() => {
const win = BrowserWindow.fromWebContents(event.sender);
return win ? editorViewMenuStates.get(win.id) : editorViewMenuStates.current();
@@ -5994,6 +6399,36 @@ function registerIpcHandlers() {
return undefined;
});
+ handle('ok:window:open-note', async (event, request) => {
+ return withIpcErrorLogging(
+ {
+ channel: 'ok:window:open-note',
+ reason: 'unexpected',
+ handler: 'openNoteWindow',
+ },
+ async () => {
+ if (request.kind === 'dispatch-to-main') {
+ const origin = BrowserWindow.fromWebContents(event.sender);
+ return dispatchNoteWindowMainActionToProject({
+ originWindowId: origin?.id ?? null,
+ action: request.action,
+ getContext: getNoteWindowContext,
+ focusProjectWindow: (projectRoot) => wm?.focusWindowForProject(projectRoot) ?? null,
+ send: (target, action) =>
+ sendToRenderer(target.webContents, 'ok:note-window:main-action', action),
+ });
+ }
+ const docName = typeof request.docName === 'string' ? request.docName.trim() : '';
+ if (!docName) return { ok: false as const, reason: 'invalid-request' as const };
+ return openNoteWindowForDoc({
+ origin: BrowserWindow.fromWebContents(event.sender),
+ docName,
+ entryPoint: request.entryPoint === 'palette' ? 'palette' : 'tab-menu',
+ });
+ },
+ );
+ });
+
// Schema-incompatibility IPC handlers. The pure handler bodies live in
// `update-state-handlers.ts` so the unit tier can pin the composition
// (persist → clear pending, including rollback on saveAppState failure).
@@ -7411,14 +7846,36 @@ function bootPrimaryInstance(): void {
// the last (most recently focused) entry — otherwise a sibling that
// reveals later would bury it. Waiting for all reveals also keeps
// `bringToFront`'s own reveal from bypassing the target's gate.
+ // Pop-outs are held back from this concurrent wave. They attach to
+ // their project's server, so one opened alongside its project would
+ // race it and find nothing to attach to; they open after the wave
+ // settles, when the project windows and servers exist.
+ const docActions = orderedKeys
+ .map((key) => actionByKey.get(key))
+ .filter((action) => action?.kind === 'doc');
const opens = orderedKeys.map((key) => {
const action = actionByKey.get(key);
- if (action === undefined) return Promise.resolve();
+ if (action === undefined || action.kind === 'doc') return Promise.resolve();
return action.kind === 'project'
? openProjectOrFallbackToNavigator(action.projectPath, 'recents')
: openEphemeralFile(action.filePath);
});
void Promise.allSettled(opens)
+ .then(() => {
+ for (const action of docActions) {
+ // Isolate each restore: a throw on one (a `BrowserWindow`
+ // constructor failure, say) would otherwise skip both the
+ // remaining pop-outs and the bring-to-front `.then` below.
+ try {
+ restoreNoteWindow(action);
+ } catch (err) {
+ getLogger('note-window').warn(
+ { err },
+ 'failed to restore a note window on relaunch',
+ );
+ }
+ }
+ })
.then(() => {
// A deep link that arrived mid-restore already put the window the
// user asked for in front. Raising the restore target now would
diff --git a/packages/desktop/src/main/ipc-log.test.ts b/packages/desktop/src/main/ipc-log.test.ts
index 7a407203b..371ae74af 100644
--- a/packages/desktop/src/main/ipc-log.test.ts
+++ b/packages/desktop/src/main/ipc-log.test.ts
@@ -20,7 +20,7 @@
*/
import { describe, expect, test } from 'vitest';
-import { logIpcError } from './ipc-log.ts';
+import { logIpcError, withIpcErrorLogging } from './ipc-log.ts';
interface CapturedWarn {
readonly args: readonly unknown[];
@@ -41,6 +41,42 @@ function captureWarn(fn: () => void): CapturedWarn[] {
}
describe('logIpcError — cause boundary normalization', () => {
+ test('withIpcErrorLogging records and rethrows unexpected handler failures', async () => {
+ const err = new Error('note window constructor failed');
+ err.stack = 'STACK: note window constructor failed';
+ const captured: CapturedWarn[] = [];
+ const original = console.warn;
+ console.warn = (...args: unknown[]) => {
+ captured.push({ args });
+ };
+ try {
+ await expect(
+ withIpcErrorLogging(
+ {
+ channel: 'ok:window:open-note',
+ reason: 'unexpected',
+ handler: 'openNoteWindow',
+ },
+ async () => {
+ throw err;
+ },
+ ),
+ ).rejects.toBe(err);
+ } finally {
+ console.warn = original;
+ }
+
+ expect(captured).toHaveLength(1);
+ const parsed = JSON.parse(captured[0].args[0] as string);
+ expect(parsed).toMatchObject({
+ event: 'ipc.error',
+ channel: 'ok:window:open-note',
+ reason: 'unexpected',
+ handler: 'openNoteWindow',
+ });
+ expect(parsed.cause.stack).toBe('STACK: note window constructor failed');
+ });
+
test('plain-object cause round-trips faithfully', () => {
const captured = captureWarn(() => {
logIpcError({
diff --git a/packages/desktop/src/main/ipc-log.ts b/packages/desktop/src/main/ipc-log.ts
index f2e273c77..2e87cc119 100644
--- a/packages/desktop/src/main/ipc-log.ts
+++ b/packages/desktop/src/main/ipc-log.ts
@@ -155,3 +155,19 @@ export function logIpcError(payload: IpcErrorLogPayload): void {
console.warn(JSON.stringify({ ...safe, _causeSerializationFailed: true }));
}
}
+
+/**
+ * Preserve an unexpected main-process failure before Electron serializes the
+ * rejection down to its message for the invoking renderer.
+ */
+export async function withIpcErrorLogging<T>(
+ payload: Omit<IpcErrorLogPayload, 'event' | 'cause'>,
+ run: () => T | Promise<T>,
+): Promise<T> {
+ try {
+ return await run();
+ } catch (cause) {
+ logIpcError({ event: 'ipc.error', ...payload, cause });
+ throw cause;
+ }
+}
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 026f2ffbe..c96666a40 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -179,6 +179,14 @@ export interface MenuDeps {
* the menu without wiring a fake snapshot.
*/
activeTarget?: EditorActiveTargetSnapshot;
+ /**
+ * Window → Open in New Window click handler — pops the focused window's
+ * active document into its own note window. Main-originated: it resolves the
+ * document from the per-window active-target registry and creates the window
+ * directly, so this entry point adds no IPC channel. Disabled when
+ * `activeTarget.kind` is not `'doc'` (nothing to pop).
+ */
+ onOpenInNewWindow?(): void;
/**
* File → New file click handler. Routes through the renderer-side
* inline-rename flow at FileTree's startCreating helper — same path the
@@ -295,6 +303,8 @@ export interface MenuDeps {
* the keypress to this menu item before it reaches the renderer.
*/
onToggleSidebar?(): void;
+ /** The focused window is a reduced single-document pop-out. */
+ noteWindow?: boolean;
docPanelVisible?: boolean;
onToggleDocPanel?(): void;
/**
@@ -489,6 +499,10 @@ const MENU_BINDINGS: Record<string, MenuCommandBinding> = {
click: (d) => () => d.onNavigateForward?.(),
enabled: (d) => d.onNavigateForward !== undefined,
},
+ 'open-in-new-window': {
+ click: (d) => () => d.onOpenInNewWindow?.(),
+ enabled: (d) => d.onOpenInNewWindow !== undefined,
+ },
'new-file': { click: (d) => () => d.onNewFile?.(), enabled: (d) => d.onNewFile !== undefined },
'new-folder': {
click: (d) => () => d.onNewFolder?.(),
@@ -580,6 +594,7 @@ const MENU_BINDINGS: Record<string, MenuCommandBinding> = {
uninstall: { click: (d) => () => d.onUninstall?.(), present: (d) => d.onUninstall !== undefined },
'new-terminal': {
click: (d) => () => d.onNewTerminal?.(),
+ present: (d) => d.noteWindow !== true,
enabled: (d) => d.onNewTerminal !== undefined,
},
'new-terminal-window': {
@@ -588,6 +603,7 @@ const MENU_BINDINGS: Record<string, MenuCommandBinding> = {
},
'kill-terminal': {
click: (d) => () => d.onKillTerminal?.(),
+ present: (d) => d.noteWindow !== true,
enabled: (d) => d.onKillTerminal !== undefined,
},
'toggle-spell-check': {
@@ -597,22 +613,27 @@ const MENU_BINDINGS: Record<string, MenuCommandBinding> = {
},
'toggle-sidebar': {
click: (d) => () => d.onToggleSidebar?.(),
+ present: (d) => d.noteWindow !== true,
enabled: (d) => d.onToggleSidebar !== undefined,
},
'toggle-doc-panel': {
click: (d) => () => d.onToggleDocPanel?.(),
+ present: (d) => d.noteWindow !== true,
enabled: (d) => d.onToggleDocPanel !== undefined,
},
'toggle-terminal': {
click: (d) => () => d.onToggleTerminal?.(),
+ present: (d) => d.noteWindow !== true,
enabled: (d) => d.onToggleTerminal !== undefined,
},
'move-terminal': {
click: (d) => () => d.onMoveTerminal?.(),
+ present: (d) => d.noteWindow !== true,
enabled: (d) => d.onMoveTerminal !== undefined,
},
'toggle-agent-panel': {
click: (d) => () => d.onToggleAgentPanel?.(),
+ present: (d) => d.noteWindow !== true,
enabled: (d) => d.onToggleAgentPanel !== undefined,
},
'toggle-show-hidden-files': {
@@ -682,8 +703,10 @@ function menuCommandContext(deps: MenuDeps): CommandContext {
terminalLive: deps.terminalLive === true,
canExpandAll: deps.canExpandAll ?? true,
canCollapseAll: deps.canCollapseAll ?? true,
- // No Open-graph leaf in the menu; the field is palette-only.
- hasActiveDoc: false,
+ // Window → Open in New Window is the one menu leaf that gates on this, so
+ // it derives from the pushed target rather than being hard-false. Open
+ // graph, the other `requiresActiveDoc` command, stays palette-only.
+ hasActiveDoc: deps.activeTarget?.kind === 'doc',
showInstallSkill: SHOW_INSTALL_SKILL,
};
}
@@ -985,6 +1008,9 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
{
label: translate(NATIVE_MENU_LABELS.menuWindow),
submenu: [
+ // Pop-out heads the menu, above the OS window roles — it acts on the
+ // document, where the roles act on the window itself.
+ ...withTrailingSep(leafOf('window')),
roleItem('minimize'),
...(isMac
? ([
diff --git a/packages/desktop/src/main/note-window-registry.test.ts b/packages/desktop/src/main/note-window-registry.test.ts
new file mode 100644
index 000000000..ceaa45553
--- /dev/null
+++ b/packages/desktop/src/main/note-window-registry.test.ts
@@ -0,0 +1,119 @@
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ __resetNoteWindowRegistryForTests,
+ findNoteWindowForDoc,
+ getNoteWindowContext,
+ listNoteWindows,
+ listNoteWindowsForProject,
+ registerNoteWindow,
+ setNoteWindowDoc,
+ touchNoteWindow,
+ unregisterNoteWindow,
+} from './note-window-registry.ts';
+
+const PROJECT_A = '/Users/me/project-a';
+const PROJECT_B = '/Users/me/project-b';
+
+function ctx(projectRoot: string, currentDocName: string) {
+ return {
+ projectRoot,
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+ currentDocName,
+ };
+}
+
+afterEach(() => {
+ __resetNoteWindowRegistryForTests();
+});
+
+describe('note-window registry', () => {
+ test('round-trips a registered window context by windowId', () => {
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ expect(getNoteWindowContext(1)).toEqual(ctx(PROJECT_A, 'notes/alpha'));
+ });
+
+ test('returns undefined for an unregistered window', () => {
+ expect(getNoteWindowContext(999)).toBeUndefined();
+ });
+
+ test('unregister removes the entry', () => {
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ unregisterNoteWindow(1);
+ expect(getNoteWindowContext(1)).toBeUndefined();
+ });
+});
+
+describe('note-window dedup identity', () => {
+ test('finds the window showing a document in a project', () => {
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ expect(findNoteWindowForDoc(PROJECT_A, 'notes/alpha')).toBe(1);
+ });
+
+ test('does not match the same document name in a different project', () => {
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ expect(findNoteWindowForDoc(PROJECT_B, 'notes/alpha')).toBeUndefined();
+ });
+
+ test('does not match a different document in the same project', () => {
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ expect(findNoteWindowForDoc(PROJECT_A, 'notes/beta')).toBeUndefined();
+ });
+
+ test('identity follows in-place navigation rather than the birth document', () => {
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ expect(setNoteWindowDoc(1, 'notes/beta')).toBe(true);
+
+ expect(findNoteWindowForDoc(PROJECT_A, 'notes/beta')).toBe(1);
+ expect(findNoteWindowForDoc(PROJECT_A, 'notes/alpha')).toBeUndefined();
+ });
+
+ test('a navigation push for an unregistered window is ignored, not resurrected', () => {
+ expect(setNoteWindowDoc(404, 'notes/ghost')).toBe(false);
+ expect(getNoteWindowContext(404)).toBeUndefined();
+ });
+
+ test('two windows on one identity resolve most-recently-used', () => {
+ // Reachable only through in-place navigation: window 2 navigates onto the
+ // document window 1 already shows. The collision is permitted.
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ registerNoteWindow(2, ctx(PROJECT_A, 'notes/beta'));
+ setNoteWindowDoc(2, 'notes/alpha');
+
+ expect(findNoteWindowForDoc(PROJECT_A, 'notes/alpha')).toBe(2);
+
+ touchNoteWindow(1);
+ expect(findNoteWindowForDoc(PROJECT_A, 'notes/alpha')).toBe(1);
+ });
+
+ test('touching an unregistered window is a no-op', () => {
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ touchNoteWindow(404);
+ expect(findNoteWindowForDoc(PROJECT_A, 'notes/alpha')).toBe(1);
+ });
+});
+
+describe('note-window enumeration', () => {
+ test('N windows coexist for one project and across projects', () => {
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ registerNoteWindow(2, ctx(PROJECT_A, 'notes/beta'));
+ registerNoteWindow(3, ctx(PROJECT_B, 'notes/gamma'));
+
+ expect(listNoteWindowsForProject(PROJECT_A)).toEqual([1, 2]);
+ expect(listNoteWindowsForProject(PROJECT_B)).toEqual([3]);
+ expect(listNoteWindows()).toHaveLength(3);
+ });
+
+ test('listNoteWindows carries each window current document for the restore snapshot', () => {
+ registerNoteWindow(1, ctx(PROJECT_A, 'notes/alpha'));
+ setNoteWindowDoc(1, 'notes/navigated-here');
+
+ expect(listNoteWindows()).toEqual([
+ { windowId: 1, context: ctx(PROJECT_A, 'notes/navigated-here') },
+ ]);
+ });
+
+ test('a project with no note windows enumerates empty', () => {
+ expect(listNoteWindowsForProject(PROJECT_A)).toEqual([]);
+ });
+});
diff --git a/packages/desktop/src/main/note-window-registry.ts b/packages/desktop/src/main/note-window-registry.ts
new file mode 100644
index 000000000..f1ab3a4fe
--- /dev/null
+++ b/packages/desktop/src/main/note-window-registry.ts
@@ -0,0 +1,136 @@
+/**
+ * windowId-keyed registry of popped-out note windows (`--ok-mode=note`).
+ *
+ * Note windows are deliberately NOT tracked in the window manager's per-project
+ * `windowsByPath` map (one-per-project, focus-existing) so that N pop-outs can
+ * coexist for a single project — the case in-window split panes cannot serve.
+ * Because they are absent from `windowsByPath`, `getContextForBrowserWindow`
+ * returns nothing for them, so main-side project resolution (menus, shell and
+ * clipboard handlers) reads their project from here instead.
+ *
+ * Two properties this registry owns beyond the terminal-window precedent:
+ *
+ * - **Identity is content-keyed, not window-keyed.** Dedup is on
+ * `(projectRoot, currentDocName)` so re-invoking "Open in New Window" on an
+ * already-popped document focuses the window that has it. `currentDocName`
+ * is mutable because a note window navigates in place through wiki links, so
+ * a window can drift from the document it was born with.
+ * - **Collisions are permitted and resolved most-recently-used.** In-place
+ * navigation can legitimately land two windows on one identity; that is
+ * allowed, and a re-invoke focuses whichever of them was touched last rather
+ * than erroring or spawning a third.
+ */
+
+/** Where an open request came from. Bounded set — it is a telemetry attribute. */
+export type NoteWindowEntryPoint = 'tab-menu' | 'palette' | 'window-menu';
+
+export interface NoteWindowContext {
+ /** Inherited project root. Note windows are never project-less: a popped-out
+ * document only exists inside a project, unlike a terminal window. */
+ readonly projectRoot: string;
+ /** Inherited collab server URL (attach-mode). */
+ readonly collabUrl: string;
+ /** Inherited API origin (attach-mode). */
+ readonly apiOrigin: string;
+ /** The document the window is showing right now, not the one it opened with. */
+ readonly currentDocName: string;
+}
+
+/**
+ * The stored shape. It restates the context fields rather than extending
+ * `NoteWindowContext` because the public type is fully readonly (correct for
+ * consumers) while the two fields the registry itself mutates — the document a
+ * window navigated to, and its focus recency — must not be.
+ */
+interface NoteWindowRecord {
+ readonly projectRoot: string;
+ readonly collabUrl: string;
+ readonly apiOrigin: string;
+ currentDocName: string;
+ /** Monotonic touch counter; the tiebreak when two windows share an identity. */
+ touchSeq: number;
+}
+
+const noteWindows = new Map<number, NoteWindowRecord>();
+let touchCounter = 0;
+
+export function registerNoteWindow(windowId: number, context: NoteWindowContext): void {
+ touchCounter += 1;
+ noteWindows.set(windowId, { ...context, touchSeq: touchCounter });
+}
+
+export function getNoteWindowContext(windowId: number): NoteWindowContext | undefined {
+ const record = noteWindows.get(windowId);
+ if (!record) return undefined;
+ const { touchSeq: _touchSeq, ...context } = record;
+ return context;
+}
+
+export function unregisterNoteWindow(windowId: number): void {
+ noteWindows.delete(windowId);
+}
+
+/**
+ * Re-point a window at the document it navigated to, so the dedup identity and
+ * anything keyed off it (title, menu targeting) follow the window rather than
+ * its birth document. No-ops for an unregistered window so a late navigation
+ * push from a closing window cannot resurrect a dropped entry.
+ */
+export function setNoteWindowDoc(windowId: number, docName: string): boolean {
+ const record = noteWindows.get(windowId);
+ if (!record) return false;
+ record.currentDocName = docName;
+ return true;
+}
+
+/** Mark a window as most recently used. Called on focus. */
+export function touchNoteWindow(windowId: number): void {
+ const record = noteWindows.get(windowId);
+ if (!record) return;
+ touchCounter += 1;
+ record.touchSeq = touchCounter;
+}
+
+/**
+ * The dedup lookup: the window already showing this document in this project,
+ * or undefined. When several windows share the identity (reachable only through
+ * in-place navigation) the most recently touched one wins.
+ */
+export function findNoteWindowForDoc(projectRoot: string, docName: string): number | undefined {
+ let bestId: number | undefined;
+ let bestSeq = -1;
+ for (const [windowId, record] of noteWindows) {
+ if (record.projectRoot !== projectRoot) continue;
+ if (record.currentDocName !== docName) continue;
+ if (record.touchSeq > bestSeq) {
+ bestSeq = record.touchSeq;
+ bestId = windowId;
+ }
+ }
+ return bestId;
+}
+
+/** Every note window belonging to a project, for the owner-close cascade and
+ * for the restore snapshot. Ordered oldest-touched first for stable output. */
+export function listNoteWindowsForProject(projectRoot: string): number[] {
+ return [...noteWindows.entries()]
+ .filter(([, record]) => record.projectRoot === projectRoot)
+ .sort((a, b) => a[1].touchSeq - b[1].touchSeq)
+ .map(([windowId]) => windowId);
+}
+
+/** Every registered note window with its context. The restore snapshot source. */
+export function listNoteWindows(): Array<{ windowId: number; context: NoteWindowContext }> {
+ return [...noteWindows.entries()]
+ .sort((a, b) => a[1].touchSeq - b[1].touchSeq)
+ .map(([windowId, record]) => {
+ const { touchSeq: _touchSeq, ...context } = record;
+ return { windowId, context };
+ });
+}
+
+/** Test-only: drop every entry so the module-global Map cannot leak across cases. */
+export function __resetNoteWindowRegistryForTests(): void {
+ noteWindows.clear();
+ touchCounter = 0;
+}
diff --git a/packages/desktop/src/main/note-window-telemetry.ts b/packages/desktop/src/main/note-window-telemetry.ts
new file mode 100644
index 000000000..837b21ce4
--- /dev/null
+++ b/packages/desktop/src/main/note-window-telemetry.ts
@@ -0,0 +1,29 @@
+/**
+ * Pop-out note-window adoption telemetry.
+ *
+ * OK Desktop has no product-analytics surface; opt-in OpenTelemetry is the only
+ * signal available, and it is off by default, so this reads only for opted-in
+ * users and dogfood. `withSpanSync` is a no-op when the SDK is disabled, so
+ * default builds pay nothing.
+ *
+ * The lone attribute is the entry-point enum. No document name, no path, no
+ * project identifier ever rides along: the whole point of the pop-out is that a
+ * document is on screen, and document names are unbounded user content.
+ */
+
+import { withSpanSync } from '@inkeep/open-knowledge-server';
+import type { NoteWindowEntryPoint } from './note-window-registry.ts';
+
+/**
+ * Emit one `ok.desktop.noteWindowOpened` span. Fired from the factory, which is
+ * the single creation path, so the span count is the open count. A dedup hit
+ * (focus-existing) is deliberately NOT an open and emits nothing — otherwise the
+ * adoption number would count focus events as new windows.
+ */
+export function recordNoteWindowOpened(info: { entryPoint: NoteWindowEntryPoint }): void {
+ withSpanSync(
+ 'ok.desktop.noteWindowOpened',
+ { attributes: { 'ok.desktop.note_entry_point': info.entryPoint } },
+ () => undefined,
+ );
+}
diff --git a/packages/desktop/src/main/note-window.test.ts b/packages/desktop/src/main/note-window.test.ts
new file mode 100644
index 000000000..f045fb0d0
--- /dev/null
+++ b/packages/desktop/src/main/note-window.test.ts
@@ -0,0 +1,788 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import type { AssetOpenResult } from './asset-allowlist.ts';
+import { attachAssetSafetyNet } from './asset-safety-net.ts';
+import {
+ closeNoteWindowsForProject,
+ createNoteWindow,
+ dispatchNoteWindowMainActionToProject,
+ type NoteBrowserWindow,
+ type NoteWindowProject,
+ noteWindowNativeChromeOptions,
+ openNoteWindow,
+ parseNoteWindowMainAction,
+ resolveNoteWindowProject,
+ resolveWindowProjectScope,
+} from './note-window.ts';
+import {
+ __resetNoteWindowRegistryForTests,
+ findNoteWindowForDoc,
+ getNoteWindowContext,
+ listNoteWindowsForProject,
+} from './note-window-registry.ts';
+import type { ShowGateRegistry } from './show-gate.ts';
+
+const recordNoteWindowOpened = vi.hoisted(() => vi.fn());
+vi.mock('./note-window-telemetry.ts', () => ({ recordNoteWindowOpened }));
+
+const PROJECT: NoteWindowProject = {
+ projectPath: '/Users/me/project',
+ projectName: 'project',
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+};
+
+/** A fake window exposing only what the factory touches; `closed` handlers are
+ * captured so a test can fire the lifecycle event. */
+function makeFakeWindow(id: number) {
+ const closedHandlers: Array<() => void> = [];
+ const window = {
+ id,
+ on: (event: string, cb: () => void) => {
+ if (event === 'closed') closedHandlers.push(cb);
+ },
+ once: () => {},
+ loadFile: vi.fn(async () => {}),
+ loadURL: vi.fn(async () => {}),
+ webContents: { send: () => {}, once: () => {} },
+ } as unknown as NoteBrowserWindow;
+ return {
+ window,
+ fireClosed: () => {
+ for (const cb of closedHandlers) cb();
+ },
+ };
+}
+
+function makeDeps(opts: {
+ id: number;
+ docName: string;
+ project?: NoteWindowProject;
+ rendererDevUrl?: string | null;
+}) {
+ const fake = makeFakeWindow(opts.id);
+ const createWindow = vi.fn((_o: { additionalArguments: string[]; title: string }) => fake.window);
+ const disposeShowGate = vi.fn(() => {});
+ const register = vi.fn((_window: unknown, _opts?: { kind?: string }) => disposeShowGate);
+ const showGate = { register, fireThemeApplied: () => {} } as unknown as ShowGateRegistry;
+ const placeWindow = vi.fn((_w: NoteBrowserWindow) => {});
+ return {
+ fake,
+ createWindow,
+ disposeShowGate,
+ register,
+ placeWindow,
+ deps: {
+ createWindow,
+ rendererEntryPath: '/app/index.html',
+ rendererDevUrl: opts.rendererDevUrl ?? null,
+ appVersion: '1.2.3',
+ showGate,
+ project: opts.project ?? PROJECT,
+ docName: opts.docName,
+ placeWindow,
+ },
+ };
+}
+
+afterEach(() => {
+ __resetNoteWindowRegistryForTests();
+ recordNoteWindowOpened.mockClear();
+});
+
+describe('parseNoteWindowMainAction', () => {
+ test('accepts every bounded conversation and comment action', () => {
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'active-input',
+ text: 'Review this',
+ newTab: true,
+ submit: true,
+ }),
+ ).toEqual({ kind: 'active-input', text: 'Review this', newTab: true, submit: true });
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'agent-thread',
+ agentSource: 'registry',
+ agentId: 'claude-acp',
+ prompt: 'Review this',
+ docName: 'notes/alpha',
+ titleHint: null,
+ }),
+ ).toEqual({
+ kind: 'agent-thread',
+ agentSource: 'registry',
+ agentId: 'claude-acp',
+ prompt: 'Review this',
+ docName: 'notes/alpha',
+ titleHint: null,
+ });
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'terminal-launch',
+ prompt: 'Review this',
+ cli: 'codex',
+ stage: false,
+ }),
+ ).toEqual({ kind: 'terminal-launch', prompt: 'Review this', cli: 'codex', stage: false });
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'reveal-comments',
+ docName: 'notes/alpha',
+ scope: 'doc',
+ }),
+ ).toEqual({ kind: 'reveal-comments', docName: 'notes/alpha', scope: 'doc' });
+ });
+
+ test('rejects inherited registry keys, unknown CLIs, and malformed comment scope', () => {
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'terminal-launch',
+ prompt: 'Review',
+ cli: 'toString',
+ stage: false,
+ }),
+ ).toBeNull();
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'terminal-launch',
+ prompt: 'Review',
+ cli: 'shell',
+ stage: false,
+ }),
+ ).toBeNull();
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'reveal-comments',
+ docName: 'notes/alpha',
+ scope: 'project',
+ }),
+ ).toBeNull();
+ });
+
+ test('accepts the agents target and queue comment scope, and rejects unknown targets', () => {
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'active-input',
+ text: 'Review this',
+ newTab: true,
+ submit: true,
+ target: 'agents',
+ }),
+ ).toEqual({
+ kind: 'active-input',
+ text: 'Review this',
+ newTab: true,
+ submit: true,
+ target: 'agents',
+ });
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'active-input',
+ text: 'Review this',
+ newTab: true,
+ submit: true,
+ target: 'unknown',
+ }),
+ ).toBeNull();
+ expect(
+ parseNoteWindowMainAction({
+ kind: 'reveal-comments',
+ docName: 'notes/alpha',
+ scope: 'queue',
+ }),
+ ).toEqual({ kind: 'reveal-comments', docName: 'notes/alpha', scope: 'queue' });
+ });
+});
+
+describe('dispatchNoteWindowMainActionToProject', () => {
+ const context = {
+ projectRoot: PROJECT.projectPath,
+ collabUrl: PROJECT.collabUrl,
+ apiOrigin: PROJECT.apiOrigin,
+ currentDocName: 'notes/alpha',
+ };
+
+ test('focuses the owning project before delivering the validated action', () => {
+ const order: string[] = [];
+ const target = { id: 'main-window' };
+ const action = { kind: 'active-input', text: 'Review', newTab: true, submit: true };
+
+ const result = dispatchNoteWindowMainActionToProject({
+ originWindowId: 7,
+ action,
+ getContext: (windowId) => (windowId === 7 ? context : undefined),
+ focusProjectWindow: (projectRoot) => {
+ order.push(`focus:${projectRoot}`);
+ return target;
+ },
+ send: (actualTarget, actualAction) => {
+ order.push(`send:${actualTarget.id}:${actualAction.kind}`);
+ },
+ });
+
+ expect(result).toEqual({ ok: true });
+ expect(order).toEqual([`focus:${PROJECT.projectPath}`, 'send:main-window:active-input']);
+ });
+
+ test.each([
+ {
+ name: 'the sender is not a registered note window',
+ originWindowId: null,
+ action: { kind: 'active-input', text: 'Review', newTab: true, submit: true },
+ context: undefined,
+ target: { id: 'main-window' },
+ reason: 'not-note-window',
+ },
+ {
+ name: 'the action is malformed',
+ originWindowId: 7,
+ action: { kind: 'terminal-launch', prompt: 'Review', cli: 'toString', stage: false },
+ context,
+ target: { id: 'main-window' },
+ reason: 'invalid-action',
+ },
+ {
+ name: 'the owning project window is gone',
+ originWindowId: 7,
+ action: { kind: 'active-input', text: 'Review', newTab: true, submit: true },
+ context,
+ target: null,
+ reason: 'project-not-open',
+ },
+ ] as const)('fails closed when $name', ({ originWindowId, action, context, target, reason }) => {
+ const send = vi.fn();
+ const result = dispatchNoteWindowMainActionToProject({
+ originWindowId,
+ action,
+ getContext: () => context,
+ focusProjectWindow: () => target,
+ send,
+ });
+
+ expect(result).toEqual({ ok: false, reason });
+ expect(send).not.toHaveBeenCalled();
+ });
+});
+
+describe('noteWindowNativeChromeOptions', () => {
+ test('centers macOS traffic lights in the compact titlebar and avoids sidebar framing', () => {
+ expect(noteWindowNativeChromeOptions('darwin')).toEqual({
+ vibrancy: 'window',
+ trafficLightPosition: { x: 22, y: 17 },
+ });
+ });
+
+ test.each([
+ 'win32',
+ 'linux',
+ ] as const)('leaves %s chrome to the shared WCO policy', (platform) => {
+ expect(noteWindowNativeChromeOptions(platform)).toEqual({});
+ });
+});
+
+describe('createNoteWindow', () => {
+ test('opens a --ok-mode=note window with attach argv and the initial document', () => {
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ createNoteWindow(h.deps);
+
+ const args = h.createWindow.mock.calls[0]?.[0]?.additionalArguments ?? [];
+ expect(args).toContain('--ok-mode=note');
+ expect(args).toContain('--ok-collab-url=ws://localhost:5200/collab');
+ expect(args).toContain('--ok-api-origin=http://localhost:5200');
+ expect(args).toContain('--ok-project-path=/Users/me/project');
+ expect(args).toContain('--ok-initial-doc=notes/alpha');
+ });
+
+ test('titles the window with the document name', () => {
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ createNoteWindow(h.deps);
+ expect(h.createWindow.mock.calls[0]?.[0]?.title).toBe('notes/alpha');
+ });
+
+ test('registers with the show gate as kind note', () => {
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ createNoteWindow(h.deps);
+ expect(h.register).toHaveBeenCalledWith(h.fake.window, { kind: 'note' });
+ });
+
+ test('registers the window context before the renderer load starts', () => {
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ createNoteWindow(h.deps);
+
+ expect(getNoteWindowContext(1)).toEqual({
+ projectRoot: '/Users/me/project',
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+ currentDocName: 'notes/alpha',
+ });
+ });
+
+ test('applies placement', () => {
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ createNoteWindow(h.deps);
+ expect(h.placeWindow).toHaveBeenCalledWith(h.fake.window);
+ });
+
+ test('closing the window disposes the show gate and drops the registry entry', () => {
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ createNoteWindow(h.deps);
+
+ h.fake.fireClosed();
+
+ expect(h.disposeShowGate).toHaveBeenCalledTimes(1);
+ expect(getNoteWindowContext(1)).toBeUndefined();
+ });
+
+ test('closing notifies main-side per-window state so nothing keeps a stale entry', () => {
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ const onClosed = vi.fn();
+ createNoteWindow({ ...h.deps, onClosed });
+
+ h.fake.fireClosed();
+
+ expect(onClosed).toHaveBeenCalledWith(1);
+ });
+
+ test('loads the dev URL when one is configured, else the built entry', () => {
+ const dev = makeDeps({
+ id: 1,
+ docName: 'notes/alpha',
+ rendererDevUrl: 'http://localhost:5173',
+ });
+ createNoteWindow(dev.deps);
+ expect(dev.fake.window.loadURL).toHaveBeenCalledWith('http://localhost:5173');
+ expect(dev.fake.window.loadFile).not.toHaveBeenCalled();
+
+ __resetNoteWindowRegistryForTests();
+
+ const prod = makeDeps({ id: 2, docName: 'notes/alpha' });
+ createNoteWindow(prod.deps);
+ expect(prod.fake.window.loadFile).toHaveBeenCalledWith('/app/index.html');
+ });
+
+ test('preserves the stack trace when renderer loading fails', async () => {
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ const err = new Error('renderer failed');
+ err.stack = 'STACK: renderer failed';
+ vi.mocked(h.fake.window.loadFile).mockRejectedValue(err);
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ try {
+ createNoteWindow(h.deps);
+ await vi.waitFor(() => expect(warn).toHaveBeenCalled());
+ const parsed = JSON.parse(warn.mock.calls[0]?.[0] as string);
+ expect(parsed.message).toBe('STACK: renderer failed');
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ test('attaches the external-link safety net before the renderer loads, so a stray external window.open is denied and delegated to the OS browser', () => {
+ // The note window renders the same untrusted document content as an editor
+ // window; without this net a click that escapes the renderer's own handler
+ // navigates the top frame to an external origin, where the preload
+ // re-exposes the `okDesktop` bridge. Seam: the real `attachAssetSafetyNet`
+ // over a capturing webContents fake — asserting the captured handler denies
+ // an external URL and routes it to `openExternal` is the real behavior, not
+ // a mock of the factory's own logic. Mirrors `window-manager-safety-net`.
+ let windowOpenHandler: ((details: { url: string }) => { action: 'allow' | 'deny' }) | null =
+ null;
+ let handlerRegisteredBeforeLoad = false;
+ const openExternal = vi.fn(async () => {});
+ const openAsset = vi.fn(async (): Promise<AssetOpenResult> => ({ ok: true }));
+ const loadFile = vi.fn(async () => {
+ handlerRegisteredBeforeLoad = windowOpenHandler !== null;
+ });
+ const window = {
+ id: 1,
+ on: () => {},
+ once: () => {},
+ loadFile,
+ loadURL: vi.fn(async () => {}),
+ webContents: {
+ send: () => {},
+ once: () => {},
+ setWindowOpenHandler: (
+ handler: (details: { url: string }) => { action: 'allow' | 'deny' },
+ ) => {
+ windowOpenHandler = handler;
+ },
+ on: () => {},
+ getURL: () => PROJECT.apiOrigin,
+ },
+ } as unknown as NoteBrowserWindow;
+ const showGate = {
+ register: vi.fn(() => vi.fn(() => {})),
+ fireThemeApplied: () => {},
+ } as unknown as ShowGateRegistry;
+
+ createNoteWindow({
+ createWindow: () => window,
+ rendererEntryPath: '/app/index.html',
+ rendererDevUrl: null,
+ appVersion: '1.2.3',
+ showGate,
+ project: PROJECT,
+ docName: 'notes/alpha',
+ attachSafetyNet: (win) =>
+ attachAssetSafetyNet(win.webContents, {
+ editorOrigin: PROJECT.apiOrigin,
+ openExternal,
+ openAsset,
+ }),
+ });
+
+ expect(windowOpenHandler).not.toBeNull();
+ expect(handlerRegisteredBeforeLoad).toBe(true);
+ if (windowOpenHandler === null) throw new Error('safety net not attached');
+ expect(windowOpenHandler({ url: 'https://evil.example.com/' })).toEqual({ action: 'deny' });
+ expect(openExternal).toHaveBeenCalledWith('https://evil.example.com/');
+ });
+});
+
+describe('openNoteWindow — dedup and focus-existing', () => {
+ test('creates a window when the document has none, and emits one adoption span', () => {
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ const focusWindowById = vi.fn(() => true);
+
+ const result = openNoteWindow({ ...h.deps, entryPoint: 'tab-menu', focusWindowById });
+
+ expect(result).toEqual({ outcome: 'created', windowId: 1 });
+ expect(focusWindowById).not.toHaveBeenCalled();
+ expect(recordNoteWindowOpened).toHaveBeenCalledWith({ entryPoint: 'tab-menu' });
+ });
+
+ test('re-invoking on an already-popped document focuses instead of creating', () => {
+ const first = makeDeps({ id: 1, docName: 'notes/alpha' });
+ const focusWindowById = vi.fn(() => true);
+ openNoteWindow({ ...first.deps, entryPoint: 'tab-menu', focusWindowById });
+
+ const second = makeDeps({ id: 2, docName: 'notes/alpha' });
+ const result = openNoteWindow({ ...second.deps, entryPoint: 'palette', focusWindowById });
+
+ expect(result).toEqual({ outcome: 'focused', windowId: 1 });
+ expect(second.createWindow).not.toHaveBeenCalled();
+ expect(focusWindowById).toHaveBeenCalledWith(1);
+ });
+
+ test('an open with no entry point is not counted either', () => {
+ // A server-restart recreate puts back a window that was already there.
+ // Counting it would inflate the one adoption number this feature reports.
+ const h = makeDeps({ id: 1, docName: 'notes/alpha' });
+ const result = openNoteWindow({ ...h.deps, focusWindowById: () => true });
+
+ expect(result.outcome).toBe('created');
+ expect(recordNoteWindowOpened).not.toHaveBeenCalled();
+ });
+
+ test('a dedup hit is not counted as an open', () => {
+ const first = makeDeps({ id: 1, docName: 'notes/alpha' });
+ const focusWindowById = vi.fn(() => true);
+ openNoteWindow({ ...first.deps, entryPoint: 'tab-menu', focusWindowById });
+ recordNoteWindowOpened.mockClear();
+
+ const second = makeDeps({ id: 2, docName: 'notes/alpha' });
+ openNoteWindow({ ...second.deps, entryPoint: 'palette', focusWindowById });
+
+ expect(recordNoteWindowOpened).not.toHaveBeenCalled();
+ });
+
+ test('two same-tick opens for one document yield exactly one window', () => {
+ // Registration is synchronous and precedes the async renderer load, so the
+ // second call cannot miss the first call's entry. No in-flight promise map
+ // is needed (the slides-registry race does not apply here).
+ const focusWindowById = vi.fn(() => true);
+ const first = makeDeps({ id: 1, docName: 'notes/alpha' });
+ const second = makeDeps({ id: 2, docName: 'notes/alpha' });
+
+ const a = openNoteWindow({ ...first.deps, entryPoint: 'tab-menu', focusWindowById });
+ const b = openNoteWindow({ ...second.deps, entryPoint: 'tab-menu', focusWindowById });
+
+ expect(a.outcome).toBe('created');
+ expect(b.outcome).toBe('focused');
+ expect(listNoteWindowsForProject(PROJECT.projectPath)).toEqual([1]);
+ });
+
+ test('N documents from one project plus one from another yield three windows', () => {
+ const focusWindowById = vi.fn(() => true);
+ const other: NoteWindowProject = {
+ ...PROJECT,
+ projectPath: '/Users/me/other',
+ projectName: 'other',
+ };
+
+ openNoteWindow({
+ ...makeDeps({ id: 1, docName: 'notes/alpha' }).deps,
+ entryPoint: 'tab-menu',
+ focusWindowById,
+ });
+ openNoteWindow({
+ ...makeDeps({ id: 2, docName: 'notes/beta' }).deps,
+ entryPoint: 'tab-menu',
+ focusWindowById,
+ });
+ openNoteWindow({
+ ...makeDeps({ id: 3, docName: 'notes/gamma', project: other }).deps,
+ entryPoint: 'tab-menu',
+ focusWindowById,
+ });
+
+ expect(listNoteWindowsForProject(PROJECT.projectPath)).toEqual([1, 2]);
+ expect(listNoteWindowsForProject('/Users/me/other')).toEqual([3]);
+ expect(recordNoteWindowOpened).toHaveBeenCalledTimes(3);
+ });
+
+ test('a stale entry whose window cannot be focused is replaced, not shadowed', () => {
+ const first = makeDeps({ id: 1, docName: 'notes/alpha' });
+ openNoteWindow({ ...first.deps, entryPoint: 'tab-menu', focusWindowById: () => true });
+
+ // The window died without firing 'closed', so focusing it fails.
+ const second = makeDeps({ id: 2, docName: 'notes/alpha' });
+ const result = openNoteWindow({
+ ...second.deps,
+ entryPoint: 'tab-menu',
+ focusWindowById: () => false,
+ });
+
+ expect(result).toEqual({ outcome: 'created', windowId: 2 });
+ expect(findNoteWindowForDoc(PROJECT.projectPath, 'notes/alpha')).toBe(2);
+ });
+});
+
+describe('resolveNoteWindowProject', () => {
+ const helpers = {
+ collabUrlFromApiOrigin: (apiOrigin: string) => `${apiOrigin.replace('http', 'ws')}/collab`,
+ projectNameFromPath: (projectPath: string) => projectPath.split('/').pop() ?? '',
+ };
+
+ test('an editor window contributes its windowsByPath project', () => {
+ expect(
+ resolveNoteWindowProject({
+ editor: {
+ projectPath: '/Users/me/project',
+ projectName: 'project',
+ apiOrigin: 'http://localhost:5200',
+ },
+ note: undefined,
+ ...helpers,
+ }),
+ ).toEqual({
+ projectPath: '/Users/me/project',
+ projectName: 'project',
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+ });
+ });
+
+ test('popping out from inside a note window inherits that window project', () => {
+ expect(
+ resolveNoteWindowProject({
+ editor: null,
+ note: {
+ projectRoot: '/Users/me/project',
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+ currentDocName: 'notes/alpha',
+ },
+ ...helpers,
+ }),
+ ).toEqual({
+ projectPath: '/Users/me/project',
+ projectName: 'project',
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+ });
+ });
+
+ test('an editor context wins over a note context', () => {
+ const resolved = resolveNoteWindowProject({
+ editor: {
+ projectPath: '/Users/me/editor-project',
+ projectName: 'editor-project',
+ apiOrigin: 'http://localhost:5200',
+ },
+ note: {
+ projectRoot: '/Users/me/other',
+ collabUrl: 'ws://localhost:5300/collab',
+ apiOrigin: 'http://localhost:5300',
+ currentDocName: 'notes/alpha',
+ },
+ ...helpers,
+ });
+ expect(resolved?.projectPath).toBe('/Users/me/editor-project');
+ });
+
+ test('no project context resolves to null, never a project-less window', () => {
+ // A terminal window falls back to a home-directory shell here. A note
+ // window cannot: a document only exists inside a project.
+ expect(resolveNoteWindowProject({ editor: null, note: undefined, ...helpers })).toBeNull();
+ });
+});
+
+describe('resolveWindowProjectScope', () => {
+ const note = {
+ projectRoot: '/Users/me/project',
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+ currentDocName: 'notes/alpha',
+ };
+
+ test('an editor window keeps its windowsByPath scope', () => {
+ expect(
+ resolveWindowProjectScope({
+ editor: { projectPath: '/Users/me/editor', apiOrigin: 'http://localhost:5300' },
+ note: undefined,
+ }),
+ ).toEqual({ projectPath: '/Users/me/editor', apiOrigin: 'http://localhost:5300' });
+ });
+
+ test('a note window resolves through the registry instead of refusing', () => {
+ // Before this fallback, every containment-gated handler saw a focused
+ // pop-out as project-less: asset clicks and copy-image refused outright.
+ expect(resolveWindowProjectScope({ editor: undefined, note })).toEqual({
+ projectPath: '/Users/me/project',
+ apiOrigin: 'http://localhost:5200',
+ });
+ });
+
+ test('a window in neither map still resolves to nothing', () => {
+ expect(resolveWindowProjectScope({ editor: null, note: undefined })).toEqual({
+ projectPath: undefined,
+ apiOrigin: undefined,
+ });
+ });
+
+ test('resolves per field, so a path-only editor context is unchanged', () => {
+ // An editor context carrying a path but no origin must keep behaving
+ // exactly as it did; falling back wholesale would change its behavior.
+ expect(
+ resolveWindowProjectScope({ editor: { projectPath: '/Users/me/editor' }, note: undefined }),
+ ).toEqual({ projectPath: '/Users/me/editor', apiOrigin: undefined });
+ });
+
+ test('an editor context wins field-by-field over a note context', () => {
+ expect(
+ resolveWindowProjectScope({
+ editor: { projectPath: '/Users/me/editor', apiOrigin: 'http://localhost:5300' },
+ note,
+ }),
+ ).toEqual({ projectPath: '/Users/me/editor', apiOrigin: 'http://localhost:5300' });
+ });
+});
+
+describe('closeNoteWindowsForProject — owner-close cascade', () => {
+ test('preserves recreated note windows when the closing owner has a live replacement', () => {
+ openNoteWindow({
+ ...makeDeps({ id: 1, docName: 'notes/alpha' }).deps,
+ entryPoint: 'tab-menu',
+ focusWindowById: () => true,
+ });
+
+ const closingProjectWindow = makeFakeWindow(90).window;
+ const activeProjectWindow = makeFakeWindow(91).window;
+ const closeWindowById = vi.fn(() => {});
+ const closeRequest = {
+ projectRoot: PROJECT.projectPath,
+ reason: 'project-close' as const,
+ closingProjectWindow,
+ activeProjectWindow,
+ closeWindowById,
+ };
+
+ const closed = closeNoteWindowsForProject(closeRequest);
+
+ expect(closed).toEqual([]);
+ expect(closeWindowById).not.toHaveBeenCalled();
+ expect(listNoteWindowsForProject(PROJECT.projectPath)).toEqual([1]);
+ });
+
+ test('closes pop-outs when the replacement project window is already destroyed', () => {
+ openNoteWindow({
+ ...makeDeps({ id: 1, docName: 'notes/alpha' }).deps,
+ entryPoint: 'tab-menu',
+ focusWindowById: () => true,
+ });
+
+ const closingProjectWindow = makeFakeWindow(90).window;
+ const activeProjectWindow = makeFakeWindow(91).window;
+ activeProjectWindow.isDestroyed = () => true;
+ const closeWindowById = vi.fn(() => {});
+
+ const closed = closeNoteWindowsForProject({
+ projectRoot: PROJECT.projectPath,
+ reason: 'project-close',
+ closingProjectWindow,
+ activeProjectWindow,
+ closeWindowById,
+ });
+
+ expect(closed).toEqual([1]);
+ expect(closeWindowById).toHaveBeenCalledWith(1);
+ });
+
+ test('closes every note window of the project and leaves no registry entry', () => {
+ const focusWindowById = vi.fn(() => true);
+ openNoteWindow({
+ ...makeDeps({ id: 1, docName: 'notes/alpha' }).deps,
+ entryPoint: 'tab-menu',
+ focusWindowById,
+ });
+ openNoteWindow({
+ ...makeDeps({ id: 2, docName: 'notes/beta' }).deps,
+ entryPoint: 'tab-menu',
+ focusWindowById,
+ });
+
+ const closeWindowById = vi.fn(() => {});
+ const closed = closeNoteWindowsForProject({
+ projectRoot: PROJECT.projectPath,
+ reason: 'project-close',
+ closeWindowById,
+ });
+
+ expect(closed).toEqual([1, 2]);
+ expect(closeWindowById).toHaveBeenCalledTimes(2);
+ expect(listNoteWindowsForProject(PROJECT.projectPath)).toEqual([]);
+ expect(getNoteWindowContext(1)).toBeUndefined();
+ expect(getNoteWindowContext(2)).toBeUndefined();
+ });
+
+ test('leaves another project note windows alone', () => {
+ const focusWindowById = vi.fn(() => true);
+ const other: NoteWindowProject = {
+ ...PROJECT,
+ projectPath: '/Users/me/other',
+ projectName: 'other',
+ };
+ openNoteWindow({
+ ...makeDeps({ id: 1, docName: 'notes/alpha' }).deps,
+ entryPoint: 'tab-menu',
+ focusWindowById,
+ });
+ openNoteWindow({
+ ...makeDeps({ id: 2, docName: 'notes/gamma', project: other }).deps,
+ entryPoint: 'tab-menu',
+ focusWindowById,
+ });
+
+ closeNoteWindowsForProject({
+ projectRoot: PROJECT.projectPath,
+ reason: 'project-close',
+ closeWindowById: () => {},
+ });
+
+ expect(listNoteWindowsForProject('/Users/me/other')).toEqual([2]);
+ });
+
+ test('a project with no note windows closes nothing', () => {
+ const closeWindowById = vi.fn(() => {});
+ expect(
+ closeNoteWindowsForProject({
+ projectRoot: PROJECT.projectPath,
+ reason: 'quit',
+ closeWindowById,
+ }),
+ ).toEqual([]);
+ expect(closeWindowById).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/desktop/src/main/note-window.ts b/packages/desktop/src/main/note-window.ts
new file mode 100644
index 000000000..918a47f90
--- /dev/null
+++ b/packages/desktop/src/main/note-window.ts
@@ -0,0 +1,448 @@
+/**
+ * Popped-out note window — a dedicated `--ok-mode=note` window showing exactly
+ * one document full-window.
+ *
+ * Modeled on `terminal-window.ts`: same renderer bundle, a distinct window mode,
+ * attach-mode argv, the dual-signal show gate, and a windowId-keyed registry
+ * outside `windowsByPath` so N pop-outs coexist per project. It differs from the
+ * terminal window in three ways:
+ * - It targets a document. `--ok-initial-doc` seeds the renderer hash before
+ * first render, so the window boots straight into its document.
+ * - It is never project-less. A document only exists inside a project, so the
+ * factory requires a project context rather than accepting null.
+ * - Its registry identity is content-keyed `(projectRoot, docName)`, so
+ * `openNoteWindow` focuses an existing window instead of creating a second.
+ *
+ * Dedup is race-free without the slides registry's in-flight-promise map:
+ * `openNoteWindow` looks up and registers synchronously, before the async
+ * renderer load starts, so two calls in the same tick cannot both miss.
+ */
+
+import { TERMINAL_CLIS } from '@inkeep/open-knowledge-core';
+import type { OkNoteWindowMainAction } from '@inkeep/open-knowledge-core/desktop-bridge';
+import type { NoteWindowContext, NoteWindowEntryPoint } from './note-window-registry.ts';
+import {
+ findNoteWindowForDoc,
+ listNoteWindowsForProject,
+ registerNoteWindow,
+ touchNoteWindow,
+ unregisterNoteWindow,
+} from './note-window-registry.ts';
+import { recordNoteWindowOpened } from './note-window-telemetry.ts';
+import type { VibrancyMaterial } from './reduced-transparency-handler.ts';
+import type { ShowGateRegistry } from './show-gate.ts';
+import type { BrowserWindowLike } from './window-manager.ts';
+
+/** A created window exposing the numeric `id` the registry wiring needs. */
+export type NoteBrowserWindow = BrowserWindowLike & { readonly id: number };
+
+/** Project context a note window inherits (attach-mode). Never null. */
+export interface NoteWindowProject {
+ readonly projectPath: string;
+ readonly projectName: string;
+ readonly collabUrl: string;
+ readonly apiOrigin: string;
+}
+
+export interface CreateNoteWindowDeps {
+ /** Creates the real BrowserWindow (with `show: false`); the show gate reveals it. */
+ createWindow(opts: { additionalArguments: string[]; title: string }): NoteBrowserWindow;
+ /** Path to the built renderer HTML (packaged/prod). */
+ rendererEntryPath: string;
+ /** electron-vite dev-server URL for HMR; when set, `loadURL` is used over `loadFile`. */
+ rendererDevUrl?: string | null;
+ /** App version, passed to the preload via additionalArguments. */
+ appVersion: string;
+ /** Dual-signal show coordinator — note windows get `kind: 'note'`. */
+ showGate: ShowGateRegistry;
+ /** Inherited project context (attach-mode). */
+ project: NoteWindowProject;
+ /** The document this window opens on. */
+ docName: string;
+ /** Applies cascade placement (and, later, the remembered per-project frame). */
+ placeWindow?(window: NoteBrowserWindow): void;
+ /**
+ * Attaches the external-link navigation safety net, called before the renderer
+ * loads. Injected because the net's openAsset/openExternal delegates are
+ * Electron/shell-bound and belong in the composition root, not this pure
+ * factory — the same reason `WindowManager` injects its own `safetyNet`. A
+ * note window renders the same untrusted document content as an editor window
+ * (raw `<a href>`, `target=_blank`, asset links), so without this a click that
+ * escapes the renderer's own handler navigates the top frame to an external
+ * origin, where the preload re-exposes the `okDesktop` bridge.
+ */
+ attachSafetyNet?(window: NoteBrowserWindow): void;
+ /** Fired after the registry entry is dropped, for main-side per-window state
+ * that also has to forget this window (its active-target snapshot). */
+ onClosed?(windowId: number): void;
+}
+
+export interface NoteWindowNativeChromeOptions {
+ readonly vibrancy?: VibrancyMaterial;
+ readonly trafficLightPosition?: { readonly x: number; readonly y: number };
+}
+
+/**
+ * Native chrome policy for the compact note surface.
+ *
+ * Electron positions the macOS traffic-light frame by its top edge. The native
+ * frame is 14px tall, so y=17 centers it in the renderer's 48px titlebar.
+ * `window` vibrancy avoids electron/electron#27882's double-border artifact from
+ * the `sidebar` material while retaining the translucent native treatment.
+ */
+export function noteWindowNativeChromeOptions(
+ platform: NodeJS.Platform,
+): NoteWindowNativeChromeOptions {
+ if (platform !== 'darwin') return {};
+ return {
+ vibrancy: 'window',
+ trafficLightPosition: { x: 22, y: 17 },
+ };
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null;
+}
+
+function isNullableString(value: unknown): value is string | null {
+ return typeof value === 'string' || value === null;
+}
+
+type NoteWindowMainActionKind = OkNoteWindowMainAction['kind'];
+const NOTE_WINDOW_MAIN_ACTION_KINDS = {
+ 'active-input': true,
+ 'agent-thread': true,
+ 'terminal-launch': true,
+ 'reveal-comments': true,
+} satisfies Record<NoteWindowMainActionKind, true>;
+
+function isNoteWindowMainActionKind(value: unknown): value is NoteWindowMainActionKind {
+ return typeof value === 'string' && Object.hasOwn(NOTE_WINDOW_MAIN_ACTION_KINDS, value);
+}
+
+/** Runtime validation for the renderer-originated cross-window intent. */
+export function parseNoteWindowMainAction(value: unknown): OkNoteWindowMainAction | null {
+ if (!isRecord(value) || !isNoteWindowMainActionKind(value.kind)) return null;
+
+ if (value.kind === 'active-input') {
+ if (
+ typeof value.text !== 'string' ||
+ typeof value.newTab !== 'boolean' ||
+ typeof value.submit !== 'boolean' ||
+ (value.target !== undefined && value.target !== 'agents')
+ )
+ return null;
+ return {
+ kind: 'active-input',
+ text: value.text,
+ newTab: value.newTab,
+ submit: value.submit,
+ ...(value.target === 'agents' ? { target: 'agents' as const } : {}),
+ };
+ }
+
+ if (value.kind === 'agent-thread') {
+ if (
+ (value.agentSource !== 'registry' && value.agentSource !== 'custom') ||
+ typeof value.agentId !== 'string' ||
+ !isNullableString(value.prompt) ||
+ !isNullableString(value.docName) ||
+ !isNullableString(value.titleHint)
+ )
+ return null;
+ return {
+ kind: 'agent-thread',
+ agentSource: value.agentSource,
+ agentId: value.agentId,
+ prompt: value.prompt,
+ docName: value.docName,
+ titleHint: value.titleHint,
+ };
+ }
+
+ if (value.kind === 'terminal-launch') {
+ if (
+ typeof value.prompt !== 'string' ||
+ typeof value.cli !== 'string' ||
+ !Object.hasOwn(TERMINAL_CLIS, value.cli) ||
+ typeof value.stage !== 'boolean'
+ )
+ return null;
+ const cli = value.cli as keyof typeof TERMINAL_CLIS;
+ return {
+ kind: 'terminal-launch',
+ prompt: value.prompt,
+ cli,
+ stage: value.stage,
+ };
+ }
+
+ if (value.kind === 'reveal-comments') {
+ if (
+ typeof value.docName !== 'string' ||
+ value.docName.trim() === '' ||
+ (value.scope !== 'doc' && value.scope !== 'queue')
+ )
+ return null;
+ return { kind: 'reveal-comments', docName: value.docName, scope: value.scope };
+ }
+
+ const exhaustiveKind: never = value.kind;
+ return exhaustiveKind;
+}
+
+export interface DispatchNoteWindowMainActionDeps<TTarget> {
+ readonly originWindowId: number | null;
+ readonly action: unknown;
+ readonly getContext: (windowId: number) => NoteWindowContext | undefined;
+ /** Focuses the owning project window and returns the live delivery target. */
+ readonly focusProjectWindow: (projectRoot: string) => TTarget | null;
+ readonly send: (target: TTarget, action: OkNoteWindowMainAction) => void;
+}
+
+/**
+ * Authorize, validate, focus, then deliver a note-window action.
+ *
+ * Kept outside the Electron composition root so the load-bearing order is
+ * executable in the unit tier; the live Electron smoke separately proves the
+ * renderer/preload/main/renderer wiring that this pure decision cannot see.
+ */
+export function dispatchNoteWindowMainActionToProject<TTarget>(
+ deps: DispatchNoteWindowMainActionDeps<TTarget>,
+):
+ | { readonly ok: true }
+ | {
+ readonly ok: false;
+ readonly reason: 'invalid-action' | 'not-note-window' | 'project-not-open';
+ } {
+ if (deps.originWindowId === null) return { ok: false, reason: 'not-note-window' };
+ const context = deps.getContext(deps.originWindowId);
+ if (!context) return { ok: false, reason: 'not-note-window' };
+ const action = parseNoteWindowMainAction(deps.action);
+ if (!action) return { ok: false, reason: 'invalid-action' };
+ const target = deps.focusProjectWindow(context.projectRoot);
+ if (!target) return { ok: false, reason: 'project-not-open' };
+ deps.send(target, action);
+ return { ok: true };
+}
+
+/**
+ * Window titles are main-owned and set at construction. The title tracks the
+ * displayed document from here on via the active-target push, not via the
+ * renderer's `page-title-updated` (which every creation site preventDefaults).
+ */
+export function noteWindowTitle(docName: string): string {
+ return docName;
+}
+
+export function createNoteWindow(deps: CreateNoteWindowDeps): NoteBrowserWindow {
+ const { project, docName } = deps;
+ const window = deps.createWindow({
+ additionalArguments: [
+ '--ok-mode=note',
+ `--ok-app-version=${deps.appVersion}`,
+ // Attach-mode: inherit the launching project's collab + api server. The
+ // note window never spawns a server, so its edits land on the same Y.Doc
+ // the main window is editing — that is the whole live-sync story.
+ `--ok-collab-url=${project.collabUrl}`,
+ `--ok-api-origin=${project.apiOrigin}`,
+ `--ok-project-path=${project.projectPath}`,
+ `--ok-project-name=${project.projectName}`,
+ // Seeds location.hash pre-render, so the window boots on its document
+ // rather than flashing the home surface first.
+ `--ok-initial-doc=${docName}`,
+ ],
+ title: noteWindowTitle(docName),
+ });
+
+ // Guard the window's navigation BEFORE it loads: `setWindowOpenHandler` /
+ // `will-navigate` must be registered before `loadFile`/`loadURL` to catch the
+ // first navigation.
+ deps.attachSafetyNet?.(window);
+
+ // Register BEFORE the renderer loads: this is the window's only project
+ // source for main-side resolution, and registering synchronously is what
+ // makes same-tick dedup race-free.
+ registerNoteWindow(window.id, {
+ projectRoot: project.projectPath,
+ collabUrl: project.collabUrl,
+ apiOrigin: project.apiOrigin,
+ currentDocName: docName,
+ });
+
+ const disposeShowGate = deps.showGate.register(window, { kind: 'note' });
+ window.on('closed', () => {
+ disposeShowGate();
+ unregisterNoteWindow(window.id);
+ deps.onClosed?.(window.id);
+ });
+
+ deps.placeWindow?.(window);
+
+ // Surface load failures with a grep-able structured warn rather than
+ // discarding the rejection — the show gate's 5 s safety timeout still reveals
+ // the (blank) window so the failure is visible instead of silent.
+ const loadPromise = deps.rendererDevUrl
+ ? window.loadURL(deps.rendererDevUrl)
+ : window.loadFile(deps.rendererEntryPath);
+ loadPromise.catch((err: unknown) => {
+ console.warn(
+ JSON.stringify({
+ event: 'note-window-load-failed',
+ windowId: window.id,
+ target: deps.rendererDevUrl ?? deps.rendererEntryPath,
+ message: err instanceof Error ? (err.stack ?? err.message) : String(err),
+ }),
+ );
+ });
+
+ return window;
+}
+
+/** The editor-window project fields the resolver reads. The full `ProjectContext`
+ * (window-manager.ts) is structurally assignable to this. */
+interface EditorProjectContext {
+ readonly projectPath: string;
+ readonly projectName: string;
+ readonly apiOrigin: string;
+}
+
+/**
+ * Resolve the project a new note window inherits from the invoking window.
+ *
+ * An editor window's `windowsByPath` context wins, with its collab URL derived
+ * from `apiOrigin` through the same helper the editor's own dials use.
+ * Otherwise an invoking NOTE window's registry context carries the project, so
+ * popping out from inside a pop-out works.
+ *
+ * Returns null when neither resolves. Unlike a terminal window there is no
+ * project-less fallback: a document only exists inside a project, so no project
+ * means no window rather than a home-directory one.
+ */
+export function resolveNoteWindowProject(args: {
+ readonly editor: EditorProjectContext | null;
+ readonly note: NoteWindowContext | undefined;
+ readonly collabUrlFromApiOrigin: (apiOrigin: string) => string;
+ readonly projectNameFromPath: (projectPath: string) => string;
+}): NoteWindowProject | null {
+ if (args.editor) {
+ return {
+ projectPath: args.editor.projectPath,
+ projectName: args.editor.projectName,
+ collabUrl: args.collabUrlFromApiOrigin(args.editor.apiOrigin),
+ apiOrigin: args.editor.apiOrigin,
+ };
+ }
+ if (args.note) {
+ return {
+ projectPath: args.note.projectRoot,
+ projectName: args.projectNameFromPath(args.note.projectRoot),
+ collabUrl: args.note.collabUrl,
+ apiOrigin: args.note.apiOrigin,
+ };
+ }
+ return null;
+}
+
+/**
+ * The project scope a window's main-side actions operate against.
+ *
+ * Editor windows resolve through `windowsByPath`. Note windows are deliberately
+ * absent from that map — it is one-per-project focus-existing, which would block
+ * N pop-outs — so `getContextForBrowserWindow` returns nothing for them. Without
+ * this fallback, every containment-gated handler would treat a focused pop-out
+ * as having no project at all: asset clicks and copy-image refuse outright;
+ * reveal, trash, and show-item-in-folder fall back to their no-project arms; and
+ * spawn-cursor takes its deliberately PERMISSIVE no-scope path (a containment
+ * gap). Resolving the note window's project here closes all of those for a
+ * focused pop-out.
+ *
+ * Resolved per field rather than per source, so an editor context that carries
+ * a path but no origin behaves exactly as an editor-only context does.
+ */
+export function resolveWindowProjectScope(args: {
+ readonly editor:
+ | { readonly projectPath?: string; readonly apiOrigin?: string }
+ | null
+ | undefined;
+ readonly note: NoteWindowContext | undefined;
+}): { projectPath: string | undefined; apiOrigin: string | undefined } {
+ return {
+ projectPath: args.editor?.projectPath ?? args.note?.projectRoot,
+ apiOrigin: args.editor?.apiOrigin ?? args.note?.apiOrigin,
+ };
+}
+
+export interface OpenNoteWindowResult {
+ /** 'created' when a new window was made, 'focused' on a dedup hit. */
+ readonly outcome: 'created' | 'focused';
+ readonly windowId: number;
+}
+
+/**
+ * The single entry point every surface (tab menu, palette, Window menu) calls.
+ * Focuses the existing window for this `(project, document)` identity when one
+ * exists, otherwise creates it. Only a real creation emits the adoption span.
+ */
+export function openNoteWindow(
+ deps: CreateNoteWindowDeps & {
+ /**
+ * Which surface the user opened this from, or undefined when nothing did —
+ * a server-restart recreate, say. Undefined emits NO adoption span: those
+ * windows are the app putting back what was already there, and counting
+ * them would inflate the one number this feature reports.
+ */
+ readonly entryPoint?: NoteWindowEntryPoint;
+ /** Resolves a live window object from its id, for the focus-existing path. */
+ focusWindowById(windowId: number): boolean;
+ },
+): OpenNoteWindowResult {
+ const existingId = findNoteWindowForDoc(deps.project.projectPath, deps.docName);
+ if (existingId !== undefined && deps.focusWindowById(existingId)) {
+ touchNoteWindow(existingId);
+ return { outcome: 'focused', windowId: existingId };
+ }
+ // A registry entry whose window could not be focused is stale (the window
+ // died without firing 'closed'); drop it so it cannot shadow the new window.
+ if (existingId !== undefined) unregisterNoteWindow(existingId);
+
+ const window = createNoteWindow(deps);
+ if (deps.entryPoint !== undefined) recordNoteWindowOpened({ entryPoint: deps.entryPoint });
+ return { outcome: 'created', windowId: window.id };
+}
+
+/**
+ * Owner-close cascade: a project's note windows close with its main window and
+ * do not survive as independents.
+ *
+ * `reason` is load-bearing rather than cosmetic. On `quit` the restore snapshot
+ * must already have been captured before this runs, so the windows are recorded
+ * for the next launch; on `project-close` they are gone for good and must NOT be
+ * recorded. Keeping the distinction in the signature stops a caller from
+ * cascading without having decided which case it is in.
+ */
+export function closeNoteWindowsForProject(args: {
+ readonly projectRoot: string;
+ readonly reason: 'project-close' | 'quit';
+ readonly closingProjectWindow?: BrowserWindowLike;
+ readonly activeProjectWindow?: BrowserWindowLike;
+ closeWindowById(windowId: number): void;
+}): number[] {
+ if (
+ args.activeProjectWindow !== undefined &&
+ args.activeProjectWindow !== args.closingProjectWindow &&
+ args.activeProjectWindow.isDestroyed?.() !== true
+ ) {
+ return [];
+ }
+
+ const windowIds = listNoteWindowsForProject(args.projectRoot);
+ for (const windowId of windowIds) {
+ args.closeWindowById(windowId);
+ // Drop the entry eagerly. The 'closed' handler also unregisters, but a
+ // destroyed-window close() can skip it, and an orphaned entry would keep
+ // shadowing later dedup lookups for a window that no longer exists.
+ unregisterNoteWindow(windowId);
+ }
+ return windowIds;
+}
diff --git a/packages/desktop/src/main/reduced-transparency-handler.ts b/packages/desktop/src/main/reduced-transparency-handler.ts
index fdd42db99..9ab2ae403 100644
--- a/packages/desktop/src/main/reduced-transparency-handler.ts
+++ b/packages/desktop/src/main/reduced-transparency-handler.ts
@@ -15,9 +15,10 @@
* reduce)` block in globals.css reverts the alpha-aware outer canvas
* to solid `var(--sidebar)` — the renderer side is purely declarative
* and runs whether or not `window.okDesktop` is present.
- * 2. Per-window material differentiation. All open windows share the
- * Electron one-vibrancy-per-window constraint; the runtime toggle
- * applies uniformly.
+ * 2. Material policy. Windows use the shared default unless their factory
+ * registers a preferred material for a native-chrome compatibility
+ * reason. The accessibility toggle still applies uniformly: reduced
+ * transparency disables every material.
* 3. State.json caching. The preference is observed live via matchMedia
* and recovers on cold-launch by the same path; nothing to cache.
*
@@ -92,6 +93,16 @@ export interface ReducedTransparencyDeps {
*/
const lastAppliedMaterial = new WeakMap<BrowserWindowVibrancyTarget, VibrancyMaterial | null>();
+/** Per-window native material exceptions registered by BrowserWindow factories. */
+const preferredMaterial = new WeakMap<BrowserWindowVibrancyTarget, VibrancyMaterial>();
+
+export function setPreferredWindowVibrancy(
+ win: BrowserWindowVibrancyTarget,
+ material: VibrancyMaterial,
+): void {
+ preferredMaterial.set(win, material);
+}
+
/**
* Apply the user's `prefers-reduced-transparency` preference to every open
* BrowserWindow's vibrancy material, skipping windows already at the target
@@ -111,7 +122,6 @@ export function applyReducedTransparency(
deps: ReducedTransparencyDeps,
reducedTransparency: boolean,
): void {
- const material: VibrancyMaterial | null = reducedTransparency ? null : deps.defaultVibrancy;
// Four-way partition of the windows we iterated: applied (windowCount) +
// skipped (already at target) + failed (threw and was caught) + destroyed
// (filtered mid-teardown). All four are emitted so the counts sum to
@@ -121,16 +131,25 @@ export function applyReducedTransparency(
let skippedCount = 0;
let failedCount = 0;
let destroyedCount = 0;
+ const vibrancyMaterials: Partial<Record<VibrancyMaterial | 'none', number>> = {};
+ const recordMaterial = (material: VibrancyMaterial | null): void => {
+ const key = material ?? 'none';
+ vibrancyMaterials[key] = (vibrancyMaterials[key] ?? 0) + 1;
+ };
for (const win of deps.getAllWindows()) {
if (win.isDestroyed?.() === true) {
destroyedCount += 1;
continue;
}
+ const material: VibrancyMaterial | null = reducedTransparency
+ ? null
+ : (preferredMaterial.get(win) ?? deps.defaultVibrancy);
// Idempotence guard: skip a window already at the target material (see
// `lastAppliedMaterial` for the flicker rationale). `material` is never
// `undefined`, so the WeakMap's absent-key `undefined` reads as "never
// applied to this window" and falls through to apply.
if (lastAppliedMaterial.get(win) === material) {
+ recordMaterial(material);
skippedCount += 1;
continue;
}
@@ -139,6 +158,7 @@ export function applyReducedTransparency(
// Memo only AFTER a successful native call — a throw leaves the window
// unmemoized so the next pass re-attempts rather than skipping it.
lastAppliedMaterial.set(win, material);
+ recordMaterial(material);
windowCount += 1;
} catch (err) {
failedCount += 1;
@@ -156,7 +176,8 @@ export function applyReducedTransparency(
JSON.stringify({
event: 'reduced-transparency-applied',
reducedTransparency,
- vibrancy: material,
+ vibrancy: reducedTransparency ? null : deps.defaultVibrancy,
+ vibrancyMaterials,
windowCount,
skippedCount,
failedCount,
diff --git a/packages/desktop/src/main/show-gate.ts b/packages/desktop/src/main/show-gate.ts
index 77d5713e5..992c1cf2b 100644
--- a/packages/desktop/src/main/show-gate.ts
+++ b/packages/desktop/src/main/show-gate.ts
@@ -100,7 +100,7 @@ export interface ShowGateRegistry {
fireThemeApplied(window: BrowserWindowLike): void;
}
-type WindowKind = 'editor' | 'navigator' | 'terminal';
+type WindowKind = 'editor' | 'navigator' | 'terminal' | 'note';
interface PerWindowGateState {
readyToShow: boolean;
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index 85b411080..1f1b3aea4 100644
Binary files a/packages/desktop/src/main/state-store.ts and b/packages/desktop/src/main/state-store.ts differ
diff --git a/packages/desktop/src/main/terminal-window.test.ts b/packages/desktop/src/main/terminal-window.test.ts
index 30ca86a03..68be0eb1d 100644
--- a/packages/desktop/src/main/terminal-window.test.ts
+++ b/packages/desktop/src/main/terminal-window.test.ts
@@ -282,4 +282,46 @@ describe('resolveTerminalWindowProject', () => {
test('no focused project (Navigator / no window) resolves to null', () => {
expect(resolveTerminalWindowProject({ editor: null, terminal: undefined })).toBeNull();
});
+
+ test('a focused note window contributes its project instead of opening project-less', () => {
+ // A pop-out is in neither windowsByPath nor the terminal registry, so
+ // without this arm New Terminal Window from a focused pop-out silently
+ // opened a home-directory shell.
+ expect(
+ resolveTerminalWindowProject({
+ editor: null,
+ terminal: undefined,
+ note: {
+ projectRoot: '/Users/me/proj',
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+ currentDocName: 'notes/alpha',
+ },
+ }),
+ ).toEqual({
+ projectPath: '/Users/me/proj',
+ projectName: 'proj',
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+ });
+ });
+
+ test('an editor context still wins over a focused note window', () => {
+ const resolved = resolveTerminalWindowProject({
+ editor: {
+ projectPath: '/Users/me/editor',
+ projectName: 'editor',
+ port: 5300,
+ apiOrigin: 'http://localhost:5300',
+ },
+ terminal: undefined,
+ note: {
+ projectRoot: '/Users/me/proj',
+ collabUrl: 'ws://localhost:5200/collab',
+ apiOrigin: 'http://localhost:5200',
+ currentDocName: 'notes/alpha',
+ },
+ });
+ expect(resolved?.projectPath).toBe('/Users/me/editor');
+ });
});
diff --git a/packages/desktop/src/main/terminal-window.ts b/packages/desktop/src/main/terminal-window.ts
index 33468fcd4..a4f4ed95a 100644
--- a/packages/desktop/src/main/terminal-window.ts
+++ b/packages/desktop/src/main/terminal-window.ts
@@ -17,6 +17,7 @@
*/
import { basename } from 'node:path';
+import type { NoteWindowContext } from './note-window-registry.ts';
import type { ShowGateRegistry } from './show-gate.ts';
import { type TerminalReaper, wireWindowTerminalReap } from './terminal-lifecycle.ts';
import {
@@ -142,6 +143,9 @@ interface EditorProjectContext {
export function resolveTerminalWindowProject(args: {
readonly editor: EditorProjectContext | null;
readonly terminal: TerminalWindowContext | undefined;
+ /** A focused NOTE window's project, so New Terminal Window invoked from a
+ * pop-out inherits that project instead of opening project-less. */
+ readonly note?: NoteWindowContext | undefined;
}): TerminalWindowProject | null {
if (args.editor) {
return {
@@ -159,5 +163,13 @@ export function resolveTerminalWindowProject(args: {
apiOrigin: args.terminal.apiOrigin ?? '',
};
}
+ if (args.note) {
+ return {
+ projectPath: args.note.projectRoot,
+ projectName: basename(args.note.projectRoot),
+ collabUrl: args.note.collabUrl,
+ apiOrigin: args.note.apiOrigin,
+ };
+ }
return null;
}
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index ba40d997e..2339f1683 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -788,6 +788,22 @@ export interface WindowManagerDeps {
* injections typically pass a much smaller value.
*/
utilityInitTimeoutMs?: number;
+ /**
+ * Notified after a server restart has successfully recreated a project's
+ * window on the fresh server, before the old window closes.
+ *
+ * Exists for popped-out note windows. They live outside `windowsByPath`, so
+ * the recreate above does not reach them, and their attach argv is a frozen
+ * snapshot — a note window left behind would hold a collab URL pointing at
+ * the terminated server and could never reconnect, even though the project is
+ * healthy again. The window manager stays unaware of the note registry (as it
+ * is of the terminal registry); the consumer wires the recreate.
+ */
+ onProjectServerRestarted?(args: {
+ readonly projectPath: string;
+ /** The FRESH server's origin, so the recreate attaches to the new port. */
+ readonly apiOrigin: string;
+ }): void;
/** Logger. */
log?: {
info(obj: object, msg: string): void;
@@ -1485,8 +1501,9 @@ export class WindowManager {
// exists — see the failure branch below.
const originating = this.windowsByPath.get(canonicalKey);
if (originating) this.windowsByPath.delete(canonicalKey);
+ let recreated: ProjectContext;
try {
- await this.createProjectWindow({
+ recreated = await this.createProjectWindow({
projectPath: resolved,
pendingServerRestartedToast: true,
localOpCliArgs: opts?.localOpCliArgs,
@@ -1511,6 +1528,33 @@ export class WindowManager {
}
return { ok: false, reason: 'other' };
}
+ // The project window is back on the fresh server. Note windows are not in
+ // `windowsByPath`, so they were not recreated above and still hold argv
+ // pointing at the terminated server — recreate them before the old window
+ // closes, so the pop-outs come back with the project rather than lingering
+ // as permanently disconnected windows.
+ //
+ // Isolated in its own try/catch: the note-window recreate is a SECONDARY
+ // concern, so a throw in the injected callback (a `BrowserWindow`
+ // constructor failure under memory pressure, say) must not skip the
+ // `closeAndAwait` teardown below and strand the old window as a zombie
+ // pointing at the terminated server.
+ try {
+ this.deps.onProjectServerRestarted?.({
+ projectPath: resolved,
+ apiOrigin: recreated.apiOrigin,
+ });
+ } catch (err) {
+ this.deps.log?.warn(
+ {
+ event: 'desktop-server-restart',
+ outcome: 'note-recreate-failed',
+ err: err instanceof Error ? (err.stack ?? err.message) : String(err),
+ projectPath: resolved,
+ },
+ '[window-manager] project window recreated, but a note-window recreate threw',
+ );
+ }
if (originating) await this.closeAndAwait(originating.window);
return { ok: true };
}
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index db2a50aab..3932f2bb8 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -47,6 +47,8 @@ import type {
OkMcpWiringShowPayload,
OkMenuAction,
OkMenuDispatchRequest,
+ OkNoteWindowMainAction,
+ OkNoteWindowMainActionResult,
OkOnboardingShowPayload,
OkPtyData,
OkPtyExit,
@@ -603,6 +605,34 @@ const bridge: OkDesktopBridge = {
open: () => invoke('ok:navigator:open'),
},
+ noteWindow: {
+ open: async (docName: string, entryPoint: 'tab-menu' | 'palette') => {
+ const result = await invoke('ok:window:open-note', { kind: 'open', docName, entryPoint });
+ // `ok:window:open-note` is overloaded (`open` + `dispatch-to-main`), so its
+ // result type unions both verbs' responses. Fail loudly on the one arm
+ // that would otherwise slip through the cast as a silent lie — a dispatch
+ // success `{ ok: true }` with no `outcome`, which a caller branching on
+ // `outcome` would read as `undefined` while the type insists it is
+ // `'created' | 'focused'`. A well-behaved main handler never returns it
+ // for an `open` request; this makes a future branch bug loud, not silent.
+ if (result.ok && !('outcome' in result)) {
+ throw new Error('ok:window:open-note returned a non-open result for an open request');
+ }
+ return result as Awaited<ReturnType<OkDesktopBridge['noteWindow']['open']>>;
+ },
+ dispatchToMain: (action: OkNoteWindowMainAction) =>
+ invoke('ok:window:open-note', {
+ kind: 'dispatch-to-main',
+ action,
+ }) as Promise<OkNoteWindowMainActionResult>,
+ onMainAction(cb: (action: OkNoteWindowMainAction) => void) {
+ const listener = (_event: IpcRendererEvent, action: OkNoteWindowMainAction) => cb(action);
+ // biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)
+ ipcRenderer.on('ok:note-window:main-action', listener);
+ return () => ipcRenderer.removeListener('ok:note-window:main-action', listener);
+ },
+ },
+
seed: {
plan: (options) => invoke('ok:seed:plan', options),
apply: (plan, options) => invoke('ok:seed:apply', plan, options),
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index fc79a87cc..693468239 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -30,7 +30,16 @@
* existing channels is preferred over net-new hand-rolled channels until
* that migration lands.
*
- * Count is 93 (ratchet cap 93). The 74→75 bump reconciled a merge collision:
+ * Count is 94 (ratchet cap 94). The 93→94 bump added the pop-out note window
+ * (`ok:window:open-note`): the doc-tab context menu and the palette both need
+ * main to spawn a `--ok-mode=note` BrowserWindow for a document. The same
+ * channel now carries the discriminated note→main conversation handoff; this
+ * widens its window-routing contract without adding a second request slot. It
+ * could not fold — `ok:menu:dispatch` is contractually the custom-drawn
+ * Windows/Linux menu bar alone, and `ok:project:open` is keyed by project path
+ * and opens a project window. One slot covers both renderer surfaces and the
+ * handoff; the Window-menu entry point is main-originated and adds none.
+ * The 74→75 bump reconciled a merge collision:
* the worktree selector (`ok:worktree:dispatch`) and the terminal-controls PR
* (`ok:terminal:cli-installed-map`) each landed in the base tree's single free
* slot concurrently. The 75→76 bump then unioned in the desktop
@@ -122,6 +131,8 @@ import type {
OkMenuDispatchRequest,
OkMenuDispatchRole,
OkMenuRendererSnapshot,
+ OkNoteWindowMainAction,
+ OkNoteWindowMainActionResult,
OkPtyAdoptResult,
OkPtyCreateResult,
OkPtyListEntry,
@@ -1187,6 +1198,29 @@ export interface RequestChannels {
* dropdown, `CommandPalette`. No payload, no return — IPC-ack only.
*/
'ok:navigator:open': { args: []; result: undefined };
+ /**
+ * Popped-note-window dispatch. `open` creates/focuses a note window from an
+ * editor renderer; `dispatch-to-main` carries a conversation/comments intent
+ * from a note renderer back to its owning project window.
+ *
+ * Could not fold. `ok:menu:dispatch` is contractually the custom-drawn
+ * Windows/Linux menu bar and nothing else; `ok:project:open` is keyed by
+ * project path and opens a project window. The Window-menu entry point needs
+ * no channel at all — it runs main-side — so this one channel serves both
+ * renderer-originated surfaces and the feedback handoff without another
+ * request channel.
+ */
+ 'ok:window:open-note': {
+ args: [
+ request:
+ | { kind: 'open'; docName: string; entryPoint: 'tab-menu' | 'palette' }
+ | { kind: 'dispatch-to-main'; action: OkNoteWindowMainAction },
+ ];
+ result:
+ | { ok: true; outcome: 'created' | 'focused' }
+ | { ok: false; reason: 'no-project' | 'invalid-request' }
+ | OkNoteWindowMainActionResult;
+ };
/**
* Toast A "Relaunch now" action: renderer invokes this after the user
* clicks the sonner action button. Main handler calls
diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.ts
index ea3b1f114..7313299a0 100644
--- a/packages/desktop/src/shared/ipc-events.ts
+++ b/packages/desktop/src/shared/ipc-events.ts
@@ -15,6 +15,7 @@
*/
import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
+import type { OkNoteWindowMainAction } from '@inkeep/open-knowledge-core/desktop-bridge';
import type {
OkDesktopConfig,
OkLocalOpAuthEvent,
@@ -49,6 +50,11 @@ export interface EventChannels {
'ok:project:recent-removed-missing': { payload: OkRecentRemovedMissingInfo };
/** Main → renderer menu-action dispatch (File → New Doc, Edit → Toggle Sidebar, etc.). */
'ok:menu-action': { payload: OkMenuAction };
+ /**
+ * A popped-out note window handed a conversation/comments intent to its
+ * owning project window. Main focuses that window before sending.
+ */
+ 'ok:note-window:main-action': { payload: OkNoteWindowMainAction };
/**
* `autoUpdater.on('update-downloaded')` fan-out to every open BrowserWindow
* so renderer Toast A ("Update downloaded" + "Relaunch now" action) can
diff --git a/packages/desktop/src/shared/ok-desktop-mode.test.ts b/packages/desktop/src/shared/ok-desktop-mode.test.ts
index 43e6c5207..2c405c3bb 100644
--- a/packages/desktop/src/shared/ok-desktop-mode.test.ts
+++ b/packages/desktop/src/shared/ok-desktop-mode.test.ts
@@ -14,6 +14,10 @@ describe('resolveOkDesktopMode', () => {
expect(resolveOkDesktopMode('editor')).toBe('editor');
});
+ test('maps the note flag to the popped-out note window mode', () => {
+ expect(resolveOkDesktopMode('note')).toBe('note');
+ });
+
test('falls back to editor when the flag is absent', () => {
expect(resolveOkDesktopMode(undefined)).toBe('editor');
});
diff --git a/packages/desktop/src/shared/ok-desktop-mode.ts b/packages/desktop/src/shared/ok-desktop-mode.ts
index adec5d33e..8c934265d 100644
--- a/packages/desktop/src/shared/ok-desktop-mode.ts
+++ b/packages/desktop/src/shared/ok-desktop-mode.ts
@@ -9,5 +9,6 @@ import type { OkDesktopConfig } from './bridge-contract.ts';
export function resolveOkDesktopMode(raw: string | undefined): OkDesktopConfig['mode'] {
if (raw === 'navigator') return 'navigator';
if (raw === 'terminal') return 'terminal';
+ if (raw === 'note') return 'note';
return 'editor';
}
diff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
index 090138d49..7b4d04092 100644
--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
@@ -430,10 +430,32 @@ const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');
* `write-text`'s payload to carry both would erase the type safety
* of both channels' callers.
*
+ * Bumped from 93 to 94 for the pop-out note window:
+ *
+ * - `ok:window:open-note` — the doc-tab context menu and the command
+ * palette both ask main to pop a document into its own
+ * `--ok-mode=note` BrowserWindow. Main owns it because only main can
+ * create a window, resolve the sender's project from `windowsByPath`,
+ * and consult the note-window registry for focus-existing dedup.
+ *
+ * Could not fold. `ok:menu:dispatch` is contractually the custom-drawn
+ * Windows/Linux menu bar and nothing else ("the menubar is one
+ * surface"), so an unrelated verb there would break that contract.
+ * `ok:project:open` is keyed by project path and opens a PROJECT
+ * window, a different lifecycle and a different registry. There is no
+ * existing window-opening channel with a compatible payload.
+ *
+ * The same slot also carries a discriminated `dispatch-to-main` verb for
+ * conversation/comment actions started in a reduced note renderer. Main
+ * already owns the note→project-window association, so widening this
+ * window-routing channel preserves that boundary and adds no channel.
+ * One slot serves both renderer-originated open entry points and the
+ * handoff; the Window-menu entry point is main-originated and adds none.
+ *
* The typed-ipc migration remains the committed end state, with the
* `ipc-channels.ts` header updated in lock-step.
*/
-const REQUEST_CHANNEL_CAP = 93;
+const REQUEST_CHANNEL_CAP = 94;
/**
* Extract the body of an interface block by name. Returns the substring
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index 8dc4fa1ba..81d904983 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -1200,6 +1200,38 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
(findByLabel(collapsed, 'Show document panel')?.click as (() => void) | undefined)?.();
expect(onToggleDocPanel2).toHaveBeenCalledTimes(1);
});
+
+ test('note windows omit editor-only panel, sidebar, and terminal commands', () => {
+ const template = buildMenuTemplateForPlatform(
+ 'darwin',
+ makeDeps({
+ noteWindow: true,
+ onToggleSidebar: vi.fn(() => {}),
+ onToggleDocPanel: vi.fn(() => {}),
+ onToggleTerminal: vi.fn(() => {}),
+ onMoveTerminal: vi.fn(() => {}),
+ onNewTerminal: vi.fn(() => {}),
+ onNewTerminalWindow: vi.fn(() => {}),
+ onKillTerminal: vi.fn(() => {}),
+ terminalLive: true,
+ onToggleAgentPanel: vi.fn(() => {}),
+ }),
+ );
+
+ expect(findByLabel(template, 'Hide sidebar')).toBeUndefined();
+ expect(findByLabel(template, 'Show sidebar')).toBeUndefined();
+ expect(findByLabel(template, 'Hide document panel')).toBeUndefined();
+ expect(findByLabel(template, 'Show document panel')).toBeUndefined();
+ expect(findByLabel(template, 'Show Terminal')).toBeUndefined();
+ expect(findByLabel(template, 'Hide Terminal')).toBeUndefined();
+ expect(findByLabel(template, 'Move Terminal to right')).toBeUndefined();
+ expect(findByLabel(template, 'Move Terminal to bottom')).toBeUndefined();
+ expect(findByLabel(template, 'New Terminal')).toBeUndefined();
+ expect(findByLabel(template, 'Kill Terminal')).toBeUndefined();
+ expect(findByLabel(template, 'New Terminal Window')).toBeDefined();
+ expect(findByLabel(template, 'Show Agents')).toBeUndefined();
+ expect(findByLabel(template, 'Hide Agents')).toBeUndefined();
+ });
});
describe('buildMenuTemplate — View → Show/Hide Terminal', () => {
@@ -1639,3 +1671,64 @@ describe('buildMenuTemplate — View navigation history', () => {
expect(findByLabel(template, 'Forward')?.enabled).toBe(false);
});
});
+
+describe('Window → Open in New Window', () => {
+ const LABEL = 'Open in New Window';
+
+ test('is enabled when the focused window has a document active', () => {
+ const template = buildMenuTemplate(
+ makeDeps({
+ activeTarget: { kind: 'doc', identifier: 'notes/alpha' },
+ onOpenInNewWindow: vi.fn(() => {}),
+ }),
+ );
+ expect(findByLabel(template, LABEL)?.enabled).toBe(true);
+ });
+
+ test('is disabled when the focused window has no document active', () => {
+ // A menu leaf disables rather than hides — the user opened this menu
+ // deliberately, so the row should be visible and inert, not absent.
+ for (const activeTarget of [
+ { kind: 'folder' as const, identifier: 'notes' },
+ { kind: 'asset' as const, identifier: 'images/cat.png' },
+ { kind: null as const },
+ ]) {
+ const template = buildMenuTemplate(
+ makeDeps({ activeTarget, onOpenInNewWindow: vi.fn(() => {}) }),
+ );
+ expect(findByLabel(template, LABEL)?.enabled).toBe(false);
+ }
+ });
+
+ test('is disabled when the handler is unwired', () => {
+ const template = buildMenuTemplate(
+ makeDeps({ activeTarget: { kind: 'doc', identifier: 'notes/alpha' } }),
+ );
+ expect(findByLabel(template, LABEL)?.enabled).toBe(false);
+ });
+
+ test('invokes its handler once', () => {
+ const onOpenInNewWindow = vi.fn(() => {});
+ const template = buildMenuTemplate(
+ makeDeps({ activeTarget: { kind: 'doc', identifier: 'notes/alpha' }, onOpenInNewWindow }),
+ );
+
+ (findByLabel(template, LABEL)?.click as (() => void) | undefined)?.();
+ expect(onOpenInNewWindow).toHaveBeenCalledOnce();
+ });
+
+ test('sits in the Window menu on both platform branches', () => {
+ for (const platform of ['darwin', 'win32'] as const) {
+ const template = buildMenuTemplateForPlatform(
+ platform,
+ makeDeps({
+ activeTarget: { kind: 'doc', identifier: 'notes/alpha' },
+ onOpenInNewWindow: vi.fn(() => {}),
+ }),
+ );
+ const windowMenu = template.find((item) => item.label === 'Window');
+ const sub = windowMenu?.submenu as MenuItemConstructorOptions[] | undefined;
+ expect(findByLabel(sub ?? [], LABEL)).toBeDefined();
+ }
+ });
+});
diff --git a/packages/desktop/tests/main/reduced-transparency-handler.test.ts b/packages/desktop/tests/main/reduced-transparency-handler.test.ts
index 4aa15d405..cd9c3fe9d 100644
--- a/packages/desktop/tests/main/reduced-transparency-handler.test.ts
+++ b/packages/desktop/tests/main/reduced-transparency-handler.test.ts
@@ -4,6 +4,7 @@ import {
applyReducedTransparency,
type BrowserWindowVibrancyTarget,
type ReducedTransparencyDeps,
+ setPreferredWindowVibrancy,
} from '../../src/main/reduced-transparency-handler.ts';
interface WindowFixture {
@@ -102,6 +103,36 @@ describe('applyReducedTransparency — restore path (reduced=false)', () => {
expect(w.setVibrancy.mock.calls[0]).toEqual(['window']);
});
+
+ test('restores a preferred material without changing the shared default', () => {
+ const editor = makeWindow();
+ const note = makeWindow();
+ setPreferredWindowVibrancy(note.win, 'window');
+ const deps: ReducedTransparencyDeps = {
+ getAllWindows: () => [editor.win, note.win],
+ defaultVibrancy: 'sidebar',
+ };
+
+ applyReducedTransparency(deps, false);
+
+ expect(editor.setVibrancy.mock.calls[0]).toEqual(['sidebar']);
+ expect(note.setVibrancy.mock.calls[0]).toEqual(['window']);
+ });
+
+ test('reduced transparency disables preferred and default materials alike', () => {
+ const editor = makeWindow();
+ const note = makeWindow();
+ setPreferredWindowVibrancy(note.win, 'window');
+ const deps: ReducedTransparencyDeps = {
+ getAllWindows: () => [editor.win, note.win],
+ defaultVibrancy: 'sidebar',
+ };
+
+ applyReducedTransparency(deps, true);
+
+ expect(editor.setVibrancy.mock.calls[0]).toEqual([null]);
+ expect(note.setVibrancy.mock.calls[0]).toEqual([null]);
+ });
});
describe('applyReducedTransparency — diagnostic logging', () => {
@@ -146,6 +177,24 @@ describe('applyReducedTransparency — diagnostic logging', () => {
expect(parsed.windowCount).toBe(1);
});
+ test('reports every material actually restored when windows have preferences', () => {
+ const editor = makeWindow();
+ const note = makeWindow();
+ setPreferredWindowVibrancy(note.win, 'window');
+ const warn = vi.fn(() => {});
+ const deps: ReducedTransparencyDeps = {
+ getAllWindows: () => [editor.win, note.win],
+ defaultVibrancy: 'sidebar',
+ warn,
+ };
+
+ applyReducedTransparency(deps, false);
+
+ const line = warn.mock.calls.at(-1)?.[0] as unknown as string;
+ const parsed = JSON.parse(line);
+ expect(parsed.vibrancyMaterials).toEqual({ sidebar: 1, window: 1 });
+ });
+
test('windowCount counts only successfully-applied windows; destroyed windows go to destroyedCount', () => {
const live = makeWindow();
const dead = makeWindow({ destroyed: true });
diff --git a/packages/desktop/tests/main/show-gate.test.ts b/packages/desktop/tests/main/show-gate.test.ts
index fa81ccb78..6e6632030 100644
--- a/packages/desktop/tests/main/show-gate.test.ts
+++ b/packages/desktop/tests/main/show-gate.test.ts
@@ -121,6 +121,17 @@ describe('createShowGateRegistry — dual-signal show contract', () => {
expect(win.show).toHaveBeenCalledTimes(1);
});
+ test('note window reveals on the same dual signal as every other kind', () => {
+ const win = makeWindow();
+ env.registry.register(win, { kind: 'note' });
+
+ win.fireReadyToShow();
+ expect(win.show).not.toHaveBeenCalled();
+
+ env.registry.fireThemeApplied(win);
+ expect(win.show).toHaveBeenCalledTimes(1);
+ });
+
test('onShown fires once with the window kind after a successful show', () => {
const onShown = vi.fn((_kind: 'editor' | 'navigator') => {});
const registry = createShowGateRegistry({
@@ -242,6 +253,20 @@ describe('createShowGateRegistry — timeout fallback', () => {
});
});
+ test('note window + timeout → show called with the note kind in the warning', () => {
+ const win = makeWindow();
+ env.registry.register(win, { kind: 'note' });
+ win.fireReadyToShow();
+ expect(win.show).not.toHaveBeenCalled();
+ env.timers[0]?.cb();
+ expect(win.show).toHaveBeenCalledTimes(1);
+ expect(env.warns[0]?.obj).toEqual({
+ event: 'show-gate-timeout',
+ missing: 'theme-applied',
+ windowKind: 'note',
+ });
+ });
+
test('only theme-applied + timeout → show called with missing=ready-to-show', () => {
const win = makeWindow();
env.registry.register(win, { kind: 'navigator' });
diff --git a/packages/desktop/tests/main/state-store.test.ts b/packages/desktop/tests/main/state-store.test.ts
index 961e0920e..21d54ad63 100644
--- a/packages/desktop/tests/main/state-store.test.ts
+++ b/packages/desktop/tests/main/state-store.test.ts
@@ -12,13 +12,16 @@ import {
type PersistedWindowBounds,
parseAppState,
removeRecentProject,
+ restoreSurvivorPath,
type SaveAppStateFs,
saveAppStateToDir,
setLastUsedProjectParent,
+ setNoteWindowBounds,
setProjectSessionState,
setProjectWindowBounds,
setSpellCheckEnabled,
setTerminalDockState,
+ windowRestoreKey,
} from '../../src/main/state-store.ts';
function persistedWorkspace(
@@ -866,3 +869,177 @@ describe('state-store (projectWindowBounds — per-project window frame memory)'
expect(next.projectWindowBounds['/tmp/b']).toEqual(BOUNDS);
});
});
+
+describe('state-store (noteWindowBounds — per-project pop-out frame memory)', () => {
+ const FRAME: PersistedWindowBounds = {
+ x: 2400,
+ y: 120,
+ width: 900,
+ height: 1000,
+ isMaximized: false,
+ isFullScreen: false,
+ };
+
+ test('emptyState seeds an empty map', () => {
+ expect(emptyState().noteWindowBounds).toEqual({});
+ });
+
+ test('setNoteWindowBounds immutably records a frame', () => {
+ const original = emptyState();
+ const next = setNoteWindowBounds(original, '/tmp/a', FRAME);
+
+ expect(next.noteWindowBounds['/tmp/a']).toEqual(FRAME);
+ expect(original.noteWindowBounds).toEqual({});
+ });
+
+ test('the pop-out slot is independent of the project window frame', () => {
+ // Same key, different fields: a user who parks pop-outs on a second monitor
+ // must not have that overwrite where the project window itself opens.
+ let s = setProjectWindowBounds(emptyState(), '/tmp/a', {
+ ...FRAME,
+ x: 0,
+ y: 0,
+ });
+ s = setNoteWindowBounds(s, '/tmp/a', FRAME);
+
+ expect(s.projectWindowBounds['/tmp/a']?.x).toBe(0);
+ expect(s.noteWindowBounds['/tmp/a']?.x).toBe(2400);
+ });
+
+ test('round-trips through parseAppState', () => {
+ const s = setNoteWindowBounds(emptyState(), '/tmp/a', FRAME);
+ const reparsed = parseAppState(JSON.parse(JSON.stringify(s)));
+
+ expect(reparsed?.noteWindowBounds['/tmp/a']).toEqual(FRAME);
+ });
+
+ test('state written before the field existed parses to an empty map', () => {
+ // The additive contract: an older build's state has no such key, and this
+ // build must read it without a schema bump.
+ const legacy = { ...emptyState() } as Record<string, unknown>;
+ delete legacy.noteWindowBounds;
+
+ expect(parseAppState(legacy)?.noteWindowBounds).toEqual({});
+ });
+
+ test('a corrupt value coerces to an empty map rather than throwing', () => {
+ const parsed = parseAppState({ ...emptyState(), noteWindowBounds: 'nonsense' });
+ expect(parsed?.noteWindowBounds).toEqual({});
+ });
+
+ test('a corrupt entry is dropped while healthy siblings survive', () => {
+ const parsed = parseAppState({
+ ...emptyState(),
+ noteWindowBounds: { '/tmp/a': FRAME, '/tmp/broken': { x: 'no' } },
+ });
+
+ expect(parsed?.noteWindowBounds['/tmp/a']).toEqual(FRAME);
+ expect(parsed?.noteWindowBounds['/tmp/broken']).toBeUndefined();
+ });
+
+ test('removeRecentProject clears the pop-out slot with everything else', () => {
+ // One key deletes all of a project's persisted state; a leaked pop-out
+ // frame would resurrect a forgotten project's window position.
+ let s = setNoteWindowBounds(emptyState(), '/tmp/a', FRAME);
+ s = setProjectWindowBounds(s, '/tmp/a', FRAME);
+ s = removeRecentProject(s, '/tmp/a');
+
+ expect(s.noteWindowBounds['/tmp/a']).toBeUndefined();
+ expect(s.projectWindowBounds['/tmp/a']).toBeUndefined();
+ });
+
+ test('the schema version is unchanged — the field is additive', () => {
+ expect(setNoteWindowBounds(emptyState(), '/tmp/a', FRAME).schemaVersion).toBe(
+ emptyState().schemaVersion,
+ );
+ });
+});
+
+describe('state-store (doc restore entries — popped-out note windows)', () => {
+ const FRAME: PersistedWindowBounds = {
+ x: 2400,
+ y: 120,
+ width: 900,
+ height: 1000,
+ isMaximized: false,
+ isFullScreen: false,
+ };
+ const DOC = {
+ kind: 'doc' as const,
+ projectPath: '/tmp/a',
+ docName: 'notes/alpha',
+ bounds: FRAME,
+ };
+
+ test('a doc key does not collide with its own project window key', () => {
+ // Both windows restore, so one key cannot stand for both — a collision
+ // would silently drop the pop-out at the dedup step.
+ expect(windowRestoreKey(DOC)).not.toBe(
+ windowRestoreKey({ kind: 'project', projectPath: '/tmp/a' }),
+ );
+ });
+
+ test('two pop-outs of one project get distinct keys', () => {
+ expect(windowRestoreKey(DOC)).not.toBe(windowRestoreKey({ ...DOC, docName: 'notes/beta' }));
+ });
+
+ test('the survivor path for a pop-out is its project folder, not its key', () => {
+ // The key is a composite identity and would never stat. The right survivor
+ // question is whether the PROJECT still exists.
+ expect(restoreSurvivorPath(DOC)).toBe('/tmp/a');
+ expect(restoreSurvivorPath({ kind: 'project', projectPath: '/tmp/a' })).toBe('/tmp/a');
+ expect(restoreSurvivorPath({ kind: 'file', filePath: '/tmp/loose.md' })).toBe('/tmp/loose.md');
+ });
+
+ test('round-trips a doc entry with its frame', () => {
+ const s = { ...emptyState(), pendingWindowRestore: [DOC] };
+ const reparsed = parseAppState(JSON.parse(JSON.stringify(s)));
+
+ expect(reparsed?.pendingWindowRestore).toEqual([DOC]);
+ });
+
+ test('a doc entry with a corrupt frame keeps the document and drops the frame', () => {
+ // The document is the point of the window; the pixels are a nicety.
+ const parsed = parseAppState({
+ ...emptyState(),
+ pendingWindowRestore: [{ ...DOC, bounds: { x: 'nope' } }],
+ });
+
+ expect(parsed?.pendingWindowRestore).toEqual([
+ { kind: 'doc', projectPath: '/tmp/a', docName: 'notes/alpha' },
+ ]);
+ });
+
+ test('a doc entry missing its document name is dropped', () => {
+ const parsed = parseAppState({
+ ...emptyState(),
+ pendingWindowRestore: [{ kind: 'doc', projectPath: '/tmp/a' }],
+ });
+
+ expect(parsed?.pendingWindowRestore).toEqual([]);
+ });
+
+ test('an unknown kind is dropped while known kinds survive', () => {
+ // This is the forward-compatibility contract that let the union grow
+ // without a schema bump: an older build treats `doc` exactly this way.
+ const parsed = parseAppState({
+ ...emptyState(),
+ pendingWindowRestore: [
+ { kind: 'project', projectPath: '/tmp/a' },
+ { kind: 'newer-kind', whatever: true },
+ DOC,
+ ],
+ });
+
+ expect(parsed?.pendingWindowRestore).toEqual([{ kind: 'project', projectPath: '/tmp/a' }, DOC]);
+ });
+
+ test('two pop-outs of one project both survive the de-dupe', () => {
+ const parsed = parseAppState({
+ ...emptyState(),
+ pendingWindowRestore: [DOC, { ...DOC, docName: 'notes/beta' }],
+ });
+
+ expect(parsed?.pendingWindowRestore).toHaveLength(2);
+ });
+});
diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.ts
index 1e4968bea..af356586a 100644
--- a/packages/desktop/tests/main/window-manager.test.ts
+++ b/packages/desktop/tests/main/window-manager.test.ts
@@ -962,6 +962,13 @@ describe('WindowManager', () => {
return { pid: 6666 };
};
+ // Note windows live outside windowsByPath, so the recreate below does not
+ // reach them, and their attach argv is frozen at creation — a pop-out left
+ // behind would hold a URL for the terminated server forever. The hook has
+ // to carry the FRESH origin, not the old one.
+ const restarted: Array<{ projectPath: string; apiOrigin: string }> = [];
+ env.deps.onProjectServerRestarted = (args) => restarted.push({ ...args });
+
const wm = new WindowManager(env.deps);
const attached = await wm.createProjectWindow({ projectPath: '/tmp/dragon' });
expect(attached.ownsServer).toBe(false);
@@ -976,6 +983,11 @@ describe('WindowManager', () => {
const ctx = wm.getContextForBrowserWindow(env.windows[1] as BrowserWindowLike);
expect(ctx?.port).toBe(60000);
+ // The note-window recreate hook fired once, carrying the NEW origin.
+ expect(restarted).toHaveLength(1);
+ expect(restarted[0]?.projectPath).toBe('/tmp/dragon');
+ expect(restarted[0]?.apiOrigin).toContain('60000');
+
// Same-version respawn → no drift notification on the new window.
const newWindow = env.windows[1];
if (!newWindow) throw new Error('no recreated window');
@@ -990,6 +1002,52 @@ describe('WindowManager', () => {
expect((restartedSends[0] as unknown[])[1]).toEqual({ appRuntime: '0.8.2' });
});
+ test('a note-window recreate hook that throws does not fail the restart or strand the old window', async () => {
+ // The recreate hook is a SECONDARY concern (note windows live outside
+ // windowsByPath). A throw in it — a `BrowserWindow` constructor failure
+ // under memory pressure, say — must not propagate out of the restart and
+ // skip the `closeAndAwait` teardown, which would leave the old window as a
+ // zombie pointing at the terminated server.
+ env.deps.selfProtocolVersion = 1;
+ env.deps.selfRuntimeVersion = '0.8.2';
+ let killed = false;
+ let spawned = false;
+ const oldLock = { ...liveLock, pid: 5555, protocolVersion: 1, runtimeVersion: '0.8.0' };
+ const freshLock = {
+ ...liveLock,
+ pid: 6666,
+ port: 60000,
+ protocolVersion: 1,
+ runtimeVersion: '0.8.2',
+ };
+ enableAttachProbe({
+ readServerLock: () => (spawned ? freshLock : killed ? null : oldLock),
+ isProcessAlive: (pid) => (pid === 5555 ? !killed : true),
+ });
+ env.deps.killProbe = vi.fn((_pid: number, signal: string) => {
+ if (signal === 'SIGTERM') killed = true;
+ });
+ env.deps.spawnDetachedServer = async () => {
+ spawned = true;
+ return { pid: 6666 };
+ };
+ env.deps.onProjectServerRestarted = () => {
+ throw new Error('recreate boom');
+ };
+
+ const wm = new WindowManager(env.deps);
+ await wm.createProjectWindow({ projectPath: '/tmp/dragon' });
+ const originating = env.windows[0];
+ if (!originating) throw new Error('no originating window');
+
+ const outcome = await wm.restartAttachedServer('/tmp/dragon');
+ // Isolated: the restart still succeeds and the fresh window came up…
+ expect(outcome).toEqual({ ok: true });
+ expect(env.windows.length).toBe(2);
+ // …and the old window was still torn down despite the hook throwing.
+ expect(originating.isDestroyed?.()).toBe(true);
+ });
+
test('restartAttachedServer returns eperm without recreating when the kill is blocked', async () => {
const lockWithPid = { ...liveLock, pid: 7777, protocolVersion: 1, runtimeVersion: '0.8.0' };
env.deps.readServerLock = () => lockWithPid;
diff --git a/packages/desktop/tests/smoke/note-window.e2e.ts b/packages/desktop/tests/smoke/note-window.e2e.ts
new file mode 100644
index 000000000..513475407
--- /dev/null
+++ b/packages/desktop/tests/smoke/note-window.e2e.ts
@@ -0,0 +1,477 @@
+/**
+ * Popped-out note window live-Electron smoke.
+ *
+ * The only rung that can show what the lower tiers structurally cannot: two
+ * real editor renderers in one app instance, over one project's Y.Doc. The
+ * integration harness proves CRDT convergence at the transport layer and the
+ * dom tier proves the chrome reduction under jsdom, but neither can observe
+ * window mechanics — registry dedup, focus-existing, menu targeting from a
+ * focused pop-out, the close cascade, or a relaunch putting the layout back.
+ *
+ * Skip gates mirror terminal-window.e2e.ts: opt-in via OK_DESKTOP_E2E_SMOKE=1,
+ * darwin-only, and the electron-vite build must exist. Not part of `pnpm check`;
+ * run via `pnpm exec playwright test` or `pnpm run check:full:parallel`.
+ */
+
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { ElectronApplication, Page } from '@playwright/test';
+import { _electron as electron } from '@playwright/test';
+import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
+import {
+ homeEnv,
+ PLATFORM_SKIP_REASON,
+ PLATFORM_SUPPORTED,
+ SMOKE_ENABLED,
+ userDataDirFor,
+} from './_helpers/platform-gate';
+import { expect, test } from './_helpers/smoke-test';
+
+const TARGET = resolveDesktopTarget();
+
+const DARWIN = process.platform === 'darwin';
+
+interface Seed {
+ tmpHome: string;
+ userDataDir: string;
+ projectDir: string;
+}
+
+/** A project with two documents, so the N-per-project case has something to pop. */
+function seed(prefix: string): Seed {
+ const tmpHome = realpathSync(mkdtempSync(join(tmpdir(), `ok-notewin-${prefix}-home-`)));
+ const projectDir = realpathSync(mkdtempSync(join(tmpdir(), `ok-notewin-${prefix}-proj-`)));
+ mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");
+ writeFileSync(join(projectDir, 'start.md'), '# Start\n\nSeed document.\n');
+ writeFileSync(join(projectDir, 'second.md'), '# Second\n\nAnother document.\n');
+
+ const userDataDir = userDataDirFor(tmpHome);
+ mkdirSync(userDataDir, { recursive: true });
+ writeFileSync(
+ join(userDataDir, 'state.json'),
+ JSON.stringify({
+ recentProjects: [
+ { path: projectDir, name: 'Note Window Smoke', lastOpenedAt: new Date().toISOString() },
+ ],
+ lastOpenedProject: projectDir,
+ versionPendingInstall: null,
+ lastSeenVersion: null,
+ lastSuccessfulCheckAt: null,
+ stuckHintShown: false,
+ }),
+ );
+ return { tmpHome, userDataDir, projectDir };
+}
+
+async function launchApp(s: Seed, opts: { deepLink?: boolean } = {}): Promise<ElectronApplication> {
+ const args = [`--user-data-dir=${s.userDataDir}`];
+ // The relaunch leg deliberately omits the deep link: it must prove the
+ // RESTORE path reopened the pop-out, not that a URL reopened the project.
+ if (opts.deepLink !== false) {
+ args.push(`openknowledge://open?project=${encodeURIComponent(s.projectDir)}&doc=start`);
+ }
+ return electron.launch(
+ desktopLaunchOptions({
+ target: TARGET,
+ args,
+ timeout: 30_000,
+ env: {
+ ...process.env,
+ ...homeEnv(s.tmpHome),
+ ...(process.platform === 'win32' ? {} : { PATH: '/usr/bin:/bin:/usr/sbin:/sbin' }),
+ OK_DESKTOP_E2E_SMOKE: '1',
+ OK_RECLAIM_DISABLE: '1',
+ },
+ }),
+ );
+}
+
+async function findWindowByMode(
+ app: ElectronApplication,
+ mode: 'editor' | 'note' | 'terminal',
+ timeoutMs = 15_000,
+): Promise<Page> {
+ let page: Page | undefined;
+ await expect(async () => {
+ for (const p of app.windows()) {
+ const m = await p.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);
+ if (m === mode) {
+ page = p;
+ return;
+ }
+ }
+ throw new Error(`no ${mode} window yet`);
+ }).toPass({ timeout: timeoutMs });
+ if (!page) throw new Error(`${mode} window vanished after readiness poll`);
+ return page;
+}
+
+async function windowCountByMode(
+ app: ElectronApplication,
+ mode: 'editor' | 'note' | 'terminal',
+): Promise<number> {
+ let count = 0;
+ for (const p of app.windows()) {
+ const m = await p.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);
+ if (m === mode) count += 1;
+ }
+ return count;
+}
+
+async function webContentsIdFor(app: ElectronApplication, page: Page): Promise<number> {
+ const win = await app.browserWindow(page);
+ return win.evaluate((w: unknown) => (w as { webContents: { id: number } }).webContents.id);
+}
+
+/**
+ * Drive the real Window → Open in New Window menu command.
+ *
+ * The focus shim is the same platform seam the terminal smoke scopes: Electron's
+ * headless runner cannot establish native macOS focus, while the production
+ * command resolves both the document and the origin window from
+ * `BrowserWindow.getFocusedWindow()`. Shimming only for the click keeps the real
+ * menu, the real registry lookup, and the real project inheritance in the path.
+ */
+async function clickOpenInNewWindow(
+ app: ElectronApplication,
+ sourceWebContentsId: number,
+): Promise<boolean> {
+ return app.evaluate(async ({ BrowserWindow, Menu }, expectedSourceId) => {
+ const item = Menu.getApplicationMenu()
+ ?.items.find((i) => i.label === 'Window')
+ ?.submenu?.items.find((i) => i.label === 'Open in New Window');
+ if (!item?.enabled) return false;
+ const source = BrowserWindow.getAllWindows().find(
+ (candidate) => candidate.webContents.id === expectedSourceId,
+ );
+ if (!source) return false;
+ const getFocusedWindow = BrowserWindow.getFocusedWindow;
+ Reflect.set(BrowserWindow, 'getFocusedWindow', () => source);
+ try {
+ item.click();
+ } finally {
+ Reflect.set(BrowserWindow, 'getFocusedWindow', getFocusedWindow);
+ }
+ return true;
+ }, sourceWebContentsId);
+}
+
+function editorBody(page: Page) {
+ return page.locator('.ProseMirror[contenteditable="true"]:not(.composer-prosemirror)').first();
+}
+
+/**
+ * Navigate a window to a document and wait for it to be the live editor target.
+ *
+ * The launch deep link opens the PROJECT but lands on the empty surface with no
+ * document active, so a pop-out has nothing to act on until something navigates.
+ * The hash is the app's own source of truth for navigation, which is why
+ * setting it (rather than clicking through the sidebar) is a faithful drive
+ * rather than a shortcut around the product.
+ */
+async function openDocument(page: Page, docName: string): Promise<void> {
+ await page.evaluate((name) => {
+ window.location.hash = `#/${name}`;
+ }, docName);
+ await expect(editorBody(page)).toContainText(docName === 'start' ? 'Start' : 'Second', {
+ timeout: 25_000,
+ });
+}
+
+/** Wait for the menu item to enable — it gates on the renderer's active-target push. */
+async function popOutFrom(app: ElectronApplication, source: Page): Promise<void> {
+ const sourceId = await webContentsIdFor(app, source);
+ await expect(async () => {
+ if (!(await clickOpenInNewWindow(app, sourceId))) throw new Error('menu item not enabled yet');
+ }).toPass({ timeout: 15_000 });
+}
+
+const cleanup: string[] = [];
+function track(...paths: string[]): void {
+ cleanup.push(...paths);
+}
+
+test.describe('Popped-out note window — live Electron', () => {
+ test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');
+ test.skip(!PLATFORM_SUPPORTED, PLATFORM_SKIP_REASON);
+ test.skip(!TARGET.exists, TARGET.missingReason);
+ test.afterEach(() => {
+ for (const target of cleanup.splice(0)) {
+ try {
+ rmSync(target, { recursive: true, force: true });
+ } catch {
+ // best-effort
+ }
+ }
+ });
+
+ test('opens one document full-window with attach-mode collab and reduced chrome', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('open');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const editor = await findWindowByMode(app, 'editor');
+ await openDocument(editor, 'start');
+
+ await popOutFrom(app, editor);
+ const note = await findWindowByMode(app, 'note');
+
+ // Attach-mode: it inherited the project's collab server rather than
+ // spawning one, which is what makes the live sync below free.
+ expect(await note.evaluate(() => window.okDesktop?.config.collabUrl)).not.toBe('');
+ expect(await note.evaluate(() => window.okDesktop?.config.projectPath)).toBe(s.projectDir);
+
+ // The document is on screen, and the workspace chrome is not.
+ await expect(editorBody(note)).toBeVisible({ timeout: 15_000 });
+ await expect(note.locator('[data-sidebar="trigger"]')).toHaveCount(0);
+ await expect(note.locator('[data-editor-tab-scroll]')).toHaveCount(0);
+ await expect(note.locator('[data-doc-panel-toggle]')).toHaveCount(0);
+ await expect(note.getByRole('button', { name: 'Open agents panel' })).toHaveCount(0);
+ await expect(note.getByRole('button', { name: 'Resources' })).toHaveCount(0);
+ await expect(note.locator('[data-note-window-mode-toggle]')).toBeVisible();
+
+ // The rendered titlebar elements share one centerline in real Electron.
+ // Native traffic-light coordinates are a write-only BrowserWindow option
+ // in this Electron version, so their exact policy is covered by the main
+ // unit test and the composed result remains a visual-review oracle.
+ const noteWindow = await app.browserWindow(note);
+ const titlebar = await note.evaluate(() => {
+ const header = document.querySelector('header');
+ const current = document.querySelector('[data-slot="breadcrumb-page"][aria-current="page"]');
+ const modeToggle = document.querySelector('[data-note-window-mode-toggle]');
+ if (!(header instanceof HTMLElement)) throw new Error('note titlebar missing');
+ if (!(current instanceof HTMLElement)) throw new Error('current breadcrumb missing');
+ if (!(modeToggle instanceof HTMLElement)) throw new Error('mode toggle missing');
+ const headerRect = header.getBoundingClientRect();
+ const currentRect = current.getBoundingClientRect();
+ const toggleRect = modeToggle.getBoundingClientRect();
+ return {
+ headerHeight: headerRect.height,
+ headerCenterY: headerRect.top + headerRect.height / 2,
+ breadcrumb: current.textContent,
+ breadcrumbCenterY: currentRect.top + currentRect.height / 2,
+ toggleCenterY: toggleRect.top + toggleRect.height / 2,
+ };
+ });
+ expect(titlebar.headerHeight).toBe(48);
+ expect(titlebar.breadcrumb).toBe('start');
+ expect(Math.abs(titlebar.breadcrumbCenterY - titlebar.headerCenterY)).toBeLessThan(1);
+ expect(Math.abs(titlebar.toggleCenterY - titlebar.headerCenterY)).toBeLessThan(1);
+
+ // The window is titled with its document, not the app or the project.
+ expect(
+ await noteWindow.evaluate((w: unknown) => (w as { getTitle(): string }).getTitle()),
+ ).toContain('start');
+ });
+
+ test('conversation and comments actions cross IPC into the owning project window', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('handoff');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const editor = await findWindowByMode(app, 'editor');
+ await openDocument(editor, 'start');
+
+ await popOutFrom(app, editor);
+ const note = await findWindowByMode(app, 'note');
+
+ // Observe the destination's real local bus. The action still has to cross
+ // note renderer → preload → main → project preload → receiver before this
+ // listener can see it.
+ await editor.evaluate(() => {
+ const probe = window as unknown as { __noteWindowActiveInput?: unknown };
+ window.addEventListener(
+ 'open-knowledge:active-terminal-input',
+ (event) => {
+ probe.__noteWindowActiveInput = (event as CustomEvent).detail;
+ },
+ { once: true },
+ );
+ });
+ expect(
+ await note.evaluate(() =>
+ window.okDesktop?.noteWindow.dispatchToMain({
+ kind: 'active-input',
+ text: 'Review this passage',
+ newTab: true,
+ submit: true,
+ target: 'agents',
+ }),
+ ),
+ ).toEqual({ ok: true });
+ await expect
+ .poll(
+ () =>
+ editor.evaluate(
+ () =>
+ (window as unknown as { __noteWindowActiveInput?: unknown }).__noteWindowActiveInput,
+ ),
+ { timeout: 15_000 },
+ )
+ .toEqual({
+ text: 'Review this passage',
+ newTab: true,
+ submit: true,
+ target: 'agents',
+ });
+
+ // Comments belong in the main window too: the handoff navigates that
+ // window to the originating document and opens its real document panel.
+ expect(
+ await note.evaluate(() =>
+ window.okDesktop?.noteWindow.dispatchToMain({
+ kind: 'reveal-comments',
+ docName: 'second',
+ scope: 'doc',
+ }),
+ ),
+ ).toEqual({ ok: true });
+ await expect(editorBody(editor)).toContainText('Second', { timeout: 15_000 });
+ await expect(editor.locator('#doc-panel')).toBeVisible({ timeout: 15_000 });
+ });
+
+ test('edits cross both live editor UIs in one app instance', async ({ captureStderrFor }) => {
+ // The novel seam: two renderer processes, one Y.Doc. Lower tiers prove
+ // convergence at the transport; only this proves it through two real UIs.
+ const s = seed('sync');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const editor = await findWindowByMode(app, 'editor');
+ await openDocument(editor, 'start');
+
+ await popOutFrom(app, editor);
+ const note = await findWindowByMode(app, 'note');
+ await expect(editorBody(note)).toBeVisible({ timeout: 15_000 });
+
+ const fromPopOut = `pop-out-${Date.now()}`;
+ await editorBody(note).click();
+ await note.keyboard.type(fromPopOut);
+ await expect(editorBody(editor)).toContainText(fromPopOut, { timeout: 15_000 });
+
+ const fromMain = `main-${Date.now()}`;
+ await editorBody(editor).click();
+ await editor.keyboard.type(fromMain);
+ await expect(editorBody(note)).toContainText(fromMain, { timeout: 15_000 });
+ });
+
+ test('re-popping the same document focuses the existing window', async ({ captureStderrFor }) => {
+ const s = seed('dedup');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const editor = await findWindowByMode(app, 'editor');
+ await openDocument(editor, 'start');
+
+ await popOutFrom(app, editor);
+ await findWindowByMode(app, 'note');
+ await popOutFrom(app, editor);
+
+ // Still exactly one: the registry deduped on (project, document) rather
+ // than stacking a second window on the same content.
+ await expect.poll(() => windowCountByMode(app, 'note'), { timeout: 15_000 }).toBe(1);
+ });
+
+ test('New Terminal Window from a focused pop-out inherits its project', async ({
+ captureStderrFor,
+ }) => {
+ test.skip(!DARWIN, 'node-pty is excluded from Windows and Linux packages.');
+ // Note windows are absent from windowsByPath, so before registry-aware
+ // resolution this opened a project-less shell.
+ const s = seed('menu');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const editor = await findWindowByMode(app, 'editor');
+ await openDocument(editor, 'start');
+
+ await popOutFrom(app, editor);
+ const note = await findWindowByMode(app, 'note');
+ const noteId = await webContentsIdFor(app, note);
+
+ const clicked = await app.evaluate(async ({ BrowserWindow, Menu }, expectedSourceId) => {
+ const item = Menu.getApplicationMenu()
+ ?.items.find((i) => i.label === 'Terminal')
+ ?.submenu?.items.find((i) => i.label === 'New Terminal Window');
+ if (!item) return false;
+ const source = BrowserWindow.getAllWindows().find(
+ (candidate) => candidate.webContents.id === expectedSourceId,
+ );
+ if (!source) return false;
+ const getFocusedWindow = BrowserWindow.getFocusedWindow;
+ Reflect.set(BrowserWindow, 'getFocusedWindow', () => source);
+ try {
+ item.click();
+ } finally {
+ Reflect.set(BrowserWindow, 'getFocusedWindow', getFocusedWindow);
+ }
+ return true;
+ }, noteId);
+ expect(clicked).toBe(true);
+
+ const term = await findWindowByMode(app, 'terminal');
+ expect(await term.evaluate(() => window.okDesktop?.config.projectPath)).toBe(s.projectDir);
+ });
+
+ test('closing the project window closes its pop-outs, leaving no orphan', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('cascade');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const editor = await findWindowByMode(app, 'editor');
+ await openDocument(editor, 'start');
+
+ await popOutFrom(app, editor);
+ await findWindowByMode(app, 'note');
+
+ const editorId = await webContentsIdFor(app, editor);
+ await app.evaluate(({ BrowserWindow }, id) => {
+ BrowserWindow.getAllWindows()
+ .find((candidate) => candidate.webContents.id === id)
+ ?.close();
+ }, editorId);
+
+ // In dev the project's server dies with its window, so a surviving pop-out
+ // could never reconnect — an unrecoverable orphan is the case this closes.
+ await expect.poll(() => windowCountByMode(app, 'note'), { timeout: 15_000 }).toBe(0);
+ });
+
+ test('a pop-out returns after quit and relaunch, attached and on its document', async ({
+ captureStderrFor,
+ }) => {
+ // Two full app launches, so roughly twice the budget of every sibling here.
+ // Opted into explicitly rather than by trimming the individual waits: the
+ // second launch has to boot a server and restore before the pop-out can
+ // appear, and a tight window there would fail on a slow runner rather than
+ // on a regression.
+ test.setTimeout(200_000);
+ const s = seed('restore');
+ track(s.tmpHome, s.projectDir);
+
+ const first = await launchApp(s);
+ captureStderrFor(first, { cleanupDirs: [] });
+ const editor = await findWindowByMode(first, 'editor');
+ await openDocument(editor, 'start');
+ await popOutFrom(first, editor);
+ await findWindowByMode(first, 'note');
+ // Quit, not close: the restore snapshot is captured at the earliest
+ // teardown hook, ahead of the close cascade that would otherwise discard it.
+ await first.close();
+
+ const second = await launchApp(s, { deepLink: false });
+ captureStderrFor(second, { cleanupDirs: [s.tmpHome, s.projectDir] });
+
+ const restored = await findWindowByMode(second, 'note', 30_000);
+ expect(await restored.evaluate(() => window.okDesktop?.config.projectPath)).toBe(s.projectDir);
+ expect(await restored.evaluate(() => window.okDesktop?.config.collabUrl)).not.toBe('');
+ await expect(editorBody(restored)).toBeVisible({ timeout: 20_000 });
+ });
+});
diff --git a/turbo.json b/turbo.json
index 4bf27302b..5e1348237 100644
--- a/turbo.json
+++ b/turbo.json
@@ -29,6 +29,7 @@
"cache": false,
"dependsOn": []
},
+ "lint": {},
"typecheck": {
"dependsOn": ["^build"]
},