Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Single-source the desktop host bridge contract (#3052)
Dimitri POSTOLOV6e8558ec8d5c
diff --git a/packages/app/src/components/ReportBugDialog.dom.test.tsx b/packages/app/src/components/ReportBugDialog.dom.test.tsxindex dfcb93927..0aeefeb82 100644--- a/packages/app/src/components/ReportBugDialog.dom.test.tsx+++ b/packages/app/src/components/ReportBugDialog.dom.test.tsx@@ -12,10 +12,10 @@ import type {OkBugReportCrashDetectedEvent,OkBugReportCreateResult,OkBugReportScreenshot,- OkBugReportSendMetadata,OkBugReportSendResult,ReportBundleSummary,} from '@inkeep/open-knowledge-core';+import type { OkBugReportSendInput } from '@inkeep/open-knowledge-core/desktop-bridge';import { act, cleanup, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import type { ReactNode } from 'react';@@ -82,7 +82,7 @@ type CreateRequest = {includeCrashDump?: boolean;includeScreenshot?: boolean;};-type SendRequest = { zipPath: string; metadata: OkBugReportSendMetadata };+type SendRequest = OkBugReportSendInput;interface BridgeLog {createCalls: CreateRequest[];diff --git a/packages/app/src/components/TrashFailureModal.tsx b/packages/app/src/components/TrashFailureModal.tsxindex 341eff310..dedf18859 100644--- a/packages/app/src/components/TrashFailureModal.tsx+++ b/packages/app/src/components/TrashFailureModal.tsx@@ -35,20 +35,13 @@ import {*//**- * **DRIFT WARNING — this union mirrors `TrashItemReason` declared inline in- * the bridge contract.** The bridge surfaces can't import from `app/components/`- * (renderer-only) so the IPC boundary's outcome reason and the renderer's- * display reason are declared separately. Keep these in lockstep with the- * `reason: 'not-found' | 'permission-denied' | 'system-error' | 'path-escape'`- * field declared on the trashItem outcome at:- *- * 1. `packages/desktop/src/shared/bridge-contract.ts` — `OkDesktopBridge.shell.trashItem` outcome- * 2. `packages/core/src/desktop-bridge.ts` — canonical `OkDesktopBridge.shell.trashItem` outcome- * 3. `packages/app/src/lib/desktop-bridge-types.ts` — renderer-side augmentation+ * **DRIFT WARNING — this display-only union mirrors the reason declared on+ * `OkDesktopBridge.shell.trashItem` in the canonical core desktop-bridge+ * contract.** Keep the two unions in lockstep.** TypeScript catches structural drift at the bridge-contract level (the cast* site in FileTree.tsx narrows via `coerceTrashFailureReason` below); the- * unions themselves must stay byte-identical.+ * unions themselves must stay structurally identical.*/type TrashFailureReason = 'not-found' | 'permission-denied' | 'system-error' | 'path-escape';diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.tsindex 3e7fc9447..c8ad04eca 100644--- a/packages/app/src/lib/desktop-bridge-types.ts+++ b/packages/app/src/lib/desktop-bridge-types.ts@@ -1,1636 +1,26 @@/**- * Local copy of the OkDesktopBridge contract types — see comment in- * `packages/core/src/desktop-bridge.ts` and `packages/desktop/src/shared/- * bridge-contract.ts` for why the contract is duplicated rather than- * exported through core's barrel.- *- * This file's purpose is twofold:- * 1. Type the optional `window.okDesktop` global so `useCollabUrl` and any- * future Electron-aware app code can read it with full type safety.- * 2. Stay in sync with the desktop preload's contract — drift across the- * three copies is caught by the bridge-contract drift test (top-level- * `OkDesktopBridge` member parity + `KeyringSmokeResult` /- * `OkKeyringSmokeResult` field shape).- *- * Web / CLI distribution: `window.okDesktop` is `undefined` and the optional- * chaining + `if (window.okDesktop?.config.collabUrl)` guards in `useCollabUrl`- * fall through to the existing /api/config poll path.+ * Compatibility exports for renderer consumers. The desktop host contract is+ * defined by the dedicated core leaf so app and preload consumers share one+ * declaration without importing the core barrel.*/import type {- BranchInfoResponse,- CheckoutResponse,- CreateNewBannerKind,- EditorId,- LocalOpOkInitResponse,- OkBugReportCrashAckResult,- OkBugReportCrashDetectedEvent,- OkBugReportCreateResult,- OkBugReportDeleteResult,- OkBugReportListResult,- OkBugReportScreenshot,- OkBugReportSendMetadata,- OkBugReportSendResult,- OkFolderState,- RecentProjectEntry,- ReportBundleLevel,- ShareTargetStatusResponse,- TerminalCli,- WorktreeCreateRequest,- WorktreeCreateResult,- WorktreeListResult,-} from '@inkeep/open-knowledge-core';+ OkCheckTargetExistsResult,+ OkDesktopBridge,+ OkHeadBranchInfo,+ ShareTarget,+} from '@inkeep/open-knowledge-core/desktop-bridge';-export type { OkFolderState, RecentProjectEntry };+export type * from '@inkeep/open-knowledge-core/desktop-bridge';-/** Seed scaffolder shapes — structurally duplicated from- * `@inkeep/open-knowledge-server`'s seed module. See core's desktop-bridge.ts- * for rationale (avoids pulling server into the app compilation tree).- *- * Folder defaults moved out of `config.yml` `folders:` and into nested- * `<folder>/.ok/frontmatter.yml` files written via the standard file-entry- * path. */-interface OkScaffoldFileEntry {- path: string;- kind: 'folder' | 'file';- contentPreview?: string;-}-interface OkScaffoldSkipEntry {- path: string;- reason: 'already-exists' | 'user-content' | 'glob-collision';-}-export interface OkScaffoldPlan {- created: OkScaffoldFileEntry[];- skipped: OkScaffoldSkipEntry[];- warnings: string[];- /** The pack's project-local skill, when it ships one. `pending` = the skill- * source is absent from `.ok/skills/` and apply would (re)author it, so the- * pack isn't fully set up even if its folders/templates exist. */- packSkills?: { name: string; pending: boolean }[];-}-interface OkScaffoldApplyError {- path: string;- error: string;-}-export interface OkScaffoldApplyResult {- applied: number;- errors: OkScaffoldApplyError[];- durationMs: number;- /** Editor display-names that received the pack's project skill (e.g. "Claude Code"). */- packSkillsInstalled: string[];-}-export interface OkSeedError {- kind: 'no-project' | 'prerequisite-missing' | 'invalid-root' | 'internal';- message: string;-}--/** Pack-id wire shape — accepted strings; coerced server-side via `coercePackId`. */-export type OkPackId =- | 'knowledge-base'- | 'software-lifecycle'- | 'codebase-wiki'- | 'plain-notes'- | 'worldbuilding'- | 'writing-pipeline'- | 'entity-vault'- | 'okf';--interface OkSeedPlanOptions {- rootDir?: string;- packId?: OkPackId;-}--interface OkSeedApplyOptions {- packId?: OkPackId;-}--interface OkSeedPackFolderInfo {- path: string;- summary: string;-}--interface OkSeedPackEntryCounts {- files: number;- folders: number;-}--export interface OkSeedPackInfo {- id: OkPackId;- name: string;- description: string;- defaultSubfolder?: string;- folders: OkSeedPackFolderInfo[];- entryCounts: OkSeedPackEntryCounts;-}--export type OkSeedPlanResult =- | { ok: true; plan: OkScaffoldPlan }- | { ok: false; error: OkSeedError };-export type OkSeedApplyResult =- | { ok: true; result: OkScaffoldApplyResult }- | { ok: false; error: OkSeedError };-export type OkSeedListPacksResult =- | { ok: true; packs: OkSeedPackInfo[] }- | { ok: false; error: { kind: 'internal'; message: string } };--/** Pure-fs upward-walk result types mirrored from- * `@inkeep/open-knowledge-server`'s `fs/` module. Structurally duplicated- * for the same reason as the seed shapes above. */-export interface OkFindEnclosingProjectRootResult {- readonly rootPath: string;- readonly distance: number;-}-export interface OkFindEnclosingGitRootResult {- readonly gitRoot: string;- readonly distance: number;-}+export type CheckTargetExistsResult = OkCheckTargetExistsResult;+export type HeadBranchInfo = OkHeadBranchInfo;-type OkDesktopMode = 'editor' | 'navigator' | 'terminal';--export interface OkDesktopConfig {- readonly collabUrl: string;- readonly apiOrigin: string;- readonly projectPath: string;- readonly projectName: string;- readonly mode: OkDesktopMode;- /**- * `true` only under the Electron smoke suite. The renderer reads it to use- * xterm's DOM renderer instead of the WebGL canvas (see `TerminalPanel`).- * Lockstep with the desktop-side `OkDesktopConfig`.- */- readonly e2eSmoke: boolean;- /**- * `true` on an ephemeral single-file window (`ok <file>`). The renderer's- * no-project chrome gate drops the sidebar / tabs / project switcher / Settings- * while keeping the editor editable. The desktop loads from `file://`, so this- * rides the bridge config (the browser fallback reads the same signal from- * `/api/config`). Absent flag → `false` on every project window.- */- readonly singleFile: boolean;- /**- * Doc to open on first paint, or `null`. Set only on an ephemeral single-file- * window (`ok <file>`): the ext-less docName the renderer seeds into- * `window.location.hash` before React mounts (`seedInitialDocHash`), so the- * editor lands on the file deterministically instead of depending on the- * post-load `ok:deep-link` IPC (which raced the lazy subscriber and dropped,- * leaving the empty-state splash). `null` on every project window — those- * navigate via the hash / deep-link channels. Lockstep with the desktop-side- * `OkDesktopConfig` (`packages/desktop/src/shared/bridge-contract.ts`).- */- readonly initialDoc: string | null;- /**- * `true` when this window was opened by a first-run create-new flow (blank- * OR starter-pack seed) — the `create-new` entry point. The onboarding-card- * visibility predicate (`evaluateFreshProject`) reads it — see there for why a- * seeded project needs this signal. `false` on every other entry point and on- * a re-queried live window. Lockstep with the desktop-side `OkDesktopConfig`.- */- readonly freshlyCreated: boolean;- /**- * W3C `traceparent` of the Electron main process's `ok.app-startup` root- * span, or `undefined` when OTel is disabled in main. The renderer extracts- * it to parent its startup span to the desktop launch trace. Carried- * on the bridge config (set from the `--ok-startup-traceparent=` arg). Not on- * the core mirror — see `OkDesktopConfig` there.- */- readonly startupTraceparent?: string;- /**- * Whether an interactive PTY can be spawned in this install — the terminal- * dock's plain-terminal-tab capability gate. `false` on Windows/Linux- * (node-pty is not bundled there; the terminal dock is dark off-mac), so- * the renderer hides the terminal affordances instead of surfacing a spawn- * failure. Gates only the pty-tab surface — future non-pty dock content- * (e.g. ACP threads) must not key off this. Lockstep with the desktop-side- * `OkDesktopConfig`.- */- readonly ptyAvailable: boolean;-}--export type OkMenuAction =- | 'new-doc'- | 'new-folder'- // Opens the create-new-project dialog in the focused window (a whole new- // project, distinct from new-doc/new-folder which create inside the current- // project). Sibling of Switch Project, which dispatches via `openNavigator`.- | 'new-project'- | 'rename'- | 'delete'- | 'close-active-tab-or-window'- | 'toggle-sidebar'- | 'toggle-source'- | 'save-version'- | 'version-history'- | 'focus-search'- | 'focus-command-palette'- // Navigation history.- | 'navigate-back'- | 'navigate-forward'- // File menu state-aware items. See bridge-contract.ts for- // rationale; mirrored here per the OkDesktopBridge 3-way-mirror invariant.- | 'new-from-template'- | 'duplicate'- | 'move-to-trash'- | 'reveal-in-finder'- | 'send-to-ai'- | 'copy-full-path'- | 'copy-relative-path'- // View menu items — visibility toggles + tree-scoped expand/collapse.- | 'toggle-show-hidden-files'- | 'toggle-show-ok-folders'- | 'toggle-show-only-markdown-files'- | 'toggle-show-skills-section'- | 'expand-all-tree'- | 'collapse-all-tree'- | 'toggle-doc-panel'- | 'toggle-terminal'- // Right agents-panel visibility (⌘L / Ctrl+L). The ACP twin of- // `toggle-terminal`, and deliberately NOT desktop-gated: agent threads are- // server-hosted, so the panel works on the web host and where pty does not.- | 'toggle-agent-panel'- // Terminal application menu. `new-terminal` opens a new terminal tab- // (revealing the dock if hidden; never hides, unlike the toggle).- // `kill-terminal` closes the active tab, killing that session's PTY.- | 'new-terminal'- | 'kill-terminal'- // Worktree selector (worktree = window). `new-worktree` opens the- // create dialog; `switch-worktree` opens the sidebar worktree switcher.- | 'new-worktree'- | 'switch-worktree'- // Help → Report a bug… — opens the in-app bug-report dialog. Both window- // types subscribe: editor windows report project-scoped, the Navigator- // reports system-wide.- | 'report-bug'- // Help → Send feedback… — opens the in-app feedback form, the same one- // the Resources menu and the Cmd+K palette open. Both window types subscribe.- | 'send-feedback';--type OkUnsubscribe = () => void;--/**- * Discriminator for the Navigator-side surface that initiated a project-open.- * Mirrors `EntryPoint` in `packages/desktop/src/shared/entry-point.ts`. Drift- * across the three bridge-contract copies is caught by the bridge-contract drift test.- */-export type OkProjectEntryPoint =- | 'create-new'- | 'create-new-nested-redirect'- | 'pick-existing'- | 'recents'- | 'deep-link'- | 'drag-drop'- | 'share-receive'- | 'worktree';--interface ProjectSessionState {- openTabs: string[];- pinnedTabIds: string[];- activeDocName: string | null;- activeTabId: string | null;- activeTabByMode: { files: string | null; skills: string | null };- updatedAt: string | null;-}--/**- * Outcome of `bridge.project.checkTargetExists({projectPath, kind, path})`.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */-export type CheckTargetExistsResult = 'exists' | 'missing' | 'unreadable';--/**- * Kind-discriminated receiver target carried by `OkSharePayloadFields`. See- * canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */-export type ShareTarget =- | { readonly kind: 'doc'; readonly docPath: string }- | { readonly kind: 'folder'; readonly folderPath: string };--/**- * Collapse a kind-discriminated `ShareTarget` to its bare repo-relative path.- * A `doc` target carries the file path on `docPath`; a `folder` target carries- * the directory path on `folderPath` (empty string for the content-dir root).- */export function shareTargetPath(target: ShareTarget): string {return target.kind === 'doc' ? target.docPath : target.folderPath;}-/**- * Outcome of `bridge.project.readHeadBranch(projectPath)`. See canonical- * JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */-export interface HeadBranchInfo {- readonly currentBranch: string | null;- readonly headSha: string | null;- readonly detached: boolean;-}--interface OkUpdateDownloadedInfo {- readonly version: string;-}--interface OkUpdateRelaunchingInfo {- readonly version: string;-}--interface OkUpdateRelaunchFailedInfo {- readonly version: string;- readonly message?: string;- /**- * Manual-download fallback URL, present only on the boot-detected- * failed-install variant. When set, the renderer shows the richer- * "Retry / Download manually" card instead of the plain relaunch-error notice.- */- readonly downloadUrl?: string;-}--interface OkWhatsNewInfo {- readonly version: string;- readonly releaseUrl: string;-}--interface OkUpdateStuckHintInfo {- readonly downloadUrl: string;-}--/**- * Renderer-facing payload for `ok:share:received`. Carried by the main-- * process share-flow handler after `parseShareUrl` dispatches on the- * universal-link / custom-scheme input shapes. Main resolves the share- * target and dispatches one of the surface-specific variants below.- * Mirrored across the three bridge-contract copies (desktop, core, app)- * so the bridge-contract drift tests catch divergent copies.- *- * - `kind: 'project-branch-switch'` — editor-shell branch-switch surface- * - `kind: 'launcher-consent'` / `launcher-miss` — Navigator surfaces- * - `kind: 'unsupported-version'` — sonner toast "Update OpenKnowledge"- * - `kind: 'invalid'` — sonner toast "Invalid share URL"- */-/** Local copy — see canonical `OkSharePayloadFields` in- * `packages/desktop/src/shared/bridge-contract.ts`. */-export interface OkSharePayloadFields {- /** GitHub host of the shared repo: `github.com` or a GHES hostname. */- readonly host: string;- readonly owner: string;- readonly repo: string;- readonly branch: string;- readonly sharedUrl: string;- readonly target: ShareTarget;-}--/** Local copy — see canonical `OkShareReceivedPayload` in- * `packages/desktop/src/shared/bridge-contract.ts`. */-export type OkShareReceivedPayload =- | { readonly kind: 'unsupported-version' }- | { readonly kind: 'invalid' }- | {- readonly kind: 'project-branch-switch';- readonly share: OkSharePayloadFields;- readonly projectPath: string;- readonly currentBranch: string | null;- }- | {- readonly kind: 'launcher-consent';- readonly share: OkSharePayloadFields;- readonly candidatePath: string;- /**- * Name of the Recents project whose `listGitWorktrees` anchor surfaced- * `candidatePath`, when the candidate came from worktree-enum off an- * existing OK project. `null` when the candidate was surfaced from- * a Recents path that itself matched the share. Drives the- * "(a worktree of <name>)" caption in the Navigator consent dialog.- */- readonly parentProjectName: string | null;- }- | {- readonly kind: 'launcher-miss';- readonly share: OkSharePayloadFields;- };--/**- * Renderer-facing mirror of `ShareFolderValidationResult` from- * `@inkeep/open-knowledge`'s `validateLocalFolderForShare`. Carried- * by the `share.validateLocalFolder` IPC. Mirrored across the three bridge-- * contract copies (desktop, core, app) so the bridge-contract drift tests catch divergent copies.- */-export type ShareFolderValidationResult =- | { readonly kind: 'ok'; readonly gitRemoteUrl: string }- | { readonly kind: 'not-git' }- | { readonly kind: 'no-origin' }- | { readonly kind: 'wrong-repo'; readonly actualOwner: string; readonly actualRepo: string }- | { readonly kind: 'wrong-host'; readonly actualHost: string }- | { readonly kind: 'non-github' }- | { readonly kind: 'symlink-escape' };--/**- * Auto-update channel — derived in desktop's main from the running build's- * version string. `'beta'` for a prerelease build, `'latest'` for a stable- * one. Not a runtime preference; surfaced read-only via `state.query()`.- * Mirrors `UpdateChannel` in desktop's `state-store.ts`.- */-type OkUpdateChannel = 'latest' | 'beta';--/**- * User-intent theme value. Mirrors Electron's `nativeTheme.themeSource`- * union and the canonical desktop / core copies. Carried verbatim through- * the `ok:theme:set-source` IPC channel — never resolved at the renderer- * call site. Renderer ConfigProvider passes the unresolved CRDT value- * (`merged.appearance.theme`) directly. Lint enforcement:- * `packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts`.- *- * Not re-exported (matches the `OkUpdateChannel` precedent in this file) —- * external consumers reach the type through the `OkDesktopBridge` interface- * surface. If a future call site needs the bare type, lift the export then.- */-type OkThemeSource = 'system' | 'light' | 'dark';--interface OkStateSnapshot {- readonly channel: OkUpdateChannel;- readonly schemaIncompatibility: {- readonly currentBuild: string;- readonly persistedSchemaVersion: number;- readonly maxSupported: number;- } | null;-}--/**- * Editor IDs surfaced through the first-launch MCP consent bridge.- * Aliased to the canonical `EditorId` from `@inkeep/open-knowledge-core` —- * single source of truth. Local name preserved so renderer call sites keep- * importing `OkMcpWiringEditorId` from this module.- */-export type OkMcpWiringEditorId = EditorId;--/** Payload passed to `mcpWiring.onShow` subscribers. `willReplace: true`- * signals the editor has an existing OK-managed MCP entry (canonical npx,- * `-y` variant, or prior cliPath shape) that Add would overwrite.- * `pathInstall` drives the dialog's shell-PATH toggle row:- * `shellDetected: false` hides the row; `alreadyInstalled: true` renders- * it informational (block already on disk or consent already granted);- * `rcFilesToTouch` names the tildified shell files a grant would edit. */-export interface OkMcpWiringShowPayload {- readonly detectedEditors: readonly {- readonly id: OkMcpWiringEditorId;- readonly label: string;- readonly detected: boolean;- readonly willReplace: boolean;- /** Display-form user-global config path (home collapsed to `~`), or null- * when the editor has no user-global surface on this platform. Feeds the- * per-row location tooltip — mirrors `OkIntegrationsStatus`. */- readonly configPath: string | null;- /** Locator for this editor's `open-knowledge` entry within its config file. */- readonly entryLocator: string;- }[];- readonly pathInstall: {- readonly shellDetected: boolean;- readonly rcFilesToTouch: readonly string[];- readonly alreadyInstalled: boolean;- };- /** Per-bundle opt-in rows for the two user-global skills. Empty ⇒ no skill- * decision solicited. `alreadyInstalled: true` renders the row pre-checked- * as an existing install the user can uncheck to remove. */- readonly globalSkills: readonly {- readonly id: string;- readonly name: string;- readonly alreadyInstalled: boolean;- }[];-}--/** Confirm payload for `mcpWiring.confirm`. `pathInstall` is the PATH- * toggle, tri-state: `true` → append the managed rc block; `false` →- * record declined, touch nothing; absent → no PATH decision was solicited- * (row hidden or informational).- *- * `skills` — bundle ids the user left checked. Present ⇒ a skill decision was- * solicited; every offered bundle not in the list is recorded declined. */-export interface OkMcpWiringConfirmRequest {- readonly editorIds: readonly OkMcpWiringEditorId[];- readonly pathInstall?: boolean;- readonly skills?: readonly string[];-}--/** Result shape for `mcpWiring.confirm` / `skip`. */-export type OkMcpWiringResult = { ok: true } | { ok: false; error: string };--/**- * Per-editor MCP state for Settings → AI tools. `installed` rows uncheck to- * remove; `not-installed` rows check to install; `foreign` is an entry under- * OK's server name that isn't recognizably OK's own (uninstall refuses,- * install overwrites); `unmanageable` is a config OK can't safely edit.- */-export type OkIntegrationsEditorState = 'installed' | 'not-installed' | 'foreign' | 'unmanageable';--/** Component inventory for Settings → AI tools. `available: false` renders- * the section read-only (install actors gated off for this process). `path.- * installed` reflects the managed rc block actually being on disk. */-export interface OkIntegrationsStatus {- readonly available: boolean;- readonly editors: readonly {- readonly id: OkMcpWiringEditorId;- readonly label: string;- readonly detected: boolean;- readonly state: OkIntegrationsEditorState;- readonly configPath: string | null;- readonly entryLocator: string;- }[];- readonly path: {- readonly shellDetected: boolean;- readonly rcFilesToTouch: readonly string[];- readonly installed: boolean;- };- readonly skills: readonly {- readonly id: string;- readonly name: string;- readonly installed: boolean;- readonly paths: readonly string[];- }[];-}--/** One toggle for `integrations.setComponent`. */-export interface OkIntegrationsSetRequest {- readonly component:- | { readonly kind: 'editor'; readonly id: OkMcpWiringEditorId }- | { readonly kind: 'path' }- | { readonly kind: 'skill'; readonly id: string };- readonly enabled: boolean;-}--/** Set-component result — both arms carry a fresh status snapshot so the- * renderer re-renders truthfully after failed/refused toggles too. */-export type OkIntegrationsSetResult =- | { readonly ok: true; readonly status: OkIntegrationsStatus }- | { readonly ok: false; readonly error: string; readonly status: OkIntegrationsStatus };--/** Post-install manual step a project MCP config needs before OK's tools- * connect: `approve-once` (Claude Code), `enable-manually` (Cursor, silently- * disabled until toggled), `auto-connect` (Codex on a trusted project),- * `none`. */-export type OkProjectIntegrationsFollowUp =- | 'approve-once'- | 'enable-manually'- | 'auto-connect'- | 'none';--/** Component inventory for Settings → This project → AI tools (per-editor- * PROJECT MCP config files + the single project runtime skill), scoped to the- * project the requesting window has open. `hasProject: false` → empty state;- * `available: false` → read-only. */-export interface OkProjectIntegrationsStatus {- readonly available: boolean;- readonly hasProject: boolean;- readonly projectDir: string | null;- readonly editors: readonly {- readonly id: OkMcpWiringEditorId;- readonly label: string;- readonly state: OkIntegrationsEditorState;- readonly configPath: string;- readonly entryLocator: string;- readonly followUp: OkProjectIntegrationsFollowUp;- }[];- readonly skill: {- readonly installed: boolean;- readonly paths: readonly string[];- } | null;-}--/** One toggle for `projectIntegrations.setComponent`. The skill is a single- * row (no id) — it fans out across every capable editor. */-export interface OkProjectIntegrationsSetRequest {- readonly component:- | { readonly kind: 'editor'; readonly id: OkMcpWiringEditorId }- | { readonly kind: 'skill' };- readonly enabled: boolean;-}--export type OkProjectIntegrationsSetResult =- | { readonly ok: true; readonly status: OkProjectIntegrationsStatus }- | { readonly ok: false; readonly error: string; readonly status: OkProjectIntegrationsStatus };--/**- * Per-project consent dialog — renderer-facing payload + result shapes.- * Mirrors `bridge-contract.ts` and `core/src/desktop-bridge.ts`. Drift- * across the three copies is caught by the bridge-contract drift test.- */-export type OkOnboardingWarningKind =- | 'root'- | 'home'- | 'home-documents'- | 'home-desktop'- | 'home-downloads'- | 'volumes-mount'- | 'drive-root';--type OkOnboardingGitState = 'present' | 'absent' | 'shell-only';--export interface OkOnboardingShowPayload {- readonly pickedPath: string;- readonly projectDir: string;- readonly defaultContentDir: string;- readonly gitState: OkOnboardingGitState;- readonly gitRootPromoted: boolean;- readonly warnings: readonly { readonly kind: OkOnboardingWarningKind }[];- readonly editorOptions: readonly {- readonly id: OkMcpWiringEditorId;- readonly label: string;- /** True when the editor exposes a per-project MCP config file; false- * when only the user-level config is writable. Drives the per-row- * scope badge in the consent dialog. */- readonly hasProjectConfig: boolean;- /** Optional for back-compat; absent reads as `true`. `false` = the editor- * has no user-global config surface (Pi — project-scope only). */- readonly hasUserConfig?: boolean;- }[];-}--export interface OkOnboardingConfirmRequest {- readonly initGit: boolean;- readonly contentDir: string;- readonly additionalIgnores: string;- readonly editorIds: readonly OkMcpWiringEditorId[];- /** OK config sharing mode — sharing posture chosen by the user. */- readonly sharing: 'shared' | 'local-only';-}--export type OkOnboardingResult = { ok: true } | { ok: false; error: string };--interface OkOnboardingProbeContentRequest {- readonly contentDir: string;-}--export type OkOnboardingProbeContentResult =- | {- readonly ok: true;- readonly count: number;- readonly sample: readonly string[];- readonly truncated: boolean;- }- | { readonly ok: false; readonly error: string };--/**- * Pre-project local-op event shapes — auth + clone flows surfaced to the- * Navigator window via IPC because it has no backing API server. See- * `packages/desktop/src/shared/bridge-contract.ts` for canonical JSDoc.- */-export type OkLocalOpAuthEvent =- | {- type: 'verification';- user_code: string;- verification_uri: string;- expires_in: number;- }- | {- type: 'complete';- host: string;- login: string;- name?: string;- email?: string;- avatarUrl?: string;- }- | { type: 'error'; message: string };--export type OkLocalOpCloneEvent =- | { type: 'progress'; phase: string; pct: number }- | { type: 'complete'; dir: string }- | { type: 'branch-fallback'; branch: string }- | { type: 'error'; message: string };--interface OkLocalOpStream<E> {- readonly events: AsyncIterable<E>;- cancel(): void;-}--export type OkLocalOpAuthStatusResponse =- | {- authenticated: true;- host: string;- login: string;- tier?: 'A' | 'B' | 'C';- name?: string;- email?: string;- /** Whether the gh CLI is installed (offer "Sign in with gh" for GHES). */- ghAvailable?: boolean;- }- | { authenticated: false; host: string; error?: string; ghAvailable?: boolean };--interface OkLocalOpRepoEntry {- full_name: string;- clone_url: string;- private: boolean;-}--export type OkLocalOpAuthReposResponse =- | { ok: true; host: string; repos: OkLocalOpRepoEntry[] }- | { ok: false; error: string };--export type OkLocalOpAuthSignoutResponse =- | { ok: true }- // `error` is the server's RFC 9457 title when present; it can be absent (e.g.- // a non-JSON 502), so the UI supplies a localized fallback rather than the- // transport baking in an English string.- | { ok: false; error?: string };--/**- * Renderer → main snapshot of the editor area's active target.- * Discriminated-union shape so TypeScript narrows `identifier` per `kind`.- * Drives the macOS File menu's state-aware enable/disable. See canonical- * JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */-type OkEditorActiveTargetSnapshot =- | { readonly kind: 'doc'; readonly identifier: string }- | { readonly kind: 'folder'; readonly identifier: string }- | { readonly kind: 'asset'; readonly identifier: string }- | { readonly kind: null };--/**- * Renderer → main snapshot of the View menu's checkbox + smart-hide state.- * Sibling of `OkEditorActiveTargetSnapshot`. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */-export interface OkEditorViewMenuStateSnapshot {- readonly showHiddenFiles: boolean;- readonly showOkFolders: boolean;- readonly showOnlyMarkdownFiles: boolean;- readonly showSkillsSection: boolean;- readonly canExpandAll: boolean;- readonly canCollapseAll: boolean;- readonly sidebarVisible: boolean;- readonly docPanelVisible?: boolean;- readonly terminalVisible?: boolean;- readonly terminalLive?: boolean;- readonly agentPanelVisible?: boolean;- readonly canViewInSource?: boolean;-}--/**- * Windows/Linux renderer-menubar dispatch payloads (the windows-linux-port- * renderer-menubar decision). macOS keeps the native menu bar; win/linux draw it in the- * renderer and route every click through main via `menu.dispatch` so menu- * semantics stay single-sourced: `menu-action` relays through the same- * dispatch path the native menu items use, `role` maps onto Electron's- * built-in menu roles, `command` covers the main-side click handlers- * (navigator, folder picker, settings, updater…), and `query` returns the- * aggregated state the native menu renders from. Same shapes as- * `MenuDispatch*` in `ipc-channels.ts` — duplicated for the- * module-resolution reason the wider `OkDesktopBridge` is duplicated.- */-export type OkMenuDispatchRole =- | 'undo'- | 'redo'- | 'cut'- | 'copy'- | 'paste'- | 'selectAll'- | 'reload'- | 'forceReload'- | 'toggleDevTools'- | 'resetZoom'- | 'zoomIn'- | 'zoomOut'- | 'toggleFullScreen'- | 'minimize'- | 'close'- | 'quit';--export type OkMenuDispatchCommand =- | 'open-navigator'- | 'open-folder-dialog'- | 'clear-recent-projects'- | 'open-settings'- | 'check-for-updates'- | 'reconfigure-mcp-wiring'- | 'open-github'- | 'toggle-spell-check';--export type OkMenuDispatchRequest =- | { readonly kind: 'query' }- | { readonly kind: 'menu-action'; readonly action: OkMenuAction }- | { readonly kind: 'command'; readonly command: OkMenuDispatchCommand }- | { readonly kind: 'open-recent-project'; readonly path: string }- | { readonly kind: 'role'; readonly role: OkMenuDispatchRole };--/** `query` result — the same aggregated state the native menu renders from. */-export interface OkMenuRendererSnapshot {- readonly recentProjects: ReadonlyArray<{ readonly path: string; readonly name: string }>;- readonly spellCheckEnabled: boolean;- readonly showDevToolsMenu: boolean;- readonly canCheckForUpdates: boolean;- readonly canReconfigureMcpWiring: boolean;- readonly activeTarget: OkEditorActiveTargetSnapshot;- readonly viewMenuState: OkEditorViewMenuStateSnapshot;-}--/**- * Result shape for `bridge.debug?.keyringSmoke()` — mirrors- * `KeyringSmokeResult` in `packages/desktop/src/utility/keyring-smoke.ts`- * and `OkKeyringSmokeResult` in `packages/core/src/desktop-bridge.ts`.- * Duplicated across the three copies; drift is caught by the bridge-contract- * drift test (field-set equality across all three files).- */-interface OkKeyringSmokeResult {- ok: boolean;- backend?: 'keyring' | 'file';- error?: string;- durationMs?: number;- timestamp: string;-}--/** OK config sharing mode — see bridge-contract.ts for the canonical types. */-export interface OkSharingStatusResult {- readonly kind: 'status';- readonly mode: 'shared' | 'local-only' | 'no-git';- readonly excluded: readonly string[];- readonly trackedUpstream: readonly string[];- /** True when local-only but `.ok/skills/` is carved back out as shareable. */- readonly skillsShared: boolean;-}--export type OkSharingSetModeResult =- | { readonly kind: 'applied'; readonly mode: 'shared' | 'local-only' | 'no-git' }- | {- readonly kind: 'refused-tracked';- readonly tracked: readonly string[];- readonly remediation: string;- }- | {- readonly kind: 'no-exclude';- readonly reason: 'no-git' | 'no-info-dir' | 'malformed-pointer' | 'inaccessible';- };--/**- * Payload for `onServerVersionDrift`. Canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */-export interface OkServerVersionDriftInfo {- readonly relation: 'older' | 'newer';- readonly dimension: 'protocol' | 'runtime';- readonly serverRuntime: string;- readonly appRuntime: string;-}--/** Result of `restartServer`. Canonical JSDoc in `bridge-contract.ts`. */-export type OkServerRestartOutcome =- | { readonly ok: true }- | { readonly ok: false; readonly reason: 'eperm' | 'other' };--/** Result of `terminal.create`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */-export type OkPtyCreateResult =- | { readonly ok: true; readonly ptyId: string }- | { readonly ok: false; readonly reason: 'no-project' | 'not-consented' };--/** Entry of `terminal.list`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */-export interface OkPtyListEntry {- readonly ptyId: string;- /** User-set custom tab name that survives a renderer reload; null when unset. */- readonly customLabel: string | null;- /** Sticky per-session tab number, preserved across a renderer reload; null- * until the renderer has reported it for a just-created session. */- readonly ordinal: number | null;-}--/** Result of `terminal.adopt`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */-export type OkPtyAdoptResult =- | { readonly ok: true; readonly replay: string }- | { readonly ok: false; readonly reason: 'unknown-session' };--/** Push payload for `ok:pty:data`. Canonical JSDoc in `bridge-contract.ts`. */-export interface OkPtyData {- readonly ptyId: string;- readonly data: string;-}--/** Push payload for `ok:pty:exit`. Canonical JSDoc in `bridge-contract.ts`. */-export interface OkPtyExit {- readonly ptyId: string;- readonly exitCode: number;- readonly signal: number | null;- readonly error?: string;-}--/**- * Claude Code readiness for the docked terminal. Canonical definition in- * `desktop/src/shared/bridge-contract.ts`; mirrored verbatim here (drift-tested).- */-export interface ClaudeReadiness {- readonly claude: 'present' | 'not-found' | 'unknown';- readonly mcp: 'wired' | 'needs-rewire';- /** True when the project's own `open-knowledge` `.mcp.json` entry is verified- * to be OK's canonical managed server (cli `isOwnManagedEntry`), so the docked- * terminal may pre-approve it on Claude launch instead of re-showing Claude's- * trust prompt. False/absent for a foreign, tampered, or missing entry (the- * supply-chain risk in a shared/cloned project) — launch bare and let Claude- * prompt. Computed per-project by the desktop preflight; absent means false- * (fail-safe). */- readonly mcpPreApprovable?: boolean;- /** Set only on a `rewire`-action result when re-arming MCP wiring threw, so- * the renderer can surface the failure instead of the button silently no-op'ing. */- readonly rewireError?: string;-}--/** On-PATH readiness for a non-Claude agent CLI (codex / cursor-agent) in the- * docked terminal. Canonical shape in `desktop/src/shared/bridge-contract.ts`;- * mirrored verbatim here (drift-tested). */-export interface CliReadiness {- readonly onPath: 'present' | 'not-found' | 'unknown';- /** Codex-only: whether OK's `open-knowledge` MCP server is already configured- * in the user's codex config. Gates the per-launch `-c` tool-auto-approve- * override — codex fails to load its config if `-c` targets a server that is- * not defined, so the launch site adds the override only when this is true.- * Absent for CLIs where it does not apply.- *- * DELIBERATELY WEAKER THAN CLAUDE'S GATE, and not its security equivalent.- * This is existence-by-name (any object under `mcp_servers.open-knowledge`),- * whereas claude's `mcpPreApprovable` runs `isOwnManagedEntry` to verify the- * entry is byte-exactly OK's own. The asymmetry is sound because the two read- * different files: claude's is a PROJECT-scoped `.mcp.json` that travels in a- * clone, so a same-named foreign entry is a real RCE vector; codex's target is- * `scope: 'global'` (`~/.codex/config.toml`, resolved from `home`, never from- * cwd), so anyone able to plant a foreign entry there can already register- * arbitrary MCP servers and has won regardless. Tightening this to an exact- * ownership match would also fail closed on a legitimate entry carrying any- * extra codex key, silently disabling auto-approve for real users. This gate's- * job is availability (don't break codex's config load), not authorization. */- readonly okServerConfigured?: boolean;-}--export interface OkDesktopBridge {- readonly config: OkDesktopConfig;- onProjectSwitched(cb: (next: OkDesktopConfig) => void): OkUnsubscribe;- onMenuAction(cb: (action: OkMenuAction) => void): OkUnsubscribe;- onUpdateDownloaded(cb: (info: OkUpdateDownloadedInfo) => void): OkUnsubscribe;- /** Subscribe to `ok:update:relaunching` — another window's "Relaunch" click committed; swap this window's `update-downloaded` card to the button-less "Relaunching…" in-progress state so every window shows consistent feedback during teardown. */- onUpdateRelaunching(cb: (info: OkUpdateRelaunchingInfo) => void): OkUnsubscribe;- /** Subscribe to `ok:update:relaunch-failed` — a committed relaunch failed (async error event or no-quit watchdog); surface the relaunch-error notice. Main re-arms the banner separately via a re-broadcast `ok:update:downloaded`. */- onUpdateRelaunchFailed(cb: (info: OkUpdateRelaunchFailedInfo) => void): OkUnsubscribe;- onWhatsNew(cb: (info: OkWhatsNewInfo) => void): OkUnsubscribe;- /** Subscribe to `ok:update:whats-new-dismissed` — another window dismissed the what's-new notice; clear this window's `whats-new-<version>` card. */- onWhatsNewDismissed(cb: (info: { readonly version: string }) => void): OkUnsubscribe;- onUpdateStuckHint(cb: (info: OkUpdateStuckHintInfo) => void): OkUnsubscribe;- onDeepLink(- cb: (evt: {- doc: string;- kind: 'doc' | 'folder';- branch?: string | null;- multiCandidate?: boolean;- targetMissing?: boolean;- }) => void,- ): OkUnsubscribe;- onShareReceived(cb: (payload: OkShareReceivedPayload) => void): OkUnsubscribe;- /** Subscribe to `ok:server-version-drift`. Canonical JSDoc in `bridge-contract.ts`. */- onServerVersionDrift(cb: (info: OkServerVersionDriftInfo) => void): OkUnsubscribe;- /** Subscribe to `ok:server-restarted`. Canonical JSDoc in `bridge-contract.ts`. */- onServerRestarted(cb: (info: { readonly appRuntime: string }) => void): OkUnsubscribe;- /** Subscribe to `ok:project:recent-removed-missing`. Canonical JSDoc in `bridge-contract.ts`. */- onRecentRemovedMissing(- cb: (info: { readonly path: string; readonly projectName: string }) => void,- ): OkUnsubscribe;- /** Restart the project's server to match this app's version. Canonical JSDoc in `bridge-contract.ts`. */- restartServer(projectPath: string): Promise<OkServerRestartOutcome>;- /**- * Push the user's chosen `nativeTheme.themeSource` value to main. Carries- * the user-intent value (`'system' | 'light' | 'dark'`) verbatim — never- * resolved at the call site. Renderer ConfigProvider runs this on every- * CRDT mutation of `appearance.theme`. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- setThemeSource(source: OkThemeSource): Promise<{ ok: true }>;- /**- * Fire-and-forget signal that the theme has been applied to chrome.- * Main's per-window show-gate uses this to release `BrowserWindow.show()`- * alongside `ready-to-show`. Optional `opts.reducedTransparency` carries- * the renderer's `matchMedia('(prefers-reduced-transparency: reduce)')`- * value — main toggles vibrancy material accordingly. See canonical- * JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */- signalThemeApplied(opts?: {- reducedTransparency?: boolean;- chrome?: { bg: string; symbol: string };- }): void;- dialog: {- openFolder(opts?: { defaultPath?: string }): Promise<string | null>;- };- shell: {- openExternal(url: string): Promise<void>;- /**- * Scheme format contract: `scheme` is the scheme NAME without trailing- * colon (e.g. `'claude'`, not `'claude:'`). Matches the main-process- * shell-injection sanitizer and the Linux `xdg-mime` shell-command form- * — callers with a colonful scheme MUST strip the trailing `:` first.- * See `packages/desktop/src/shared/bridge-contract.ts` for canonical JSDoc.- */- detectProtocol(scheme: string): Promise<{ installed: boolean; displayName?: string }>;- spawnCursor(- path: string,- ): Promise<- | { ok: true }- | { ok: false; reason: 'invalid-path' | 'not-installed' | 'timeout' | 'spawn-error' }- >;- recordHandoff(line: {- readonly target: 'claude-cowork' | 'claude-code' | 'codex' | 'cursor';- readonly host: 'electron' | 'web';- readonly outcome: 'ok' | 'error';- readonly ts: string;- readonly reason?:- | 'not-installed'- | 'scheme-blocked'- | 'web-endpoint-error'- | 'invalid-payload'- | 'dispatch-error'- | 'web-host-cursor-unsupported';- readonly scope?: 'selection';- }): Promise<void>;-- /**- * Open an asset via the OS default handler. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`. Asset-click-dispatcher- * surface.- */- openAsset(- relPath: string,- ): Promise<- | { ok: true }- | { ok: false; reason: 'extension-blocked' | 'path-escape' | 'not-found' | 'resolve-error' }- >;-- /**- * Reveal an asset in the native file manager. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`. Asset-click-dispatcher- * surface.- */- revealAsset(- relPath: string,- ): Promise<{ ok: true } | { ok: false; reason: 'path-escape' | 'not-found' | 'resolve-error' }>;-- /**- * Reveal an ABSOLUTE path outside the project (the terminal's out-of-project- * clickable-link flow). Main pops a "reveal in Finder?" confirmation naming- * the path and reveals on confirm. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- revealExternal(- absPath: string,- ): Promise<- | { ok: true; outcome: 'revealed' | 'dismissed' }- | { ok: false; reason: 'not-found' | 'invalid-path' | 'error' }- >;-- /**- * Display the native right-click context menu for an on-disk reference.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- * Asset-click-dispatcher surface.- */- showAssetMenu(params: {- readonly relPath: string;- readonly title: string;- readonly kind: 'asset' | 'wiki-link' | 'image';- }): Promise<void>;- /**- * Reveal a file or folder in the OS file manager. See canonical JSDoc- * in `packages/desktop/src/shared/bridge-contract.ts`.- */- showItemInFolder(path: string): Promise<void>;- /**- * Move a file or folder to the OS Trash. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- trashItem(absPath: string): Promise<- | { ok: true }- | {- ok: false;- reason: 'not-found' | 'permission-denied' | 'system-error' | 'path-escape';- detail?: string;- }- >;- };- clipboard: {- writeText(text: string): Promise<void>;- };- project: {- listRecent(): Promise<RecentProjectEntry[]>;- /**- * Forget one entry from the recent-projects list. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- removeRecent(path: string): Promise<void>;- getSessionState(): Promise<ProjectSessionState>;- setSessionState(state: ProjectSessionState): Promise<void>;- open(request: {- path: string;- target: 'new-window';- entryPoint: OkProjectEntryPoint;- /**- * Optional kind-discriminated target to deep-link into after the- * project window mounts. Used by share-receive: Q1 hits and Q2/Q3- * success both pass the share's target (a `doc` path or a `folder`- * path) so the editor opens it directly. Threaded through to- * `wm.createProjectWindow`'s `pendingDeepLinkTarget` (cold spawn →- * `dom-ready` deep-link IPC) and to `sendDeepLink` for the warm-focus- * path. Mirrors the existing `openknowledge://open?project=&doc=` plumbing.- */- pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };- /**- * Optional share branch riding alongside `pendingDeepLinkTarget`. See- * canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */- pendingBranch?: string | null;- /**- * Optional branch-switch payload for the share-receive "I already have- * it locally" path. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`. When the located- * clone is on a different branch than the share, main delivers the- * `project-branch-switch` surface instead of a plain deep-link open.- */- pendingShareBranchSwitch?: {- share: OkSharePayloadFields;- projectPath: string;- currentBranch: string | null;- };- }): Promise<void>;- /**- * File → Open file… — show the native md/mdx picker and open the pick in a- * temporary single-file session (the desktop side of `ok <file>`). Picker +- * open both run main-side; the picked path never crosses back to the- * renderer. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- openFile(): Promise<void>;- /**- * Atomically scaffold a new project under `parent/name` with the- * user-chosen `editors` set. `editors` is the renderer's exact selection- * (default-all unless the user unchecked entries); main never widens or- * narrows it. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- createNew(args: {- parent: string;- name: string;- editors: OkMcpWiringEditorId[];- /** OK config sharing mode — defaults to 'shared' when omitted. */- sharing?: 'shared' | 'local-only';- /**- * Starter pack to seed into the newly-created project (first-run- * packs-forward launcher). Omitted → blank project (today's behavior).- */- packId?: OkPackId;- }): Promise<void>;- /**- * Fire-and-forget renderer→main telemetry counter for the Create-new-project- * dialog cascade banners. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- recordCreateNewBannerShown(banner: CreateNewBannerKind): Promise<void>;- /**- * Probe `<projectPath>/<path>` for the share-receive target-existence- * gate, dispatching the on-disk predicate on `kind`. See canonical JSDoc- * in `packages/desktop/src/shared/bridge-contract.ts`.- */- checkTargetExists(request: {- projectPath: string;- kind: 'doc' | 'folder';- path: string;- }): Promise<CheckTargetExistsResult>;- /**- * Read `<projectPath>/.git/HEAD` and classify the result. See canonical- * JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */- readHeadBranch(projectPath: string): Promise<HeadBranchInfo>;- /**- * Proxy `GET /api/git/branch-info` against the project's running server.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */- fetchBranchInfo(request: {- projectPath: string;- branch: string;- kind: 'doc' | 'folder';- path: string;- }): Promise<BranchInfoResponse | null>;- /**- * Proxy `POST /api/git/checkout` against the project's running server.- * `fastForward` (on-origin "Switch and update branch") fast-forwards the- * target branch to origin's tip before checkout; divergence → `ff-diverged`- * (nothing mutated). See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- runCheckout(request: {- projectPath: string;- branch: string;- fastForward?: boolean;- }): Promise<CheckoutResponse | null>;- /**- * Proxy `POST /api/share/target-status` for the branch-switch dialog's- * verdict pivot (on-origin / renamed / deleted / never-on-branch /- * unknown). See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- fetchTargetStatus(request: {- projectPath: string;- branch: string;- path: string;- kind: 'doc' | 'folder';- }): Promise<ShareTargetStatusResponse | null>;- /**- * Gate dialog dismissal on the `branch-switched` broadcast landing- * in the project window. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- awaitBranchSwitched(request: {- projectPath: string;- branch: string;- timeoutMs: number;- }): Promise<{ ok: true } | { ok: false; reason: 'timeout' | 'project-not-open' }>;- /**- * Run the share-receive scaffold inside a CLI-managed git worktree.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */- okInit(request: { projectPath: string }): Promise<LocalOpOkInitResponse>;- close(): Promise<void>;- };-- /**- * Worktree selector (worktree = window). `list` enumerates the current- * project's local branches + their worktrees; `create` creates or locates a- * branch's worktree under `<mainRoot>/.ok/worktrees/`; `checkout` is the- * share-receive arm (resolves where the branch lives — fetching from- * `origin` when needed — then create-or-locates). The renderer opens the- * worktree window via `project.open({ entryPoint: 'worktree' })`. Canonical- * contract in `packages/desktop/src/shared/bridge-contract.ts`. Renderer- * consumers: `ProjectSwitcher` + `NewWorktreeDialog`.- */- worktree: {- list(): Promise<WorktreeListResult>;- create(request: WorktreeCreateRequest): Promise<WorktreeCreateResult>;- checkout(request: { branch: string }): Promise<WorktreeCreateResult>;- };-- /**- * OK config sharing mode — per-project sharing-mode posture.- * Canonical contract in `packages/desktop/src/shared/bridge-contract.ts`.- * Renderer consumers: `SharingSection` in the Settings dialog.- */- sharing: {- status(): Promise<OkSharingStatusResult>;- setMode(mode: 'shared' | 'local-only'): Promise<OkSharingSetModeResult>;- /** Toggle `.ok/skills/` shareability within local-only mode. */- setSkillsShared(shared: boolean): Promise<OkSharingSetModeResult>;- };-- /**- * In-app "Report a bug" — `create` builds the redacted diagnostic zip- * (optional crash-dump opt-in via `includeCrashDump`, optional app- * screenshot via `includeScreenshot`); `captureScreenshot` grabs the app- * before the dialog paints; `send` uploads it with an email fallback;- * `onCrashDetected` / `crashAck` carry the crash-invite round-trip.- * Canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- * Mirrored here per the OkDesktopBridge 3-way-mirror invariant.- */- bugReport: {- create(request: {- level: ReportBundleLevel;- note?: string;- includeCrashDump?: boolean;- includeScreenshot?: boolean;- }): Promise<OkBugReportCreateResult>;- captureScreenshot(): Promise<OkBugReportScreenshot | null>;- send(request: {- zipPath: string;- metadata: OkBugReportSendMetadata;- /**- * Whether the bundle at `zipPath` contains the app screenshot, taken from- * the bundle's own file inventory rather than the dialog's checkbox state.- * The inventory is what the reporter reviewed, so it is the authoritative- * consent record: absent or false means main must not upload the capture it- * is still holding.- */- includeScreenshot?: boolean;- }): Promise<OkBugReportSendResult>;- crashAck(request: { eventId: string }): Promise<OkBugReportCrashAckResult>;- list(): Promise<OkBugReportListResult>;- delete(id: string): Promise<OkBugReportDeleteResult>;- onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void): OkUnsubscribe;- };-- /**- * Filesystem probes that back the Create-new-project dialog cascade. See- * canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */- fs: {- defaultProjectsRoot(): Promise<string>;- folderState(path: string): Promise<OkFolderState>;- findEnclosingProjectRoot(path: string): Promise<OkFindEnclosingProjectRootResult | null>;- findEnclosingGitRoot(path: string): Promise<OkFindEnclosingGitRootResult | null>;- removeGitFolder(gitRoot: string): Promise<void>;- };- /**- * Re-summon the Project Navigator window from inside an editor window.- * Focus-existing-or-create — idempotent on already-focused. Used by- * `ProjectSwitcher` and `CommandPalette` to expose the navigator from- * inside the editor without closing the current window.- */- navigator: {- open(): Promise<void>;- };- seed: {- plan(options?: OkSeedPlanOptions): Promise<OkSeedPlanResult>;- apply(plan: OkScaffoldPlan, options?: OkSeedApplyOptions): Promise<OkSeedApplyResult>;- listPacks(): Promise<OkSeedListPacksResult>;- };- skill: {- /** True when Claude Desktop's config dir exists on this machine. */- detectClaudeDesktop(): Promise<boolean>;- /**- * Build `openknowledge.skill` from the bundled source, save to- * Downloads, invoke the OS file association (`.skill` → Claude- * Desktop). Local build; no network.- *- * Gated by `~/.ok/skill-state/claude-cowork`: when the recorded- * version matches the current bundled skill version, resolves with- * `{ ok: true, skipped: true, version, recordedAt? }` without- * rebuilding. Pass `force: true` to bypass for reinstall.- */- buildAndOpen(opts?: { force?: boolean }): Promise<- | { ok: true; path: string; skipped?: false; version?: string }- | {- ok: true;- path?: undefined;- skipped: true;- version: string;- recordedAt?: string;- }- | {- ok: false;- reason: 'build-failed' | 'open-failed' | 'no-downloads-dir';- message?: string;- }- >;- };- update: {- relaunchNow(): Promise<void>;- checkNow(): Promise<void>;- /**- * Fire `ok:update:whats-new-dismiss` — tells main this window dismissed the- * what's-new notice so main clears it across all windows. Fire-and-forget.- */- dismissWhatsNew(version: string): Promise<void>;- };- state: {- query(): Promise<OkStateSnapshot>;- resetIncompatible(): Promise<void>;- };- mcpWiring: {- onShow(cb: (payload: OkMcpWiringShowPayload) => void): OkUnsubscribe;- signalReady(): void;- confirm(request: OkMcpWiringConfirmRequest): Promise<OkMcpWiringResult>;- skip(): Promise<OkMcpWiringResult>;- /**- * Re-arm the MCP consent dialog (File → "Set up OpenKnowledge integrations…"- * and the Cmd+K command). Resolves `true` when armed, `false` when- * unavailable (non-darwin / unpackaged / arming threw). Mirror of the- * canonical `bridge-contract.ts` method.- */- reconfigure(): Promise<boolean>;- };- /**- * App-wide spell-check toggle (Edit → "Check spelling while typing" and the- * Cmd+K command). `toggle()` flips the flag and resolves to the new enabled- * state. Mirror of the canonical `bridge-contract.ts` method.- */- spellcheck: {- toggle(): Promise<boolean>;- };- /**- * Settings → AI tools: live per-component install state + one-component- * install/uninstall for OK's global footprint (per-editor MCP entries,- * shell-PATH shim, user-global skill bundles). Mutations serialize in main.- */- integrations: {- status(): Promise<OkIntegrationsStatus>;- setComponent(request: OkIntegrationsSetRequest): Promise<OkIntegrationsSetResult>;- };- /**- * Settings → This project → AI tools: live per-component install state +- * one-component install/uninstall for OK's PROJECT-LOCAL footprint (per-editor- * project MCP config files + the project runtime skill) against the project- * the requesting window has open. Mutations serialize in main.- */- projectIntegrations: {- status(): Promise<OkProjectIntegrationsStatus>;- setComponent(request: OkProjectIntegrationsSetRequest): Promise<OkProjectIntegrationsSetResult>;- };- /**- * Per-project consent dialog surface. Navigator-only. Renderer mounts a- * shadcn Dialog when `onShow` fires; calls `confirm` / `cancel` on user- * action; calls `signalReady()` on app mount. `onToast` fires on- * freshly-spawned editor windows for ancestor- and git-root-promote- * events.- */- onboarding: {- onShow(cb: (payload: OkOnboardingShowPayload) => void): OkUnsubscribe;- signalReady(): void;- confirm(request: OkOnboardingConfirmRequest): Promise<OkOnboardingResult>;- cancel(): Promise<OkOnboardingResult>;- probeContent(request: OkOnboardingProbeContentRequest): Promise<OkOnboardingProbeContentResult>;- onToast(- cb: (- payload:- | { readonly kind: 'ancestor-promote'; readonly ancestorPath: string }- | {- readonly kind: 'git-root-promote';- readonly gitRoot: string;- readonly pickedPath: string;- }- | {- readonly kind: 'startup-reclaim';- readonly mcp:- | { readonly status: 'none' }- | { readonly status: 'repaired'; readonly editors: readonly string[] }- | { readonly status: 'failed'; readonly editors: readonly string[] };- readonly path:- | { readonly status: 'none' }- | { readonly status: 'installed'; readonly summary: string }- | { readonly status: 'failed'; readonly summary: string };- }- | {- readonly kind: 'sharing-refused-tracked';- readonly tracked: readonly string[];- readonly remediation: string;- }- | {- readonly kind: 'sharing-no-git';- readonly requestedMode: 'local-only';- },- ) => void,- ): OkUnsubscribe;- };- /**- * Pre-project local-op flows. Required by the Project Navigator window- * (no backing API server). See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- localOp: {- auth: {- start(): OkLocalOpStream<OkLocalOpAuthEvent>;- };- clone: {- start(request: {- url: string;- dir: string;- branch?: string | null;- }): OkLocalOpStream<OkLocalOpCloneEvent>;- };- authStatus(request?: { host?: string }): Promise<OkLocalOpAuthStatusResponse>;- authRepos(request?: { host?: string }): Promise<OkLocalOpAuthReposResponse>;- };- /**- * Share-receive flow surface. `validateLocalFolder` runs the- * "I have it locally" folder validator in the main process via- * `validateLocalFolderForShare` from the CLI package.- */- share: {- validateLocalFolder(args: {- folderPath: string;- host: string;- owner: string;- repo: string;- }): Promise<ShareFolderValidationResult>;- };- /**- * Editor area state push surface. Renderer fires- * `notifyActiveTargetChanged` once per `activeTarget` transition. See- * canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */- editor: {- notifyActiveTargetChanged(target: OkEditorActiveTargetSnapshot): void;- /**- * Fire-and-forget push of the sidebar's view-menu state. See canonical- * JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */- notifyViewMenuStateChanged(state: Partial<OkEditorViewMenuStateSnapshot>): void;- /**- * Fire-and-forget push keying the window's Chromium background-throttling- * to its unsynced work. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */- notifyBackgroundThrottle(signal: { hasPendingWork: boolean; enabled: boolean }): void;- };-- /**- * Windows/Linux renderer-menubar dispatch surface (windows-linux-port- * renderer-menubar decision). macOS keeps the native menu bar and never calls this; on- * win/linux the renderer-drawn menu bar routes every click through main- * so menu semantics live in one place. `query` resolves the aggregated- * `OkMenuRendererSnapshot`; every other kind performs the action- * main-side and resolves undefined.- */- menu: {- dispatch(request: OkMenuDispatchRequest): Promise<OkMenuRendererSnapshot | undefined>;- };- /**- * Startup-instrumentation push surface. The renderer reports its two- * launch checkpoints (page-list ready, first content) as epoch-ms once both- * land; main folds them into the `desktop.startup-timeline` waterfall log.- * Fire-and-forget. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim- * (drift-tested).- */- startup: {- reportMarks(marks: { pageListReadyMs: number; firstContentMs: number }): void;- };- /**- * Sidebar tree-state push subscriptions. Main pushes- * `ok:sidebar:expand-all` / `ok:sidebar:collapse-all` on View menu picks.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */- sidebar: {- expandAll(cb: () => void): OkUnsubscribe;- collapseAll(cb: () => void): OkUnsubscribe;- };-- /**- * Bottom-docked terminal panel surface. Canonical JSDoc in- * `bridge-contract.ts`; mirrored verbatim here (drift-tested).- */- terminal: {- create(opts: {- cols: number;- rows: number;- launchCommand?: string;- }): Promise<OkPtyCreateResult>;- input(ptyId: string, data: string): void;- resize(ptyId: string, cols: number, rows: number): void;- kill(ptyId: string): Promise<void>;- drain(ptyId: string, bytes: number): void;- /** Reload-rehydration inventory. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */- list(): Promise<OkPtyListEntry[]>;- /** Reload-rehydration adopt. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */- adopt(ptyId: string): Promise<OkPtyAdoptResult>;- /**- * Persist per-session tab metadata (custom name + sticky ordinal) in main so- * it survives a renderer reload — main outlives the reload, so a reloaded dock- * reads it back via `list`. Fire-and-forget; omit a field to leave it unchanged.- */- setMeta(ptyId: string, meta: { customLabel?: string | null; ordinal?: number }): void;- /**- * Persist the tab display order in main (ptyIds in visual order) so a reorder- * survives a renderer reload. Fire-and-forget.- */- setOrder(orderedPtyIds: readonly string[]): void;- /** Per-window panel state (per-surface visibility + tab order + active key). Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */- getDockState(): Promise<{- terminalVisible: boolean;- agentPanelVisible: boolean;- terminal?: { order: string[]; activeKey: string | null };- agents?: { order: string[]; activeKey: string | null };- }>;- /** Persist one panel's tab order + active key per window. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */- setDockState(state: {- surface: 'terminal' | 'agents';- order: string[];- activeKey: string | null;- }): void;- onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;- onExit(cb: (msg: OkPtyExit) => void): OkUnsubscribe;- claudePreflight(): Promise<ClaudeReadiness>;- cliPreflight(cli: TerminalCli): Promise<CliReadiness>;- /** Batched CLI installed-map for the New-chat default auto-pick. Canonical JSDoc in `bridge-contract.ts`; mirrored (drift-tested). */- cliInstalledMap(): Promise<Record<TerminalCli, boolean>>;- rewireClaudeMcp(): Promise<ClaudeReadiness>;- };-- /**- * OS assistive-tech signal gating xterm's `screenReaderMode`. Canonical- * JSDoc in `bridge-contract.ts`. Optional in this mirror: session-only- * bridges (and test doubles) omit it — consumers treat an absent surface- * as screen-reader-active (fail-accessible).- */- accessibility?: {- isScreenReaderActive(): boolean;- onScreenReaderChanged(cb: (active: boolean) => void): OkUnsubscribe;- };-- readonly platform: 'darwin' | 'win32' | 'linux';- readonly appVersion: string;- /**- * Named parallel dev-instance label (branch/worktree) when this launch- * relocated `userData` to a named sibling — auto-derived from the git- * checkout or an explicit `OK_INSTANCE`. Null for the default install and in- * web / CLI distribution. Drives the header branch badge. Lockstep with the- * main-side `OkDesktopBridge` (`packages/desktop/src/shared/bridge-contract.ts`).- */- readonly instanceLabel: string | null;- /**- * Resolve a dropped `File` to its absolute filesystem path via Electron- * `webUtils.getPathForFile` (renderer-side, no IPC). Returns null for a File- * with no backing path on disk (e.g. an in-memory clipboard blob). The- * docked terminal uses this to insert a dropped file's path at the prompt.- */- getPathForFile(file: File): string | null;- /**- * Debug-only namespace populated by preload when the runtime gate- * allows. Absent in production so a typo surfaces at compile time.- */- debug?: {- keyringSmoke(): Promise<OkKeyringSmokeResult>;- };-}-declare global {interface Window {- /** Populated by the desktop preload script. Absent in web / CLI distribution. */okDesktop?: OkDesktopBridge;}}diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.tsindex 7e398e834..b5eae7fab 100644--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts@@ -330,7 +330,7 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P// Typed with `satisfies OkDesktopBridge` so any drift between the// canonical contract (`packages/core/src/desktop-bridge.ts`) and this- // fixture fails `bun run typecheck` instead of going silent.+ // fixture fails `pnpm run typecheck` instead of going silent.// `tests/stress/fixtures` is in `packages/app/tsconfig.json` `include`// for this reason. Imported types erase at runtime, so the// `addInitScript` callback's stringification is unaffected.@@ -338,13 +338,8 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P// Coverage limit: TypeScript function subtyping accepts shape-// compatible parameters silently, so signature-shape drift on// existing methods (e.g. a new required field on a request param)- // passes here. That drift class is caught instead by the three- // OkDesktopBridge contract copies (core / desktop / app) being- // consumed across enough call sites that divergence surfaces at- // `bun run typecheck`. `packages/desktop/tests/integration/- // m1-smoke.test.ts` is the member-name drift catcher (set-equality- // on extracted member names across the three copies); its own- // signature-coverage disclaimer documents the gap explicitly.+ // passes here. The canonical core contract and the dedicated preload+ // forwarding tests cover the declaration and transport boundaries.const bridge = {config: {// Hocuspocus is mounted at /collab by the Vite plugin (the upgradediff --git a/packages/core/package.json b/packages/core/package.jsonindex 6121bd630..02db3c375 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -44,6 +44,11 @@"development": "./src/acp/thread-protocol.ts","types": "./src/acp/thread-protocol.ts","default": "./dist/acp-thread-protocol.mjs"+ },+ "./desktop-bridge": {+ "development": "./src/desktop-bridge.ts",+ "types": "./src/desktop-bridge.ts",+ "default": "./dist/desktop-bridge.mjs"}},"files": [diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex 0ee5132b6..e8d738a6a 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -17,6 +17,7 @@ import type {WorktreeListResult,} from './git/worktree-selector-model.ts';import type { TerminalCli } from './handoff/terminal-launch.ts';+import type { HandoffFailureReason, HandoffScope } from './handoff/types.ts';import type {OkBugReportCrashAckResult,OkBugReportCrashDetectedEvent,@@ -36,8 +37,12 @@ import type {} from './schemas/api/share.ts';import type { RecentProjectEntry } from './sharing/index.ts';+export type { OkFolderState } from './constants/folder-state.ts';+export type { BridgeWorktreeEntry } from './git/worktree-list-parser.ts';+export type { RecentProjectEntry } from './sharing/index.ts';+/** Render mode picked by the main process when creating a BrowserWindow. */-type OkDesktopMode = 'editor' | 'navigator' | 'terminal';+export type OkDesktopMode = 'editor' | 'navigator' | 'terminal';/*** Config values injected at preload-exposure time. A frozen snapshot, not a@@ -46,7 +51,7 @@ type OkDesktopMode = 'editor' | 'navigator' | 'terminal';* because the main process awaits the utility's `ready` message before* creating the BrowserWindow.*/-interface OkDesktopConfig {+export interface OkDesktopConfig {/** WebSocket URL for the HocuspocusProvider (ws://localhost:<port>/collab). */readonly collabUrl: string;/** Origin for HTTP /api/* fetches (http://localhost:<port>). */@@ -57,6 +62,12 @@ interface OkDesktopConfig {readonly projectName: string;/** Render mode — `navigator` renders the Project Navigator, `editor` renders the doc editor, `terminal` renders the standalone terminal window. */readonly mode: OkDesktopMode;+ readonly e2eSmoke: boolean;+ readonly singleFile: boolean;+ readonly initialDoc: string | null;+ readonly freshlyCreated: boolean;+ readonly startupTraceparent?: string;+ readonly ptyAvailable: boolean;}/**@@ -65,7 +76,7 @@ interface OkDesktopConfig {* store. Keep this union flat and strongly typed — a single `kind` field* discriminates without payload.*/-type OkMenuAction =+export type OkMenuAction =| 'new-doc'| 'new-folder'// Opens the create-new-project dialog in the focused window (a whole new@@ -84,8 +95,7 @@ type OkMenuAction =// Navigation history.| 'navigate-back'| 'navigate-forward'- // File menu state-aware items. See bridge-contract.ts for- // rationale; mirrored here per the OkDesktopBridge 3-way-mirror invariant.+ // File menu state-aware items share this canonical bridge declaration.| 'new-from-template'| 'duplicate'| 'move-to-trash'@@ -102,9 +112,8 @@ type OkMenuAction =| 'collapse-all-tree'| 'toggle-doc-panel'| 'toggle-terminal'- // Right agents-panel visibility (⌘L / Ctrl+L). The ACP twin of- // `toggle-terminal`, and deliberately NOT desktop-gated: agent threads are- // server-hosted, so the panel works on the web host and where pty does not.+ // Right agents-panel visibility. Unlike the terminal, agent threads are+ // server-hosted and the panel is available outside the desktop PTY host.| 'toggle-agent-panel'// Terminal application menu. `new-terminal` opens a new terminal tab// (revealing the dock if hidden; never hides, unlike the toggle).@@ -131,9 +140,9 @@ type OkMenuAction =* callers must use this returned closure rather than trying to remove by* reference from their own code.*/-type OkUnsubscribe = () => void;+export type OkUnsubscribe = () => void;-interface ProjectSessionState {+export interface ProjectSessionState {openTabs: string[];pinnedTabIds: string[];activeDocName: string | null;@@ -144,10 +153,9 @@ interface ProjectSessionState {/*** Discriminator for the Navigator-side surface that initiated a project-open.- * Mirrors `EntryPoint` in `packages/desktop/src/shared/entry-point.ts`. Drift- * across the three bridge-contract copies is caught by the drift test.+ * Matches the desktop runtime `EntryPoint` discriminator.*/-type OkProjectEntryPoint =+export type OkProjectEntryPoint =| 'create-new'| 'create-new-nested-redirect'| 'pick-existing'@@ -163,7 +171,7 @@ type OkProjectEntryPoint =* today (no switch-in-place). `entryPoint` tags the originating surface so* the consent-dialog gate can branch on user intent.*/-interface OkProjectOpenRequest {+export interface OkProjectOpenRequest {path: string;target: 'new-window';entryPoint: OkProjectEntryPoint;@@ -179,13 +187,12 @@ interface OkProjectOpenRequest {pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };/*** Optional share branch riding alongside `pendingDeepLinkTarget`. See- * canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.+ * canonical bridge contract below.*/pendingBranch?: string | null;/*** Optional branch-switch payload for the share-receive "I already have it- * locally" path. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`. When the located clone+ * locally" path. When the located clone* is on a different branch than the share, main delivers the* `project-branch-switch` surface instead of a plain deep-link open.*/@@ -198,8 +205,7 @@ interface OkProjectOpenRequest {/*** Outcome of `bridge.project.checkTargetExists({projectPath, kind, path})`.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`- * (`CheckTargetExistsResult`).+ * Alias used by existing desktop consumers as `CheckTargetExistsResult`.** Used by the main-side target-existence gate AFTER the branch comparison* passes — answers "does the share's target actually exist on the receiver's@@ -210,8 +216,7 @@ interface OkProjectOpenRequest {export type OkCheckTargetExistsResult = 'exists' | 'missing' | 'unreadable';/**- * Outcome of `bridge.project.readHeadBranch(projectPath)`. See canonical- * JSDoc in `packages/desktop/src/shared/bridge-contract.ts` (`HeadBranchInfo`).+ * Outcome of `bridge.project.readHeadBranch(projectPath)`.** All-null + `detached: false` is the "couldn't determine" sentinel returned* on every failure mode (missing `.git`, malformed HEAD, I/O error, traversal@@ -229,7 +234,7 @@ export interface OkHeadBranchInfo {* install-on-quit (or an imperative `autoUpdater.quitAndInstall()` via* Toast A's "Relaunch now" action).*/-interface OkUpdateDownloadedInfo {+export interface OkUpdateDownloadedInfo {readonly version: string;}@@ -239,7 +244,7 @@ interface OkUpdateDownloadedInfo {* passed its `versionPendingInstall` gate). Every window swaps its* `update-downloaded` card to the in-progress "Relaunching…" state.*/-interface OkUpdateRelaunchingInfo {+export interface OkUpdateRelaunchingInfo {readonly version: string;}@@ -250,9 +255,10 @@ interface OkUpdateRelaunchingInfo {* `quitAndInstall()` threw. Main re-arms the banner separately via a* re-broadcast `ok:update:downloaded`; this carries the failure detail.*/-interface OkUpdateRelaunchFailedInfo {+export interface OkUpdateRelaunchFailedInfo {readonly version: string;readonly message?: string;+ readonly downloadUrl?: string;}/**@@ -261,7 +267,7 @@ interface OkUpdateRelaunchFailedInfo {* to `AppState.lastSeenVersion`). `releaseUrl` is the GitHub Releases page* for the new version — renderer opens it via `bridge.shell.openExternal`.*/-interface OkWhatsNewInfo {+export interface OkWhatsNewInfo {readonly version: string;readonly releaseUrl: string;}@@ -273,7 +279,7 @@ interface OkWhatsNewInfo {* OpenKnowledge download CTA); renderer opens it via* `bridge.shell.openExternal`.*/-interface OkUpdateStuckHintInfo {+export interface OkUpdateStuckHintInfo {readonly downloadUrl: string;}@@ -287,20 +293,16 @@ interface OkUpdateStuckHintInfo {* - `kind: 'unsupported-version'` — sonner toast "Update OpenKnowledge"* - `kind: 'invalid'` — sonner toast "Invalid share URL"*- * Mirrored across the three bridge-contract copies (desktop, core, app). Source- * (universal-link vs custom-scheme) is NOT propagated — main-process diagnostic- * logging only.+ * Source (universal-link vs custom-scheme) is NOT propagated — main-process+ * diagnostic logging only.*/-/** Kind-discriminated receiver target carried by `OkSharePayloadFields`.- * Local copy — see canonical `ShareTarget` in- * `packages/desktop/src/shared/bridge-contract.ts`. */-type ShareTarget =+/** Kind-discriminated receiver target carried by `OkSharePayloadFields`. */+export type ShareTarget =| { readonly kind: 'doc'; readonly docPath: string }| { readonly kind: 'folder'; readonly folderPath: string };-/** Local copy — see canonical `OkSharePayloadFields` in- * `packages/desktop/src/shared/bridge-contract.ts`. */-interface OkSharePayloadFields {+/** Parsed project-share fields carried across the desktop host bridge. */+export interface OkSharePayloadFields {/** GitHub host of the shared repo: `github.com` or a GHES hostname. */readonly host: string;readonly owner: string;@@ -310,9 +312,8 @@ interface OkSharePayloadFields {readonly target: ShareTarget;}-/** Local copy — see canonical `OkShareReceivedPayload` in- * `packages/desktop/src/shared/bridge-contract.ts`. */-type OkShareReceivedPayload =+/** Renderer-facing payload for a received project share. */+export type OkShareReceivedPayload =| { readonly kind: 'unsupported-version' }| { readonly kind: 'invalid' }| {@@ -340,12 +341,11 @@ type OkShareReceivedPayload =};/**- * Renderer-facing mirror of `ShareFolderValidationResult` from+ * Renderer-facing representation of `ShareFolderValidationResult` from* `@inkeep/open-knowledge`'s `validateLocalFolderForShare`. Carried- * by the `share.validateLocalFolder` IPC. Mirrored across the three bridge-- * contract copies (desktop, core, app) so the drift tests catch divergent copies.+ * by the `share.validateLocalFolder` IPC.*/-type ShareFolderValidationResult =+export type ShareFolderValidationResult =| { readonly kind: 'ok'; readonly gitRemoteUrl: string }| { readonly kind: 'not-git' }| { readonly kind: 'no-origin' }@@ -360,17 +360,24 @@ type ShareFolderValidationResult =* one. Not a runtime preference. Mirrors `UpdateChannel` in desktop's* `state-store.ts`.*/-type OkUpdateChannel = 'latest' | 'beta';+export type OkUpdateChannel = 'latest' | 'beta';/*** User-intent theme value. Mirrors Electron's `nativeTheme.themeSource`* union. Carried verbatim through the `ok:theme:set-source` IPC channel —* never resolved to a concrete light/dark value at the renderer call site* (the `'system'` value IS the lever that delegates appearance tracking to- * macOS). Drift across the three bridge-contract copies (desktop, core,- * app) is caught by an invariant test.+ * macOS). The desktop and app compatibility paths re-export this declaration.*/-type OkThemeSource = 'system' | 'light' | 'dark';+export type OkThemeSource = 'system' | 'light' | 'dark';++/** Colors handed to Electron for OS-drawn window chrome. */+export interface OkChromeColors {+ /** Active theme's sidebar surface color. */+ bg: string;+ /** Active theme's sidebar foreground color. */+ symbol: string;+}/*** Snapshot returned by `state.query()` — newly-opened windows query on@@ -378,7 +385,7 @@ type OkThemeSource = 'system' | 'light' | 'dark';* build-derived) and to route the refuse-downgrade UX when a future-build* state was rolled back.*/-interface OkStateSnapshot {+export interface OkStateSnapshot {readonly channel: OkUpdateChannel;readonly schemaIncompatibility: {readonly currentBuild: string;@@ -390,11 +397,9 @@ interface OkStateSnapshot {/*** Editor IDs surfaced through the first-launch MCP consent bridge.* Aliased to the canonical `EditorId` from `constants/editors.ts` — single- * source of truth for the literal union. Bridge mirrors in desktop + app- * also alias to the same `EditorId` so the type is structurally identical- * across all three copies.+ * source of truth for the literal union.*/-type OkMcpWiringEditorId = EditorId;+export type OkMcpWiringEditorId = EditorId;/*** Payload delivered to `mcpWiring.onShow` subscribers on first-launch MCP@@ -407,13 +412,15 @@ type OkMcpWiringEditorId = EditorId;* `alreadyInstalled: true` renders it informational; `rcFilesToTouch`* names the tildified shell files a grant would edit.*/-interface OkMcpWiringShowPayload {+export interface OkMcpWiringShowPayload {readonly detectedEditors: readonly {readonly id: OkMcpWiringEditorId;readonly label: string;readonly detected: boolean;readonly willReplace: boolean;+ /** Display-form user-global config path, or null when unavailable. */readonly configPath: string | null;+ /** Locator for OpenKnowledge's entry within the editor config. */readonly entryLocator: string;}[];readonly pathInstall: {@@ -441,7 +448,7 @@ interface OkMcpWiringShowPayload {* solicited; every offered bundle not in the list is recorded declined (and* removed if already installed).*/-interface OkMcpWiringConfirmRequest {+export interface OkMcpWiringConfirmRequest {readonly editorIds: readonly OkMcpWiringEditorId[];readonly pathInstall?: boolean;readonly skills?: readonly string[];@@ -453,7 +460,7 @@ interface OkMcpWiringConfirmRequest {* `ok:true` and are surfaced to operator logs via structured* `mcp-wiring-write-failed` events (deferred-marker semantics).*/-type OkMcpWiringResult = { ok: true } | { ok: false; error: string };+export type OkMcpWiringResult = { ok: true } | { ok: false; error: string };/*** Per-editor MCP state for Settings → AI tools. `installed` rows uncheck to@@ -461,12 +468,12 @@ type OkMcpWiringResult = { ok: true } | { ok: false; error: string };* OK's server name that isn't recognizably OK's own (uninstall refuses,* install overwrites); `unmanageable` is a config OK can't safely edit.*/-type OkIntegrationsEditorState = 'installed' | 'not-installed' | 'foreign' | 'unmanageable';+export type OkIntegrationsEditorState = 'installed' | 'not-installed' | 'foreign' | 'unmanageable';/** Component inventory for Settings → AI tools. `available: false` renders* the section read-only (install actors gated off for this process). `path.* installed` reflects the managed rc block actually being on disk. */-interface OkIntegrationsStatus {+export interface OkIntegrationsStatus {readonly available: boolean;readonly editors: readonly {readonly id: OkMcpWiringEditorId;@@ -490,7 +497,7 @@ interface OkIntegrationsStatus {}/** One toggle for `integrations.setComponent`. */-interface OkIntegrationsSetRequest {+export interface OkIntegrationsSetRequest {readonly component:| { readonly kind: 'editor'; readonly id: OkMcpWiringEditorId }| { readonly kind: 'path' }@@ -500,7 +507,7 @@ interface OkIntegrationsSetRequest {/** Set-component result — both arms carry a fresh status snapshot so the* renderer re-renders truthfully after failed/refused toggles too. */-type OkIntegrationsSetResult =+export type OkIntegrationsSetResult =| { readonly ok: true; readonly status: OkIntegrationsStatus }| { readonly ok: false; readonly error: string; readonly status: OkIntegrationsStatus };@@ -508,13 +515,17 @@ type OkIntegrationsSetResult =* connect: `approve-once` (Claude Code), `enable-manually` (Cursor, silently* disabled until toggled), `auto-connect` (Codex on a trusted project),* `none`. */-type OkProjectIntegrationsFollowUp = 'approve-once' | 'enable-manually' | 'auto-connect' | 'none';+export type OkProjectIntegrationsFollowUp =+ | 'approve-once'+ | 'enable-manually'+ | 'auto-connect'+ | 'none';/** Component inventory for Settings → This project → AI tools (per-editor* PROJECT MCP config files + the single project runtime skill), scoped to the* project the requesting window has open. `hasProject: false` → empty state;* `available: false` → read-only. */-interface OkProjectIntegrationsStatus {+export interface OkProjectIntegrationsStatus {readonly available: boolean;readonly hasProject: boolean;readonly projectDir: string | null;@@ -534,23 +545,21 @@ interface OkProjectIntegrationsStatus {/** One toggle for `projectIntegrations.setComponent`. The skill is a single* row (no id) — it fans out across every capable editor. */-interface OkProjectIntegrationsSetRequest {+export interface OkProjectIntegrationsSetRequest {readonly component:| { readonly kind: 'editor'; readonly id: OkMcpWiringEditorId }| { readonly kind: 'skill' };readonly enabled: boolean;}-type OkProjectIntegrationsSetResult =+export type OkProjectIntegrationsSetResult =| { readonly ok: true; readonly status: OkProjectIntegrationsStatus }| { readonly ok: false; readonly error: string; readonly status: OkProjectIntegrationsStatus };/*** Per-project consent dialog — renderer-facing payload + result shapes.- * Mirrors the desktop and app copies; drift caught by the- * bridge-contract drift-catcher test.*/-type OkOnboardingWarningKind =+export type OkOnboardingWarningKind =| 'root'| 'home'| 'home-documents'@@ -559,9 +568,9 @@ type OkOnboardingWarningKind =| 'volumes-mount'| 'drive-root';-type OkOnboardingGitState = 'present' | 'absent' | 'shell-only';+export type OkOnboardingGitState = 'present' | 'absent' | 'shell-only';-interface OkOnboardingShowPayload {+export interface OkOnboardingShowPayload {readonly pickedPath: string;readonly projectDir: string;readonly defaultContentDir: string;@@ -578,20 +587,21 @@ interface OkOnboardingShowPayload {}[];}-interface OkOnboardingConfirmRequest {+export interface OkOnboardingConfirmRequest {readonly initGit: boolean;readonly contentDir: string;readonly additionalIgnores: string;readonly editorIds: readonly OkMcpWiringEditorId[];+ readonly sharing: 'shared' | 'local-only';}-type OkOnboardingResult = { ok: true } | { ok: false; error: string };+export type OkOnboardingResult = { ok: true } | { ok: false; error: string };-interface OkOnboardingProbeContentRequest {+export interface OkOnboardingProbeContentRequest {readonly contentDir: string;}-type OkOnboardingProbeContentResult =+export type OkOnboardingProbeContentResult =| {readonly ok: true;readonly count: number;@@ -604,11 +614,10 @@ type OkOnboardingProbeContentResult =* Result shape for `bridge.debug?.keyringSmoke()` — mirrors* `KeyringSmokeResult` in `packages/desktop/src/utility/keyring-smoke.ts`* (identical field set). Duplicated here (not imported) because core has no- * dep on desktop. Drift across the three copies (desktop, core, app) is- * caught by the bridge-contract drift-catcher test, which walks the- * interface body of each file and asserts field-name set equality.+ * dep on desktop. The desktop utility remains checked against this canonical+ * field set by the desktop architecture test.*/-interface OkKeyringSmokeResult {+export interface OkKeyringSmokeResult {ok: boolean;backend?: 'keyring' | 'file';error?: string;@@ -628,28 +637,28 @@ interface OkKeyringSmokeResult {* path. The previous `OkFolderRule` / `OkScaffoldConfigEdit` mirror types* + the `configEdits` field on `OkScaffoldPlan` were removed alongside.*/-interface OkScaffoldFileEntry {+export interface OkScaffoldFileEntry {path: string;kind: 'folder' | 'file';contentPreview?: string;}-interface OkScaffoldSkipEntry {+export interface OkScaffoldSkipEntry {path: string;reason: 'already-exists' | 'user-content' | 'glob-collision';}-interface OkScaffoldPlan {+export interface OkScaffoldPlan {created: OkScaffoldFileEntry[];skipped: OkScaffoldSkipEntry[];warnings: string[];- /** The pack's project-local skill, when it ships one. `pending` = the skill- * source is absent from `.ok/skills/` and apply would (re)author it. */+ /** Project-local skills shipped by the pack. `pending` means apply would+ * author or refresh the skill source. */packSkills?: { name: string; pending: boolean }[];}-interface OkScaffoldApplyError {+export interface OkScaffoldApplyError {path: string;error: string;}-interface OkScaffoldApplyResult {+export interface OkScaffoldApplyResult {applied: number;errors: OkScaffoldApplyError[];durationMs: number;@@ -657,7 +666,7 @@ interface OkScaffoldApplyResult {packSkillsInstalled: string[];}-interface OkSeedError {+export interface OkSeedError {kind: 'no-project' | 'prerequisite-missing' | 'invalid-root' | 'internal';message: string;}@@ -665,14 +674,9 @@ interface OkSeedError {/*** Pack-id wire shape — accepted strings; coerced server-side via `coercePackId`.*- * DRIFT WARNING: three-way structural mirror with- * - `packages/desktop/src/shared/bridge-contract.ts` (imports `PackId` from server)- * - `packages/app/src/lib/desktop-bridge-types.ts` (local copy)- *- * Adding a pack: update all three sites. Drift is caught at typecheck time by- * the `Eq<>` type-check assertions.+ * This bridge leaf is the renderer contract's single declaration point.*/-type OkPackId =+export type OkPackId =| 'knowledge-base'| 'software-lifecycle'| 'codebase-wiki'@@ -682,31 +686,30 @@ type OkPackId =| 'entity-vault'| 'okf';-interface OkSeedPlanOptions {+export interface OkSeedPlanOptions {rootDir?: string;packId?: OkPackId;}-interface OkSeedApplyOptions {+export interface OkSeedApplyOptions {packId?: OkPackId;}-interface OkSeedPackFolderInfo {+export interface OkSeedPackFolderInfo {path: string;summary: string;}/*** User-visible entry counts surfaced on each pack picker card as- * "N files · N folders". Three-way mirror with the desktop + app copies;- * the Eq<> drift catcher fails if this diverges.+ * "N files · N folders".*/-interface OkSeedPackEntryCounts {+export interface OkSeedPackEntryCounts {files: number;folders: number;}-interface OkSeedPackInfo {+export interface OkSeedPackInfo {id: OkPackId;name: string;description: string;@@ -718,28 +721,31 @@ interface OkSeedPackInfo {/** Pure-fs upward-walk result types mirrored from `@inkeep/open-knowledge-server`'s* `fs/` module. Structurally duplicated for the same reason as the seed shapes* above (core has no dep on server). */-interface OkFindEnclosingProjectRootResult {+export interface OkFindEnclosingProjectRootResult {readonly rootPath: string;readonly distance: number;}-interface OkFindEnclosingGitRootResult {+export interface OkFindEnclosingGitRootResult {readonly gitRoot: string;readonly distance: number;}-type OkSeedPlanResult = { ok: true; plan: OkScaffoldPlan } | { ok: false; error: OkSeedError };-type OkSeedApplyResult =+export type OkSeedPlanResult =+ | { ok: true; plan: OkScaffoldPlan }+ | { ok: false; error: OkSeedError };+export type OkSeedApplyResult =| { ok: true; result: OkScaffoldApplyResult }| { ok: false; error: OkSeedError };-type OkSeedListPacksResult =+export type OkSeedListPacksResult =| { ok: true; packs: OkSeedPackInfo[] }| { ok: false; error: { kind: 'internal'; message: string } };+export type OkLocalOpAuthSignoutResponse = { ok: true } | { ok: false; error?: string };+/*** Pre-project local-op event shapes — auth + clone flows surfaced to the- * Navigator window via IPC because it has no backing API server. See the- * desktop bridge-contract for the canonical wire shape.+ * Navigator window via IPC because it has no backing API server.*/-type OkLocalOpAuthEvent =+export type OkLocalOpAuthEvent =| {type: 'verification';user_code: string;@@ -756,18 +762,18 @@ type OkLocalOpAuthEvent =}| { type: 'error'; message: string };-type OkLocalOpCloneEvent =+export type OkLocalOpCloneEvent =| { type: 'progress'; phase: string; pct: number }| { type: 'complete'; dir: string }| { type: 'branch-fallback'; branch: string }| { type: 'error'; message: string };-interface OkLocalOpStream<E> {+export interface OkLocalOpStream<E> {readonly events: AsyncIterable<E>;cancel(): void;}-type OkLocalOpAuthStatusResponse =+export type OkLocalOpAuthStatusResponse =| {authenticated: true;host: string;@@ -775,16 +781,17 @@ type OkLocalOpAuthStatusResponse =tier?: 'A' | 'B' | 'C';name?: string;email?: string;+ ghAvailable?: boolean;}- | { authenticated: false; host: string; error?: string };+ | { authenticated: false; host: string; error?: string; ghAvailable?: boolean };-interface OkLocalOpRepoEntry {+export interface OkLocalOpRepoEntry {full_name: string;clone_url: string;private: boolean;}-type OkLocalOpAuthReposResponse =+export type OkLocalOpAuthReposResponse =| { ok: true; host: string; repos: OkLocalOpRepoEntry[] }| { ok: false; error: string };@@ -792,10 +799,9 @@ type OkLocalOpAuthReposResponse =* Renderer → main snapshot of the editor area's active target.* Discriminated-union shape so TypeScript narrows `identifier` per `kind`.* Drives the macOS File menu's state-aware enable/disable for items like- * Rename / Move to Trash / Open with AI. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * Rename / Move to Trash / Open with AI.*/-type OkEditorActiveTargetSnapshot =+export type OkEditorActiveTargetSnapshot =| { readonly kind: 'doc'; readonly identifier: string }| { readonly kind: 'folder'; readonly identifier: string }| { readonly kind: 'asset'; readonly identifier: string }@@ -803,10 +809,9 @@ type OkEditorActiveTargetSnapshot =/*** Renderer → main snapshot of the View menu's checkbox + smart-hide state.- * Sibling of `OkEditorActiveTargetSnapshot`. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * Sibling of `OkEditorActiveTargetSnapshot`.*/-interface OkEditorViewMenuStateSnapshot {+export interface OkEditorViewMenuStateSnapshot {readonly showHiddenFiles: boolean;readonly showOkFolders: boolean;readonly showOnlyMarkdownFiles: boolean;@@ -829,9 +834,8 @@ interface OkEditorViewMenuStateSnapshot {* dispatch path the native menu items use, `role` maps onto Electron's* built-in menu roles, `command` covers the main-side click handlers* (navigator, folder picker, settings, updater…), and `query` returns the- * aggregated state the native menu renders from. Same shapes as- * `MenuDispatch*` in `ipc-channels.ts` — duplicated for the- * module-resolution reason the wider `OkDesktopBridge` is duplicated.+ * aggregated state the native menu renders from. The IPC channel module+ * re-exports these canonical types under its transport-facing names.*/export type OkMenuDispatchRole =| 'undo'@@ -879,6 +883,18 @@ export interface OkMenuRendererSnapshot {readonly viewMenuState: OkEditorViewMenuStateSnapshot;}+/** Consent-bearing payload for the renderer-to-main bug-report send hop. */+export interface OkBugReportSendInput {+ zipPath: string;+ metadata: OkBugReportSendMetadata;+ /**+ * Whether the reviewed bundle contains an app screenshot. The bundle's+ * inventory is the consent record; absent or false means main must not+ * upload the capture it may still hold.+ */+ includeScreenshot?: boolean;+}+/*** Renderer-facing Electron bridge. Populated on `window.okDesktop` by the* desktop preload script. Web distribution omits the@@ -890,7 +906,7 @@ export interface OkMenuRendererSnapshot {* omitted — new capabilities cross the preload boundary deliberately, one at* a time, via new typed methods.*/-/** OK config sharing mode — mirrored from bridge-contract.ts. */+/** OK config sharing mode. */export interface OkSharingStatusResult {readonly kind: 'status';readonly mode: 'shared' | 'local-only' | 'no-git';@@ -951,12 +967,12 @@ export type OkServerRestartOutcome =| { readonly ok: true }| { readonly ok: false; readonly reason: 'eperm' | 'other' };-/** Result of `terminal.create`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */+/** Result of `terminal.create`. */export type OkPtyCreateResult =| { readonly ok: true; readonly ptyId: string }| { readonly ok: false; readonly reason: 'no-project' | 'not-consented' };-/** Entry of `terminal.list`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */+/** Entry of `terminal.list`. */export interface OkPtyListEntry {readonly ptyId: string;/** User-set custom tab name that survives a renderer reload; null when unset. */@@ -966,18 +982,18 @@ export interface OkPtyListEntry {readonly ordinal: number | null;}-/** Result of `terminal.adopt`. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */+/** Result of `terminal.adopt`. */export type OkPtyAdoptResult =| { readonly ok: true; readonly replay: string }| { readonly ok: false; readonly reason: 'unknown-session' };-/** Push payload for `ok:pty:data`. Canonical JSDoc in `bridge-contract.ts`. */+/** Push payload for `ok:pty:data`. */export interface OkPtyData {readonly ptyId: string;readonly data: string;}-/** Push payload for `ok:pty:exit`. Canonical JSDoc in `bridge-contract.ts`. */+/** Push payload for `ok:pty:exit`. */export interface OkPtyExit {readonly ptyId: string;readonly exitCode: number;@@ -986,8 +1002,7 @@ export interface OkPtyExit {}/**- * Claude Code readiness for the docked terminal. Canonical definition in- * `desktop/src/shared/bridge-contract.ts`; mirrored verbatim here (drift-tested).+ * Claude Code readiness for the docked terminal.*/export interface ClaudeReadiness {readonly claude: 'present' | 'not-found' | 'unknown';@@ -1006,8 +1021,7 @@ export interface ClaudeReadiness {}/** On-PATH readiness for a non-Claude agent CLI (codex / cursor-agent) launched- * in the docked terminal. Mirror of the same interface in the desktop bridge- * contract + the app renderer copy (drift-tested). */+ * in the docked terminal. */export interface CliReadiness {readonly onPath: 'present' | 'not-found' | 'unknown';/** Codex-only: whether OK's `open-knowledge` MCP server is already configured@@ -1146,17 +1160,10 @@ export interface OkDesktopBridge {** Optional `opts.reducedTransparency` carries the renderer's live* `matchMedia('(prefers-reduced-transparency: reduce)').matches` value;- * main toggles vibrancy material accordingly. Optional `opts.chrome`- * carries the active color theme's window-chrome colors (`bg` from- * `--sidebar`, `symbol` from `--sidebar-foreground`) so main can paint the- * OS-drawn titlebar to match the palette rather than its build-time- * snapshot. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * main toggles vibrancy material accordingly. `opts.chrome` carries the+ * active palette's OS-drawn chrome colors.*/- signalThemeApplied(opts?: {- reducedTransparency?: boolean;- chrome?: { bg: string; symbol: string };- }): void;+ signalThemeApplied(opts?: { reducedTransparency?: boolean; chrome?: OkChromeColors }): void;/** Native folder-picker dialog surfaces. */dialog: {@@ -1202,23 +1209,16 @@ export interface OkDesktopBridge {/*** Append a local-only telemetry line to `~/.ok/stats.jsonl`. Zero* phone-home. Resolves even if HOME is unwritable — telemetry failure- * must never bubble up and affect the dispatch path. Literal-union- * shape mirrors `HandoffTarget`, `HandoffFailureReason`, and- * `HandoffScope` from `core/handoff/types.ts`.+ * must never bubble up and affect the dispatch path. The reason and scope+ * fields use the handoff subsystem's canonical literal-union discriminators.*/recordHandoff(line: {readonly target: 'claude-cowork' | 'claude-code' | 'codex' | 'cursor';readonly host: 'electron' | 'web';readonly outcome: 'ok' | 'error';readonly ts: string;- readonly reason?:- | 'not-installed'- | 'scheme-blocked'- | 'web-endpoint-error'- | 'invalid-payload'- | 'dispatch-error'- | 'web-host-cursor-unsupported';- readonly scope?: 'selection';+ readonly reason?: HandoffFailureReason;+ readonly scope?: HandoffScope;}): Promise<void>;/**@@ -1282,8 +1282,7 @@ export interface OkDesktopBridge {showItemInFolder(path: string): Promise<void>;/*** Move a file or folder to the OS Trash via `shell.trashItem`. Step 1- * of the sidebar Delete flow's two-step Option B orchestration. See- * canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.+ * of the sidebar Delete flow's two-step Option B orchestration.*/trashItem(absPath: string): Promise<| { ok: true }@@ -1308,10 +1307,7 @@ export interface OkDesktopBridge {*/project: {listRecent(): Promise<RecentProjectEntry[]>;- /**- * Forget one entry from the recent-projects list. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.- */+ /** Forget one entry from the recent-projects list. */removeRecent(path: string): Promise<void>;getSessionState(): Promise<ProjectSessionState>;setSessionState(state: ProjectSessionState): Promise<void>;@@ -1320,16 +1316,14 @@ export interface OkDesktopBridge {* File → Open file… — show the native md/mdx picker and open the pick in a* temporary single-file session (the desktop side of `ok <file>`). Picker +* open both run main-side; the picked path never crosses back to the- * renderer. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * renderer.*/openFile(): Promise<void>;/*** Atomically scaffold a new project under `parent/name` with the* user-chosen `editors` set. `editors` is the renderer's exact selection* (default-all unless the user unchecked entries); main never widens or- * narrows it. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * narrows it.*/createNew(args: {parent: string;@@ -1337,32 +1331,25 @@ export interface OkDesktopBridge {editors: OkMcpWiringEditorId[];/** OK config sharing mode — defaults to 'shared' when omitted. */sharing?: 'shared' | 'local-only';+ packId?: OkPackId;}): Promise<void>;/*** Fire-and-forget renderer→main telemetry counter for the Create-new-project- * dialog cascade banners. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * dialog cascade banners.*/recordCreateNewBannerShown(banner: CreateNewBannerKind): Promise<void>;/*** Probe `<projectPath>/<path>` for the share-receive target-existence- * gate, dispatching the on-disk predicate on `kind`. See canonical JSDoc- * in `packages/desktop/src/shared/bridge-contract.ts`.+ * gate, dispatching the on-disk predicate on `kind`.*/checkTargetExists(request: {projectPath: string;kind: 'doc' | 'folder';path: string;}): Promise<OkCheckTargetExistsResult>;- /**- * Read `<projectPath>/.git/HEAD` and classify the result. See canonical- * JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */+ /** Read `<projectPath>/.git/HEAD` and classify the result. */readHeadBranch(projectPath: string): Promise<OkHeadBranchInfo>;- /**- * Proxy `GET /api/git/branch-info` against the project's running server.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */+ /** Proxy `GET /api/git/branch-info` against the project's running server. */fetchBranchInfo(request: {projectPath: string;branch: string;@@ -1373,8 +1360,7 @@ export interface OkDesktopBridge {* Proxy `POST /api/git/checkout` against the project's running server.* `fastForward` (on-origin "Switch and update branch") fast-forwards the* target branch to origin's tip before checkout; divergence → `ff-diverged`- * (nothing mutated). See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * (nothing mutated).*/runCheckout(request: {projectPath: string;@@ -1383,8 +1369,7 @@ export interface OkDesktopBridge {}): Promise<CheckoutResponse | null>;/*** Proxy `POST /api/share/target-status` for the branch-switch dialog's- * verdict pivot. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * verdict pivot.*/fetchTargetStatus(request: {projectPath: string;@@ -1394,18 +1379,14 @@ export interface OkDesktopBridge {}): Promise<ShareTargetStatusResponse | null>;/*** Gate dialog dismissal on the `branch-switched` broadcast landing- * in the project window. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * in the project window.*/awaitBranchSwitched(request: {projectPath: string;branch: string;timeoutMs: number;}): Promise<{ ok: true } | { ok: false; reason: 'timeout' | 'project-not-open' }>;- /**- * Run the share-receive J2 scaffold inside a CLI-managed worktree.- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */+ /** Run the share-receive scaffold inside a CLI-managed worktree. */okInit(request: { projectPath: string }): Promise<LocalOpOkInitResponse>;close(): Promise<void>;};@@ -1417,8 +1398,7 @@ export interface OkDesktopBridge {* `<mainRoot>/.ok/worktrees/`; `checkout` is the share-receive arm* (resolves where the branch lives — fetching from `origin` when* needed — then create-or-locates). Opening a worktree window reuses- * `project.open({ entryPoint: 'worktree' })`. Canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * `project.open({ entryPoint: 'worktree' })`.*/worktree: {list(): Promise<WorktreeListResult>;@@ -1428,8 +1408,6 @@ export interface OkDesktopBridge {/*** OK config sharing mode — per-project sharing-mode posture.- * Canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- * Mirrored here per the OkDesktopBridge 3-way-mirror invariant.*/sharing: {status(): Promise<OkSharingStatusResult>;@@ -1444,8 +1422,6 @@ export interface OkDesktopBridge {* screenshot via `includeScreenshot`); `captureScreenshot` grabs the app* before the dialog paints; `send` uploads it with an email fallback;* `onCrashDetected` / `crashAck` carry the crash-invite round-trip.- * Canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- * Mirrored here per the OkDesktopBridge 3-way-mirror invariant.*/bugReport: {create(request: {@@ -1455,28 +1431,14 @@ export interface OkDesktopBridge {includeScreenshot?: boolean;}): Promise<OkBugReportCreateResult>;captureScreenshot(): Promise<OkBugReportScreenshot | null>;- send(request: {- zipPath: string;- metadata: OkBugReportSendMetadata;- /**- * Whether the bundle at `zipPath` contains the app screenshot, taken from- * the bundle's own file inventory rather than the dialog's checkbox state.- * The inventory is what the reporter reviewed, so it is the authoritative- * consent record: absent or false means main must not upload the capture it- * is still holding.- */- includeScreenshot?: boolean;- }): Promise<OkBugReportSendResult>;+ send(request: OkBugReportSendInput): Promise<OkBugReportSendResult>;crashAck(request: { eventId: string }): Promise<OkBugReportCrashAckResult>;list(): Promise<OkBugReportListResult>;delete(id: string): Promise<OkBugReportDeleteResult>;onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void): OkUnsubscribe;};- /**- * Filesystem probes that back the Create-new-project dialog cascade. See- * canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */+ /** Filesystem probes that back the Create-new-project dialog cascade. */fs: {defaultProjectsRoot(): Promise<string>;folderState(path: string): Promise<OkFolderState>;@@ -1527,8 +1489,6 @@ export interface OkDesktopBridge {* version matches the current bundled skill version, resolves with* `{ ok: true, skipped: true, version, recordedAt? }` without* rebuilding. Pass `force: true` to bypass.- *- * See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.*/buildAndOpen(opts?: { force?: boolean }): Promise<| { ok: true; path: string; skipped?: false; version?: string }@@ -1666,7 +1626,13 @@ export interface OkDesktopBridge {| { readonly status: 'none' }| { readonly status: 'installed'; readonly summary: string }| { readonly status: 'failed'; readonly summary: string };- },+ }+ | {+ readonly kind: 'sharing-refused-tracked';+ readonly tracked: readonly string[];+ readonly remediation: string;+ }+ | { readonly kind: 'sharing-no-git'; readonly requestedMode: 'local-only' },) => void,): OkUnsubscribe;};@@ -1699,6 +1665,7 @@ export interface OkDesktopBridge {share: {validateLocalFolder(args: {folderPath: string;+ host: string;owner: string;repo: string;}): Promise<ShareFolderValidationResult>;@@ -1707,20 +1674,15 @@ export interface OkDesktopBridge {/*** Editor area state push surface. Renderer fires* `notifyActiveTargetChanged` once per `activeTarget` transition in- * `useDocumentContext()`. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * `useDocumentContext()`.*/editor: {notifyActiveTargetChanged(target: OkEditorActiveTargetSnapshot): void;- /**- * Fire-and-forget push of the sidebar's view-menu state. See canonical- * JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.- */+ /** Fire-and-forget push of the sidebar's view-menu state. */notifyViewMenuStateChanged(state: Partial<OkEditorViewMenuStateSnapshot>): void;/*** Fire-and-forget push keying the window's Chromium background-throttling- * to its unsynced work. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * to its unsynced work.*/notifyBackgroundThrottle(signal: { hasPendingWork: boolean; enabled: boolean }): void;};@@ -1741,8 +1703,7 @@ export interface OkDesktopBridge {* Startup-instrumentation push surface (desktop launch waterfall). The* renderer reports its two launch checkpoints — page-list ready and first* content — as epoch-ms once both land; main folds them into the- * `desktop.startup-timeline` log line. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * `desktop.startup-timeline` log line.*/startup: {reportMarks(marks: { pageListReadyMs: number; firstContentMs: number }): void;@@ -1751,18 +1712,14 @@ export interface OkDesktopBridge {/*** Sidebar tree-state push subscriptions. Main pushes* `ok:sidebar:expand-all` / `ok:sidebar:collapse-all` when the user picks- * View → Expand All / Collapse All. See canonical JSDoc in- * `packages/desktop/src/shared/bridge-contract.ts`.+ * View → Expand All / Collapse All.*/sidebar: {expandAll(cb: () => void): OkUnsubscribe;collapseAll(cb: () => void): OkUnsubscribe;};- /**- * Bottom-docked terminal panel surface. Canonical JSDoc in- * `bridge-contract.ts`; mirrored verbatim here (drift-tested).- */+ /** Bottom-docked terminal panel surface. */terminal: {create(opts: {cols: number;@@ -1773,9 +1730,9 @@ export interface OkDesktopBridge {resize(ptyId: string, cols: number, rows: number): void;kill(ptyId: string): Promise<void>;drain(ptyId: string, bytes: number): void;- /** Reload-rehydration inventory. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */+ /** Reload-rehydration inventory. */list(): Promise<OkPtyListEntry[]>;- /** Reload-rehydration adopt. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */+ /** Reload-rehydration adopt. */adopt(ptyId: string): Promise<OkPtyAdoptResult>;/*** Persist per-session tab metadata (custom name + sticky ordinal) in main so@@ -1788,14 +1745,14 @@ export interface OkDesktopBridge {* survives a renderer reload. Fire-and-forget.*/setOrder(orderedPtyIds: readonly string[]): void;- /** Per-window panel state (per-surface visibility + tab order + active key). Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */+ /** Per-window state for the independent terminal and agents panels. */getDockState(): Promise<{terminalVisible: boolean;agentPanelVisible: boolean;terminal?: { order: string[]; activeKey: string | null };agents?: { order: string[]; activeKey: string | null };}>;- /** Persist one panel's tab order + active key per window. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */+ /** Persist one panel's tab order and active key per window. */setDockState(state: {surface: 'terminal' | 'agents';order: string[];@@ -1810,8 +1767,8 @@ export interface OkDesktopBridge {};/**- * OS assistive-tech signal gating xterm's `screenReaderMode`. Canonical- * JSDoc in `bridge-contract.ts`. Optional in this mirror: session-only+ * OS assistive-tech signal gating xterm's `screenReaderMode`. Optional in+ * the renderer contract: session-only* bridges omit it, and consumers treat an absent surface as* screen-reader-active (fail-accessible).*/diff --git a/packages/core/src/git/worktree-selector-model.ts b/packages/core/src/git/worktree-selector-model.tsindex d631b5798..36f570600 100644--- a/packages/core/src/git/worktree-selector-model.ts+++ b/packages/core/src/git/worktree-selector-model.ts@@ -68,8 +68,8 @@ export interface WorktreeSelectorModel {/*** IPC-facing result of enumerating the worktree selector. Canonical here (not- * in desktop) so the three `OkDesktopBridge` contract copies + `ipc-channels`- * all import one definition. `no-git` = the project isn't inside a git repo.+ * in desktop) so the desktop host contract and `ipc-channels` import one+ * definition. `no-git` = the project isn't inside a git repo.*/export type WorktreeListResult =| { readonly ok: true; readonly model: WorktreeSelectorModel }diff --git a/packages/core/src/handoff/types.ts b/packages/core/src/handoff/types.tsindex 012dc8601..f82d18b0c 100644--- a/packages/core/src/handoff/types.ts+++ b/packages/core/src/handoff/types.ts@@ -64,18 +64,7 @@ export interface HandoffPayload {readonly prompt: string;}-/**- * **DRIFT WARNING — this union is mirrored inline in four places** for- * IPC-channel / bridge-contract isolation (the bridge surfaces cannot import- * from `core/handoff/` without pulling the whole handoff package into the- * Electron preload bundle). TypeScript catches drift at call-site boundaries- * but not at the definitions. Keep these in lockstep:- *- * 1. `packages/desktop/src/shared/ipc-channels.ts` — `HandoffStatsLine.reason`- * 2. `packages/desktop/src/shared/bridge-contract.ts` — `OkDesktopBridge.shell.recordHandoff` param- * 3. `packages/core/src/desktop-bridge.ts` — canonical `OkDesktopBridge.shell.recordHandoff` param- * 4. `packages/app/src/lib/desktop-bridge-types.ts` — renderer-side augmentation- */+/** Failure classes reported by handoff telemetry and the desktop host bridge. */export type HandoffFailureReason =| 'not-installed'| 'scheme-blocked'@@ -89,10 +78,8 @@ export type HandoffFailureReason =* selection-scoped dispatch; the file / folder / project scopes omit the* field, so an absent `scope` reads as a non-selection handoff.*- * **DRIFT WARNING** — like `HandoffFailureReason` above, this is mirrored- * inline as an optional `scope?` field in the same four IPC-channel /- * bridge-contract sites enumerated above (they cannot import from- * `core/handoff/`). Keep in lockstep.+ * Reused by the desktop telemetry channel and bridge rather than redeclared+ * at each boundary.*/export type HandoffScope = 'selection';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 7afa43d2e..b49d023bf 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1342,16 +1342,9 @@ export {youtubeEmbedUrl,} from './utils/youtube-embed.ts';-// Desktop bridge types (`OkDesktopBridge`, `OkDesktopConfig`, etc.) are-// defined locally per package: `packages/desktop/src/shared/bridge-contract.ts`-// for the desktop preload, and a future `packages/app/src/lib/desktop-bridge--// types.ts` for the app renderer's optional `window.okDesktop` access. Keeping-// the contract co-located instead of re-exporting from this barrel avoids-// dragging the full markdown / CRDT-bridge surface into desktop's compilation-// context (TypeScript follows barrel re-exports through workspace symlinks-// and complains about transitive deps that desktop doesn't declare directly).-// `packages/core/src/desktop-bridge.ts` is the canonical reference shape;-// drift between the per-package copies is caught by a contract-equality test.+// Desktop bridge types live on the dedicated `./desktop-bridge` leaf. Keeping+// that leaf off this barrel avoids pulling markdown and CRDT dependencies into+// Electron's type-resolution graph.// Shadow-repo layout helpers are NOT re-exported here — they import `node:fs`// and would contaminate core's browser-compatibility contract. Import via thediff --git a/packages/core/src/logger-types.ts b/packages/core/src/logger-types.tsindex af3776169..191de4958 100644--- a/packages/core/src/logger-types.ts+++ b/packages/core/src/logger-types.ts@@ -60,8 +60,8 @@ export interface BundleManifest {* availability-gated by what exists at capture time.** Lives in core (not the CLI package that implements the capture) so the- * desktop bridge contract's three per-package copies can all name the same- * type — the app renderer and core cannot depend on the CLI package.+ * dedicated desktop-bridge leaf and the CLI implementation can share the type+ * without making the renderer depend on the CLI package.*/export type ReportBundleLevel = 'standard' | 'full';@@ -169,7 +169,7 @@ export type OkBugReportSendResult =* prompts twice, across restarts included.** Lives in core for the same reason as the sibling bug-report types: the- * desktop bridge contract's per-package copies must all name one type.+ * desktop-bridge leaf and the capture implementation must share one type.** `minidumpAvailable` is main's authoritative answer (only main can stat the* crash-dumps dir) to "is there a crash minidump to include for this event?".diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.tsindex ed6f83ea6..d8db905d3 100644--- a/packages/core/tsdown.config.ts+++ b/packages/core/tsdown.config.ts@@ -10,6 +10,7 @@ export default defineConfig({'helper-bundle': 'src/helper-bundle.ts','skills-catalog': 'src/skills-catalog/index.ts','acp-thread-protocol': 'src/acp/thread-protocol.ts',+ 'desktop-bridge': 'src/desktop-bridge.ts',},unbundle: false,format: 'esm',diff --git a/packages/desktop/package.json b/packages/desktop/package.jsonindex 1dce41b94..9bb61ad91 100644--- a/packages/desktop/package.json+++ b/packages/desktop/package.json@@ -60,6 +60,7 @@"electron": "41.2.1","electron-builder": "^26.9.0","electron-vite": "^6.0.0-beta.1",+ "ts-morph": "^28.0.0","typescript": "^5.7.2","vite": "^8.0.0"}diff --git a/packages/desktop/src/main/ipc/bug-report.ts b/packages/desktop/src/main/ipc/bug-report.tsindex e6c4c6355..8d4897d56 100644--- a/packages/desktop/src/main/ipc/bug-report.ts+++ b/packages/desktop/src/main/ipc/bug-report.ts@@ -36,6 +36,7 @@ import {type OkBugReportSendResult,type ReportBundleLevel,} from '@inkeep/open-knowledge-core';+import type { OkBugReportSendInput } from '@inkeep/open-knowledge-core/desktop-bridge';import { logIpcError } from '../ipc-log.ts';import { isPathWithinProject } from '../path-containment.ts';import type { UpdateChannel } from '../state-store.ts';@@ -78,24 +79,9 @@ interface OkBugReportDeleteRequest {id: string;}-export interface OkBugReportSendRequest {+export type OkBugReportSendRequest = OkBugReportSendInput & {kind: 'send';- /** Zip produced by a prior `create` — the exact file the user reviewed is what uploads. */- zipPath: string;- metadata: OkBugReportSendMetadata;- /**- * Whether the bundle contains the app screenshot, derived by the renderer from- * the bundle's own file inventory. Gates the separate screenshot upload that- * embeds the picture inline in the ticket.- *- * This has to be carried explicitly because `create` owns the consent decision- * and `send` is a separate operation that cannot see it: main still holds the- * capture for the window, so without this gate a reporter who unchecked the- * screenshot would have it uploaded anyway. Fail-closed — absent means no- * upload, which is also what a list retry in a later session gets.- */- includeScreenshot?: boolean;-}+};export interface OkBugReportCrashAckRequest {kind: 'crash-ack';diff --git a/packages/desktop/src/main/theme-handler.ts b/packages/desktop/src/main/theme-handler.tsindex 943623b2a..6a4f62729 100644--- a/packages/desktop/src/main/theme-handler.ts+++ b/packages/desktop/src/main/theme-handler.ts@@ -46,8 +46,8 @@ interface ApplyThemeSourceDeps {* was acknowledged. The diagnostic surface is the structured warn log.** The defensive branch handles:- * - A future bridge-contract divergence (setThemeSource accepts a 4th value- * at one of the three mirrors but not another).+ * - Future drift between the canonical bridge union and this runtime+ * allowlist.* - A non-typed IPC bypass (e.g. raw `ipcRenderer.invoke` from a debugger).** The trust-boundary classification is unambiguous: data crosses thediff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.tsindex 046e97661..bec4a1854 100644--- a/packages/desktop/src/shared/bridge-contract.ts+++ b/packages/desktop/src/shared/bridge-contract.ts@@ -1,2260 +1,25 @@/**- * `window.okDesktop` bridge contract — desktop-side canonical source.- *- * The same shape is also defined at `@inkeep/open-knowledge-core`'s- * `desktop-bridge.ts` (consumed by the app package via its existing core- * dependency) and app-locally at `packages/app/src/lib/desktop-bridge-types.ts`.- * Drift across the three copies is caught by a drift-catcher test, which asserts- * top-level `OkDesktopBridge` member parity AND the `KeyringSmokeResult` /- * `OkKeyringSmokeResult` field shape across all three files.- *- * Why duplicated: moving the types to core's `exports` map + re-exports from- * the core barrel pulls core's full compilation tree (markdown, CRDT bridge,- * etc.) into desktop's TypeScript program via `moduleResolution: bundler`.- * Desktop doesn't have core's mdast-adjacent dependencies declared, so the- * module augmentation in core's `mdast-augmentation.ts` fails to resolve in- * desktop's context. Duplication avoids the cross-package module-resolution- * issue while preserving a single logical contract.+ * Compatibility exports for desktop consumers. The renderer-facing host+ * contract is defined in the dedicated core leaf; this path remains stable+ * for existing main and preload imports.*/--import type {- BranchInfoResponse,- BridgeWorktreeEntry,- CheckoutResponse,- CreateNewBannerKind,- EditorId,- LocalOpOkInitResponse,- OkBugReportCrashAckResult,- OkBugReportCrashDetectedEvent,- OkBugReportCreateResult,- OkBugReportDeleteResult,- OkBugReportListResult,- OkBugReportScreenshot,- OkBugReportSendMetadata,- OkBugReportSendResult,- OkFolderState,- ReportBundleLevel,- ShareTargetStatusResponse,- TerminalCli,- WorktreeCreateRequest,- WorktreeCreateResult,- WorktreeListResult,-} from '@inkeep/open-knowledge-core';--export type { BridgeWorktreeEntry };-import type {- ApplyResult,- FindEnclosingGitRootResult,- FindEnclosingProjectRootResult,- PackId,- ScaffoldPlan,-} from '@inkeep/open-knowledge-server';-import type { KeyringSmokeResult } from '../utility/keyring-smoke.ts';-import type { EntryPoint } from './entry-point.ts';--/**- * Options for `okDesktop.seed.plan()`. Replaces the old `rootDir?: string`- * single-arg shape with an options object so multi-pack metadata threads- * through cleanly. All fields optional — passing `{}` (or undefined) plans- * the default Knowledge base pack at project root.- */-export interface SeedPlanOptions {- /** Subfolder relative to project root. `'.'` / `''` / undefined → project root. */- rootDir?: string;- /** Pack id to plan. Unknown ids fall back to `'knowledge-base'`. */- packId?: PackId;-}--/** Options for `okDesktop.seed.apply()`. Same shape as plan minus rootDir. */-export interface SeedApplyOptions {- packId?: PackId;-}+ OkCheckTargetExistsResult,+ OkDesktopBridge,+ OkHeadBranchInfo,+ OkSeedApplyOptions,+ OkSeedPlanOptions,+} from '@inkeep/open-knowledge-core/desktop-bridge';-/** Per-folder metadata inside `OkSeedPackInfo.folders[]`. */-interface OkSeedPackFolderInfo {- path: string;- summary: string;-}--/**- * User-visible entry counts surfaced on each pack picker card.- * Counts only meaningful entries (top-level folders, template files,- * rootFiles); `.ok/` infrastructure is excluded.- */-interface OkSeedPackEntryCounts {- files: number;- folders: number;-}--/** Per-pack metadata returned by `okDesktop.seed.listPacks()`. */-interface OkSeedPackInfo {- id: PackId;- name: string;- description: string;- defaultSubfolder?: string;- folders: OkSeedPackFolderInfo[];- entryCounts: OkSeedPackEntryCounts;-}--/** Renderer-facing result of `okDesktop.seed.plan()`. Mirrors `SeedPlanResult` in main. */-export type OkSeedPlanResult =- | { ok: true; plan: ScaffoldPlan }- | {- ok: false;- error: {- kind: 'no-project' | 'prerequisite-missing' | 'invalid-root' | 'internal';- message: string;- };- };--/** Renderer-facing result of `okDesktop.seed.apply(plan)`. Mirrors `SeedApplyResult` in main. */-export type OkSeedApplyResult =- | { ok: true; result: ApplyResult }- | {- ok: false;- error: { kind: 'no-project' | 'prerequisite-missing' | 'internal'; message: string };- };--/** Renderer-facing result of `okDesktop.seed.listPacks()`. Static data; no error path beyond internal. */-export type OkSeedListPacksResult =- | { ok: true; packs: OkSeedPackInfo[] }- | { ok: false; error: { kind: 'internal'; message: string } };--/** Render mode picked by the main process when creating a BrowserWindow. */-type OkDesktopMode = 'editor' | 'navigator' | 'terminal';--/** Frozen snapshot of window-level config injected at preload-exposure time. */-export interface OkDesktopConfig {- readonly collabUrl: string;- readonly apiOrigin: string;- readonly projectPath: string;- readonly projectName: string;- readonly mode: OkDesktopMode;- /**- * `true` only under the Electron smoke suite (main injects `--ok-e2e-smoke=1`).- * The renderer reads it to use xterm's DOM renderer instead of the WebGL- * canvas (see `TerminalPanel`), so the DOM-based terminal smoke assertions can- * read output + deliver input without a blanket `--disable-gpu`. Lockstep with- * the app-side `OkDesktopConfig` — the member-name drift- * catcher enforces set-equality.- */- readonly e2eSmoke: boolean;- /**- * `true` on an ephemeral single-file window (`ok <file>`). Drives the- * renderer's no-project chrome gate. Kept in lockstep with the app-side- * `OkDesktopConfig` (`packages/app/src/lib/desktop-bridge-types.ts`) — the- * member-name drift catcher enforces set-equality.- */- readonly singleFile: boolean;- /**- * Doc to open on first paint, or `null`. Set only on an ephemeral single-file- * window (`ok <file>`) — the ext-less docName the renderer seeds into- * `window.location.hash` before React mounts, so the editor lands on the file- * deterministically. Replaces the post-load `ok:deep-link` IPC for this path,- * which raced the renderer's lazy `ipcRenderer.on` subscription and- * intermittently dropped (leaving the hash empty → the empty-state splash).- * Lockstep with the app-side `OkDesktopConfig`.- */- readonly initialDoc: string | null;- /**- * `true` when this window was opened by a first-run create-new flow (blank- * OR starter-pack seed) — the `create-new` entry point. The onboarding card's- * visibility predicate reads it (see `evaluateFreshProject` for why a seeded- * project needs this signal). `false` on every other entry point and on a- * re-queried live window (get-info). Lockstep with the app-side- * `OkDesktopConfig`.- */- readonly freshlyCreated: boolean;- /**- * W3C `traceparent` of the Electron main process's `ok.app-startup` root- * span, or `undefined` when OTel is disabled in main. Injected as- * `--ok-startup-traceparent=` and read into the frozen config by preload; the- * renderer extracts it to parent its startup span to the desktop launch trace.- * The `m1-smoke.test.ts` drift catcher only checks the- * `OkDesktopBridge` interface, not `OkDesktopConfig` fields, so this lives on- * the desktop + app copies (the core mirror keeps the minimal config shape).- */- readonly startupTraceparent?: string;- /**- * Whether an interactive PTY can be spawned in this install — the terminal- * dock's plain-terminal-tab capability gate. `false` on Windows/Linux- * (node-pty is not bundled there; the terminal dock is dark off-mac), so- * the renderer hides the terminal affordances instead of surfacing a spawn- * failure. Gates only the pty-tab surface — future non-pty dock content- * (e.g. ACP threads) must not key off this. Lockstep with the app-side- * `OkDesktopConfig`.- */- readonly ptyAvailable: boolean;-}--/** Menu-action IDs fired by main → renderer on user menu selection. */-export type OkMenuAction =- | 'new-doc'- | 'new-folder'- // Opens the create-new-project dialog in the focused window (a whole new- // project, distinct from new-doc/new-folder which create inside the current- // project). Sibling of Switch Project, which dispatches via `openNavigator`.- | 'new-project'- | 'rename'- | 'delete'- | 'close-active-tab-or-window'- | 'toggle-sidebar'- | 'toggle-source'- | 'save-version'- | 'version-history'- | 'focus-search'- | 'focus-command-palette'- // Navigation history.- | 'navigate-back'- | 'navigate-forward'- // File menu state-aware items. Renderer subscribes via the existing- // `onMenuAction` bridge surface; routing through the same channel- // avoids inventing a new IPC for what is conceptually "user picked a menu- // item." Each action maps to a renderer-side handler that knows the current- // `activeTarget` (file / folder / asset / project scope) and dispatches the- // appropriate primitive.- | 'new-from-template'- | 'duplicate'- | 'move-to-trash'- | 'reveal-in-finder'- | 'send-to-ai'- | 'copy-full-path'- | 'copy-relative-path'- // View menu items. Sidebar visibility toggles- // (mirror the sidebar's tree-options popover + empty-space menu state) +- // tree-scoped Expand/Collapse All (sibling of subtree-scoped versions on- // folder rows). Renderer handler reads merged config / Pierre tree state- // to dispatch the appropriate primitive when the menu item is clicked.- | 'toggle-show-hidden-files'- | 'toggle-show-ok-folders'- | 'toggle-show-only-markdown-files'- | 'toggle-show-skills-section'- | 'expand-all-tree'- | 'collapse-all-tree'- | 'toggle-doc-panel'- // Docked terminal-panel visibility (⌘J / Ctrl+J).- | 'toggle-terminal'- // Right agents-panel visibility (⌘L / Ctrl+L). The ACP twin of- // `toggle-terminal`, and deliberately NOT desktop-gated: agent threads are- // server-hosted, so the panel works on the web host and where pty does not.- | 'toggle-agent-panel'- // Terminal application menu. `new-terminal` opens a new terminal tab- // (revealing the dock if hidden; never hides, unlike the toggle).- // `kill-terminal` closes the active tab, killing that session's PTY.- | 'new-terminal'- | 'kill-terminal'- // Worktree selector (worktree = window). `new-worktree` opens the- // create dialog; `switch-worktree` opens the sidebar worktree switcher.- | 'new-worktree'- | 'switch-worktree'- // Help → Report a bug… — opens the in-app bug-report dialog. Both window- // types subscribe: editor windows report project-scoped, the Navigator- // reports system-wide.- | 'report-bug'- // Help → Send feedback… — opens the in-app feedback form, the same one- // the Resources menu and the Cmd+K palette open. Both window types subscribe.- | 'send-feedback';--/** Returned by `onProjectSwitched` / `onMenuAction`. Call to detach the listener. */-type OkUnsubscribe = () => void;--interface RecentProjectEntry {- path: string;- name: string;- lastOpenedAt: string;- missing?: boolean;- /**- * Canonical GitHub remote URL when the project has a github.com origin.- * Read at open-time from `<projectPath>/.git/config`, normalized to- * `https://github.com/<owner>/<repo>.git`. Powers the share-receive- * lookup.- */- gitRemoteUrl?: string;-}--interface ProjectSessionState {- openTabs: string[];- pinnedTabIds: string[];- activeDocName: string | null;- activeTabId: string | null;- activeTabByMode: { files: string | null; skills: string | null };- updatedAt: string | null;-}--/**- * Outcome of `bridge.project.readHeadBranch(projectPath)`. See the bridge- * method's JSDoc for the failure-mode contract.- *- * `currentBranch` and `headSha` are mutually exclusive — the implementation- * only ever produces three states:- * 1. attached → `{ currentBranch: string, headSha: null, detached: false }`- * 2. detached → `{ currentBranch: null, headSha: string, detached: true }`- * 3. unknown → `{ currentBranch: null, headSha: null, detached: false }`- *- * Field semantics:- * - `currentBranch` is set when HEAD points at a symbolic ref. Slashed- * branch names (`feat/foo`) survive intact.- * - `headSha` is the first 7 chars of the SHA on a detached HEAD; caller- * may use it as a display label.- * - `detached === true` distinguishes a real detached HEAD from a- * graceful-fail. The all-null + `detached: false` shape is the- * "couldn't determine" sentinel; the caller falls back to silent- * dispatch as if no branch check had been attempted.- */-export interface HeadBranchInfo {- readonly currentBranch: string | null;- readonly headSha: string | null;- readonly detached: boolean;-}--/**- * Outcome of `bridge.project.checkTargetExists({projectPath, kind, path})`.- * See the bridge method's JSDoc for the failure-mode contract.- *- * - `'exists'` — the joined path matches the requested kind: a regular file- * for `doc`, a directory for `folder`.- * - `'missing'` — the joined path returned `ENOENT`, or it resolved to the- * wrong type for its kind (a `doc` probe hitting a directory, a `folder`- * probe hitting a file). Surface "not on this branch yet."- * - `'unreadable'` — input rejected (unsafe path / containment violation)- * OR an I/O error other than `ENOENT`. Caller treats this identically- * to `'exists'`: graceful-fail collapses to silent dispatch.- */-export type CheckTargetExistsResult = 'exists' | 'missing' | 'unreadable';--/** Payload passed to `onUpdateDownloaded` subscribers. Mirrors ok:update:downloaded. */-/**- * Window-chrome colors resolved from the ACTIVE color theme, reported by the- * renderer so the OS-drawn chrome matches the palette rather than the- * default theme's build-time snapshot. `bg` is the theme's `--sidebar`- * (the chrome row's own surface); `symbol` is the glyph color for the- * Windows/Linux overlay's min/max/close controls.- */-export interface OkChromeColors {- bg: string;- symbol: string;-}--export interface OkUpdateDownloadedInfo {- readonly version: string;-}--/** Payload passed to `onUpdateRelaunching` subscribers. Mirrors ok:update:relaunching. */-export interface OkUpdateRelaunchingInfo {- readonly version: string;-}--/** Payload passed to `onUpdateRelaunchFailed` subscribers. Mirrors ok:update:relaunch-failed. */-export interface OkUpdateRelaunchFailedInfo {- readonly version: string;- readonly message?: string;- /**- * Manual-download fallback URL, present only on the boot-detected- * failed-install variant (a clean quit whose post-quit install never ran).- * When set, the renderer shows the richer "Retry / Download manually" card;- * the in-session async/watchdog failures omit it and keep the plain message.- */- readonly downloadUrl?: string;-}--/** Payload passed to `onWhatsNew` subscribers. Mirrors ok:update:whats-new. */-export interface OkWhatsNewInfo {- readonly version: string;- readonly releaseUrl: string;-}--/** Payload passed to `onUpdateStuckHint` subscribers. Mirrors ok:update:stuck-hint. */-export interface OkUpdateStuckHintInfo {- readonly downloadUrl: string;-}--/**- * Auto-update channel — derived from the running build's version string in- * main (`channelFromVersion(app.getVersion())`). `'beta'` for a prerelease- * build, `'latest'` for a stable one. Not a runtime preference; surfaced- * read-only via `state.query()`. Mirrors `UpdateChannel`.- */-export type OkUpdateChannel = 'latest' | 'beta';+export type * from '@inkeep/open-knowledge-core/desktop-bridge';-/**- * User-intent theme value. Mirrors Electron's `nativeTheme.themeSource` union.- * Carried verbatim through the `ok:theme:set-source` IPC channel — never- * resolved to a concrete light/dark value at the renderer call site. The- * `'system'` value IS the lever that delegates appearance tracking to- * macOS; resolving at the call site loses OS auto-tracking.- */-export type OkThemeSource = 'system' | 'light' | 'dark';--/**- * Snapshot returned by `state.query()` — used by newly-opened windows on- * mount to render the correct BETA badge / About-panel label and to route- * the refuse-downgrade UX when a future-build state was rolled back.- * `channel` is build-derived (a property of the binary). `schemaIncompatibility`- * is non-null only when the persisted state's `schemaVersion` exceeds what- * this build supports.- */-interface OkStateSnapshot {- readonly channel: OkUpdateChannel;- readonly schemaIncompatibility: {- readonly currentBuild: string;- readonly persistedSchemaVersion: number;- readonly maxSupported: number;- } | null;-}--/**- * Editor IDs surfaced through the first-launch MCP consent bridge.- * Aliased to the canonical `EditorId` from `@inkeep/open-knowledge-core` —- * single source of truth for the literal union. The local name is preserved- * so existing call sites keep their imports stable.- */-type OkMcpWiringEditorId = EditorId;--/** Payload passed to `onShow` subscribers. Mirrors ok:mcp-wiring:show.- * `willReplace: true` signals the editor has an existing OK-managed entry- * that Add would overwrite — per-editor disclosure. `pathInstall` drives- * the dialog's shell-PATH toggle row: `shellDetected: false` hides the- * row; `alreadyInstalled: true` renders it informational (block already on- * disk or consent already granted); `rcFilesToTouch` names the tildified- * shell files a grant would edit. */-export interface OkMcpWiringShowPayload {- readonly detectedEditors: readonly {- readonly id: OkMcpWiringEditorId;- readonly label: string;- readonly detected: boolean;- readonly willReplace: boolean;- readonly configPath: string | null;- readonly entryLocator: string;- }[];- readonly pathInstall: {- readonly shellDetected: boolean;- readonly rcFilesToTouch: readonly string[];- readonly alreadyInstalled: boolean;- };- /** Per-bundle opt-in rows for the two user-global skills. Empty ⇒ no skill- * decision solicited. `alreadyInstalled: true` renders the row pre-checked- * as an existing install the user can uncheck to remove. */- readonly globalSkills: readonly {- readonly id: string;- readonly name: string;- readonly alreadyInstalled: boolean;- }[];-}--/** Confirm payload for `mcpWiring.confirm`. `pathInstall` is the PATH- * toggle, tri-state: `true` → append the managed rc block; `false` →- * record declined, touch nothing; absent → no PATH decision was solicited- * (row hidden or informational).- *- * `skills` — bundle ids the user left checked. Present ⇒ a skill decision was- * solicited; every offered bundle not in the list is recorded declined. */-export interface OkMcpWiringConfirmRequest {- readonly editorIds: readonly OkMcpWiringEditorId[];- readonly pathInstall?: boolean;- readonly skills?: readonly string[];-}--/** Result shape for `mcpWiring.confirm` / `skip`. */-type OkMcpWiringResult = { ok: true } | { ok: false; error: string };--/**- * Per-editor MCP state for Settings → AI tools. `installed` rows uncheck to- * remove; `not-installed` rows check to install; `foreign` is an entry under- * OK's server name that isn't recognizably OK's own (uninstall refuses,- * install overwrites); `unmanageable` is a config OK can't safely edit.- */-type OkIntegrationsEditorState = 'installed' | 'not-installed' | 'foreign' | 'unmanageable';--/** Component inventory for Settings → AI tools. `available: false` renders- * the section read-only (install actors gated off for this process). `path.- * installed` reflects the managed rc block actually being on disk. */-interface OkIntegrationsStatus {- readonly available: boolean;- readonly editors: readonly {- readonly id: OkMcpWiringEditorId;- readonly label: string;- readonly detected: boolean;- readonly state: OkIntegrationsEditorState;- readonly configPath: string | null;- readonly entryLocator: string;- }[];- readonly path: {- readonly shellDetected: boolean;- readonly rcFilesToTouch: readonly string[];- readonly installed: boolean;- };- readonly skills: readonly {- readonly id: string;- readonly name: string;- readonly installed: boolean;- readonly paths: readonly string[];- }[];-}--/** One toggle for `integrations.setComponent`. */-interface OkIntegrationsSetRequest {- readonly component:- | { readonly kind: 'editor'; readonly id: OkMcpWiringEditorId }- | { readonly kind: 'path' }- | { readonly kind: 'skill'; readonly id: string };- readonly enabled: boolean;-}--/** Set-component result — both arms carry a fresh status snapshot so the- * renderer re-renders truthfully after failed/refused toggles too. */-type OkIntegrationsSetResult =- | { readonly ok: true; readonly status: OkIntegrationsStatus }- | { readonly ok: false; readonly error: string; readonly status: OkIntegrationsStatus };--/** Post-install manual step a project MCP config needs before OK's tools- * connect: `approve-once` (Claude Code), `enable-manually` (Cursor, silently- * disabled until toggled), `auto-connect` (Codex on a trusted project),- * `none`. */-type OkProjectIntegrationsFollowUp = 'approve-once' | 'enable-manually' | 'auto-connect' | 'none';--/** Component inventory for Settings → This project → AI tools (per-editor- * PROJECT MCP config files + the single project runtime skill), scoped to the- * project the requesting window has open. `hasProject: false` → empty state;- * `available: false` → read-only. */-interface OkProjectIntegrationsStatus {- readonly available: boolean;- readonly hasProject: boolean;- readonly projectDir: string | null;- readonly editors: readonly {- readonly id: OkMcpWiringEditorId;- readonly label: string;- readonly state: OkIntegrationsEditorState;- readonly configPath: string;- readonly entryLocator: string;- readonly followUp: OkProjectIntegrationsFollowUp;- }[];- readonly skill: {- readonly installed: boolean;- readonly paths: readonly string[];- } | null;-}--/** One toggle for `projectIntegrations.setComponent`. The skill is a single- * row (no id) — it fans out across every capable editor. */-interface OkProjectIntegrationsSetRequest {- readonly component:- | { readonly kind: 'editor'; readonly id: OkMcpWiringEditorId }- | { readonly kind: 'skill' };- readonly enabled: boolean;-}--type OkProjectIntegrationsSetResult =- | { readonly ok: true; readonly status: OkProjectIntegrationsStatus }- | { readonly ok: false; readonly error: string; readonly status: OkProjectIntegrationsStatus };--/**- * Per-project consent dialog — renderer-facing payload + result- * shapes. Mirrors the IPC types in `./ipc-channels.ts` so the bridge surface- * can be consumed without crossing the IPC barrel. `OkOnboardingShowPayload`- * is the only one exported because preload imports it for the listener wire;- * the rest live inside the `OkDesktopBridge` interface signature.- */-type OkOnboardingWarningKind =- | 'root'- | 'home'- | 'home-documents'- | 'home-desktop'- | 'home-downloads'- | 'volumes-mount'- | 'drive-root';--type OkOnboardingGitState = 'present' | 'absent' | 'shell-only';--/** OK config sharing mode. */-export interface OkSharingStatusResult {- readonly kind: 'status';- readonly mode: 'shared' | 'local-only' | 'no-git';- readonly excluded: readonly string[];- readonly trackedUpstream: readonly string[];- /** True when local-only but `.ok/skills/` is carved back out as shareable. */- readonly skillsShared: boolean;-}--export type OkSharingSetModeResult =- | { readonly kind: 'applied'; readonly mode: 'shared' | 'local-only' | 'no-git' }- | {- readonly kind: 'refused-tracked';- readonly tracked: readonly string[];- readonly remediation: string;- }- | {- readonly kind: 'no-exclude';- readonly reason: 'no-git' | 'no-info-dir' | 'malformed-pointer' | 'inaccessible';- };--export interface OkOnboardingShowPayload {- readonly pickedPath: string;- readonly projectDir: string;- readonly defaultContentDir: string;- readonly gitState: OkOnboardingGitState;- readonly gitRootPromoted: boolean;- readonly warnings: readonly { readonly kind: OkOnboardingWarningKind }[];- readonly editorOptions: readonly {- readonly id: OkMcpWiringEditorId;- readonly label: string;- /** True when the editor exposes a per-project MCP config file (e.g.- * `.mcp.json`). False when only the user-level config is writable- * (e.g. Claude Desktop's `claude_desktop_config.json`). The dialog- * uses this to label scope per option so the user understands which- * editors will scaffold project-local config vs which will only- * update their user profile. */- readonly hasProjectConfig: boolean;- }[];-}--interface OkOnboardingConfirmRequest {- readonly initGit: boolean;- readonly contentDir: string;- readonly additionalIgnores: string;- readonly editorIds: readonly OkMcpWiringEditorId[];- /** OK config sharing mode. Sharing posture chosen in the- * consent dialog. */- readonly sharing: 'shared' | 'local-only';-}--type OkOnboardingResult = { ok: true } | { ok: false; error: string };--interface OkOnboardingProbeContentRequest {- readonly contentDir: string;-}--type OkOnboardingProbeContentResult =- | {- readonly ok: true;- readonly count: number;- readonly sample: readonly string[];- readonly truncated: boolean;- }- | { readonly ok: false; readonly error: string };--/**- * Pre-project local-op event shapes — auth + clone flows surfaced to the- * Navigator window via IPC because it has no backing API server. Editor- * windows continue to use the HTTP path (`/api/local-op/...`) which the- * `installClientFetchWrapper` helper rewrites against the utility's- * apiOrigin. See `packages/desktop/src/shared/ipc-events.ts` for the- * canonical wire shapes.- */-export type OkLocalOpAuthEvent =- | {- type: 'verification';- user_code: string;- verification_uri: string;- expires_in: number;- }- | {- type: 'complete';- host: string;- login: string;- name?: string;- email?: string;- avatarUrl?: string;- }- | { type: 'error'; message: string };--export type OkLocalOpCloneEvent =- | { type: 'progress'; phase: string; pct: number }- | { type: 'complete'; dir: string }- /**- * Emitted when the CLI's `-b <branch>` request falls back to the remote- * default branch because the requested ref is gone upstream. Non-terminal —- * the clone keeps running and a `complete` follows. Mirrors the HTTP- * transport's `CloneEvent` variant so both transports surface the same- * "branch no longer exists" signal to the share-receive controller.- */- | { type: 'branch-fallback'; branch: string }- | { type: 'error'; message: string };--/** Returned by `localOp.{auth,clone}.start` — handle for streaming events + cancel. */-export interface OkLocalOpStream<E> {- /** Async iterable of events. Terminates on `complete` / `error` or `cancel()`. */- readonly events: AsyncIterable<E>;- /** SIGTERM the underlying subprocess. Idempotent. */- cancel(): void;-}--/** One-shot result for `localOp.auth.status()`. Also imported by- * `./ipc-channels.ts` as the IPC channel result type so the wire shape- * and the bridge method signature can't drift.- *- * `tier` reflects which credential source the CLI used:- * A — `gh` CLI delegation (no keychain entry needed)- * B — HTTPS token from the OK TokenStore- * C — SSH-paired token from the OK TokenStore- * Optional for forward-compat with CLIs that don't emit it. */-export type OkLocalOpAuthStatusResponse =- | {- authenticated: true;- host: string;- login: string;- tier?: 'A' | 'B' | 'C';- name?: string;- email?: string;- }- | { authenticated: false; host: string; error?: string };--/** Bounded repo entry returned by `localOp.auth.repos()`. */-interface OkLocalOpRepoEntry {- full_name: string;- clone_url: string;- private: boolean;-}--/** One-shot result for `localOp.auth.repos()`. Also imported by- * `./ipc-channels.ts` — see `OkLocalOpAuthStatusResponse`. */-export type OkLocalOpAuthReposResponse =- | { ok: true; host: string; repos: OkLocalOpRepoEntry[] }- | { ok: false; error: string };--/**- * Common fields extracted from a share URL (universal-link / custom-scheme- * decoded). Carried on every `OkShareReceivedPayload` variant that- * successfully decoded so the receiver can render copy + reach back to- * `sharedUrl` without re-decoding. `target` discriminates doc vs folder- * shares (`ShareTarget`); the bare path is recovered via `shareTargetPath`.- */-export interface OkSharePayloadFields {- /** GitHub host of the shared repo: `github.com` or a GHES hostname. Part- * of the receiver's repo identity, so a GHES `acme/kb` and a github.com- * `acme/kb` never resolve to the same local clone. */- readonly host: string;- readonly owner: string;- readonly repo: string;- readonly branch: string;- readonly sharedUrl: string;- readonly target: ShareTarget;-}--/**- * Renderer-facing payload for the `ok:share:received` event. Carried by the- * main-process share-flow handler in `url-scheme.ts` AFTER main has already- * resolved the share target via `resolveShareTarget`. The discriminant- * names the surface the renderer must mount — the renderer never re-runs- * candidate selection.- *- * Routing matrix (main → renderer):- * - `invalid` / `unsupported-version` — toast on the focused/any window- * - `project-branch-switch` — sent to the editor window owning- * `projectPath`; renderer mounts the branch-switch surface- * (driven by `branch-switch-flow.ts`)- * - `launcher-consent` — sent to the Navigator; renderer mounts the- * consent/init surface for the worktree at `candidatePath` (HEAD- * matches the share branch but `.ok/config.yml` is absent)- * - `launcher-miss` — sent to the Navigator; renderer mounts the- * clone/locate surface (no usable local copy exists)- *- * Present-on-shared-branch (the `branch-match-ok` candidate-selection- * outcome) is delivered via the existing `ok:deep-link` channel- * (`pendingDeepLinkTarget`/`pendingBranch`/`pendingMultiCandidate`), not- * `ok:share:received` — no panel needed. The kind-aware target-existence- * gate runs main-side before that dispatch (see `dispatchResolvedShare`).- *- * Source (universal-link vs custom-scheme) is intentionally NOT propagated —- * main-process diagnostic logging only.- */-export type OkShareReceivedPayload =- | { readonly kind: 'unsupported-version' }- | { readonly kind: 'invalid' }- | {- readonly kind: 'project-branch-switch';- readonly share: OkSharePayloadFields;- readonly projectPath: string;- readonly currentBranch: string | null;- }- | {- readonly kind: 'launcher-consent';- readonly share: OkSharePayloadFields;- readonly candidatePath: string;- /**- * Name of the Recents project whose `listGitWorktrees` anchor surfaced- * `candidatePath`, when the candidate came from worktree-enum off an- * existing OK project. `null` when the candidate was surfaced from- * a Recents path that itself matched the share. Drives the- * "(a worktree of <name>)" caption in the Navigator consent dialog.- */- readonly parentProjectName: string | null;- }- | {- readonly kind: 'launcher-miss';- readonly share: OkSharePayloadFields;- };--/**- * Kind-discriminated receiver target carried by the `ok` arm of- * `OkShareReceivedPayload`. A GitHub blob share resolves to a `doc` target- * (a single markdown file); a GitHub tree share resolves to a `folder`- * target (a directory whose `folderPath` MAY be empty for the repo/branch- * root). Mirrored byte-identically across the three bridge-contract copies- * (desktop, core, app).- */-export type ShareTarget =- | { readonly kind: 'doc'; readonly docPath: string }- | { readonly kind: 'folder'; readonly folderPath: string };--/**- * Renderer-facing mirror of `ShareFolderValidationResult` from- * `@inkeep/open-knowledge`'s `validateLocalFolderForShare`. Carried- * by the `share.validateLocalFolder` IPC. Mirrored across the three bridge-- * contract copies (desktop, core, app) so the drift tests catch divergent copies.- */-export type ShareFolderValidationResult =- | { readonly kind: 'ok'; readonly gitRemoteUrl: string }- | { readonly kind: 'not-git' }- | { readonly kind: 'no-origin' }- | { readonly kind: 'wrong-repo'; readonly actualOwner: string; readonly actualRepo: string }- | { readonly kind: 'wrong-host'; readonly actualHost: string }- | { readonly kind: 'non-github' }- | { readonly kind: 'symlink-escape' };--/**- * Renderer → main snapshot of the editor area's active target.- * Discriminated-union shape so TypeScript narrows `identifier` per `kind`- * at consumer sites. `'doc'` carries the active doc name; `'folder'`- * carries the active folder path; `'asset'` carries the active asset path;- * `kind: null` represents the no-active-target / project-scope state- * (FolderOverview-style entry).- *- * Drives the macOS File menu's state-aware item enable/disable: doc → all- * doc-targeted items enabled; folder → all folder-targeted items enabled;- * asset → Rename / Move to Trash / Reveal enabled, Duplicate disabled;- * null → only project-level items (New File, Reveal in Finder for- * `contentDir`, etc.) enabled; Rename / Duplicate / Move to Trash disabled. Same- * shape as `EditorActiveTargetSnapshot` in `./ipc-channels.ts` —- * duplicated for the same module-resolution reason the wider- * `OkDesktopBridge` is duplicated (see top-of-file comment).- */-export type OkEditorActiveTargetSnapshot =- | { readonly kind: 'doc'; readonly identifier: string }- | { readonly kind: 'folder'; readonly identifier: string }- | { readonly kind: 'asset'; readonly identifier: string }- | { readonly kind: null };--/**- * Renderer → main snapshot of the View menu's checkbox + smart-hide state, plus- * the editor capabilities main's other native menus gate rows on.- * Drives the macOS View menu's live `checked` reflection for "Show Hidden Files"- * and the `visible: false` smart-hide on "Expand All" /- * "Collapse All" so a fully-expanded tree doesn't render a no-op item.- * `sidebarVisible` flips the "Show Sidebar" / "Hide Sidebar" label on the- * View-menu sidebar-toggle item (Apple HIG: same row, label toggles).- *- * Sibling of `OkEditorActiveTargetSnapshot` — kept on its own surface- * (rather than folded into the active-target snapshot) because the two- * signals change on independent edges: active-target on navigation,- * view-menu-state on config CRDT mutations + tree expand/collapse.- * Same shape as `EditorViewMenuStateSnapshot` in `./ipc-channels.ts` —- * duplicated for the module-resolution reason the wider `OkDesktopBridge`- * is duplicated (see top-of-file comment).- */-export interface OkEditorViewMenuStateSnapshot {- readonly showHiddenFiles: boolean;- readonly showOkFolders: boolean;- readonly showOnlyMarkdownFiles: boolean;- readonly showSkillsSection: boolean;- readonly canExpandAll: boolean;- readonly canCollapseAll: boolean;- readonly sidebarVisible: boolean;- readonly docPanelVisible?: boolean;- // Docked terminal-panel visibility. Optional + defaults hidden: the View- // menu reads "Show Terminal" until the renderer pushes the first snapshot.- readonly terminalVisible?: boolean;- // Whether a terminal session (PTY) is currently mounted. Distinct from- // `terminalVisible`: the latch survives a collapse, so a hidden-but-alive- // terminal reads `terminalLive: true, terminalVisible: false`. Drives the- // Terminal menu's "Kill Terminal" enablement.- readonly terminalLive?: boolean;- // Right agents-panel visibility. Independent of `terminalVisible` — the two- // panels own different edges and are open or closed on their own. Optional +- // defaults hidden, like the terminal.- readonly agentPanelVisible?: boolean;- // Whether the editor context menu's "View in Source" jump would do anything:- // it reads the visual editor's caret for the active document, so it is inert- // in source mode and with no document open. Optional + defaults false, so the- // row stays out of the menu until the renderer says the jump is live — main- // has no way to compute this, and must not learn about document content.- readonly canViewInSource?: boolean;-}--/**- * Windows/Linux renderer-menubar dispatch payloads (the windows-linux-port- * renderer-menubar decision). macOS keeps the native menu bar; win/linux draw it in the- * renderer and route every click through main via `menu.dispatch` so menu- * semantics stay single-sourced: `menu-action` relays through the same- * dispatch path the native menu items use, `role` maps onto Electron's- * built-in menu roles, `command` covers the main-side click handlers- * (navigator, folder picker, settings, updater…), and `query` returns the- * aggregated state the native menu renders from. Same shapes as- * `MenuDispatch*` in `ipc-channels.ts` — duplicated for the- * module-resolution reason the wider `OkDesktopBridge` is duplicated.- */-export type OkMenuDispatchRole =- | 'undo'- | 'redo'- | 'cut'- | 'copy'- | 'paste'- | 'selectAll'- | 'reload'- | 'forceReload'- | 'toggleDevTools'- | 'resetZoom'- | 'zoomIn'- | 'zoomOut'- | 'toggleFullScreen'- | 'minimize'- | 'close'- | 'quit';--export type OkMenuDispatchCommand =- | 'open-navigator'- | 'open-folder-dialog'- | 'clear-recent-projects'- | 'open-settings'- | 'check-for-updates'- | 'reconfigure-mcp-wiring'- | 'open-github'- | 'toggle-spell-check';--export type OkMenuDispatchRequest =- | { readonly kind: 'query' }- | { readonly kind: 'menu-action'; readonly action: OkMenuAction }- | { readonly kind: 'command'; readonly command: OkMenuDispatchCommand }- | { readonly kind: 'open-recent-project'; readonly path: string }- | { readonly kind: 'role'; readonly role: OkMenuDispatchRole };--/** `query` result — the same aggregated state the native menu renders from. */-export interface OkMenuRendererSnapshot {- readonly recentProjects: ReadonlyArray<{ readonly path: string; readonly name: string }>;- readonly spellCheckEnabled: boolean;- readonly showDevToolsMenu: boolean;- readonly canCheckForUpdates: boolean;- readonly canReconfigureMcpWiring: boolean;- readonly activeTarget: OkEditorActiveTargetSnapshot;- readonly viewMenuState: OkEditorViewMenuStateSnapshot;-}--/**- * Payload for `onServerVersionDrift` — the desktop attached to a server whose- * version differs from the running app's (most often a prior version's- * detached server still alive after an auto-update).- */-export interface OkServerVersionDriftInfo {- /** `older` = the attached server predates the app; `newer` = it is ahead. */- readonly relation: 'older' | 'newer';- /** Which dimension differed — diagnostic, not surfaced in copy. */- readonly dimension: 'protocol' | 'runtime';- /** The attached server's runtime semver (for the notification body). */- readonly serverRuntime: string;- /** The running app's runtime semver. */- readonly appRuntime: string;-}--/** Payload for `onServerRestarted` — fired on the freshly-spawned window after a successful restart. */-export interface OkServerRestartedInfo {- readonly appRuntime: string;-}--/**- * Payload for `onRecentRemovedMissing` — fired on the window that initiated a- * recents open when the target folder was gone and its stale entry was pruned.- */-export interface OkRecentRemovedMissingInfo {- readonly path: string;- readonly projectName: string;-}--/**- * Result of `restartServer`. Only the failure case reaches the originating- * renderer — on success the window is recreated, so its invoke promise never- * resolves (by design); the success toast fires on the new window instead.- */-export type OkServerRestartOutcome =- | { readonly ok: true }- | { readonly ok: false; readonly reason: 'eperm' | 'other' };--/**- * Result of `window.okDesktop.terminal.create`. `no-project` is returned when- * the calling window has no resolved project root (e.g. the Navigator window):- * a terminal needs a cwd, so main refuses rather than spawning a shell at an- * arbitrary directory. `not-consented` is the main-side trust-boundary backstop- * (fail-open): the terminal is allowed by default, so main refuses only when the- * window's project-local `terminal.enabled === false`, preventing a renderer- * regression or compromise from spawning a real shell in a project a human has- * explicitly opted out of.- *- * NOTE: structurally mirrored verbatim in `core/src/desktop-bridge.ts` and- * `app/src/lib/desktop-bridge-types.ts` — the m1-smoke + bridge-contract-types- * drift tests fail if the three copies diverge.- */-export type OkPtyCreateResult =- | { readonly ok: true; readonly ptyId: string }- | { readonly ok: false; readonly reason: 'no-project' | 'not-consented' };--/**- * One entry of the reload-rehydration inventory (`terminal.list`) — a ptyId that- * is still live in the main process for the window. Mirrored verbatim in the core- * + app bridge copies (drift-tested).- */-export interface OkPtyListEntry {- readonly ptyId: string;- /** User-set custom tab name that survives a renderer reload; null when unset. */- readonly customLabel: string | null;- /** Sticky per-session tab number, preserved across a renderer reload; null- * until the renderer has reported it for a just-created session. */- readonly ordinal: number | null;-}--/**- * Result of `terminal.adopt` — re-binding a surviving session to a reloaded- * renderer. On success, `replay` is the retained screen + scrollback the renderer- * writes into the fresh xterm so the adopted tab repaints instead of coming back- * blank; it may be empty for a session that produced no- * output. `unknown-session` means the addressed shell is no longer live for the- * window (it exited in the gap between the dock's `list` and this adopt), so the- * panel spawns a fresh shell instead. Mirrored verbatim (drift-tested).- */-export type OkPtyAdoptResult =- | { readonly ok: true; readonly replay: string }- | { readonly ok: false; readonly reason: 'unknown-session' };--/** Push payload for `ok:pty:data` — a coalesced UTF-8 chunk of shell output. */-export interface OkPtyData {- readonly ptyId: string;- readonly data: string;-}--/**- * Push payload for `ok:pty:exit` — the shell exited or the PTY died. `error`- * is present only when the spawn itself failed (resource exhaustion); a normal- * shell exit carries `exitCode`/`signal` and omits it.- */-export interface OkPtyExit {- readonly ptyId: string;- readonly exitCode: number;- readonly signal: number | null;- readonly error?: string;-}--/**- * Claude Code readiness for the docked terminal. `claude` is the- * login-shell PATH probe: `unknown` means the probe could not run (a flaky- * spawn / timeout), so the panel must NOT render a "not installed" message off- * it. `mcp` is whether `~/.claude.json` carries the `open-knowledge` server, so- * a `claude` launched here sees OK tools.- *- * NOTE: structurally mirrored verbatim in `core/src/desktop-bridge.ts` and- * `app/src/lib/desktop-bridge-types.ts` — the m1-smoke + bridge-contract-types- * drift tests fail if the three copies diverge.- */-export interface ClaudeReadiness {- readonly claude: 'present' | 'not-found' | 'unknown';- readonly mcp: 'wired' | 'needs-rewire';- /** True when the project's own `open-knowledge` `.mcp.json` entry is verified- * to be OK's canonical managed server (cli `isOwnManagedEntry`), so the docked- * terminal may pre-approve it on Claude launch instead of re-showing Claude's- * trust prompt. False/absent for a foreign, tampered, or missing entry (the- * supply-chain risk in a shared/cloned project) — launch bare and let Claude- * prompt. Computed per-project by the desktop preflight; absent means false- * (fail-safe). */- readonly mcpPreApprovable?: boolean;- /** Set only on a `rewire`-action result when re-arming MCP wiring threw, so- * the renderer can surface the failure instead of the button silently no-op'ing. */- readonly rewireError?: string;-}--/**- * On-PATH readiness for a non-Claude agent CLI (codex / cursor-agent) launched- * in the docked terminal. `unknown` means the login-shell probe could not run- * (a flaky spawn / timeout), so the panel must NOT render a "not installed"- * message off it. There is no MCP-wiring field — unlike Claude these CLIs have- * no `~/.claude.json`-style OK-tools concept here.- *- * NOTE: structurally mirrored verbatim in `core/src/desktop-bridge.ts` and- * `app/src/lib/desktop-bridge-types.ts` — the drift tests fail if the three copies diverge.- */-export interface CliReadiness {- readonly onPath: 'present' | 'not-found' | 'unknown';- /** Codex-only: whether OK's `open-knowledge` MCP server is already configured- * in the user's codex config. Gates the per-launch `-c` tool-auto-approve- * override — codex fails to load its config if `-c` targets a server that is- * not defined, so the launch site adds the override only when this is true.- * Absent for CLIs where it does not apply.- *- * DELIBERATELY WEAKER THAN CLAUDE'S GATE, and not its security equivalent.- * This is existence-by-name (any object under `mcp_servers.open-knowledge`),- * whereas claude's `mcpPreApprovable` runs `isOwnManagedEntry` to verify the- * entry is byte-exactly OK's own. The asymmetry is sound because the two read- * different files: claude's is a PROJECT-scoped `.mcp.json` that travels in a- * clone, so a same-named foreign entry is a real RCE vector; codex's target is- * `scope: 'global'` (`~/.codex/config.toml`, resolved from `home`, never from- * cwd), so anyone able to plant a foreign entry there can already register- * arbitrary MCP servers and has won regardless. Tightening this to an exact- * ownership match would also fail closed on a legitimate entry carrying any- * extra codex key, silently disabling auto-approve for real users. This gate's- * job is availability (don't break codex's config load), not authorization. */- readonly okServerConfigured?: boolean;-}--/** Renderer-facing Electron bridge. Populated on `window.okDesktop` by the desktop preload script. */-export interface OkDesktopBridge {- readonly config: OkDesktopConfig;-- onProjectSwitched(cb: (next: OkDesktopConfig) => void): OkUnsubscribe;- onMenuAction(cb: (action: OkMenuAction) => void): OkUnsubscribe;- onUpdateDownloaded(cb: (info: OkUpdateDownloadedInfo) => void): OkUnsubscribe;- /** Subscribe to `ok:update:relaunching` — another window's "Relaunch" click committed; swap this window's `update-downloaded` card to the button-less "Relaunching…" in-progress state so every window shows consistent feedback during teardown. */- onUpdateRelaunching(cb: (info: OkUpdateRelaunchingInfo) => void): OkUnsubscribe;- /** Subscribe to `ok:update:relaunch-failed` — a committed relaunch failed (async error event or no-quit watchdog); surface the relaunch-error notice. Main re-arms the banner separately via a re-broadcast `ok:update:downloaded`. */- onUpdateRelaunchFailed(cb: (info: OkUpdateRelaunchFailedInfo) => void): OkUnsubscribe;- onWhatsNew(cb: (info: OkWhatsNewInfo) => void): OkUnsubscribe;- /** Subscribe to `ok:update:whats-new-dismissed` — another window dismissed the what's-new notice; clear this window's `whats-new-<version>` card. */- onWhatsNewDismissed(cb: (info: { readonly version: string }) => void): OkUnsubscribe;- onUpdateStuckHint(cb: (info: OkUpdateStuckHintInfo) => void): OkUnsubscribe;- /**- * Subscribe to `ok:deep-link` — fired when an `openknowledge://` URL is- * routed to this window. Renderer updates `location.hash` to open the- * target doc via the existing hash-route listener. When `branch` is- * present, it rides alongside on the hash as `?branch=<encoded>` so the- * share-receive flow can detect branch mismatches. Treat `null` /- * `undefined` / absent identically (no branch — back-compat with legacy- * emitters).- */- onDeepLink(- cb: (evt: {- doc: string;- /**- * Discriminates whether `doc` is a single-doc path or a folder path.- * `doc` carries the path string for both kinds today; a sibling story- * makes the renderer's hash setter kind-aware.- */- kind: 'doc' | 'folder';- branch?: string | null;- /**- * `true` iff the dispatcher's candidate-selection evaluated more- * than one candidate. The renderer's `installDeepLinkListener`- * uses this to suppress the "Opened on branch X" toast for- * single-clone receivers (no disambiguation value) and- * surface it for multi-worktree receivers (where the dispatched- * window's identity is the actionable signal). Treat- * `undefined` / absent as `false` — back-compat with legacy- * emitters that never set the flag.- */- multiCandidate?: boolean;- /**- * `true` iff main's target-existence gate found the share's target- * absent on the checked-out branch. The renderer toasts "not on this- * branch yet" in-context instead of navigating into a blank editor.- */- targetMissing?: boolean;- }) => void,- ): OkUnsubscribe;- /**- * Subscribe to `ok:share:received` — fired when a share URL (universal- * link `https://openknowledge.ai/d/<encoded>` or custom scheme- * `openknowledge://share?url=<blob-url>`) routes to this window. The- * discriminated payload tells the renderer to mount the receive dialog- * (kind `ok`) or surface a toast (kind `unsupported-version` / `invalid`).- */- onShareReceived(cb: (payload: OkShareReceivedPayload) => void): OkUnsubscribe;-- /**- * Subscribe to `ok:server-version-drift` — fired once when this window- * attaches to a server whose version differs from the app's. The renderer- * surfaces a cancelable notification offering to restart the server via- * `restartServer`.- */- onServerVersionDrift(cb: (info: OkServerVersionDriftInfo) => void): OkUnsubscribe;- /**- * Subscribe to `ok:server-restarted` — fired on a freshly-recreated window- * after a successful `restartServer`, so the renderer can confirm the- * server now matches the app.- */- onServerRestarted(cb: (info: OkServerRestartedInfo) => void): OkUnsubscribe;- /**- * Subscribe to `ok:project:recent-removed-missing` — fired on the window that- * initiated a recents open of a folder that no longer exists. The stale entry- * has already been pruned from the recents list; the renderer surfaces a- * lightweight toast (and, in the Navigator, drops the row from its list).- */- onRecentRemovedMissing(cb: (info: OkRecentRemovedMissingInfo) => void): OkUnsubscribe;- /**- * Restart the project's server to match this app's version: terminate the- * attached (not-owned) server and recreate the window against a fresh- * own-version spawn. Resolves to `{ ok:false }` only when termination fails- * (the originating window stays); on success the window is recreated and the- * success toast fires there.- */- restartServer(projectPath: string): Promise<OkServerRestartOutcome>;-- /**- * Push the user's chosen `nativeTheme.themeSource` value to main. Carries- * the user-intent value (`'system' | 'light' | 'dark'`) verbatim — NEVER- * resolve `'system'` to a concrete `'light' | 'dark'` at the call site.- * `'system'` IS the lever that delegates appearance tracking to macOS;- * resolving at the call site loses OS auto-tracking. The renderer- * ConfigProvider effect runs this on every CRDT mutation of- * `appearance.theme`.- *- * Failure model: main's handler is best-effort. On rejection (handler- * not registered, channel teardown, etc.) callers swallow + structured-- * warn; the renderer's body theme is already correct via next-themes- * and the next CRDT mutation re-fires this naturally. See ConfigProvider's- * sibling effect for the canonical caller pattern.- *- * `{ ok: true }` does NOT prove the value was honored — main's handler- * silently rejects unknown values (defensive against a future bridge-- * contract divergence or a non-typed IPC bypass) and still returns- * `{ ok: true }`. The diagnostic surface for rejection is the structured- * `console.warn` `{ event: 'theme-source-set-rejected', received, reason }`- * in `theme-handler.ts` — visible in the main-process console (DevTools,- * Console.app on packaged builds), not the renderer. Callers cannot- * observe whether `'system' | 'light' | 'dark'` was applied vs ignored- * on the renderer side; trust the type system at the call site.- */- setThemeSource(source: OkThemeSource): Promise<{ ok: true }>;-- /**- * Fire-and-forget renderer→main signal. The renderer fires this once- * after ConfigProvider's first sync settles (releasing the cold-launch- * window-show gate), and again on every `prefers-reduced-transparency`- * matchMedia change for live vibrancy updates. Main's per-window- * show-gate listens for the first fire alongside `ready-to-show` before- * calling `BrowserWindow.show()` — this eliminates the cold-launch- * staleness window where the OS-drawn chrome would briefly mismatch the- * renderer body. Subsequent fires release a no-op on the show-gate side- * (the window is already visible) and only drive the vibrancy toggle.- *- * Implemented as `invoke('ok:theme:applied', opts).catch(() => {})` so it- * composes through the typed `createInvoker` wrapper and clears the- * IPC-discipline rule. Rejections are swallowed — a missing handler- * during teardown is expected, not a programmer error. Mirrors the- * `mcpWiring.signalReady()` precedent (preload bridge file).- *- * Optional `opts.reducedTransparency` carries the renderer's live- * `matchMedia('(prefers-reduced-transparency: reduce)').matches` value.- * When provided, main toggles vibrancy material on every BrowserWindow:- * `null` (off) when reduced=true, `'sidebar'` (the DEFAULT_WIN_OPTS- * material) when false. Folded into this signal rather than introducing- * a separate IPC channel — the team's commitment to migrate to typed-ipc- * fires before any further hand-rolled channel additions, so payload-- * widening on an existing channel is the right fit.- */- signalThemeApplied(opts?: { reducedTransparency?: boolean; chrome?: OkChromeColors }): void;-- dialog: {- openFolder(opts?: { defaultPath?: string }): Promise<string | null>;- };-- shell: {- openExternal(url: string): Promise<void>;- /**- * Probe whether a URL scheme has a registered handler on this OS.- * Used by the "Open in Agent Desktop" dropdown to- * render disabled-with-tooltip rows when the target app isn't installed.- * Returns `{installed: false}` on timeout or platform-API error.- *- * **Scheme format contract:** `scheme` is the scheme NAME without- * trailing colon (e.g. `'claude'`, not `'claude:'`). Matches the Linux- * `xdg-mime query default x-scheme-handler/<name>` shell-command form- * and the main-process shell-injection sanitizer — callers with a- * colonful scheme MUST strip the trailing `:` first.- */- detectProtocol(scheme: string): Promise<{ installed: boolean; displayName?: string }>;- /**- * Step 1 of the Cursor two-step handoff — spawns `cursor <path>` via a- * validated argv (shell:false, 2s timeout). Dedicated channel because- * the threat model is a command allowlist distinct from the URL-scheme- * allowlist.- */- spawnCursor(- path: string,- ): Promise<- | { ok: true }- | { ok: false; reason: 'invalid-path' | 'not-installed' | 'timeout' | 'spawn-error' }- >;- /**- * Append a local-only telemetry line to `~/.ok/stats.jsonl`. Zero- * phone-home. Resolves even if HOME is unwritable — telemetry failure- * must never bubble up and affect the dispatch path. The literal-union- * shape mirrors `HandoffTarget`, `HandoffFailureReason`, and `HandoffScope`- * from the core handoff types.- */- recordHandoff(line: {- readonly target: 'claude-cowork' | 'claude-code' | 'codex' | 'cursor';- readonly host: 'electron' | 'web';- readonly outcome: 'ok' | 'error';- readonly ts: string;- readonly reason?:- | 'not-installed'- | 'scheme-blocked'- | 'web-endpoint-error'- | 'invalid-payload'- | 'dispatch-error'- | 'web-host-cursor-unsupported';- readonly scope?: 'selection';- }): Promise<void>;-- /**- * Open an asset via the OS default handler. `relPath` is project-relative- * (main-process resolves against `ProjectContext.projectPath` + `realpath` +- * `isPathWithinProject`). Executable extensions (`.exe`, `.sh`, `.app`, …)- * hard-refuse at the main handler — see- * `EXECUTABLE_BLOCKLIST_EXTENSIONS` in- * `packages/core/src/constants/upload.ts` for the full blocklist.- * Asset-click-dispatcher surface.- */- openAsset(- relPath: string,- ): Promise<- | { ok: true }- | { ok: false; reason: 'extension-blocked' | 'path-escape' | 'not-found' | 'resolve-error' }- >;-- /**- * Reveal an asset in the native file manager (macOS Finder / Windows- * Explorer / Linux xdg-open → default). Parent-only — does NOT invoke the- * OS default handler for content. Lower-risk than `openAsset`; the- * executable blocklist does NOT apply. Asset-click-dispatcher surface.- */- revealAsset(- relPath: string,- ): Promise<{ ok: true } | { ok: false; reason: 'path-escape' | 'not-found' | 'resolve-error' }>;-- /**- * Reveal an ABSOLUTE path that lives OUTSIDE the caller window's project —- * the terminal's "this file is outside your project" clickable-link flow.- * Unlike `revealAsset`, this is deliberately NOT containment-gated (that is- * the feature); instead main stats the path and, if it exists, pops a native- * confirmation dialog naming it, calling `shell.showItemInFolder` only on- * confirm. The dialog is the trust boundary: a compromised renderer can at- * most surface a dialog the user must dismiss, never silently steer the file- * manager. `not-found` when the path is missing (no dialog shown),- * `invalid-path` for a non-absolute / malformed input.- */- revealExternal(- absPath: string,- ): Promise<- | { ok: true; outcome: 'revealed' | 'dismissed' }- | { ok: false; reason: 'not-found' | 'invalid-path' | 'error' }- >;-- /**- * Display the native right-click context menu for an on-disk reference- * (`asset`, `wiki-link`, or `image`). Built from `Menu.buildFromTemplate`- * in main — the gesture-attested pattern: main observes the click- * directly; the gesture bit does NOT cross IPC. Entries: Reveal in- * Finder + Open in default app + Copy link.- */- showAssetMenu(params: {- readonly relPath: string;- readonly title: string;- readonly kind: 'asset' | 'wiki-link' | 'image';- }): Promise<void>;- /**- * Reveal a file or folder in the OS file manager (Finder / Explorer /- * Linux default). Path is validated against the caller window's project- * directory in main; out-of-project, non-absolute, or null-byte-bearing- * paths are silently refused at the wire (channel returns `undefined`- * regardless; refusals emit a main-process `console.warn` for debugging).- */- showItemInFolder(path: string): Promise<void>;- /**- * Move a file or folder to the OS Trash via `shell.trashItem`. Step 1 of- * the sidebar Delete flow's two-step orchestration: trashes the- * item; on `{ ok: true }` the renderer follows with- * `POST /api/trash/cleanup` (server-side cleanup). The renderer- * closes the editor tab AFTER step 1 succeeds, eliminating the- * fail-forward UX hazard prior designs had.- *- * Argument is an ABSOLUTE path (renderer composes via- * `joinWorkspacePath`). Main wraps with `realpath` + `isPathWithinProject`- * containment — mirror of `ok:shell:show-item-in-folder` and- * `ok:shell:spawn-cursor`. Reason union covers macOS edge cases:- * `permission-denied` (locked / no perms), `not-found` (target gone- * between probe + click), `system-error` (backend failures incl.- * OneDrive electron#38541 / tmpfs electron#28045), `path-escape`- * (containment violation). `detail` carries the OS-provided- * `error.localizedDescription` so the trash-failure fallback modal can- * surface it verbatim.- */- trashItem(absPath: string): Promise<- | { ok: true }- | {- ok: false;- reason: 'not-found' | 'permission-denied' | 'system-error' | 'path-escape';- detail?: string;- }- >;- };-- clipboard: {- writeText(text: string): Promise<void>;- };-- project: {- listRecent(): Promise<RecentProjectEntry[]>;- /**- * Forget one entry from the recent-projects list. This only updates the- * desktop app's persisted launcher state; it never deletes or mutates the- * project folder on disk.- */- removeRecent(path: string): Promise<void>;- getSessionState(): Promise<ProjectSessionState>;- setSessionState(state: ProjectSessionState): Promise<void>;- open(request: {- path: string;- target: 'new-window';- entryPoint: EntryPoint;- /**- * Optional kind-discriminated target to deep-link into after the- * project window mounts. Used by share-receive: Q1 hits and Q2/Q3- * success both pass the share's target (a `doc` path or a `folder`- * path) so the editor opens it directly. Threaded through to- * `wm.createProjectWindow` (cold spawn → `dom-ready` deep-link IPC)- * and to `sendDeepLink` for the warm-focus path. Mirrors the existing- * `openknowledge://open?project=&doc=` plumbing.- */- pendingDeepLinkTarget?: { kind: 'doc' | 'folder'; path: string };- /**- * Optional share branch that rides alongside `pendingDeepLinkTarget`- * so the renderer's deep-link listener surfaces it via the hash- * (`?branch=<encoded>`). Receiver-side share flow uses it to detect- * branch mismatches on Path 2 (has-local-clone). Treat `null` /- * `undefined` / absent identically (no branch).- */- pendingBranch?: string | null;- /**- * Optional branch-switch payload for the share-receive "I already have- * it locally" path. When the located clone is checked out on a- * different branch than the share, the renderer threads this so main- * delivers the project-scoped `project-branch-switch` surface (symmetric- * with the Q1/recents `fallback` path in `url-scheme.ts`) instead of a- * plain deep-link open on the wrong branch. Carries the share fields, the- * located project path, and the clone's current HEAD branch (for the- * dialog's initial label; `ShareBranchSwitchDialog` re-queries before- * acting). Absent / undefined ⇒ plain open.- */- pendingShareBranchSwitch?: {- share: OkSharePayloadFields;- projectPath: string;- currentBranch: string | null;- };- }): Promise<void>;- /**- * File → Open file… — show the native md/mdx picker and open the pick in a- * temporary single-file session (the desktop side of `ok <file>`; no project- * setup, never writes `.ok` to the file's folder). Picker + open both run- * main-side (`openEphemeralFile` owns the temp server/dir lifecycle), so- * this takes no args and returns nothing — the picked path never crosses- * back to the renderer. A cancelled picker resolves as a no-op.- */- openFile(): Promise<void>;- /**- * Atomically scaffold a new project under `parent/name` with the- * user-chosen `editors` set. `editors` is the renderer's exact selection- * (default-all unless the user unchecked entries); main never widens or- * narrows it. Resolves only on success. Failure surfaces as a structured- * rejection from the IPC handler, not a `{ok:false}` result variant.- */- createNew(args: {- parent: string;- name: string;- editors: OkMcpWiringEditorId[];- /** OK config sharing mode — defaults to 'shared' when omitted. */- sharing?: 'shared' | 'local-only';- /**- * Starter pack to seed into the newly-created project (first-run- * packs-forward launcher). Omitted → blank project (today's behavior).- */- packId?: PackId;- }): Promise<void>;- /**- * Fire-and-forget renderer→main telemetry signal for the Create-new-project- * dialog. The renderer dedupes per-dialog-open (a banner first-show fires- * exactly one event; clearing + retyping the same input does NOT refire).- * Main routes the event into the OnboardingFlow telemetry surface as a- * discrete counter. Bounded-cardinality: the `banner` argument is a closed- * literal union.- */- recordCreateNewBannerShown(banner: CreateNewBannerKind): Promise<void>;- /**- * Probe `<projectPath>/<path>` and classify it against the share- * target's `kind` — a regular-file hit for `doc`, a directory hit for- * `folder` — else ENOENT/wrong-type miss, or graceful-fail. Used by the- * main-side target-existence gate AFTER the branch-name check passes —- * without this gate, a receiver whose locally checked-out branch matches- * the share but hasn't fetched the commit that adds the target (typical- * stale-branch scenario) silently opens a blank editor. Content-root- * folder shares (empty path) skip this probe at the call site.- *- * Q1 runs pre-server; this is the only filesystem read available at- * that point. Never throws — every input rejection / non-ENOENT I/O- * error collapses to `'unreadable'` so the caller falls back to- * silent dispatch the same way `readHeadBranch` does on failure.- */- checkTargetExists(request: {- projectPath: string;- kind: 'doc' | 'folder';- path: string;- }): Promise<CheckTargetExistsResult>;- /**- * Read `<projectPath>/.git/HEAD` and classify the result. Pure filesystem- * read (no git subprocess); returns the all-null sentinel on any failure- * mode so callers can fall back gracefully. Drives the recent-projects- * branch label in the Project Navigator.- */- readHeadBranch(projectPath: string): Promise<HeadBranchInfo>;- /**- * Proxy `GET /api/git/branch-info` against the project's running- * server. The dispatcher window (Navigator) has no apiOrigin of its- * own; main reads `<projectPath>/.ok/local/server.lock` to find the- * port and HTTP-fetches on its behalf. Used by the share-receive- * branch-switch dialog to render the four-cell state matrix- * (shareTargetExists × dirtyConflicts) without a second IPC round-trip.- *- * Returns `null` on every failure mode (lock unreadable, port dead,- * fetch error, response doesn't validate). The dialog treats `null`- * as a load failure and surfaces a generic toast.- */- fetchBranchInfo(request: {- projectPath: string;- branch: string;- kind: 'doc' | 'folder';- path: string;- }): Promise<BranchInfoResponse | null>;- /**- * Proxy `POST /api/git/checkout` against the project's running server.- * Mirrors `fetchBranchInfo` — main owns the HTTP call because the- * dispatcher doesn't carry the project's apiOrigin. Server-classified- * failures (`dirty-conflict`, `branch-not-found`, `fetch-failed`,- * `checkout-failed`) flow through verbatim so the dialog can map- * each to its own toast copy.- *- * STOP rule: the dialog MUST NOT navigate when this returns- * `{ok: true}`. The CRDT transition is still in flight at HTTP 200 —- * navigation waits on the CC1 `branch-switched` signal landing in the- * project window via `awaitBranchSwitched` (below).- *- * `fastForward` (on-origin "Switch and update branch") tells the server to- * fast-forward the target branch's local ref to origin's tip before the- * checkout, so a stale receiver lands the switch WITH a recently-pushed- * doc. On divergence the server refuses and returns `ff-diverged` (nothing- * mutated) — the receive flow never merges. Omitted = today's plain switch.- */- runCheckout(request: {- projectPath: string;- branch: string;- fastForward?: boolean;- }): Promise<CheckoutResponse | null>;- /**- * Proxy `POST /api/share/target-status` for the branch-switch dialog's- * verdict pivot. When the origin-existence hint from `fetchBranchInfo` is- * `false`, the dialog asks main to run the fetch-backed verdict (on-origin- * / renamed / deleted / never-on-branch / unknown) rather than treating the- * stale hint as a terminal denial.- *- * Returns `null` on any transport-level failure; the dialog treats that- * the same as an `unknown` verdict (today's guidance). A 200 with an- * unexpected body degrades to `{ verdict: 'unknown' }` via the schema's- * value-tolerant parse, never a throw.- */- fetchTargetStatus(request: {- projectPath: string;- branch: string;- path: string;- kind: 'doc' | 'folder';- }): Promise<ShareTargetStatusResponse | null>;- /**- * Wait for the project's running server to report `currentBranch === branch`- * via `GET /api/server-info`. The share-receive branch-switch dialog calls- * this AFTER `runCheckout` returns `{ok: true}` to gate dialog dismissal- * on the CC1 `branch-switched` broadcast landing in the project window —- * server-info is the late-join backstop for that broadcast.- *- * STOP rule (one-way door): the dialog MUST NOT navigate on the- * `runCheckout` HTTP 200 alone; the CRDT transition is still async at- * that point. This bridge call is the gate that proves the recycle has- * settled.- *- * Discriminated result: `{ok: true}` on match, `{ok: false, reason}` on- * timeout or project-not-open (server lock never resolved). Never throws.- * `timeoutMs` is the maximum wall time main will spend polling.- */- awaitBranchSwitched(request: {- projectPath: string;- branch: string;- timeoutMs: number;- }): Promise<{ ok: true } | { ok: false; reason: 'timeout' | 'project-not-open' }>;- /**- * Run the share-receive J2 scaffold — initialize `.ok/config.yml`- * inside a CLI-managed git worktree that was never opened in OK.- * Mirrors the HTTP route `POST /api/local-op/ok-init`, but main- * runs it directly because the consent dialog mounts in the- * Navigator window before any project utility server exists for- * the candidate path. The Navigator's `apiOrigin === ''`, so a- * relative `fetch('/api/local-op/ok-init')` would never reach a- * server — the IPC path is the only working transport.- *- * Result shape is `LocalOpOkInitResponse` (`{ok: true, projectPath}`- * | `{ok: false, reason: 'not-a-git-worktree' | 'init-failed',- * message}`). Idempotent on already-initialized projects. Never- * throws.- */- okInit(request: { projectPath: string }): Promise<LocalOpOkInitResponse>;- close(): Promise<void>;- };-- /**- * Worktree selector (worktree = window). `list` enumerates the sender- * window's project's local branches + their worktrees (current window and- * main worktree flagged); `create` creates or locates the worktree for a- * branch under `<mainRoot>/.ok/worktrees/` and returns its path. The- * renderer opens the worktree window via `project.open({ path, target:- * 'new-window', entryPoint: 'worktree' })` — this surface is git-only.- * Backed by `ok:worktree:dispatch` (one consolidated channel, discriminated- * on `kind`, per the `ok:sharing:dispatch` precedent).- *- * `checkout` is the share-receive arm: unlike `create` (whose caller picked- * the branch from the selector model and therefore knows where it lives),- * a share payload names a branch the receiver may never have fetched. Main- * resolves it — existing local ref → plain checkout; remote-tracking ref- * only → new tracking branch off `origin/<branch>`; neither → bounded- * `git fetch origin <branch>`, then the tracking checkout — and delegates- * to the same create-or-locate path (an existing worktree is located, not- * refused). The receiver's root checkout is never touched. Failures extend- * the create result union: `branch-not-found` (branch gone from origin —- * terminal) and `fetch-failed` (network/timeout — retryable).- */- worktree: {- list(): Promise<WorktreeListResult>;- create(request: WorktreeCreateRequest): Promise<WorktreeCreateResult>;- checkout(request: { branch: string }): Promise<WorktreeCreateResult>;- };-- /**- * OK config sharing mode — per-project sharing-mode posture for- * the editor's Settings panel. `status` is a pure read invoked on- * mount; `setMode` toggles via `addOkPathsToGitExclude` /- * `removeOkPathsFromGitExclude` so the desktop and CLI surfaces cannot- * drift. The `refused-tracked` branch is surfaced via a modal in the- * SharingSection component; the `no-exclude` branch surfaces as an- * inline warning (typically `no-git`).- */- sharing: {- status(): Promise<OkSharingStatusResult>;- setMode(mode: 'shared' | 'local-only'): Promise<OkSharingSetModeResult>;- /** Toggle `.ok/skills/` shareability within local-only mode. */- setSkillsShared(shared: boolean): Promise<OkSharingSetModeResult>;- };-- /**- * In-app "Report a bug" — `create` builds the redacted diagnostic zip for- * the sender window's project (system-wide when the window has no project,- * labeled via `summary.systemWide`) under `~/.ok/bug-reports/`, folding in- * the newest un-acked crash minidump only when `includeCrashDump` is set- * (the crash invite's explicit opt-in — minidumps carry raw memory no text- * redaction can scrub) and the app screenshot (staged raw at- * `extra/screenshot.png`) only when `includeScreenshot` is set.- * `captureScreenshot` grabs the sender window's page as a downscaled preview- * and holds the full-resolution bytes in main for that later `create`; the- * report dialog calls it before it paints, so the picture is the app state- * underneath the dialog rather than the dialog itself, and returns `null`- * when capture is unavailable (non-desktop / capture failure). `send` uploads- * the reviewed zip to the private- * intake endpoint when one is configured, otherwise resolving to the- * prefilled email fallback (`fallback.mailtoUrl`) — `reason` discriminates- * the designed no-intake email path (`'email-draft'`, no network attempted)- * from a real upload failure (`'send-failed'`), so the dialog only renders- * an error for the latter. `onCrashDetected` delivers main's crash-detected invitations- * (the `ok:bug-report:crash-detected` push; boot events arrive on the first- * renderer that finishes loading, so subscribe at module init) and- * `crashAck` records the user's answer so one crash event never re-prompts,- * restarts included. Backed by `ok:bug-report:dispatch` (one consolidated- * channel, discriminated on `kind`, per the `ok:sharing:dispatch`- * precedent). Never rejects on capture or upload failure — the results are- * discriminated.- */- bugReport: {- create(request: {- level: ReportBundleLevel;- note?: string;- includeCrashDump?: boolean;- includeScreenshot?: boolean;- }): Promise<OkBugReportCreateResult>;- captureScreenshot(): Promise<OkBugReportScreenshot | null>;- send(request: {- zipPath: string;- metadata: OkBugReportSendMetadata;- /**- * Whether the bundle at `zipPath` contains the app screenshot, taken from- * the bundle's own file inventory rather than the dialog's checkbox state.- * The inventory is what the reporter reviewed, so it is the authoritative- * consent record: absent or false means main must not upload the capture it- * is still holding.- */- includeScreenshot?: boolean;- }): Promise<OkBugReportSendResult>;- crashAck(request: { eventId: string }): Promise<OkBugReportCrashAckResult>;- /** The persisted report history (newest first) read from the sidecars. */- list(): Promise<OkBugReportListResult>;- /** Remove a persisted report's zip + sidecar by `id` (containment-checked). */- delete(id: string): Promise<OkBugReportDeleteResult>;- onCrashDetected(cb: (event: OkBugReportCrashDetectedEvent) => void): OkUnsubscribe;- };-- /**- * Filesystem probes that back the Create-new-project dialog cascade. The- * find-enclosing-* probes are read-only and mirror the pure helpers in- * `@inkeep/open-knowledge-server`'s `fs/` module. `removeGitFolder` is the- * sole destructive method on this surface; it's scope-narrowed to deleting- * a `.git` directory at a caller-supplied parent (basename + realpath- * checked main-side so it can't be coerced into a generic `rm -rf`).- */- fs: {- /** Persisted last-used parent directory, or a platform-sensible default- * on first launch (`~/Documents/OpenKnowledge/`). */- defaultProjectsRoot(): Promise<string>;- /** Classify the candidate path: missing (`free`), present but empty,- * or present with entries. Stat errors fall through to `free`. */- folderState(path: string): Promise<OkFolderState>;- findEnclosingProjectRoot(path: string): Promise<FindEnclosingProjectRootResult | null>;- findEnclosingGitRoot(path: string): Promise<FindEnclosingGitRootResult | null>;- /** Permanently remove `<gitRoot>/.git`. Caller passes the directory- * CONTAINING `.git`; main appends `.git` and validates the resolved- * basename. Used only by the Create-new-project dialog's confirm-git- * banner action after an inline user confirmation step. Idempotent —- * succeeds silently if `.git` is already absent (handles the race- * where an external delete arrives between the probe and the click). */- removeGitFolder(gitRoot: string): Promise<void>;- };-- /**- * Re-summon the Project Navigator window from inside an editor window.- * Lifecycle is focus-existing-or-create (idempotent on already-focused).- * Renderer surfaces: `ProjectSwitcher` dropdown "Switch Project…",- * CommandPalette "Switch Project", and File → Switch Project… (which- * calls main's `openNavigator()` directly via the menu binding).- */- navigator: {- open(): Promise<void>;- };-- seed: {- /**- * Compute a scaffold plan for the current window's project (read-only).- * Options accept `rootDir` (project-relative subfolder) and `packId`- * (which starter pack to scaffold; defaults to `'knowledge-base'`).- * Calling with no args plans the default pack at project root —- * back-compat with the single-scaffold call shape.- */- plan(options?: SeedPlanOptions): Promise<OkSeedPlanResult>;- /**- * Apply a ScaffoldPlan returned by `plan`. Options accept `packId`- * (must match the pack `plan` was computed against). Calling with the- * plan alone applies the default pack — back-compat.- */- apply(plan: ScaffoldPlan, options?: SeedApplyOptions): Promise<OkSeedApplyResult>;- /** Enumerate available starter packs. Static metadata; no project context required. */- listPacks(): Promise<OkSeedListPacksResult>;- };-- /**- * Cowork skill install-dialog hooks. The renderer- * shows a React dialog explaining the 2-click install; these IPC channels- * implement the "concierge" actions the dialog takes.- */- skill: {- /**- * Returns true when Claude Desktop's config directory exists on this- * machine (macOS ~/Library/Application Support/Claude/ or Windows- * %APPDATA%/Claude/). False on Linux (unsupported upstream) and absent.- * Reuses `detectClaudeDesktopPresence` from the server package.- */- detectClaudeDesktop(): Promise<boolean>;- /**- * Build `openknowledge.skill` from the bundled SKILL.md source, save to- * the user's Downloads folder, then invoke the OS file association so- * the Claude Desktop App opens it (via its registered `.skill`- * CFBundleDocumentType on macOS / registry entry on Windows). Local- * build: no network, no GitHub Releases.- *- * Gated by `~/.ok/skill-state/claude-cowork`: when the recorded version- * matches the current bundled skill version, resolves with- * `{ ok: true, skipped: true, version, recordedAt? }` without- * rebuilding. Pass `force: true` to bypass (reinstall affordance).- */- buildAndOpen(opts?: { force?: boolean }): Promise<- | { ok: true; path: string; skipped?: false; version?: string }- | {- ok: true;- path?: undefined;- skipped: true;- version: string;- recordedAt?: string;- }- | {- ok: false;- reason: 'build-failed' | 'open-failed' | 'no-downloads-dir';- message?: string;- }- >;- };-- update: {- /** Invokes `autoUpdater.quitAndInstall()` in main. Triggered by Toast A's "Relaunch now" action. */- relaunchNow(): Promise<void>;- /**- * Force an out-of-cadence `checkForUpdates()` — fires the- * `ok:update:check-now` IPC. The user-facing result reaches the- * UI through the existing `onUpdateDownloaded` / toast event- * subscribers, so this resolves immediately after main fires the- * request rather than waiting for the network round-trip.- */- checkNow(): Promise<void>;- /**- * Fire `ok:update:whats-new-dismiss` — tells main this window dismissed the- * what's-new notice so main clears it across all windows. Fire-and-forget.- */- dismissWhatsNew(version: string): Promise<void>;- };-- /**- * Channel + schema-compatibility state surface. Renderer queries on mount- * to render the correct BETA badge / About-panel label and route the- * refuse-downgrade UX when a future-build state was rolled back.- */- state: {- query(): Promise<OkStateSnapshot>;- /**- * Wipe AppState back to defaults and clear any pending schema-- * incompatibility diagnostic. Pairs with the "Reset and Continue to- * Stable" button on the refuse-downgrade notice. The reset is a full- * `emptyState()` clear (recent-projects list and all other AppState- * fields, not just preferences) because the future build's reshape- * may have touched any field — partial reset would leave us trusting- * field shapes we can't verify. Caller gets the user's explicit- * confirmation before invoking — the renderer surface treats this- * as destructive.- */- resetIncompatible(): Promise<void>;- };-- /**- * First-launch MCP consent surface. Renderer mounts `<McpConsentDialog>`- * when `onShow` fires; calls `confirm` / `skip` on user action; calls- * `signalReady()` once on app mount so main knows a renderer is subscribed- * (mount-ack handshake). Available in every Electron host window- * (Navigator + editor) — first-ack wins.- */- mcpWiring: {- /** Subscribe to the consent-dialog-show event. Returns unsubscribe. */- onShow(cb: (payload: OkMcpWiringShowPayload) => void): OkUnsubscribe;- /** Fire a one-way mount-ack event — main's whenRendererReady gate. */- signalReady(): void;- /** User clicked Add. `editorIds` is the subset the user checked;- * `pathInstall` is the PATH toggle (tri-state — see- * `OkMcpWiringConfirmRequest`). */- confirm(request: OkMcpWiringConfirmRequest): Promise<OkMcpWiringResult>;- /** User clicked Skip (or pressed ESC). */- skip(): Promise<OkMcpWiringResult>;- /**- * Re-arm the consent dialog on demand (File → "Set up OpenKnowledge- * integrations…" and the Cmd+K command). Resolves `true` when armed,- * `false` when unavailable (non-darwin / unpackaged / arming threw).- */- reconfigure(): Promise<boolean>;- };-- /**- * App-wide spell-check toggle (Edit → "Check spelling while typing" and the- * Cmd+K command). `toggle()` flips the flag and resolves to the new enabled- * state. Bespoke main-side setting; NOT part of the View-menu-state snapshot.- */- spellcheck: {- toggle(): Promise<boolean>;- };-- /**- * Settings → AI tools: live per-component install state + one-component- * install/uninstall for OK's global footprint (per-editor MCP entries,- * shell-PATH shim, user-global skill bundles). Mutations serialize in main.- */- integrations: {- status(): Promise<OkIntegrationsStatus>;- setComponent(request: OkIntegrationsSetRequest): Promise<OkIntegrationsSetResult>;- };-- /**- * Settings → This project → AI tools: live per-component install state +- * one-component install/uninstall for OK's PROJECT-LOCAL footprint (per-editor- * project MCP config files + the project runtime skill) against the project- * the requesting window has open. Mutations serialize in main.- */- projectIntegrations: {- status(): Promise<OkProjectIntegrationsStatus>;- setComponent(request: OkProjectIntegrationsSetRequest): Promise<OkProjectIntegrationsSetResult>;- };-- /**- * Per-project consent dialog. Navigator-only — editor renderers never- * receive `ok:onboarding:show`. Renderer mounts a shadcn Dialog when- * `onShow` fires; calls `confirm` / `cancel` on user action; calls- * `signalReady()` once on app mount so main knows a renderer is- * subscribed. `onToast` fires on freshly-spawned editor windows for- * ancestor- and git-root-promote events. Render via sonner with a 4 s- * auto-dismiss.- */- onboarding: {- onShow(cb: (payload: OkOnboardingShowPayload) => void): OkUnsubscribe;- signalReady(): void;- confirm(request: OkOnboardingConfirmRequest): Promise<OkOnboardingResult>;- cancel(): Promise<OkOnboardingResult>;- /** Throttled async probe for the file-count preview line. */- probeContent(request: OkOnboardingProbeContentRequest): Promise<OkOnboardingProbeContentResult>;- onToast(- cb: (- payload:- | { readonly kind: 'ancestor-promote'; readonly ancestorPath: string }- | {- readonly kind: 'git-root-promote';- readonly gitRoot: string;- readonly pickedPath: string;- }- | {- readonly kind: 'startup-reclaim';- readonly mcp:- | { readonly status: 'none' }- | { readonly status: 'repaired'; readonly editors: readonly string[] }- | { readonly status: 'failed'; readonly editors: readonly string[] };- readonly path:- | { readonly status: 'none' }- | { readonly status: 'installed'; readonly summary: string }- | { readonly status: 'failed'; readonly summary: string };- }- | {- readonly kind: 'sharing-refused-tracked';- readonly tracked: readonly string[];- readonly remediation: string;- }- | {- readonly kind: 'sharing-no-git';- readonly requestedMode: 'local-only';- },- ) => void,- ): OkUnsubscribe;- };-- /**- * Pre-project local-op flows. Required by the Project Navigator window,- * which has no backing API server (apiOrigin is empty). Editor windows- * use the HTTP path; this surface is unused there.- */- localOp: {- auth: {- /**- * Start a GitHub device-flow login subprocess. Returns a stream of- * events; iteration ends after a terminal `complete` / `error`. Call- * `cancel()` to abort early.- */- start(): OkLocalOpStream<OkLocalOpAuthEvent>;- };- clone: {- /**- * Spawn `ok clone` for the given URL + target dir. Returns a stream- * of events; iteration ends after a terminal `complete` / `error`.- * The `complete` event carries `dir` (no `port`) — Electron main- * spawns a new editor window directly at that path.- *- * Optional `branch` runs `ok clone -b <branch>`; the CLI retries- * against the remote default branch + emits a non-terminal- * `branch-fallback` event when the ref is gone upstream. Treat- * `null` / `undefined` / absent identically (legacy- * default-branch clone). Slashed names (`feat/foo`) flow verbatim.- */- start(request: {- url: string;- dir: string;- branch?: string | null;- }): OkLocalOpStream<OkLocalOpCloneEvent>;- };- /**- * One-shot auth queries. Bounded responses (status: one line; repos:- * bounded list) so no streaming surface needed. Used by Navigator in- * place of the HTTP `/api/local-op/auth/{status,repos}` endpoints.- */- authStatus(request?: { host?: string }): Promise<OkLocalOpAuthStatusResponse>;- authRepos(request?: { host?: string }): Promise<OkLocalOpAuthReposResponse>;- };-- /**- * Share-receive flow surface. `validateLocalFolder` runs the- * Q2 "I have it locally" folder validator in the main process via- * `validateLocalFolderForShare` from the CLI package.- */- share: {- validateLocalFolder(args: {- folderPath: string;- host: string;- owner: string;- repo: string;- }): Promise<ShareFolderValidationResult>;- };-- /**- * Editor area state push surface. Renderer fires- * `notifyActiveTargetChanged` once per `activeTarget` transition in- * `useDocumentContext()` — the same signal the EditorHeader sparkle icon- * uses to pick its dispatch helper. Main listens to rebuild the macOS- * File menu's state-aware enable/disable for items like Rename / Move- * to Trash / Open with AI. Fire-and-forget: the preload implementation- * invokes the channel and swallows rejections, mirroring- * `signalThemeApplied`'s pattern — a missing handler during window- * teardown is expected, not a programmer error.- */- editor: {- notifyActiveTargetChanged(target: OkEditorActiveTargetSnapshot): void;- /**- * Fire-and-forget push of the sidebar's view-menu-relevant state. Main- * stores the latest snapshot and rebuilds the application menu so the- * View menu's "Show Hidden Files" check mark reflects the- * merged-config CRDT value, and "Expand All" / "Collapse All" smart-hide- * when the tree is fully expanded / collapsed. Last-write-wins across- * windows — matches the active-target singleton model.- */- notifyViewMenuStateChanged(state: Partial<OkEditorViewMenuStateSnapshot>): void;- /**- * Fire-and-forget push keying the window's Chromium background-throttling- * to its unsynced work. `hasPendingWork` is the renderer's aggregate- * unsynced-work flag; `enabled` is the resolved- * `bridge.backgroundThrottle.enabled` kill-switch. Main runs the toggle- * predicate on the sender window's webContents. Reported on each- * transition of either input.- */- notifyBackgroundThrottle(signal: { hasPendingWork: boolean; enabled: boolean }): void;- };-- /**- * Windows/Linux renderer-menubar dispatch surface (windows-linux-port- * renderer-menubar decision). macOS keeps the native menu bar and never calls this; on- * win/linux the renderer-drawn menu bar routes every click through main- * so menu semantics live in one place. `query` resolves the aggregated- * `OkMenuRendererSnapshot`; every other kind performs the action- * main-side and resolves undefined.- */- menu: {- dispatch(request: OkMenuDispatchRequest): Promise<OkMenuRendererSnapshot | undefined>;- };-- /**- * Startup-instrumentation push surface (desktop launch waterfall). The- * renderer reports its two launch checkpoints — page-list ready and first- * content — as epoch-ms `Date.now()` values, once both have landed. Main- * folds them into the single `desktop.startup-timeline` log line and (when- * OTel is enabled) the `ok.app-startup` renderer child span. Fire-and-forget,- * idempotent on the renderer side (sent once per launch). No-op for non-Electron- * hosts (the bridge is absent on the web build).- */- startup: {- reportMarks(marks: { pageListReadyMs: number; firstContentMs: number }): void;- };-- /**- * Sidebar tree-state push subscriptions. Main pushes- * `ok:sidebar:expand-all` / `ok:sidebar:collapse-all` when the user picks- * View → Expand All / Collapse All. Renderer subscribes via the returned- * unsubscribe pattern (mirrors `onProjectSwitched` / `onMenuAction`).- * Tree-scoped — main smart-hides the menu items when the tree state- * doesn't warrant the action; the bridge just delivers the signal.- * No payload — the channel itself IS the directive.- */- sidebar: {- expandAll(cb: () => void): OkUnsubscribe;- collapseAll(cb: () => void): OkUnsubscribe;- };-- /**- * Bottom-docked terminal panel surface. The renderer creates one PTY per- * window, streams shell output in via `onData`, sends keystrokes out via- * `input`, resizes on fit, and kills on teardown; main mediates to a- * window-bound utilityProcess hosting node-pty. `onData` / `onExit` follow- * the `onMenuAction` subscription shape (the returned closure detaches the- * wrapped listener). `input` / `resize` / `drain` are fire-and-forget;- * `create` / `kill` resolve.- *- * `drain` is the renderer's backpressure ack: after xterm writes a data- * batch it reports the consumed byte count so main can resume a PTY it- * paused once in-flight bytes fall back under the low-water mark. Without- * it a flood (`yes`, a large `cat`) grows unbounded in-flight bytes and- * starves the renderer.- *- * Structurally mirrored verbatim in the core + app bridge copies (drift-tested).- */- terminal: {- create(opts: {- cols: number;- rows: number;- launchCommand?: string;- }): Promise<OkPtyCreateResult>;- input(ptyId: string, data: string): void;- resize(ptyId: string, cols: number, rows: number): void;- kill(ptyId: string): Promise<void>;- drain(ptyId: string, bytes: number): void;- /**- * Reload-rehydration inventory: the live ptyIds for this window. A reloaded- * dock queries this on mount to rediscover the shells that survived in main- * (the PTY host outlives a renderer reload), then adopts each rather than- * spawning fresh ones. Empty for a window with no surviving sessions.- */- list(): Promise<OkPtyListEntry[]>;- /**- * Re-bind a surviving session to this (reloaded) renderer: main refreshes- * the session's delivery target, clears the backpressure the dead page left- * stranded, and resumes the host. Resolves `unknown-session` when the shell- * exited in the gap since `list`, so the caller spawns a fresh shell instead.- */- adopt(ptyId: string): Promise<OkPtyAdoptResult>;- /**- * Persist per-session tab metadata (custom name + sticky ordinal) in main so- * it survives a renderer reload — main outlives the reload, so a reloaded dock- * reads it back via `list`. Fire-and-forget; omit a field to leave it unchanged.- */- setMeta(ptyId: string, meta: { customLabel?: string | null; ordinal?: number }): void;- /**- * Persist the tab display order in main (ptyIds in visual order) so a reorder- * survives a renderer reload. Fire-and-forget.- */- setOrder(orderedPtyIds: readonly string[]): void;- /**- * Per-window panel state retained in main, read once on reload so each panel- * re-expands and restores its own tab order + active tab. The terminal dock and- * the agents panel are independent surfaces, so their orders are recorded- * separately: a single shared record would let each panel's write erase the- * other's keys and clobber the shared active tab. `terminal.order` holds ptyIds,- * `agents.order` holds threadIds. Both records are optional (absent until that- * panel first persists).- */- getDockState(): Promise<{- terminalVisible: boolean;- agentPanelVisible: boolean;- terminal?: { order: string[]; activeKey: string | null };- agents?: { order: string[]; activeKey: string | null };- }>;- /**- * Persist one panel's tab order + active key in main (per window) so a renderer- * reload restores that panel's arrangement. `surface` names which panel is- * writing; `order` holds its reload-stable keys (ptyIds for `terminal`,- * threadIds for `agents`) in tab order. Fire-and-forget.- */- setDockState(state: {- surface: 'terminal' | 'agents';- order: string[];- activeKey: string | null;- }): void;- onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;- onExit(cb: (msg: OkPtyExit) => void): OkUnsubscribe;- /**- * Claude Code readiness probe. Resolves whether `claude` is on the- * login-shell PATH and whether the `open-knowledge` MCP server is wired- * into `~/.claude.json`. Bounded + side-effect-free — runs a fixed- * `command -v claude` and reads the config; no renderer-supplied command.- */- claudePreflight(): Promise<ClaudeReadiness>;- /**- * On-PATH readiness probe for a non-Claude agent CLI (codex / cursor).- * Resolves whether the CLI's binary (`codex` / `cursor-agent`) is on the- * login-shell PATH. Bounded + side-effect-free — runs a fixed- * `command -v <bin>` for the registry binary; no renderer-supplied command.- * Drives the "Open in terminal" launch gate + the missing-CLI banner the- * same way `claudePreflight` does for Claude.- */- cliPreflight(cli: TerminalCli): Promise<CliReadiness>;- /**- * Batched on-PATH readiness for every launchable CLI, collapsed to a plain- * installed map (`true` ⇒ the CLI's registry binary resolves on the- * login-shell PATH). Powers the New-chat default-CLI auto-pick, which needs a- * single "which CLIs can I launch?" answer rather than one `cliPreflight` per- * CLI. Bounded + side-effect-free — a fixed `command -v <bin>` per registry- * binary, no renderer-supplied command. Cached in main (~60s) so repeated- * New-chat clicks don't re-probe the login shell each time.- */- cliInstalledMap(): Promise<Record<TerminalCli, boolean>>;- /**- * Re-arm MCP wiring when `claudePreflight` reports `mcp: 'needs-rewire'`:- * shows the consent dialog (the same forceShow path as File → Set up- * OpenKnowledge integrations) so the user can wire `open-knowledge` into Claude- * Code. Returns the still-current readiness (the grant lands once the user- * completes the dialog). Human-only — never agent-callable.- */- rewireClaudeMcp(): Promise<ClaudeReadiness>;- };-- /**- * OS assistive-tech signal — Electron's `app.isAccessibilitySupportEnabled()`,- * true while a screen reader (VoiceOver, NVDA) is attached. The terminal gates- * xterm's `screenReaderMode` on it: the mode mirrors the viewport into a live- * accessibility DOM on every write/scroll — a significant rendering cost per- * xterm's own docs — so it stays off until assistive tech is detected (the- * VS Code model), and screen-reader users still get the full a11y tree.- *- * `isScreenReaderActive` is a synchronous read of the preload's live mirror- * (seeded from the `--ok-screen-reader-active` window arg, updated by- * `ok:accessibility:changed`), so the terminal can set its a11y posture at- * construction with no async flash. The subscription re-skins an already-open- * terminal in place when a screen reader attaches or detaches mid-session.- *- * Structurally mirrored in the app bridge copy, where it is OPTIONAL —- * consumers treat an absent surface as screen-reader-active (fail-accessible).- */- accessibility: {- isScreenReaderActive(): boolean;- onScreenReaderChanged(cb: (active: boolean) => void): OkUnsubscribe;- };-- readonly platform: 'darwin' | 'win32' | 'linux';- readonly appVersion: string;- /**- * Named parallel dev-instance label (branch/worktree) when this launch- * relocated `userData` to a named sibling — auto-derived from the git- * checkout or an explicit `OK_INSTANCE`. Null for the default install and in- * web / CLI distribution. Drives the header branch badge. Lockstep with the- * app-side `OkDesktopBridge` (`packages/app/src/lib/desktop-bridge-types.ts`).- */- readonly instanceLabel: string | null;-- /**- * Resolve a dropped `File` to its absolute filesystem path via Electron- * `webUtils.getPathForFile` (renderer-side, no IPC). Returns null for a File- * with no backing path on disk (e.g. an in-memory clipboard blob). The- * docked terminal uses this to insert a dropped file's path at the prompt.- */- getPathForFile(file: File): string | null;-- /**- * Debug-only namespace — populated by preload ONLY when- * `process.env.OK_DEBUG_KEYRING_SMOKE === '1'` OR- * `app.isPackaged === false`. Absent in normal production runs, so a typo- * in renderer code calling a non-existent method surfaces at TypeScript- * compile time.- */- debug?: {- /**- * Run the utility-process keyring smoke and return the result. Rejects- * with 'debug-channel disabled in production' when the runtime gate is- * closed (app packaged + env var unset).- */- keyringSmoke(): Promise<KeyringSmokeResult>;- };-}+export type CheckTargetExistsResult = OkCheckTargetExistsResult;+export type HeadBranchInfo = OkHeadBranchInfo;+export type SeedPlanOptions = OkSeedPlanOptions;+export type SeedApplyOptions = OkSeedApplyOptions;declare global {interface Window {- /** Populated by the desktop preload script. Absent in web / CLI distribution. */okDesktop?: OkDesktopBridge;}}diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.tsindex 8f1700342..a5a3c4909 100644--- a/packages/desktop/src/shared/ipc-channels.ts+++ b/packages/desktop/src/shared/ipc-channels.ts@@ -77,6 +77,8 @@ import type {CheckoutResponse,CreateNewBannerKind,EditorId,+ HandoffFailureReason,+ HandoffScope,LocalOpOkInitResponse,OkBugReportCrashAckResult,OkBugReportCreateResult,@@ -94,58 +96,53 @@ import type {WorktreeListResult,} from '@inkeep/open-knowledge-core';import type {- FindEnclosingGitRootResult,- FindEnclosingProjectRootResult,- PackId,- ScaffoldPlan,-} from '@inkeep/open-knowledge-server';-import type { OkBugReportRequest } from '../main/ipc/bug-report.ts';-import type { BuildAndOpenResult } from '../main/ipc/install-skill.ts';-import type { SeedApplyResult, SeedListPacksResult, SeedPlanResult } from '../main/ipc/seed.ts';-import type { KeyringSmokeResult } from '../utility/keyring-smoke.ts';-import type {- CheckTargetExistsResult,+ OkCheckTargetExistsResult as CheckTargetExistsResult,ClaudeReadiness,CliReadiness,- HeadBranchInfo,+ OkHeadBranchInfo as HeadBranchInfo,OkChromeColors,OkDesktopConfig,+ OkEditorActiveTargetSnapshot,+ OkEditorViewMenuStateSnapshot,OkLocalOpAuthReposResponse,OkLocalOpAuthStatusResponse,- OkMenuAction,+ OkMenuDispatchCommand,+ OkMenuDispatchRequest,+ OkMenuDispatchRole,+ OkMenuRendererSnapshot,OkPtyAdoptResult,OkPtyCreateResult,OkPtyListEntry,OkServerRestartOutcome,OkSharePayloadFields,+ OkSharingSetModeResult,+ OkSharingStatusResult,OkThemeSource,OkUpdateChannel,- SeedApplyOptions,- SeedPlanOptions,-} from './bridge-contract.ts';+ OkSeedApplyOptions as SeedApplyOptions,+ OkSeedPlanOptions as SeedPlanOptions,+} from '@inkeep/open-knowledge-core/desktop-bridge';+import type {+ FindEnclosingGitRootResult,+ FindEnclosingProjectRootResult,+ PackId,+ ScaffoldPlan,+} from '@inkeep/open-knowledge-server';+import type { OkBugReportRequest } from '../main/ipc/bug-report.ts';+import type { BuildAndOpenResult } from '../main/ipc/install-skill.ts';+import type { SeedApplyResult, SeedListPacksResult, SeedPlanResult } from '../main/ipc/seed.ts';+import type { KeyringSmokeResult } from '../utility/keyring-smoke.ts';import type { EntryPoint } from './entry-point.ts';-/** Sharing-mode — IPC payload types. */-export interface OkSharingStatusResult {- readonly kind: 'status';- readonly mode: 'shared' | 'local-only' | 'no-git';- readonly excluded: readonly string[];- readonly trackedUpstream: readonly string[];- /** True when local-only but `.ok/skills/` is carved back out as shareable. */- readonly skillsShared: boolean;-}+export type EditorActiveTargetSnapshot = OkEditorActiveTargetSnapshot;+export type EditorViewMenuStateSnapshot = OkEditorViewMenuStateSnapshot;+export type MenuDispatchRole = OkMenuDispatchRole;+export type MenuDispatchCommand = OkMenuDispatchCommand;+export type MenuDispatchRequest = OkMenuDispatchRequest;+export type MenuRendererSnapshot = OkMenuRendererSnapshot;-export type OkSharingSetModeResult =- | { readonly kind: 'applied'; readonly mode: 'shared' | 'local-only' | 'no-git' }- | {- readonly kind: 'refused-tracked';- readonly tracked: readonly string[];- readonly remediation: string;- }- | {- readonly kind: 'no-exclude';- readonly reason: 'no-git' | 'no-info-dir' | 'malformed-pointer' | 'inaccessible';- };+/** Sharing-mode — IPC payload types. */+export type { OkSharingSetModeResult, OkSharingStatusResult };/** Discriminated union of every result the single `ok:sharing:dispatch` channel can* return. Distinguishing the `status` kind from the three `set-mode` kinds@@ -218,8 +215,7 @@ interface ProjectOpenRequest {pendingBranch?: string | null;/*** Optional branch-switch payload for the share-receive "I already have it- * locally" (Q2) path. See canonical JSDoc in `./bridge-contract.ts`. When- * the located clone is on a different branch than the share, the+ * locally" (Q2) path. When the located clone is on a different branch than the share, the* `ok:project:open` handler forwards this to `openProject` so main delivers* the `project-branch-switch` surface instead of a plain deep-link open.* Structurally matches `ShareDeepLinkBranchSwitchPayload` (url-scheme.ts).@@ -282,11 +278,7 @@ export type SpawnOutcome =* diagnostic counter — when a dogfood user reports "it didn't work," the* file gives target / outcome / reason history without any network egress.*- * Literal-union fields mirror `HandoffTarget`, `HandoffFailureReason`, and- * `HandoffScope` from `@inkeep/open-knowledge-core/handoff/types.ts`. Duplication is deliberate- * — shared/ipc-channels.ts deliberately has no app-package dependencies- * (same pattern as `SpawnOutcome` above and the `bridge-contract.ts`- * mirroring).+ * The handoff reason and scope fields reuse the core handoff discriminators.*/export interface HandoffStatsLine {readonly target: 'claude-cowork' | 'claude-code' | 'codex' | 'cursor';@@ -295,16 +287,10 @@ export interface HandoffStatsLine {/** ISO 8601 timestamp from the caller — not generated server-side so tests* can supply a deterministic value. */readonly ts: string;- /** Mirrors `HandoffFailureReason` literal union — present only on `outcome:'error'`. */- readonly reason?:- | 'not-installed'- | 'scheme-blocked'- | 'web-endpoint-error'- | 'invalid-payload'- | 'dispatch-error'- | 'web-host-cursor-unsupported';- /** Mirrors `HandoffScope` — set only on a selection-scoped dispatch. */- readonly scope?: 'selection';+ /** Present only on `outcome:'error'`. */+ readonly reason?: HandoffFailureReason;+ /** Set only on a selection-scoped dispatch. */+ readonly scope?: HandoffScope;}/** Editor IDs known to the first-launch MCP consent flow. Aliased to@@ -418,12 +404,9 @@ export interface McpWiringEditorDetection {readonly label: string;readonly detected: boolean;readonly willReplace: boolean;- /** Display-form user-global config path (home collapsed to `~`), or null when- * the editor has no user-global surface on this platform. Disclosure aid for- * the per-row location tooltip — mirrors `OkIntegrationsStatus`. */+ /** Display-form user-global config path, or null when unavailable. */readonly configPath: string | null;- /** Locator for this editor's `open-knowledge` entry within its config file- * (`[mcp_servers.open-knowledge]` / dotted key path). Disclosure aid. */+ /** Locator for OpenKnowledge's entry within the editor config. */readonly entryLocator: string;}@@ -620,132 +603,6 @@ interface DialogOpenFolderOpts {readonly defaultPath?: string;}-/**- * Renderer → main snapshot of what's currently active in the editor area.- * Drives the macOS File menu's state-aware enable/disable: `'doc'` enables- * doc-targeted items (Rename, Duplicate, Move to Trash, Open with AI on the active file);- * `'folder'` enables folder-targeted items; `'asset'` enables file-targeted- * rename/trash/reveal without Duplicate or Open with AI; `null` (no active- * target — project scope) leaves Rename / Duplicate / Move to Trash disabled- * and enables only project-level items (New File, Reveal in Finder for- * `contentDir`, etc.).- *- * Intentionally narrower than the renderer's full `ResolvedNavigationTarget`- * union — main only needs the enable/disable signal plus the- * `identifier` payload it routes through bridge.shell.* / HTTP calls when the- * user picks a menu item. Discriminated-union shape so TypeScript narrows- * `identifier` per `kind` at consumer sites.- */-export type EditorActiveTargetSnapshot =- | { readonly kind: 'doc'; readonly identifier: string }- | { readonly kind: 'folder'; readonly identifier: string }- | { readonly kind: 'asset'; readonly identifier: string }- | { readonly kind: null };--/**- * Renderer → main snapshot of the View menu's checkbox + smart-hide state.- * Drives the View menu's live `checked` reflection for the visibility- * toggles and the `visible: false` smart-hide on Expand All / Collapse All.- * `sidebarVisible` flips the Show/Hide Sidebar label on the View-menu- * sidebar-toggle item.- *- * **DRIFT WARNING — this shape is mirrored in four places** for IPC-channel /- * bridge-contract isolation (the bridge surfaces cannot import the wider bridge- * module without coupling the layers). TypeScript catches drift at call-site- * boundaries but not at the definitions — and this `ipc-channels` copy is the- * one the call-site check misses: it is reached only through the channel-args- * layer, never through `OkDesktopBridge`, and the preload→`invoke` hop passes- * the wider `OkEditorViewMenuStateSnapshot` value in, so a field added to the- * bridge copy but dropped here assigns silently (superset → subset) and main- * never sees it. Keep these in lockstep:- *- * 1. `packages/desktop/src/shared/ipc-channels.ts` — `EditorViewMenuStateSnapshot` (this copy)- * 2. `packages/desktop/src/shared/bridge-contract.ts` — `OkEditorViewMenuStateSnapshot`- * 3. `packages/core/src/desktop-bridge.ts` — canonical `OkEditorViewMenuStateSnapshot`- * 4. `packages/app/src/lib/desktop-bridge-types.ts` — renderer-side augmentation- */-export interface EditorViewMenuStateSnapshot {- readonly showHiddenFiles: boolean;- readonly showOkFolders: boolean;- readonly showOnlyMarkdownFiles: boolean;- readonly showSkillsSection: boolean;- readonly canExpandAll: boolean;- readonly canCollapseAll: boolean;- readonly sidebarVisible: boolean;- readonly docPanelVisible?: boolean;- readonly terminalVisible?: boolean;- readonly terminalLive?: boolean;- readonly agentPanelVisible?: boolean;- readonly canViewInSource?: boolean;-}--/**- * Renderer-menubar → main dispatch payloads (the windows-linux-port renderer-menubar decision).- * On Windows/Linux the menu bar is custom-drawn in the renderer (macOS- * keeps the native one); every click routes through the single- * `ok:menu:dispatch` channel so main stays the authority on menu- * semantics — `menu-action` relays through the exact `sendMenuActionToFocused`- * path the native menu items use, `role` maps to the Electron menu roles- * the native template gets for free, `command` covers the main-side click- * handlers (navigator, folder picker, settings, updater…), and `query`- * returns the same aggregated state that drives the native menu's- * enable/check rendering.- *- * **DRIFT WARNING — mirrored in four places** (same lockstep contract as- * `EditorViewMenuStateSnapshot` above; the ipc-channels copy is the one the- * call-site check misses):- *- * 1. `packages/desktop/src/shared/ipc-channels.ts` — this copy- * 2. `packages/desktop/src/shared/bridge-contract.ts` — `OkMenuDispatch*`- * 3. `packages/core/src/desktop-bridge.ts` — canonical `OkMenuDispatch*`- * 4. `packages/app/src/lib/desktop-bridge-types.ts` — renderer-side copy- */-export type MenuDispatchRole =- | 'undo'- | 'redo'- | 'cut'- | 'copy'- | 'paste'- | 'selectAll'- | 'reload'- | 'forceReload'- | 'toggleDevTools'- | 'resetZoom'- | 'zoomIn'- | 'zoomOut'- | 'toggleFullScreen'- | 'minimize'- | 'close'- | 'quit';--export type MenuDispatchCommand =- | 'open-navigator'- | 'open-folder-dialog'- | 'clear-recent-projects'- | 'open-settings'- | 'check-for-updates'- | 'reconfigure-mcp-wiring'- | 'open-github'- | 'toggle-spell-check';--export type MenuDispatchRequest =- | { readonly kind: 'query' }- | { readonly kind: 'menu-action'; readonly action: OkMenuAction }- | { readonly kind: 'command'; readonly command: MenuDispatchCommand }- | { readonly kind: 'open-recent-project'; readonly path: string }- | { readonly kind: 'role'; readonly role: MenuDispatchRole };--/** `query` result — the same aggregated state the native menu renders from. */-export interface MenuRendererSnapshot {- readonly recentProjects: ReadonlyArray<{ readonly path: string; readonly name: string }>;- readonly spellCheckEnabled: boolean;- readonly showDevToolsMenu: boolean;- readonly canCheckForUpdates: boolean;- readonly canReconfigureMcpWiring: boolean;- readonly activeTarget: EditorActiveTargetSnapshot;- readonly viewMenuState: EditorViewMenuStateSnapshot;-}-export interface RequestChannels {/** Open native folder-picker. Canonical properties live in `dialog-helpers.ts`. */'ok:dialog:open-folder': {@@ -808,7 +665,7 @@ export interface RequestChannels {* project-relative path; main-process `openAssetSafely` handler resolves* against `ProjectContext.projectPath + realpath + isPathWithinProject`,* enforces the `EXECUTABLE_BLOCKLIST_EXTENSIONS` gate, and dispatches to- * `shell.openPath(canonical)`. Reason union matches the bridge-contract+ * `shell.openPath(canonical)`. Reason union matches the core desktop bridge* `openAsset` return type.*/'ok:shell:open-asset': {@@ -921,13 +778,14 @@ export interface RequestChannels {* `ok:sharing:dispatch` precedent) so the whole report surface costs a* single hand-rolled slot; report operations widen this payload instead of* adding channels.- * - `{kind: 'create', level, note?, includeCrashDump?}` → build the- * redacted diagnostic zip for the sender window's project (system-wide- * when the sender has no project context) under `~/.ok/bug-reports/`;- * the crash-dump flag is the crash invite's explicit opt-in.- * - `{kind: 'send', zipPath, metadata}` → upload the reviewed zip to the- * private intake endpoint; any failure (endpoint unconfigured included)- * degrades to a prefilled email fallback.+ * - `{kind: 'create', level, note?, includeCrashDump?, includeScreenshot?}`+ * → build the redacted diagnostic zip for the sender window's project+ * (system-wide when the sender has no project context) under+ * `~/.ok/bug-reports/`; both attachment flags are explicit opt-ins.+ * - `{kind: 'send', zipPath, metadata, includeScreenshot?}` → upload the+ * reviewed zip to the private intake endpoint and, when explicitly+ * included, the captured screenshot; any failure (endpoint unconfigured+ * included) degrades to a prefilled email fallback.* - `{kind: 'crash-ack', eventId}` → persist that the user answered a* `ok:bug-report:crash-detected` invitation so that crash event never* re-prompts, across restarts included.@@ -1727,15 +1585,7 @@ export interface RequestChannels {args: [];result: Record<TerminalCli, boolean>;};- /**- * Per-window panel state, read once on reload to restore both panels. The two- * `*Visible` flags are recorded from the renderer's view-menu push; the per-surface- * `order` + `activeKey` records come from `ok:terminal:set-dock-state`. The terminal- * dock and agents panel are independent surfaces, so their orders are kept apart —- * one shared record would let each panel's write erase the other's keys. All- * windowId-keyed, gone after window-close / app-quit (so a fresh launch with no- * surviving sessions restores nothing).- */+ /** Per-window state for the independent terminal and agents panels. */'ok:terminal:dock-state': {args: [];result: {@@ -1745,12 +1595,7 @@ export interface RequestChannels {agents?: { order: string[]; activeKey: string | null };};};- /**- * Persist one panel's tab order + active key in main (per window) so a renderer- * reload restores that panel's arrangement + active tab. `surface` names the writer;- * `order` holds its reload-stable keys (ptyIds for `terminal`, threadIds for- * `agents`) in tab order. Fire-and-forget, the sibling of `ok:pty:set-order`.- */+ /** Persist one panel's tab order and active key per window. */'ok:terminal:set-dock-state': {args: [req: { surface: 'terminal' | 'agents'; order: string[]; activeKey: string | null }];result: undefined;diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.tsindex d0a8026be..8a51d96a2 100644--- a/packages/desktop/tests/integration/m1-smoke.test.ts+++ b/packages/desktop/tests/integration/m1-smoke.test.ts@@ -4,13 +4,13 @@* Test 1 (dev loop) — Playwright `_electron.launch` against the bundled* out/main/index.js. Skipped here with a structured reason because the* full Playwright + Electron + display-server harness is not part of- * `bun test` (it runs under `bun run test:e2e:packaged` once the- * electron-builder smoke pipeline lands). The bridge / utility /+ * the Vitest suite (it will run in the electron-builder smoke pipeline+ * once that pipeline lands). The bridge / utility /* window-manager / IPC layers ARE end-to-end tested via the unit-test* suite at the boundary they expose to the renderer.** Test 2 (keyring smoke) — exercises @napi-rs/keyring directly from a- * plain Node process to prove the binding loads under the Bun runtime+ * plain Node process to prove the binding loads under the current runtime* (ABI risk). If the binding fails to load (e.g., CI runner without* a Keychain backend), test SKIPs gracefully.*@@ -24,7 +24,7 @@* test suite at `packages/server/src/server-lock.test.ts`, which* this file CONSUMES rather than re-tests.*- * Net: this file's sole NEW gate is Test 2 (keyring smoke under Bun). The+ * Net: this file's sole NEW gate is Test 2 (keyring smoke under Node). The* other three are coverage pointers — explicit references so a future* developer can find the existing tests via this index.*/@@ -48,12 +48,10 @@ describe('M1 smoke', () => {});test('Test 2 — keyring smoke: @napi-rs/keyring loads + round-trips a secret', async () => {- // Confirms the native ABI loads under Bun. @napi-rs/keyring is a CLI+ // Confirms the native binding loads under Node. @napi-rs/keyring is a CLI// dep that must rebuild against Electron's Node ABI in packaged builds.- // This test catches the load-time failure shape (ABI mismatch, prebuilt- // missing) before packaging — if it can't load under Bun's- // Node24-compatible runtime, it definitely can't load under Electron's- // Node24-derived ABI.+ // This test catches the load-time failure shape (ABI mismatch or missing+ // prebuilt) before the packaged-build pipeline exercises Electron's ABI.let keyring: typeof import('@napi-rs/keyring') | null = null;try {keyring = await import('@napi-rs/keyring');@@ -75,7 +73,7 @@ describe('M1 smoke', () => {// backend. `entry.setPassword` blocks indefinitely on the missing// backend rather than throwing — and crucially, the native binding// holds a worker thread or D-Bus connection alive even after the test- // returns, preventing `bun test` from exiting cleanly. That manifests+ // returns, preventing `vitest run` from exiting cleanly. That manifests// as a CI-only post-test hang (15-minute job timeout cancellation).// The binding load already provides the// ABI-mismatch signal we care about for this test's purpose; the@@ -137,183 +135,6 @@ describe('M1 smoke', () => {expect(existsSync(serverLockTestPath)).toBe(true);});- test('M1 invariant: bridge contract drift catcher (US-010 promise)', async () => {- // Verify all three OkDesktopBridge contract copies (core canonical,- // desktop preload-side, app renderer-side) declare the same surface- // shape. Drift is a real risk — a future contributor adds a method to- // one copy and forgets the other two; this test fires on the first- // copy diverging.- //- // We check existence AND a lightweight member-name-set equality on the- // `OkDesktopBridge` interface text. This catches a category of drift- // (core missing the `project` surface- // while desktop + app both had it). Full signature-level equivalence is- // beyond this test's scope; pick up the delta at `bun run typecheck`- // if the TS compiler notices it across the three import paths.- const corePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');- const desktopPath = join(__dirname, '..', '..', 'src', 'shared', 'bridge-contract.ts');- const appPath = join(- __dirname,- '..',- '..',- '..',- 'app',- 'src',- 'lib',- 'desktop-bridge-types.ts',- );- expect(existsSync(corePath)).toBe(true);- expect(existsSync(desktopPath)).toBe(true);- expect(existsSync(appPath)).toBe(true);-- const { readFileSync } = await import('node:fs');- /**- * Extract member names from an `OkDesktopBridge` interface declaration,- * INCLUDING one level of nesting. Top-level members (`dialog`, `shell`,- * `project`, …) are captured by their name; members inside those nested- * blocks are captured as `<parent>.<name>` (e.g. `shell.detectProtocol`).- *- * Two-level capture (not arbitrary depth) is deliberate — the contract- * is flat-by-convention apart from the grouped surfaces, and a bounded- * walker is easier to reason about than a generic recursive one. If a- * future surface ever grows a third level, add another nesting tier- * here rather than reworking the depth bookkeeping.- */- const extractBridgeMembers = (src: string): Set<string> => {- const names = new Set<string>();- const lines = src.split('\n');- let inInterface = false;- let braceDepth = 0;- // Paren depth guards against false positives from multi-line method- // signatures like `spawnCursor(\n path: string,\n): Promise<…>` —- // without this, the continuation line `path: string,` would match the- // member regex and leak "path" as a phantom sub-member.- let parenDepth = 0;- let currentParent: string | null = null;- for (const line of lines) {- if (!inInterface) {- if (/interface\s+OkDesktopBridge\s*\{/.test(line)) {- inInterface = true;- braceDepth = (line.match(/\{/g) ?? []).length - (line.match(/\}/g) ?? []).length;- parenDepth = (line.match(/\(/g) ?? []).length - (line.match(/\)/g) ?? []).length;- }- continue;- }- const opens = (line.match(/\{/g) ?? []).length;- const closes = (line.match(/\}/g) ?? []).length;- const parenOpens = (line.match(/\(/g) ?? []).length;- const parenCloses = (line.match(/\)/g) ?? []).length;- const trimmed = line.trim();- const memberMatch = trimmed.match(/^(?:readonly\s+)?(\w+)\s*[:(?]/);- const canCapture = parenDepth === 0;- if (braceDepth === 1) {- if (canCapture && memberMatch?.[1]) {- names.add(memberMatch[1]);- if (opens > closes) currentParent = memberMatch[1];- }- } else if (braceDepth === 2 && currentParent) {- if (canCapture && memberMatch?.[1]) names.add(`${currentParent}.${memberMatch[1]}`);- }- braceDepth += opens - closes;- parenDepth += parenOpens - parenCloses;- if (braceDepth === 1 && currentParent) currentParent = null;- if (braceDepth === 0) break;- }- return names;- };-- const coreMembers = extractBridgeMembers(readFileSync(corePath, 'utf-8'));- const desktopMembers = extractBridgeMembers(readFileSync(desktopPath, 'utf-8'));- const appMembers = extractBridgeMembers(readFileSync(appPath, 'utf-8'));-- // All three extractions must actually find members — otherwise the regex- // is broken and subsequent equality checks are meaningless.- expect(coreMembers.size).toBeGreaterThan(0);- expect(desktopMembers.size).toBeGreaterThan(0);- expect(appMembers.size).toBeGreaterThan(0);-- // Positive regression: the nested walker must actually find sub-members- // of the `shell` block. If it silently fell back to top-level-only, this- // test would quietly succeed while missing an entire class of drift.- //- // Assert every shell.* sub-member shipped by the Open in Agent- // Desktop surface. A walker regression that drops- // one of these — say, the paren-depth guard degrading on a signature with- // a generic type parameter — would silently lose the drift signal for that- // method. Explicit membership makes the signal load-bearing.- const REQUIRED_SHELL_MEMBERS = [- 'shell.openExternal', // baseline- 'shell.detectProtocol', // Open in Agent- 'shell.spawnCursor', // Open in Agent- 'shell.recordHandoff', // Open in Agent telemetry- 'shell.openAsset', // asset-click dispatcher- 'shell.revealAsset', // asset-click dispatcher- 'shell.revealExternal', // terminal out-of-project reveal- 'shell.showAssetMenu', // right-click context menu- 'shell.showItemInFolder', // file-tree reveal-in-finder- 'shell.trashItem', // sidebar Trash flow- ] as const;- // The fs.* namespace was added for the Create-new-project dialog cascade.- // Mirror the shell.* coverage so a walker regression that drops one of- // these probes — say, the paren-depth guard degrading on the Promise<T |- // null> return type — would surface here instead of silently desyncing- // the three bridge-contract copies.- const REQUIRED_FS_MEMBERS = [- 'fs.defaultProjectsRoot',- 'fs.folderState',- 'fs.findEnclosingProjectRoot',- 'fs.findEnclosingGitRoot',- ] as const;- for (const [label, members] of [- ['core', coreMembers],- ['desktop', desktopMembers],- ['app', appMembers],- ] as const) {- expect(members.has('shell')).toBe(true);- for (const required of REQUIRED_SHELL_MEMBERS) {- expect(members.has(required)).toBe(true);- if (!members.has(required)) {- throw new Error(`${label} extractor missed ${required} — walker broken`);- }- }- expect(members.has('fs')).toBe(true);- for (const required of REQUIRED_FS_MEMBERS) {- expect(members.has(required)).toBe(true);- if (!members.has(required)) {- throw new Error(`${label} extractor missed ${required} — walker broken`);- }- }- }-- // Set equality pairwise. If any pair diverges, surface WHICH members- // are missing from which copy so the fix is clear.- const diff = (a: Set<string>, b: Set<string>) => Array.from(a).filter((x) => !b.has(x));- const coreMinusDesktop = diff(coreMembers, desktopMembers);- const desktopMinusCore = diff(desktopMembers, coreMembers);- const appMinusCore = diff(appMembers, coreMembers);- const coreMinusApp = diff(coreMembers, appMembers);-- if (- coreMinusDesktop.length +- desktopMinusCore.length +- appMinusCore.length +- coreMinusApp.length >- 0- ) {- throw new Error(- [- 'OkDesktopBridge contract drift across the three copies:',- ` core has but desktop missing: [${coreMinusDesktop.join(', ')}]`,- ` desktop has but core missing: [${desktopMinusCore.join(', ')}]`,- ` app has but core missing: [${appMinusCore.join(', ')}]`,- ` core has but app missing: [${coreMinusApp.join(', ')}]`,- '',- 'Fix: add the missing members so the three copies agree.',- ].join('\n'),- );- }- });-test('M1 invariant: literal unions consolidated in core; mirrors re-export or alias without the inline shape', async () => {// Three literal-union types are consolidated into `@inkeep/open-knowledge-// core`'s `constants/` directory. Each mirror file MUST reach the type@@ -354,9 +175,7 @@ describe('M1 smoke', () => {// Paths that mirror sites are pinned against.const cliEditorsPath = join(packagesRoot, 'cli', 'src', 'commands', 'editors.ts');const ipcChannelsPath = join(__dirname, '..', '..', 'src', 'shared', 'ipc-channels.ts');- const bridgeContractPath = join(__dirname, '..', '..', 'src', 'shared', 'bridge-contract.ts');const coreBridgePath = join(packagesRoot, 'core', 'src', 'desktop-bridge.ts');- const appBridgePath = join(packagesRoot, 'app', 'src', 'lib', 'desktop-bridge-types.ts');const createNewProjectPath = join(__dirname,'..',@@ -407,9 +226,7 @@ describe('M1 smoke', () => {mirrors: [['cli/commands/editors.ts', cliEditorsPath],['desktop/shared/ipc-channels.ts', ipcChannelsPath],- ['desktop/shared/bridge-contract.ts', bridgeContractPath],['core/desktop-bridge.ts', coreBridgePath],- ['app/lib/desktop-bridge-types.ts', appBridgePath],],},{@@ -420,8 +237,6 @@ describe('M1 smoke', () => {inlineRe: /'free'\s*\|\s*'exists-empty'\s*\|\s*'exists-nonempty'/,mirrors: [['core/desktop-bridge.ts', coreBridgePath],- ['app/lib/desktop-bridge-types.ts', appBridgePath],- ['desktop/shared/bridge-contract.ts', bridgeContractPath],['desktop/shared/ipc-channels.ts', ipcChannelsPath],['desktop/main/create-new-project.ts', createNewProjectPath],],@@ -434,8 +249,6 @@ describe('M1 smoke', () => {inlineRe: /'nested'\s*\|\s*'nonempty'\s*\|\s*'git-confirm'/,mirrors: [['core/desktop-bridge.ts', coreBridgePath],- ['app/lib/desktop-bridge-types.ts', appBridgePath],- ['desktop/shared/bridge-contract.ts', bridgeContractPath],['desktop/shared/ipc-channels.ts', ipcChannelsPath],['app/components/CreateProjectDialog.tsx', createProjectDialogPath],['desktop/main/onboarding-telemetry.ts', onboardingTelemetryPath],@@ -477,7 +290,7 @@ describe('M1 smoke', () => {// knowledge-core` (or the sibling `./constants/*.ts` module for the// in-core mirror).const importsFromCore =- /from\s+['"]@inkeep\/open-knowledge-core['"]/.test(src) ||+ /from\s+['"]@inkeep\/open-knowledge-core(?:\/desktop-bridge)?['"]/.test(src) ||/from\s+['"]\.\/constants\/[\w-]+\.ts['"]/.test(src);if (!importsFromCore) {offenders.push(@@ -508,29 +321,9 @@ describe('M1 smoke', () => {});test('M1 invariant: OkThemeSource literal-union drift catcher', async () => {- // The `OkThemeSource` literal union — `'system' | 'light' | 'dark'` —- // appears verbatim in THREE files (the desktop bridge contract +- // 2 mirrors). Adding a 4th value (e.g. `'auto'`) to one mirror but- // not the others would silently desynchronise the type at the IPC- // boundary AND the runtime guard `VALID_THEME_SOURCES` in- // `theme-handler.ts` would silently drop the new value.- //- // The three files (canonical + two mirrors):- // - packages/desktop/src/shared/bridge-contract.ts (`OkThemeSource`)- // - packages/core/src/desktop-bridge.ts (`OkThemeSource`)- // - packages/app/src/lib/desktop-bridge-types.ts (`OkThemeSource`)- const desktopPath = join(__dirname, '..', '..', 'src', 'shared', 'bridge-contract.ts');+ // The core leaf owns `OkThemeSource`; `VALID_THEME_SOURCES` remains an+ // independent IPC runtime guard.const corePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');- const appPath = join(- __dirname,- '..',- '..',- '..',- 'app',- 'src',- 'lib',- 'desktop-bridge-types.ts',- );const { readFileSync } = await import('node:fs');const extractLiteralUnion = (src: string, typeName: string): Set<string> => {@@ -543,42 +336,19 @@ describe('M1 smoke', () => {return new Set(literals.map((l) => l.slice(1, -1)));};- const desktopMembers = extractLiteralUnion(readFileSync(desktopPath, 'utf-8'), 'OkThemeSource');const coreMembers = extractLiteralUnion(readFileSync(corePath, 'utf-8'), 'OkThemeSource');- const appMembers = extractLiteralUnion(readFileSync(appPath, 'utf-8'), 'OkThemeSource');-// Guardrail — every extraction must find members; otherwise the regex// is broken and the equality checks are meaningless.- expect(desktopMembers.size).toBeGreaterThan(0);expect(coreMembers.size).toBeGreaterThan(0);- expect(appMembers.size).toBeGreaterThan(0);-- // Pin the canonical member count — when the spec adds a 4th source- // (e.g. `'auto'`), the maintainer updates this number AND all 3- // unions in lockstep. Also forces re-review of the runtime guard- // `VALID_THEME_SOURCES` in `theme-handler.ts`.- expect(desktopMembers.size).toBe(3);- expect(desktopMembers).toEqual(coreMembers);- expect(desktopMembers).toEqual(appMembers);+ // Pinning the count forces new members to revisit that runtime guard.+ expect(coreMembers.size).toBe(3);});test('M1 invariant: OkMenuAction literal-union drift catcher', async () => {- // Menu actions cross the desktop preload boundary and are manually mirrored- // in the desktop, core, and app bridge contracts. Keep the three unions in- // lockstep so adding a menu action cannot silently miss a renderer mirror.- const desktopPath = join(__dirname, '..', '..', 'src', 'shared', 'bridge-contract.ts');+ // Menu actions cross the desktop preload boundary. The core leaf owns the+ // union, and the consumer shims must continue re-exporting that declaration.const corePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');- const appPath = join(- __dirname,- '..',- '..',- '..',- 'app',- 'src',- 'lib',- 'desktop-bridge-types.ts',- );const { readFileSync } = await import('node:fs');const extractLiteralUnion = (src: string, typeName: string): Set<string> => {@@ -591,54 +361,32 @@ describe('M1 smoke', () => {return new Set(literals.map((l) => l.slice(1, -1)));};- const desktopMembers = extractLiteralUnion(readFileSync(desktopPath, 'utf-8'), 'OkMenuAction');const coreMembers = extractLiteralUnion(readFileSync(corePath, 'utf-8'), 'OkMenuAction');- const appMembers = extractLiteralUnion(readFileSync(appPath, 'utf-8'), 'OkMenuAction');-- expect(desktopMembers.size).toBeGreaterThan(0);expect(coreMembers.size).toBeGreaterThan(0);- expect(appMembers.size).toBeGreaterThan(0);// 26 baseline + 2 worktree + 2 Help + 3 sidebar + 2 navigation + 1 agents panel.- expect(desktopMembers.size).toBe(36);- expect(desktopMembers).toEqual(coreMembers);- expect(desktopMembers).toEqual(appMembers);+ expect(coreMembers.size).toBe(36);// Pin the visibility toggles explicitly: a bare count check wouldn't// notice a simultaneous add+remove that nets to the same size.- expect(desktopMembers.has('toggle-show-hidden-files')).toBe(true);- expect(desktopMembers.has('toggle-show-ok-folders')).toBe(true);- expect(desktopMembers.has('toggle-show-only-markdown-files')).toBe(true);- expect(desktopMembers.has('toggle-show-skills-section')).toBe(true);- expect(desktopMembers.has('new-worktree')).toBe(true);- expect(desktopMembers.has('switch-worktree')).toBe(true);- expect(desktopMembers.has('report-bug')).toBe(true);- expect(desktopMembers.has('navigate-back')).toBe(true);- expect(desktopMembers.has('navigate-forward')).toBe(true);+ expect(coreMembers.has('toggle-show-hidden-files')).toBe(true);+ expect(coreMembers.has('toggle-show-ok-folders')).toBe(true);+ expect(coreMembers.has('toggle-show-only-markdown-files')).toBe(true);+ expect(coreMembers.has('toggle-show-skills-section')).toBe(true);+ expect(coreMembers.has('new-worktree')).toBe(true);+ expect(coreMembers.has('switch-worktree')).toBe(true);+ expect(coreMembers.has('report-bug')).toBe(true);+ expect(coreMembers.has('navigate-back')).toBe(true);+ expect(coreMembers.has('navigate-forward')).toBe(true);+ expect(coreMembers.has('toggle-agent-panel')).toBe(true);});test('M1 invariant: EntryPoint / OkProjectEntryPoint literal-union drift catcher', async () => {- // The Navigator-side entry-point discriminator appears verbatim in THREE- // files (the canonical desktop type + 2 bridge-contract mirrors). The- // create-new-project work proved the drift scenario was real (it renamed- // 'start-fresh' → 'create-new' and added 'create-new-nested-redirect'),- // and the two mirror files' doc comments already claim drift is caught- // here — make that claim load-bearing.- //- // The three files (canonical + two mirrors):+ // The Navigator-side desktop entry point remains an independent runtime+ // discriminator, while the bridge declaration lives in the core leaf.+ // Relevant sources:// - packages/desktop/src/shared/entry-point.ts (`EntryPoint`)// - packages/core/src/desktop-bridge.ts (`OkProjectEntryPoint`)- // - packages/app/src/lib/desktop-bridge-types.ts (`OkProjectEntryPoint`)const desktopPath = join(__dirname, '..', '..', 'src', 'shared', 'entry-point.ts');const corePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');- const appPath = join(- __dirname,- '..',- '..',- '..',- 'app',- 'src',- 'lib',- 'desktop-bridge-types.ts',- );const { readFileSync } = await import('node:fs');const extractLiteralUnion = (src: string, typeName: string): Set<string> => {@@ -652,45 +400,25 @@ describe('M1 smoke', () => {const desktopMembers = extractLiteralUnion(readFileSync(desktopPath, 'utf-8'), 'EntryPoint');const coreMembers = extractLiteralUnion(readFileSync(corePath, 'utf-8'), 'OkProjectEntryPoint');- const appMembers = extractLiteralUnion(readFileSync(appPath, 'utf-8'), 'OkProjectEntryPoint');-- // Guardrail — every extraction must find members.+ // Guardrail — the independent desktop and canonical core declarations+ // must remain non-empty.expect(desktopMembers.size).toBeGreaterThan(0);expect(coreMembers.size).toBeGreaterThan(0);- expect(appMembers.size).toBeGreaterThan(0);- // Pin the canonical member count — when the spec adds a new entry point,- // the maintainer updates this number AND all 3 unions in lockstep. Also- // forces re-review of the runtime guard `isEntryPoint` + the- // `ENTRY_POINT_VALUES` Set in `entry-point.ts`.+ // Pinning the count forces new members to revisit the independent+ // `isEntryPoint` / `ENTRY_POINT_VALUES` runtime guard.// 7 + `'worktree'` (worktree = window — opening a worktree of the// current project; classified `managed`, so it opens without consent).expect(desktopMembers.size).toBe(8);expect(desktopMembers).toEqual(coreMembers);- expect(desktopMembers).toEqual(appMembers);});test('M1 invariant: KeyringSmokeResult shape drift catcher (M5)', async () => {- // Walks the `KeyringSmokeResult` (desktop utility source), and- // `OkKeyringSmokeResult` (core + app mirror) interfaces and asserts the- // three copies declare the SAME field-name set. Field names carry the- // contract — drift (e.g., a future contributor adds `attempts?: number`- // to one copy only) fails this test and surfaces which file is missing- // what. Complements the `OkDesktopBridge` drift catcher; both- // shapes cross the preload boundary and renaming either triplicates risk.+ // Compare the independent desktop utility result against the canonical+ // core bridge type.const desktopSmokeSrcPath = join(__dirname, '..', '..', 'src', 'utility', 'keyring-smoke.ts');const corePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');- const appPath = join(- __dirname,- '..',- '..',- '..',- 'app',- 'src',- 'lib',- 'desktop-bridge-types.ts',- );const { readFileSync } = await import('node:fs');/**@@ -734,47 +462,31 @@ describe('M1 smoke', () => {readFileSync(corePath, 'utf-8'),'OkKeyringSmokeResult',);- const appFields = extractInterfaceFields(- readFileSync(appPath, 'utf-8'),- 'OkKeyringSmokeResult',- );-- // Guardrail — all three extractions must find fields.+ // Guardrail — both independent declarations must expose fields.expect(desktopFields.size).toBeGreaterThan(0);expect(coreFields.size).toBeGreaterThan(0);- expect(appFields.size).toBeGreaterThan(0);const diff = (a: Set<string>, b: Set<string>) => Array.from(a).filter((x) => !b.has(x));const desktopMinusCore = diff(desktopFields, coreFields);const coreMinusDesktop = diff(coreFields, desktopFields);- const desktopMinusApp = diff(desktopFields, appFields);- const appMinusDesktop = diff(appFields, desktopFields);-- if (- desktopMinusCore.length +- coreMinusDesktop.length +- desktopMinusApp.length +- appMinusDesktop.length >- 0- ) {++ if (desktopMinusCore.length + coreMinusDesktop.length > 0) {throw new Error([- 'KeyringSmokeResult / OkKeyringSmokeResult shape drift across the three copies:',+ 'KeyringSmokeResult / OkKeyringSmokeResult shape drift across the desktop utility and core bridge:',` desktop has but core missing: [${desktopMinusCore.join(', ')}]`,` core has but desktop missing: [${coreMinusDesktop.join(', ')}]`,- ` desktop has but app missing: [${desktopMinusApp.join(', ')}]`,- ` app has but desktop missing: [${appMinusDesktop.join(', ')}]`,'',- 'Fix: update the missing files so all three copies agree on the field set.',+ 'Fix: update the independent desktop utility or canonical core bridge field set.',].join('\n'),);}});test('M1 invariant: project session state shape drift catcher', async () => {- // Project tab-session state is hand-mirrored across app, desktop bridge,- // IPC, and main persistence. If one copy gains a field without the- // others, desktop session restore silently truncates data at the boundary.+ // Project tab-session state remains independently shaped in the app,+ // desktop IPC, and main persistence. The host bridge declaration itself+ // is canonical in core and both consumer paths re-export it.const appEditorTabsPath = join(__dirname,'..',@@ -785,22 +497,10 @@ describe('M1 smoke', () => {'editor','editor-tabs.ts',);- const appBridgePath = join(- __dirname,- '..',- '..',- '..',- 'app',- 'src',- 'lib',- 'desktop-bridge-types.ts',- );- const desktopBridgePath = join(__dirname, '..', '..', 'src', 'shared', 'bridge-contract.ts');+ const coreBridgePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');const ipcChannelsPath = join(__dirname, '..', '..', 'src', 'shared', 'ipc-channels.ts');const stateStorePath = join(__dirname, '..', '..', 'src', 'main', 'state-store.ts');- const coreBridgePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');const { readFileSync } = await import('node:fs');-const extractInterfaceFields = (src: string, interfaceName: string): Set<string> => {const names = new Set<string>();const lines = src.split('\n');@@ -837,13 +537,9 @@ describe('M1 smoke', () => {),},{- label: 'app/desktop-bridge-types.ts (ProjectSessionState)',- fields: extractInterfaceFields(readFileSync(appBridgePath, 'utf-8'), 'ProjectSessionState'),- },- {- label: 'desktop/bridge-contract.ts (ProjectSessionState)',+ label: 'core/desktop-bridge.ts (ProjectSessionState)',fields: extractInterfaceFields(- readFileSync(desktopBridgePath, 'utf-8'),+ readFileSync(coreBridgePath, 'utf-8'),'ProjectSessionState',),},@@ -861,13 +557,6 @@ describe('M1 smoke', () => {'ProjectSessionState',),},- {- label: 'core/desktop-bridge.ts (ProjectSessionState)',- fields: extractInterfaceFields(- readFileSync(coreBridgePath, 'utf-8'),- 'ProjectSessionState',- ),- },] as const;for (const source of sources) {diff --git a/packages/desktop/tests/main/theme-handler.test.ts b/packages/desktop/tests/main/theme-handler.test.tsindex 1e1711085..388f06a49 100644--- a/packages/desktop/tests/main/theme-handler.test.ts+++ b/packages/desktop/tests/main/theme-handler.test.ts@@ -9,7 +9,7 @@* via the show-gate, not cached.* - Defensively rejects non-OkThemeSource values at the IPC sender +* imperative shell boundary. Typed IPC should prevent this in production- * but a future bridge-contract divergence at any of the three mirrors+ * but a future divergence from the canonical core bridge declaration* (or a non-typed IPC fallback) would land here.*/diff --git a/packages/desktop/tests/preload/update-listeners.test.ts b/packages/desktop/tests/preload/update-listeners.test.tsindex 35e223122..af0f6f0cc 100644--- a/packages/desktop/tests/preload/update-listeners.test.ts+++ b/packages/desktop/tests/preload/update-listeners.test.ts@@ -3,22 +3,9 @@ import { describe, expect, test, vi } from 'vitest';/*** update-listener preload-pattern test.*- * The preload file (`src/preload/index.ts`) imports `electron`'s- * `contextBridge` / `ipcRenderer` which cannot be loaded under `bun test`.- * We cannot test the preload module directly — same constraint that- * `bridge.test.ts` works around by testing the `createInvoker` factory- * instead of the preload export.- *- * This file exercises the same listener-subscribe / unsubscribe pattern the- * preload uses for its three new event subscriptions (`onUpdateDownloaded`,- * `onWhatsNew`, `onUpdateStuckHint`) against a fake ipcRenderer. Failing this- * test means the pattern itself is broken — which would break all 5 listeners- * in the bridge, not just the three. Passing this, plus the existing- * drift-catcher in `tests/integration/m1-smoke.test.ts` (structural shape- * across 3 copies) and the channel-name gate in `tests/preload/bridge.test.ts`- * (channel names match declared EventChannels), constitutes the "unsubscribe- * closure detaches the listener" without booting a real- * Electron context.+ * Exercises the listener subscribe/unsubscribe pattern used by the preload's+ * update events against a fake ipcRenderer. This isolates the reference-+ * identity behavior without booting an Electron process.*/type FakeListener = (_event: unknown, payload: unknown) => void;diff --git a/packages/desktop/tests/smoke/theme-sync.e2e.ts b/packages/desktop/tests/smoke/theme-sync.e2e.tsindex e2c4a8f15..e91884367 100644--- a/packages/desktop/tests/smoke/theme-sync.e2e.ts+++ b/packages/desktop/tests/smoke/theme-sync.e2e.ts@@ -125,7 +125,7 @@ test.describe('chrome-modernization theme-sync smoke', () => {// Bridge wired in the editor renderer — confirms preload exposed// `window.okDesktop` AND the bridge carries the theme methods. If the- // contextBridge import or one of the three bridge-file mirrors+ // contextBridge import, compatibility shim, or canonical contract// regressed, this fails fast.const bridgeShape = await editorPage.evaluate(() => ({hasBridge: typeof window.okDesktop !== 'undefined',diff --git a/packages/desktop/tests/unit/bridge-contract-types.test.ts b/packages/desktop/tests/unit/bridge-contract-types.test.tsdeleted file mode 100644index 89a7a12ab..000000000--- a/packages/desktop/tests/unit/bridge-contract-types.test.ts+++ /dev/null@@ -1,109 +0,0 @@-/**- * `OkDesktopBridge` duplication — structural-equivalence gate.- *- * The bridge interface lives in three separate packages by design- * (core → canonical, desktop/src/shared → runtime consumer, app/src/lib →- * renderer consumer). The sibling `m1-smoke.test.ts` asserts the three- * files declare the same top-level member NAMES. This test is the- * signature-equality complement — two copies with the same members but- * divergent argument/return types (e.g. `openFolder(): Promise<string>`- * vs `Promise<string | null>`) pass the name check but slip through as- * runtime "null where string was expected" failures.- *- * Implementation: `Eq<X, Y>` is the classic TypeScript "types are- * mutually assignable" pair, using a dependent-variance trick on a- * generic function type. If the shapes diverge, the constant- * assignments `const _coreEqDesktop: Eq<Core, Desktop> = true` produce- * compile errors at the literal `true` (type narrows to `false`). This- * failure mode works at PR time via `turbo run typecheck`, not just- * when someone happens to run the bun test.- *- * Test-file scope: cross-package imports are permissible here because- * test files are not shipped in the production bundle.- */--import { describe, expect, test } from 'vitest';-import type {- OkDesktopBridge as AppBridge,- OkMenuDispatchRequest as AppMenuDispatchRequest,- OkMenuRendererSnapshot as AppMenuRendererSnapshot,-} from '../../../app/src/lib/desktop-bridge-types.ts';-import type {- OkDesktopBridge as CoreBridge,- OkMenuDispatchRequest as CoreMenuDispatchRequest,- OkMenuRendererSnapshot as CoreMenuRendererSnapshot,- OkEditorViewMenuStateSnapshot as CoreViewMenuState,-} from '../../../core/src/desktop-bridge.ts';-import type {- OkMenuDispatchRequest as BridgeMenuDispatchRequest,- OkMenuRendererSnapshot as BridgeMenuRendererSnapshot,- OkEditorViewMenuStateSnapshot as BridgeViewMenuState,- OkDesktopBridge as DesktopBridge,-} from '../../src/shared/bridge-contract.ts';-import type {- MenuDispatchRequest as IpcMenuDispatchRequest,- MenuRendererSnapshot as IpcMenuRendererSnapshot,- EditorViewMenuStateSnapshot as IpcViewMenuState,-} from '../../src/shared/ipc-channels.ts';--type Eq<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false;--describe('OkDesktopBridge structural equivalence (F19)', () => {- test('core ≡ desktop (method signatures)', () => {- const _coreEqDesktop: Eq<CoreBridge, DesktopBridge> = true;- expect(_coreEqDesktop).toBe(true);- });-- test('core ≡ app (method signatures)', () => {- const _coreEqApp: Eq<CoreBridge, AppBridge> = true;- expect(_coreEqApp).toBe(true);- });-- test('desktop ≡ app (method signatures)', () => {- const _desktopEqApp: Eq<DesktopBridge, AppBridge> = true;- expect(_desktopEqApp).toBe(true);- });-});--describe('EditorViewMenuStateSnapshot 4-way structural equivalence', () => {- test('core ≡ bridge-contract (OkEditorViewMenuStateSnapshot)', () => {- const _eq: Eq<CoreViewMenuState, BridgeViewMenuState> = true;- expect(_eq).toBe(true);- });-- test('core ≡ ipc-channels (EditorViewMenuStateSnapshot)', () => {- const _eq: Eq<CoreViewMenuState, IpcViewMenuState> = true;- expect(_eq).toBe(true);- });-});--describe('MenuDispatchRequest / MenuRendererSnapshot 4-way structural equivalence', () => {- // Same lockstep contract as EditorViewMenuStateSnapshot above: the- // ipc-channels copy is reached only through the channel-args layer, so a- // field added to the bridge copies but dropped there assigns silently- // (superset → subset) and main never sees it. The `role`/`command` unions- // are covered transitively — they are members of the request union.- test('core ≡ bridge-contract ≡ app (OkMenuDispatchRequest)', () => {- const _coreBridge: Eq<CoreMenuDispatchRequest, BridgeMenuDispatchRequest> = true;- const _coreApp: Eq<CoreMenuDispatchRequest, AppMenuDispatchRequest> = true;- expect(_coreBridge).toBe(true);- expect(_coreApp).toBe(true);- });-- test('core ≡ ipc-channels (MenuDispatchRequest)', () => {- const _eq: Eq<CoreMenuDispatchRequest, IpcMenuDispatchRequest> = true;- expect(_eq).toBe(true);- });-- test('core ≡ bridge-contract ≡ app (OkMenuRendererSnapshot)', () => {- const _coreBridge: Eq<CoreMenuRendererSnapshot, BridgeMenuRendererSnapshot> = true;- const _coreApp: Eq<CoreMenuRendererSnapshot, AppMenuRendererSnapshot> = true;- expect(_coreBridge).toBe(true);- expect(_coreApp).toBe(true);- });-- test('core ≡ ipc-channels (MenuRendererSnapshot)', () => {- const _eq: Eq<CoreMenuRendererSnapshot, IpcMenuRendererSnapshot> = true;- expect(_eq).toBe(true);- });-});diff --git a/packages/desktop/tests/unit/desktop-host-contract-single-source.test.ts b/packages/desktop/tests/unit/desktop-host-contract-single-source.test.tsnew file mode 100644index 000000000..7c698d686--- /dev/null+++ b/packages/desktop/tests/unit/desktop-host-contract-single-source.test.ts@@ -0,0 +1,162 @@+import { join } from 'node:path';+import { Node, Project, type SourceFile, SyntaxKind } from 'ts-morph';+import { describe, expect, test } from 'vitest';+import corePackageJson from '../../../core/package.json';++const packagesRoot = join(__dirname, '..', '..', '..');+const coreBridge = join(packagesRoot, 'core', 'src', 'desktop-bridge.ts');+const appShim = join(packagesRoot, 'app', 'src', 'lib', 'desktop-bridge-types.ts');+const desktopShim = join(packagesRoot, 'desktop', 'src', 'shared', 'bridge-contract.ts');+const ipcChannels = join(packagesRoot, 'desktop', 'src', 'shared', 'ipc-channels.ts');+const coreLeaf = '@inkeep/open-knowledge-core/desktop-bridge';+const ipcTypeAliases = [+ ['OkEditorActiveTargetSnapshot', 'EditorActiveTargetSnapshot'],+ ['OkEditorViewMenuStateSnapshot', 'EditorViewMenuStateSnapshot'],+ ['OkMenuDispatchRole', 'MenuDispatchRole'],+ ['OkMenuDispatchCommand', 'MenuDispatchCommand'],+ ['OkMenuDispatchRequest', 'MenuDispatchRequest'],+ ['OkMenuRendererSnapshot', 'MenuRendererSnapshot'],+] as const;+const ipcTypeReexports = ['OkSharingStatusResult', 'OkSharingSetModeResult'] as const;++const project = new Project({+ skipFileDependencyResolution: true,+ skipLoadingLibFiles: true,+ skipAddingFilesFromTsConfig: true,+ compilerOptions: { noLib: true },+});++const contractSources = project.addSourceFilesAtPaths([+ join(packagesRoot, 'core', 'src', '**', '*.{ts,tsx}'),+ join(packagesRoot, 'app', 'src', '**', '*.{ts,tsx}'),+ join(packagesRoot, 'desktop', 'src', '**', '*.{ts,tsx}'),+]);+const coreBridgeSource = project.getSourceFileOrThrow(coreBridge);+const appShimSource = project.addSourceFileAtPath(appShim);+const desktopShimSource = project.addSourceFileAtPath(desktopShim);+const ipcChannelsSource = project.addSourceFileAtPath(ipcChannels);+const coreIndexSource = project.addSourceFileAtPath(join(packagesRoot, 'core', 'src', 'index.ts'));+const buildConfigSource = project.addSourceFileAtPath(+ join(packagesRoot, 'core', 'tsdown.config.ts'),+);++function expectTypeOnlyExportStar(sourceFile: SourceFile): void {+ const exportDeclaration = sourceFile+ .getExportDeclarations()+ .find((declaration) => declaration.getModuleSpecifierValue() === coreLeaf);++ expect(exportDeclaration).toBeDefined();+ expect(exportDeclaration?.isTypeOnly()).toBe(true);+ expect(exportDeclaration?.isNamespaceExport()).toBe(true);+ expect(exportDeclaration?.hasNamedExports()).toBe(false);+}++function isWindowGlobalAugmentation(declaration: import('ts-morph').InterfaceDeclaration): boolean {+ return (+ declaration.getName() === 'Window' &&+ declaration.getFirstAncestorByKind(SyntaxKind.ModuleDeclaration)?.getName() === 'global'+ );+}++describe('desktop host contract single source', () => {+ test('keeps the bridge declaration and package leaf in core', () => {+ const bridgeDeclarations = contractSources.flatMap((sourceFile) =>+ sourceFile+ .getDescendantsOfKind(SyntaxKind.InterfaceDeclaration)+ .filter((declaration) => declaration.getName() === 'OkDesktopBridge'),+ );++ expect(+ bridgeDeclarations.map((declaration) => declaration.getSourceFile().getFilePath()),+ ).toEqual([coreBridge]);++ for (const shim of [appShimSource, desktopShimSource]) {+ expectTypeOnlyExportStar(shim);++ const localInterfaces = shim+ .getDescendantsOfKind(SyntaxKind.InterfaceDeclaration)+ .filter((declaration) => !isWindowGlobalAugmentation(declaration));+ expect(localInterfaces).toHaveLength(0);++ for (const alias of shim.getDescendantsOfKind(SyntaxKind.TypeAliasDeclaration)) {+ expect(Node.isTypeReference(alias.getTypeNodeOrThrow())).toBe(true);+ }+ }++ expect(corePackageJson.exports['./desktop-bridge']).toEqual({+ development: './src/desktop-bridge.ts',+ types: './src/desktop-bridge.ts',+ default: './dist/desktop-bridge.mjs',+ });++ const desktopEntry = buildConfigSource+ .getDescendantsOfKind(SyntaxKind.PropertyAssignment)+ .filter((property) => {+ const name = property.getNameNode();+ return Node.isStringLiteral(name) && name.getLiteralText() === 'desktop-bridge';+ });+ expect(desktopEntry).toHaveLength(1);+ expect(desktopEntry[0]?.getInitializerIfKind(SyntaxKind.StringLiteral)?.getLiteralText()).toBe(+ 'src/desktop-bridge.ts',+ );+ });++ test('keeps desktop bridge types off the core barrel', () => {+ const bridgeLeafDeclarations = [...coreBridgeSource.getExportedDeclarations()]+ .filter(([, declarations]) =>+ declarations.some((declaration) => declaration.getSourceFile() === coreBridgeSource),+ )+ .map(([typeName]) => typeName);+ const coreBarrelExports = coreIndexSource.getExportedDeclarations();+ expect(bridgeLeafDeclarations.filter((typeName) => coreBarrelExports.has(typeName))).toEqual(+ [],+ );+ });++ test('keeps IPC payloads as aliases of the core contract', () => {+ const coreImport = ipcChannelsSource+ .getImportDeclarations()+ .find((declaration) => declaration.getModuleSpecifierValue() === coreLeaf);+ expect(coreImport).toBeDefined();+ expect(coreImport?.isTypeOnly()).toBe(true);++ const importedCanonicalTypes = new Map(+ coreImport+ ?.getNamedImports()+ .map((specifier) => [+ specifier.getName(),+ specifier.getAliasNode()?.getText() ?? specifier.getName(),+ ]),+ );++ for (const [canonicalName, localName] of ipcTypeAliases) {+ expect(importedCanonicalTypes.get(canonicalName)).toBe(canonicalName);++ const alias = ipcChannelsSource.getTypeAlias(localName);+ expect(alias).toBeDefined();+ expect(alias?.isExported()).toBe(true);++ const typeNode = alias?.getTypeNode();+ if (!Node.isTypeReference(typeNode)) {+ throw new TypeError(`${localName} must be a type-reference alias`);+ }++ expect(typeNode.getTypeName().getText()).toBe(canonicalName);+ expect(typeNode.getTypeArguments()).toHaveLength(0);+ }++ const directTypeReexports = new Set(+ ipcChannelsSource+ .getExportDeclarations()+ .filter((declaration) => declaration.isTypeOnly() && !declaration.getModuleSpecifier())+ .flatMap((declaration) =>+ declaration.getNamedExports().map((specifier) => specifier.getName()),+ ),+ );++ for (const typeName of ipcTypeReexports) {+ expect(importedCanonicalTypes.get(typeName)).toBe(typeName);+ expect(directTypeReexports.has(typeName)).toBe(true);+ }+ });+});diff --git a/packages/desktop/tests/unit/local-op-types-drift.test.ts b/packages/desktop/tests/unit/local-op-types-drift.test.tsindex b3fc97720..15e3a103d 100644--- a/packages/desktop/tests/unit/local-op-types-drift.test.ts+++ b/packages/desktop/tests/unit/local-op-types-drift.test.ts@@ -1,13 +1,12 @@/*** Local-op type-drift catcher across the server ↔ desktop bridge boundary.*- * Server-side runner output types and desktop-side bridge-contract types+ * Server-side runner output types and the desktop host contract types* are duplicated by design:* - Server is published as a standalone library and can't depend on* desktop.- * - Desktop's bridge contracts avoid importing server to keep server's- * compilation tree (markdown / CRDT) out of the renderer build —- * rationale lives in `bridge-contract.ts`'s top JSDoc.+ * - The desktop host contract avoids importing server to keep server's+ * compilation tree (markdown / CRDT) out of the renderer build.** Without this test, a field added on one side (e.g. `scopes: string[]`* on `AuthStatusResponse`) silently propagates to the IPC handler return@@ -16,10 +15,8 @@* (`handle()` registration + preload `invoke()` assignment) only catches* removals + breaking changes, not additive drift.*- * Pattern: `Eq<X, Y>` mutual-assignability invariant — same trick as- * `bridge-contract-types.test.ts` (the 3-mirror drift catcher).- * Failures surface during `turbo run typecheck` at the literal `true`- * assignment, not just at `bun test` execution time.+ * Pattern: `Eq<X, Y>` mutual-assignability invariant, complementing the+ * source-only core bridge contract guard.*/import type {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 92d7dc358..f4ac96e96 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1141,6 +1141,9 @@ importers:electron-vite:specifier: ^6.0.0-beta.1version: 6.0.0-beta.1([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ ts-morph:+ specifier: ^28.0.0+ version: 28.0.0typescript:specifier: ^5.7.2version: 5.9.3