Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(links): nodeterm://open links from other apps, behind a feature flag (off by default) (#1212)
Senzaikene07a521ecb79
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4f67186c5..e360f84aa 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -8844,6 +8844,51 @@ unix-socket forward and dev-server `-L` forward over it. POSIX keeps OpenSSH unt(`applyPhoneReadAck`, the ack sweeper's body), plus `fs.browse` (home-jailed, dirs only) and`pty.capture`; `host.info` lists them. All additive — an old phone keeps its old path.+## `nodeterm://` links (another app asks to open a node)++`nodeterm://open?agent=…&project=…|project-cwd=…&cwd=…&prompt=…|prompt-file=…&title=…&source=…`+lets an app with no node identity (a review tool, a script, a bookmark) ask for ONE node; the human+approves every link in a confirm sheet. Spec + as-built decisions:+`docs/superpowers/specs/2026-10-13-open-link-design.md`. Parser `@shared/open-link`, service+`main/open-link.ts` (electron-free, tested), wiring `main/open-link-wiring.ts`, sheet+`components/OpenLinkSheet.tsx`. Invariants:+- **Behind a flag, OFF by default** (`settings.allowOpenLinks`, Settings → Behavior "Allow+ nodeterm:// links"). Main reads it on every link and again on accept; off, a link is not even+ parsed — one notice says where to turn it on. The scheme is still registered, so the notice is+ what a click meets.+- **The parser refuses, never drops**: unknown/duplicate params, over-cap values, relative paths,+ controls. No canvas-control power flags exist here; `source` is display-only.+- **Paths are stat'ed before the sheet, so a path may not reach another machine.** A POSIX-form+ path with a backslash is refused (Windows reads `/\host\share` as UNC and a stat there+ authenticates to that host — NTLM), as are UNC and the macOS automount roots `/net`, `/Network`.+- **Nothing the sheet would not show reaches the agent**: `hasHiddenText` (every `\p{Cf}` except+ ZWJ, plus C1 — bidi overrides, zero-width, Unicode TAG "ASCII smuggling") refuses an inline+ prompt, a prompt file's text, every path and every label. The sheet prints the prompt's size.+- **The permission mode shown is the one launched.** A new-project choice adopts the folder's+ committed `project.json`, so the sheet probes it (Open waits) and labels from it; a mode that+ differs at landing refuses. `bypassPermissions` gets a warning in the sheet.+- **The prompt file is read from ONE non-blocking open** (no stat first, `O_NONBLOCK` so a FIFO+ cannot park a thread, looped read to EOF/cap). A project whose folder changed while the sheet was+ up refuses on accept; `/`, the home folder and its ancestors are never offered as a new project.+- **Main is the authority**: it resolves project candidates from ITS workspace index (SSH and+ handed-off projects never offered), stats the cwd, reads `prompt-file`, and on accept re-checks+ the renderer's choice (a candidate id or the offered new-project folder), re-reads the file,+ refuses if it changed, and copies it into `<userData>/launch-prompts`. Requests are single use and+ expire after 10 min.+- **Delivery**: `open-url` registered in `will-finish-launching` (macOS), argv on cold start and in+ `second-instance` (Windows/Linux); held until the renderer calls `openLink.ready()`, held again on+ every page death (`clearRendererKeyState`). 5 links a minute; a second link replaces only an+ untouched sheet. The window raise is the shared `raiseForUserLaunch`.+- **The sheet**: Enter never opens, nor Space on the focused button (`detail === 0` is ignored);+ Open is disabled for 1 s, then a pointer click only. A second link replaces the sheet only within+ that first second and untouched — after that it is dropped (reading fires no event). An accepted+ link waiting for its project to load is dropped after 30 s, never created later.+- `pair`/`join` links open the existing code prompt pre-filled; never auto-connect.+- Desktop only. Server Edition stub is inert; `open-link:` is a host-only prefix. A dev run registers+ the scheme only with `NODETERM_DEV_PROTOCOL=1`. An `NT_MULTI` sandbox takes links (argv,+ `second-instance`, `open -a <Electron.app> 'nodeterm://…'`) only with that variable and never+ registers the scheme — that is the live-test setup beside an installed app.+## Push webhook (a script or CI job rings the paired phone)Settings → Phone → **Push webhook** mints a per-host bearer token; anything that can run `curl`diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex cc2142d3e..d80d6a928 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1174,6 +1174,20 @@ Grok billing diagnostics must keep HTTP codes and safe failure categories per biwas typed. Nothing may treat it as "safe to resend": the phone keeps the draft, re-reads, and letsthe user decide. Only `'refused'` means nothing was typed.+**`nodeterm://` links.** A link proves nothing about who sent it (any web page can build one), so+the confirm sheet is its whole authority. It is off unless the user turns on+`settings.allowOpenLinks`, and main checks that flag itself. Four rules get a PR sent back:+- **No power flags.** A link opens one node in the project's default permission mode. Never add a+ param for a permission mode, `--after`, a model, a count or "open without asking" (the signed-link+ design in `docs/superpowers/specs/2026-10-13-open-link-design.md` is the only planned way to skip+ the sheet).+- **The renderer only chooses.** Its answer is a candidate id main offered, "new project", and a+ title. The cwd and prompt in the final open come from main (`src/main/open-link.ts`), never the+ reply.+- **Enter never opens it.** Only a pointer click on Open, after the 1 s arm.+- **What the human sees is what runs.** No hidden Unicode in a prompt or path (`hasHiddenText`), no+ path that can reach another machine, and the permission mode shown is re-checked at landing.+## User-owned agent settings**Nothing writes into an agent's global config except `src/core/agent-integrations.ts`** (issuediff --git a/docs/superpowers/specs/2026-10-13-open-link-design.md b/docs/superpowers/specs/2026-10-13-open-link-design.mdnew file mode 100644index 000000000..d18f2fc3f--- /dev/null+++ b/docs/superpowers/specs/2026-10-13-open-link-design.md@@ -0,0 +1,188 @@+# Design: `nodeterm://open` links++**Date:** 2026-10-13+**Status:** Built (PR 1 + PR 2). Signed links are not built. See "As built" at the end.+**First consumer:** an external code-review tool's "Discuss" button.++## Problem++An app outside nodeterm, like a review tool, a script or a bookmark, has no way to open a session on the canvas. Canvas control (`open-claude`, `open-terminal`, …) only answers callers that carry a node identity. That is on purpose: a process without a node has nothing to prove who it is. So today such an app can only copy a `claude …` command for the user to paste into a terminal node.++A URL scheme fixes this without weakening canvas control. The link proves nothing about who sent it. Instead, **the human approves every link in a confirm sheet** before anything opens. The link only fills in the form.++## The link++```+nodeterm://open?agent=claude+ &project=<project id> (or project-cwd=<absolute path>, or neither)+ &cwd=<absolute path>+ &prompt=<url-encoded text> (or prompt-file=<absolute path>)+ &title=<node title>+ &source=<short label, e.g. my-tool>+```++| Param | Required | Rules |+|---|---|---|+| `agent` | yes | One of the agents nodeterm can already open: `claude`, `codex`, `gemini`, `opencode`, … or `terminal`. Unknown means the link is refused. |+| `project` | no | A project id from the workspace store. See "Choosing the project". |+| `project-cwd` | no | Absolute path. Matches the project whose `cwd` equals it. Can't be combined with `project`. |+| `cwd` | no | Absolute, existing directory. Defaults to the chosen project's `cwd`. |+| `prompt` | no | The first message for the agent. Capped at 8 KB after decoding. |+| `prompt-file` | no | Absolute path to a regular file of at most 64 KB, read when the user accepts. Lets a caller pass a long prompt without a giant URL. Can't be combined with `prompt`. |+| `title` | no | The node title, max 80 characters. `open-claude` has no title option today (`canvas-control-core.ts:865`), so this adds one, or renames the node right after it's created. |+| `source` | no | Display-only label shown in the sheet. It is never trusted for anything, because any web page can claim any `source`. |++The parser rejects:+- unknown params+- the same param given twice+- any value over its size cap+- relative paths.++It does **not** take canvas-control's power flags: `--count`, `--group`, `--after*`, `--run-now`, `--model`, `--issue`, or a permission mode. A link opens one node in the project's default permission mode. It can never ask for a looser one.++## Choosing the project++Requirement: a link must be able to name a project, and nodeterm must never quietly guess where a session goes.++1. **`project=<id>`**: that project, if it exists in the workspace store, either open or in the reopenable list (`projects.ts:246 reopenProject`). An unknown id isn't an error. The sheet says "Project not found" and shows the picker.+2. **`project-cwd=<path>`**: the project whose `cwd` is exactly that path. If several match, the picker is shown with those preselected first.+3. **Neither**: nodeterm suggests the project whose `cwd` is the longest prefix of the link's `cwd`, and falls back to the active project.++In every case the project is a **dropdown in the confirm sheet**, pre-filled from the rules above and changeable before accepting. The sheet also offers **"Open `<cwd>` as a new project"** (`projects.ts:78 openFolderProject`) when no project fits. The sheet always shows where the node will land, and the user always gets to change it.++SSH projects (`Project.ssh`) are out of scope for v1. They aren't offered in the picker, and a `project=` naming one says so.++If the chosen project isn't the one on screen, accepting switches to it (`setActive`). The new node is placed at the centre of that project's viewport. It has no parent edge, since no node asked for it.++## The confirm sheet++The sheet is a modal in the renderer. A native `dialog.showMessageBox` can't hold a project picker and a scrollable prompt. It shows:++- **Header:** "Open a Claude session?", plus `from <source>` in muted text with a note that the label is unverified.+- **Fields:**+ - Project (dropdown), working directory (with a warning if it's outside the project's `cwd`), and title.+ - The **full prompt**, read-only and scrollable. With `prompt-file`, it also shows the file path.+ - The permission mode the session will start in (the project default).+- **Buttons:** **Open** and **Cancel**. Enter doesn't accept until the sheet has been open for about 1 second, so a click or keypress that was already happening can't approve a link that just arrived.++Only one sheet is shown at a time. A second link that arrives while a sheet is up replaces it only if the sheet is untouched. Otherwise it is dropped with a toast. More than 5 links in a minute and the rest are dropped with a toast, so a page can't spam dialogs.++## Plumbing++All of this is in the desktop app only. The Server Edition and relay are untouched.++1. **Register the scheme.**+ - Add `"protocols": [{ "name": "nodeterm", "schemes": ["nodeterm"] }]` to the electron-builder `build` block (`package.json:38`). That writes `CFBundleURLTypes` on macOS.+ - Call `app.setAsDefaultProtocolClient('nodeterm')` at startup. Dev builds pass `process.execPath` and the script path so a dev run can be the handler.+2. **Receive the URL.**+ - **macOS:** `app.on('open-url')`. Register it in `will-finish-launching` so a link that cold-starts the app isn't lost. Hold the URL until the main window and renderer are ready.+ - **Windows/Linux:** the URL arrives in `process.argv` on first launch and in the `second-instance` argv afterwards. The current `second-instance` handler (`index.ts:825`) only focuses the window, so extend it to scan argv for `nodeterm://`.+3. **Parse in a pure module.** Add `src/shared/open-link.ts`, with no electron or fs imports, unit-tested on its own like `pairing.ts`. It returns a typed request or a refusal reason.+4. **Validate in main.** Main checks:+ - the `cwd` exists and is a directory+ - `prompt-file` is a regular file under the cap+ - the `agent` is installed+ - the named project resolves.++ The renderer never receives a path main hasn't checked, which matches the posture of the `open-project` gate (`index.ts:4231`).+5. **Ask.** Main focuses the window and sends `open-link:request` with the validated request and the resolved project candidates. The renderer shows the sheet and replies with the human's choices (project id, cwd, title) or a cancel.+6. **Open.** Main re-checks the reply. The renderer is the more attackable half: it can't swap in a different cwd or prompt, it can only pick among the candidates main offered or the "new project" folder. Main then calls the same node-creation path the `open-claude` dispatch uses (`Canvas.tsx:14046`), tagged `origin: 'link'` so it has no caller identity and doesn't touch the grant ledger (`project-grants.ts`).++**Existing `nodeterm://pair` and `nodeterm://join` strings.** Once the scheme is registered, clicking one of these opens nodeterm. Route them to the existing pairing and join screens with the code pre-filled. Never auto-accept, because those flows have their own approval. Any other host (`nodeterm://anything-else`) is ignored with a toast.++## The calling app's side++- **The button:** a "Discuss in nodeterm" action becomes a plain `<a href="nodeterm://open?…">`. It needs no server round-trip, apart from writing a prompt file when the prompt is long.+- **The project:** the app keeps its own map from its repositories to nodeterm project ids. Without a mapping, it sends `project-cwd=<path of the repository>`. If that matches nothing, the sheet's picker covers it. To make ids easy to copy, nodeterm adds **Copy project id** to the project tab's menu.+- **Fallbacks:** the app keeps its existing copy-a-command path for when nodeterm isn't running or isn't the registered handler.++## Later: signed links (optional)++If the sheet gets tedious for links the user makes themselves, add signed links:+- Nodeterm stores an HMAC key per trusted source in the system keychain, created from Settings, which the user pastes into the calling app once.+- The link carries `ts` and `sig` (HMAC over the canonical params plus `ts`). Nodeterm accepts a signature for 2 minutes and only once.+- A valid signature shows **"Verified: <source name>"** instead of the unverified label. It can also unlock an opt-in **"Open without asking"** for that source, stored machine-local in the same way as `trigger-arm-store.ts`.++Unsigned links always get the sheet.++## Tests++- **`open-link.ts`:** every param, cap, duplicate, unknown param, the mutually exclusive pairs, and encoding edge cases. Encoding cases are spaces, `+` versus `%20`, unicode, and `%00`.+- **Project resolution:** id hit, id miss, a `project-cwd` that matches exactly, several, or none, longest-prefix inference, SSH projects excluded.+- **Main validation:** a missing cwd, a cwd that is a file, a prompt file over the cap or not a regular file, an agent that isn't installed.+- **Renderer reply tampering:** a cwd or project that main didn't offer is refused.+- **Delivery:** a cold-start `open-url` is held until the renderer is ready; `second-instance` argv is parsed; links over the rate limit are dropped.+- **Manual:** on macOS, `open 'nodeterm://open?agent=claude&project-cwd=…&prompt=hi'` with the app closed, open, and on a different project.++## Suggested PR split++1. **Parser and scheme registration:** the `open-link.ts` module and its tests, the scheme registration, and `open-url`/argv receipt. It only logs the parsed request and routes `pair`/`join`.+2. **Confirm sheet and node creation:** the sheet, the project picker, main re-validation, the `origin: 'link'` open path, and the `title` support.+3. **Calling app:** switch its button to the link and add its project map. This change is outside nodeterm.+4. **Later:** signed links.++## Open questions++- Should `agent=terminal` with a `prompt` be allowed? Typing text into a shell is closer to running a command than to sending a chat message. The proposal is to refuse `prompt` for `terminal` in v1.+- Which Claude account should the session use? The proposal is the project's `defaultAccountId`, shown in the sheet, with no link param for it.+- Should the node join the project's kanban board in a column? The proposal is no; it lands like any new node.++## As built (2026-10-13)++Files: `src/shared/open-link.ts` (parser, project resolution, wire types), `src/main/open-link.ts`+(delivery, rate limit, validation, accept re-check; electron-free), `src/main/open-link-wiring.ts`+(fs/PATH/launch-prompt deps + three raw `ipcMain` handlers), `src/renderer/components/OpenLinkSheet.tsx`+and `src/renderer/lib/openLinkSheet.ts` (the sheet), and the Canvas wiring next to "Open recent".++Decisions where the proposal left room, or where the build differs from it:++- **Feature flag, off by default.** `settings.allowOpenLinks` (Settings → Behavior, "Allow+ nodeterm:// links"). Main checks it on every link before parsing and again on accept (switching+ it off while a sheet is up refuses that sheet's Open). Off, a click shows one notice naming the+ setting. The scheme is registered either way.++- **Enter never opens.** The proposal let Enter accept after ~1 s. Every dialog nodeterm raises on+ someone else's behalf answers only to a click (components/confirm-key), so this one does too: the+ Open button is disabled for 1 s, then needs a click. Escape cancels (after 500 ms, never a held key).+- **The agent check is a warning, not a refusal.** A launch-command override can make the bare+ binary irrelevant, so "`claude` was not found on this machine's PATH" is shown in the sheet.+- **Open questions answered as proposed:** `agent=terminal` refuses `prompt`/`prompt-file`; the+ account is the project's `defaultAccountId` (shown in the sheet for Claude); the node does not+ join a kanban column.+- **`prompt-file` is copied.** Main reads it when the link arrives (to show it), reads it again on+ accept, refuses if it changed, and copies the text into nodeterm's own launch-prompt store+ (`<userData>/launch-prompts`, 30-day TTL). The pane reads the copy, so the session gets exactly the+ text the human saw. The structure (newlines) is kept. An inline `prompt` is flattened and spilled+ to a file when it is too long for a typed line (#706), like every other open.+- **Main resolves projects from its own workspace index**, never from the renderer. The sheet replies+ with a candidate id or "new project" plus a title; main re-checks the id is still in the index and+ still offerable, re-stats the cwd, and the cwd and prompt in the final open come from main.+- **A pending request is single use** (forgotten on the first accept, refused or not) and expires+ after 10 minutes; at most 4 are kept.+- **Delivery.** macOS `open-url` is registered in `will-finish-launching`; Windows/Linux read+ `process.argv` and `second-instance`'s argv. Links are held until the renderer calls+ `openLink.ready()`, and held again from a main-frame navigation / renderer crash / window close+ until the next page says ready. The rate limit (5 a minute) counts every link, held ones included.+- **Registration.** `build.protocols` in package.json (CFBundleURLTypes on macOS, the desktop entry+ on Linux) plus `app.setAsDefaultProtocolClient('nodeterm')` in packaged builds. A dev run+ registers only with `NODETERM_DEV_PROTOCOL=1` (it would otherwise take the scheme from the+ installed app). NT_MULTI sandboxes take links only with `NODETERM_DEV_PROTOCOL=1` and never+ register the scheme (live test: `open -a node_modules/electron/dist/Electron.app 'nodeterm://…'`).+- **pair/join links** open the existing "paste the code" prompt pre-filled; the human presses+ Connect, and the existing SAS compare / join flow runs from there.+- **Copy project id** is on the project tab's menu (local projects only).+- **Server Edition / relay:** not applicable. The bridge stub never fires and refuses `accept`; the+ `open-link:` channels are host-only.++- **Hardening from review (before the PR):** a POSIX path with a backslash, UNC, and `/net` /+ `/Network` are refused (a pre-sheet stat must not reach another machine); hidden Unicode+ (`\p{Cf}` except ZWJ, C1) is refused in prompts, prompt files, paths and labels; the prompt file+ is read from one non-blocking open; the sheet probes a new project's committed permission mode and+ the launch refuses if it differs; a sheet is replaced only in its first second; Space does not+ activate Open; a project whose folder changed refuses on accept; `/` and the home folder are never+ offered as a new project; an accepted link that has not landed in 30 s is dropped.++Not built: signed links; a `title` option on the `open-claude` control verb (the link path sets the+title itself); a device run on macOS / Windows / Linux of a real click (static checks and unit+tests, plus one live macOS run: a dev sandbox, `open -a … 'nodeterm://open?agent=claude&project-cwd=…'`,+sheet confirmed, new project + Claude node opened and answered).diff --git a/package.json b/package.jsonindex 37328f616..a7779cd80 100644--- a/package.json+++ b/package.json@@ -39,6 +39,14 @@"build": {"appId": "com.nodeterm.app","productName": "nodeterm",+ "protocols": [+ {+ "name": "nodeterm",+ "schemes": [+ "nodeterm"+ ]+ }+ ],"directories": {"output": "dist","buildResources": "build"diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 9c8f2080f..3bc4261ec 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -1955,6 +1955,23 @@ export class WorkspaceStore {.map((e) => ({ id: e.id, ssh: e.ssh as NonNullable<Project['ssh']> }))}+ /** Every project in the loaded index as a `nodeterm://open` link may name it (main/open-link.ts):+ * id, name, folder, closed, and the two kinds a link never offers (SSH, handed to a hosted team).+ * Undefined before the index is loaded. Sync, like `localCwdForProject`. */+ linkProjectEntries():+ | { id: string; name: string; cwd?: string; closed?: boolean; ssh?: boolean; handedOff?: boolean }[]+ | undefined {+ if (!this.index) return undefined+ return this.index.entries.map((e) => ({+ id: e.id,+ name: e.name,+ ...(e.cwd ? { cwd: e.cwd } : {}),+ ...(e.closed ? { closed: true } : {}),+ ...(e.ssh ? { ssh: true } : {}),+ ...(e.handedOffTo ? { handedOff: true } : {})+ }))+ }+/** The local folder cwd of a project by id (index lookup), or undefined for ssh/inline/unknown* projects. Sync (reads the in-memory index): the board-log router's local-vs-unsupported call. */localCwdForProject(projectId: string): string | undefined {diff --git a/src/main/index.ts b/src/main/index.tsindex 4e87db79f..336d4b99b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,4 +1,6 @@import { registerUpdatePrepIpc } from './update-prep'+import { installOpenLinks } from './open-link-wiring'+import { nodetermUrlFromArgv } from '../shared/open-link'import { createRemoteContextEnsure } from '../core/remote-context-ensure'import { isKnownRemoteCodexAccount } from '../core/remote-ssh/codex-home'import { createRemoteCodexContext, type RemoteCodexContextTarget } from '../core/remote-ssh/codex-context'@@ -536,6 +538,9 @@ let terminalFocused = falseconst clearRendererKeyState = (): void => {shortcutRecording = falseterminalFocused = false+ // The same page death ends the `nodeterm://` link listener: hold links again until the next page+ // says it is ready (a link must not be sent into a renderer that is not there to show it).+ openLinks.notReady()// The menu leg follows the same state, so it must follow it here too — otherwise a crash or a// reload while stood down would leave Window ▸ Minimize disabled with nothing left to re-enable// it, i.e. ⌘M dead app-wide. Safe before any window exists: it no-ops without a menu.@@ -927,15 +932,65 @@ const nodeSubagents = new Map<string, Set<string>>() // nodeId → active subage// "[detached (from session ...)]" dead terminals. Bail out and focus the existing window// instead. (This guards against a stray real GUI launch.)const gotSingleInstanceLock = NT_MULTI || app.requestSingleInstanceLock()++/** Bring the window forward because the USER launched us again: a second launch, or a click on a+ * `nodeterm://` link (which reaches us as a second launch on Windows/Linux, `open-url` on macOS).+ * The one raise both share — see window-raise.guard.test.ts. */+function raiseForUserLaunch(): void {+ const win = getMainWindow()+ if (!win) return+ if (win.isMinimized()) win.restore()+ win.show()+ win.focus()+}++// `nodeterm://` links (main/open-link.ts). Created before `ready` so a link that cold-starts the app+// is held until the renderer says it is listening. NT_MULTI dev sandboxes take links only when+// asked (NODETERM_DEV_PROTOCOL=1, for a live test beside the installed app) and never register the+// scheme: it belongs to the real app.+const openLinks = installOpenLinks({+ userDataDir: () => app.getPath('userData'),+ indexEntries: () => workspaceStore.linkProjectEntries(),+ loadIndex: () => workspaceStore.load({ sideline: false }),+ raise: raiseForUserLaunch,+ enabled: () => settingsStore.get().allowOpenLinks === true+})+const linksEnabled = !NT_MULTI || process.env.NODETERM_DEV_PROTOCOL === '1'+if (linksEnabled) {+ // macOS delivers a clicked link as `open-url`, including the one that launched the app — which+ // is why the listener goes on in `will-finish-launching`, before `ready`.+ app.on('will-finish-launching', () => {+ app.on('open-url', (event, url) => {+ event.preventDefault()+ openLinks.receive(url)+ })+ })+ // Windows/Linux: the link that launched us is on our own argv.+ const coldLink = nodetermUrlFromArgv(process.argv)+ if (coldLink) openLinks.receive(coldLink)+ // Register as the scheme's handler. A packaged build always; a dev run only when asked+ // (NODETERM_DEV_PROTOCOL=1), because registering the bare Electron binary would take the scheme+ // away from the installed app until it next launches.+ if (app.isPackaged) {+ app.setAsDefaultProtocolClient('nodeterm')+ } else if (!NT_MULTI && process.env.NODETERM_DEV_PROTOCOL === '1' && process.argv[1]) {+ app.setAsDefaultProtocolClient('nodeterm', process.execPath, [resolve(process.argv[1])])+ }+}+if (!gotSingleInstanceLock) {app.quit()} else {- app.on('second-instance', () => {- const win = getMainWindow()- if (!win) return- if (win.isMinimized()) win.restore()- win.show()- win.focus()+ app.on('second-instance', (_event, argv) => {+ // Windows/Linux: a link clicked while we run starts a second instance carrying it. The link+ // service raises the window itself when it has something to show, so a rate-limited link (or+ // one while links are off) does not pull the window forward.+ const url = nodetermUrlFromArgv(argv)+ if (url && linksEnabled) {+ openLinks.receive(url)+ return+ }+ if (!url) raiseForUserLaunch()})}diff --git a/src/main/open-link-wiring.ts b/src/main/open-link-wiring.tsnew file mode 100644index 000000000..4a22a43cc--- /dev/null+++ b/src/main/open-link-wiring.ts@@ -0,0 +1,138 @@+// The Electron half of `nodeterm://` links: real fs/PATH/launch-prompt dependencies for the service+// in ./open-link, and its three raw ipcMain handlers. Raw ipcMain, never the platform handler+// table: no relay peer or Server Edition client may answer this machine's link sheet, and every+// handler refuses a sender that is not the main window (host-control lists the prefix too).++import { ipcMain } from 'electron'+import { constants as fsConstants } from 'fs'+import { open as fsOpen, stat } from 'fs/promises'+import { homedir } from 'os'+import { randomUUID } from 'crypto'+import { IPC } from '../shared/ipc'+import { AGENT_CONFIG, type BuiltinAgentId } from '../shared/agents/config'+import { LAUNCH_PROMPT_FILE_PREFIX } from '../shared/launch-prompt'+import type { LinkProjectEntry } from '../shared/open-link'+import { findInLoginPath } from '../core/exec-path'+import { findAgy } from '../core/agents/hooks/antigravity'+import { saveUpload } from '../core/uploads'+import { getMainWindow, sendToMain } from './main-window'+import {+ createOpenLinkService,+ type OpenLinkChannel,+ type OpenLinkService,+ type PathKind,+ type ReadTextResult+} from './open-link'++const CHANNEL: Record<OpenLinkChannel, string> = {+ request: IPC.openLinkRequest,+ pair: IPC.openLinkPair,+ notice: IPC.openLinkNotice+}++export interface OpenLinkWiringDeps {+ userDataDir(): string+ /** The workspace index's projects, or undefined before it is loaded. */+ indexEntries(): LinkProjectEntry[] | undefined+ /** Load the index (only when it is not loaded yet). */+ loadIndex(): Promise<unknown>+ /** Bring the main window forward (a link click is a user action). */+ raise(): void+ /** `settings.allowOpenLinks`. */+ enabled(): boolean+}++async function statPath(p: string): Promise<{ kind: PathKind; size: number }> {+ try {+ const st = await stat(p)+ return { kind: st.isDirectory() ? 'dir' : st.isFile() ? 'file' : 'other', size: st.size }+ } catch {+ return { kind: 'missing', size: 0 }+ }+}++// O_NONBLOCK so opening a FIFO returns at once instead of parking a threadpool thread until a writer+// appears (POSIX only; Windows has no FIFOs at a path and Node defines no such flag there).+const READ_FLAGS = fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0)++/** Read at most `maxBytes + 1` bytes from ONE open, so an oversized file is detected without+ * reading all of it. No stat beforehand: the handle that is read is the handle that is checked. */+async function readText(p: string, maxBytes: number): Promise<ReadTextResult> {+ let fh+ try {+ fh = await fsOpen(p, READ_FLAGS)+ } catch (e) {+ const code = (e as NodeJS.ErrnoException).code+ return code === 'ENOENT' || code === 'ENOTDIR' ? { kind: 'missing' } : code === 'EISDIR' ? { kind: 'not-file' } : { kind: 'error' }+ }+ try {+ if (!(await fh.stat()).isFile()) return { kind: 'not-file' }+ const buf = Buffer.alloc(maxBytes + 1)+ let filled = 0+ // A single read may return fewer bytes than asked; loop to EOF or the cap.+ while (filled < buf.length) {+ const { bytesRead } = await fh.read(buf, filled, buf.length - filled, filled)+ if (bytesRead === 0) break+ filled += bytesRead+ }+ return { kind: 'ok', text: buf.subarray(0, filled).toString('utf8') }+ } catch {+ return { kind: 'error' }+ } finally {+ await fh.close().catch(() => undefined)+ }+}++export function installOpenLinks(deps: OpenLinkWiringDeps): OpenLinkService {+ const service = createOpenLinkService({+ statPath,+ readText,+ storePrompt: (text) =>+ saveUpload(+ deps.userDataDir(),+ `${LAUNCH_PROMPT_FILE_PREFIX}link-${Date.now().toString(36)}.md`,+ Buffer.from(text, 'utf8').toString('base64')+ ),+ projects: async () => {+ const now = deps.indexEntries()+ if (now) return now+ await deps.loadIndex().catch(() => undefined)+ return deps.indexEntries() ?? []+ },+ agentInstalled: async (agent) => {+ const cfg = AGENT_CONFIG[agent as BuiltinAgentId]+ if (!cfg) return undefined+ const bin = cfg.launchCmd.trim().split(/\s+/)[0]+ if (!bin) return undefined+ if (await findInLoginPath(bin).catch(() => null)) return true+ if (agent === 'antigravity' && findAgy()) return true+ return false+ },+ send: (channel, payload) => sendToMain(CHANNEL[channel], payload),+ raise: () => deps.raise(),+ enabled: () => deps.enabled(),+ homeDir: () => homedir(),+ newId: () => randomUUID(),+ now: () => Date.now()+ })++ // The main window's top frame only: a subframe or a <webview> guest is another webContents/frame.+ const fromMainWindow = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent): boolean => {+ const win = getMainWindow()+ return !!win && event.sender.id === win.webContents.id && event.senderFrame === event.sender.mainFrame+ }++ ipcMain.on(IPC.openLinkReady, (event) => {+ if (!fromMainWindow(event)) return+ service.ready()+ })+ ipcMain.handle(IPC.openLinkAccept, async (event, msg: { id?: unknown; choice?: unknown }) => {+ if (!fromMainWindow(event)) return { ok: false, reason: 'Not allowed.' }+ return service.accept(msg?.id, msg?.choice)+ })+ ipcMain.on(IPC.openLinkCancel, (event, id: unknown) => {+ if (!fromMainWindow(event)) return+ service.cancel(id)+ })+ return service+}diff --git a/src/main/open-link.test.ts b/src/main/open-link.test.tsnew file mode 100644index 000000000..63a29a85f--- /dev/null+++ b/src/main/open-link.test.ts@@ -0,0 +1,314 @@+import { describe, expect, it } from 'vitest'+import type { LinkProjectEntry, OpenLinkPrompt } from '../shared/open-link'+import { OPEN_LINKS_OFF_NOTICE, OPEN_LINK_PENDING_TTL_MS, createOpenLinkService, type OpenLinkDeps, type PathKind } from './open-link'++interface Harness {+ deps: OpenLinkDeps+ sent: { channel: string; payload: unknown }[]+ raised: number+ files: Map<string, { kind: PathKind; text?: string }>+ stored: string[]+ clock: { t: number }+ projects: LinkProjectEntry[]+ installed: boolean | undefined+ enabled: boolean+}++function harness(): Harness {+ const h: Harness = {+ sent: [],+ raised: 0,+ files: new Map([+ ['/dev/api', { kind: 'dir' }],+ ['/dev/api/sub', { kind: 'dir' }],+ ['/tmp/new', { kind: 'dir' }],+ ['/tmp/brief.md', { kind: 'file', text: '# Review\n\nPlease look.' }],+ ['/tmp/dir.md', { kind: 'dir' }]+ ]),+ stored: [],+ clock: { t: 1_000_000 },+ projects: [+ { id: 'api', name: 'asilo-api', cwd: '/dev/api' },+ { id: 'remote', name: 'remote', cwd: '/srv', ssh: true }+ ],+ installed: true,+ enabled: true,+ deps: undefined as unknown as OpenLinkDeps+ }+ let seq = 0+ h.deps = {+ statPath: async (p) => {+ const f = h.files.get(p)+ if (!f) return { kind: 'missing', size: 0 }+ return { kind: f.kind, size: f.text ? Buffer.byteLength(f.text) : 0 }+ },+ readText: async (p) => {+ const f = h.files.get(p)+ if (!f) return { kind: 'missing' }+ if (f.kind !== 'file') return { kind: 'not-file' }+ return f.text === undefined ? { kind: 'error' } : { kind: 'ok', text: f.text }+ },+ storePrompt: async (text) => {+ h.stored.push(text)+ return `/userdata/launch-prompts/${h.stored.length}.md`+ },+ projects: async () => h.projects,+ agentInstalled: async () => h.installed,+ send: (channel, payload) => h.sent.push({ channel, payload }),+ raise: () => {+ h.raised+++ },+ enabled: () => h.enabled,+ homeDir: () => '/Users/me',+ newId: () => `id${++seq}`,+ now: () => h.clock.t+ }+ return h+}++const flush = () => new Promise((r) => setTimeout(r, 0))+const requests = (h: Harness) => h.sent.filter((s) => s.channel === 'request').map((s) => s.payload as OpenLinkPrompt)+const notices = (h: Harness) => h.sent.filter((s) => s.channel === 'notice').map((s) => (s.payload as { text: string }).text)++describe('open-link service: feature flag', () => {+ it('opens nothing while links are off, and says where to turn them on', async () => {+ const h = harness()+ h.enabled = false+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ svc.receive('nodeterm://open?agent=claude&cwd=/dev/api')+ svc.receive('nodeterm://pair?code=abc')+ await flush()+ expect(requests(h)).toEqual([])+ expect(h.sent.filter((s) => s.channel === 'pair')).toEqual([])+ expect(notices(h)).toEqual([OPEN_LINKS_OFF_NOTICE, OPEN_LINKS_OFF_NOTICE])+ expect(h.raised).toBe(2)+ })++ it('refuses an accept after links were switched off with the sheet up', async () => {+ const h = harness()+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ svc.receive('nodeterm://open?agent=claude&cwd=/dev/api')+ await flush()+ const [req] = requests(h)+ h.enabled = false+ const r = await svc.accept(req.id, { projectId: 'api' })+ expect(r.ok).toBe(false)+ expect(svc.pendingIds()).toEqual([])+ })+})++describe('open-link service: delivery', () => {+ it('holds a link that arrives before the renderer is ready, then delivers it', async () => {+ const h = harness()+ const svc = createOpenLinkService(h.deps)+ svc.receive('nodeterm://open?agent=claude&cwd=/dev/api')+ await flush()+ expect(h.sent).toEqual([])+ svc.ready()+ await flush()+ expect(requests(h)).toHaveLength(1)+ expect(h.raised).toBe(1)+ })++ it('holds again after the renderer goes away', async () => {+ const h = harness()+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ svc.notReady()+ svc.receive('nodeterm://open?agent=claude')+ await flush()+ expect(h.sent).toEqual([])+ svc.ready()+ await flush()+ expect(requests(h)).toHaveLength(1)+ })++ it('drops links past 5 a minute, then accepts again', async () => {+ const h = harness()+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ for (let i = 0; i < 7; i++) svc.receive('nodeterm://open?agent=claude')+ await flush()+ expect(requests(h)).toHaveLength(5)+ expect(notices(h).filter((t) => t.includes('Too many'))).toHaveLength(2)+ h.clock.t += 60_000+ svc.receive('nodeterm://open?agent=claude')+ await flush()+ expect(requests(h)).toHaveLength(6)+ })++ it('routes pair/join to the renderer and toasts a refusal', async () => {+ const h = harness()+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ svc.receive('nodeterm://join?code=abc')+ svc.receive('nodeterm://open?agent=claude&count=9')+ await flush()+ expect(h.sent[0]).toEqual({ channel: 'pair', payload: { kind: 'join', url: 'nodeterm://join?code=abc' } })+ expect(notices(h)[0]).toContain('unknown parameter "count"')+ })+})++describe('open-link service: validation', () => {+ it('refuses a cwd that is missing or a file', async () => {+ const h = harness()+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ svc.receive('nodeterm://open?agent=claude&cwd=/nope')+ svc.receive('nodeterm://open?agent=claude&cwd=/tmp/brief.md')+ await flush()+ expect(requests(h)).toHaveLength(0)+ expect(notices(h)).toHaveLength(2)+ })++ it('refuses a prompt file that is missing, not regular, too big or empty', async () => {+ const h = harness()+ h.files.set('/tmp/big.md', { kind: 'file', text: 'x'.repeat(64 * 1024 + 1) })+ h.files.set('/tmp/empty.md', { kind: 'file', text: ' ' })+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ for (const f of ['/tmp/missing.md', '/tmp/dir.md', '/tmp/big.md', '/tmp/empty.md']) {+ svc.receive(`nodeterm://open?agent=claude&prompt-file=${f}`)+ }+ await flush()+ expect(requests(h)).toHaveLength(0)+ expect(notices(h).join('|')).toMatch(/does not exist.*not a regular file.*64 KB.*empty/)+ })++ it('shows the prompt file text and warns when the agent is missing', async () => {+ const h = harness()+ h.installed = false+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ svc.receive('nodeterm://open?agent=codex&prompt-file=/tmp/brief.md&source=my-tool')+ await flush()+ const [r] = requests(h)+ expect(r).toMatchObject({ agent: 'codex', promptFileText: '# Review\n\nPlease look.', agentMissing: true, source: 'my-tool' })+ })++ it('refuses a prompt file with text the sheet would not show', async () => {+ const h = harness()+ h.files.set('/tmp/tags.md', { kind: 'file', text: `fix the bug${String.fromCodePoint(0xe0041, 0xe0042)}` })+ h.files.set('/tmp/rlo.md', { kind: 'file', text: 'safe \u202e text' })+ h.files.set('/tmp/c1.md', { kind: 'file', text: 'x\u0085y' })+ h.files.set('/tmp/emoji.md', { kind: 'file', text: 'ship it 👨\u200d💻' })+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ for (const f of ['/tmp/tags.md', '/tmp/rlo.md', '/tmp/c1.md', '/tmp/emoji.md']) {+ svc.receive(`nodeterm://open?agent=claude&prompt-file=${f}`)+ }+ await flush()+ expect(notices(h).filter((t) => t.includes('invisible'))).toHaveLength(3)+ expect(requests(h).map((r) => r.promptFile)).toEqual(['/tmp/emoji.md'])+ })++ it('never offers /, the home folder or its ancestors as a new project', async () => {+ const h = harness()+ h.files.set('/', { kind: 'dir' })+ h.files.set('/Users', { kind: 'dir' })+ h.files.set('/Users/me', { kind: 'dir' })+ h.files.set('/Users/me/repo', { kind: 'dir' })+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ for (const f of ['/', '/Users', '/Users/me', '/Users/me/repo']) svc.receive(`nodeterm://open?agent=claude&project-cwd=${f}`)+ await flush()+ expect(requests(h).map((r) => r.resolution.newProjectCwd)).toEqual([undefined, undefined, undefined, '/Users/me/repo'])+ })++ it('does not offer a new project for a folder that does not exist', async () => {+ const h = harness()+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ svc.receive('nodeterm://open?agent=claude&project-cwd=/gone')+ await flush()+ expect(requests(h)[0].resolution.newProjectCwd).toBeUndefined()+ })+})++describe('open-link service: accept re-check', () => {+ async function asked(url: string) {+ const h = harness()+ const svc = createOpenLinkService(h.deps)+ svc.ready()+ svc.receive(url)+ await flush()+ return { h, svc, req: requests(h)[0] }+ }++ it('answers with main\'s cwd and prompt, never the renderer\'s', async () => {+ const { svc, req } = await asked('nodeterm://open?agent=claude&cwd=/dev/api/sub&prompt=hi')+ const res = await svc.accept(req.id, { projectId: 'api', title: 'T', cwd: '/etc', prompt: 'rm -rf' })+ expect(res).toEqual({ ok: true, open: { agent: 'claude', projectId: 'api', cwd: '/dev/api/sub', prompt: 'hi', title: 'T' } })+ })++ it('defaults the cwd to the chosen project\'s', async () => {+ const { svc, req } = await asked('nodeterm://open?agent=claude')+ const res = await svc.accept(req.id, { projectId: 'api' })+ expect(res).toMatchObject({ ok: true, open: { cwd: '/dev/api' } })+ })++ it('refuses a project that was not offered (incl. SSH)', async () => {+ const { svc, req } = await asked('nodeterm://open?agent=claude')+ expect(await svc.accept(req.id, { projectId: 'remote' })).toMatchObject({ ok: false })+ // single use: the id is gone after the first answer+ expect(await svc.accept(req.id, { projectId: 'api' })).toMatchObject({ ok: false })+ })++ it('refuses a new project that was not offered', async () => {+ const { svc, req } = await asked('nodeterm://open?agent=claude&cwd=/dev/api')+ expect(await svc.accept(req.id, { newProject: true })).toMatchObject({ ok: false })+ })++ it('accepts the offered new project', async () => {+ const { svc, req } = await asked('nodeterm://open?agent=claude&cwd=/tmp/new')+ expect(await svc.accept(req.id, { newProject: true })).toEqual({+ ok: true,+ open: { agent: 'claude', newProjectCwd: '/tmp/new', cwd: '/tmp/new' }+ })+ })++ it('refuses a project removed or turned SSH since', async () => {+ const { h, svc, req } = await asked('nodeterm://open?agent=claude')+ h.projects = []+ expect(await svc.accept(req.id, { projectId: 'api' })).toMatchObject({ ok: false })+ })++ it("refuses when the project's folder changed after the sheet was shown", async () => {+ const { h, svc, req } = await asked('nodeterm://open?agent=claude')+ h.projects = [{ id: 'api', name: 'asilo-api', cwd: '/dev/elsewhere' }]+ expect(await svc.accept(req.id, { projectId: 'api' })).toMatchObject({ ok: false, reason: expect.stringContaining('folder changed') })+ })++ it('refuses a bad title and an unknown id', async () => {+ const { svc, req } = await asked('nodeterm://open?agent=claude')+ expect(await svc.accept('nope', { projectId: 'api' })).toMatchObject({ ok: false })+ expect(await svc.accept(req.id, { projectId: 'api', title: 'a\nb' })).toMatchObject({ ok: false })+ })++ it('re-reads the prompt file, copies it, and refuses if it changed', async () => {+ const { h, svc, req } = await asked('nodeterm://open?agent=claude&prompt-file=/tmp/brief.md')+ const res = await svc.accept(req.id, { projectId: 'api' })+ expect(res).toMatchObject({ ok: true, open: { promptFile: '/userdata/launch-prompts/1.md' } })+ expect(h.stored).toEqual(['# Review\n\nPlease look.'])++ h.sent.length = 0+ svc.receive('nodeterm://open?agent=claude&prompt-file=/tmp/brief.md')+ await flush()+ const second = requests(h)[0]+ h.files.set('/tmp/brief.md', { kind: 'file', text: 'something else' })+ expect(await svc.accept(second.id, { projectId: 'api' })).toMatchObject({ ok: false, reason: expect.stringContaining('changed') })+ })++ it('forgets an unanswered request after the TTL, and on cancel', async () => {+ const { h, svc, req } = await asked('nodeterm://open?agent=claude')+ h.clock.t += OPEN_LINK_PENDING_TTL_MS + 1+ expect(await svc.accept(req.id, { projectId: 'api' })).toMatchObject({ ok: false, reason: expect.stringContaining('expired') })+ svc.receive('nodeterm://open?agent=claude')+ await flush()+ const next = requests(h).at(-1) as OpenLinkPrompt+ svc.cancel(next.id)+ expect(svc.pendingIds()).toEqual([])+ })+})diff --git a/src/main/open-link.ts b/src/main/open-link.tsnew file mode 100644index 000000000..f225cf44f--- /dev/null+++ b/src/main/open-link.ts@@ -0,0 +1,328 @@+// `nodeterm://` links — the main-process half. Electron-free (every effect is a dependency), so the+// whole delivery and re-check story is unit-tested without a window.+//+// The shape, and why each half is where it is:+//+// 1. RECEIVE. A URL arrives from `open-url` (macOS), `process.argv` on a cold start or+// `second-instance`'s argv (Windows/Linux). Every arrival counts against a rate limit (5 a+// minute): a page that spams links gets toasts, never a stack of sheets. URLs that arrive before+// the renderer says it is listening are HELD (a link that cold-starts the app must not be lost)+// and delivered once it does.+// 2. VALIDATE. The parser (@shared/open-link) checks shape; this checks what needs a disk: `cwd`+// is an existing directory, `prompt-file` a regular file under the cap. The renderer never+// receives a path this did not check.+// 3. ASK. The validated request, plus the project candidates resolved from THIS process's workspace+// index, goes to the renderer, which shows the confirm sheet.+// 4. RE-CHECK. The renderer is the more attackable half, so its answer is only a CHOICE among what+// was offered (a candidate id, or "open the link's folder as a new project", and a title). The+// cwd and prompt in the final open come from here, not from the reply. The prompt file is read+// again at accept and copied into nodeterm's own launch-prompt store, so the text the pane reads+// is the text the human saw, whatever happens to the original afterwards.+//+// `pair` / `join` links are handed to the renderer's existing flows, which have their own approval.+// Everything here is desktop-only: the Server Edition has no URL scheme.++import {+ OPEN_LINK_LIMITS,+ comparablePath,+ hasHiddenText,+ normalizeLinkTitle,+ pathWithin,+ parseNodetermLink,+ resolveLinkProject,+ type LinkProjectEntry,+ type OpenLinkAcceptResult,+ type OpenLinkChoice,+ type OpenLinkPrompt,+ type OpenLinkRequest+} from '../shared/open-link'++/** At most this many links per window (every kind — a link is a link). */+export const OPEN_LINK_RATE = { max: 5, windowMs: 60_000 }+/** A pending request the human never answered is forgotten after this. */+export const OPEN_LINK_PENDING_TTL_MS = 10 * 60_000+/** Pending requests kept at once (the sheet shows one; the rest are replaced/dropped there). */+export const OPEN_LINK_PENDING_MAX = 4+/** Links held while the renderer is not listening yet. */+export const OPEN_LINK_HELD_MAX = 5++/** What a link says while the feature flag is off. Nothing is parsed or opened. */+export const OPEN_LINKS_OFF_NOTICE =+ 'A nodeterm:// link was ignored: links from other apps are off. Turn on "Allow nodeterm:// links" in Settings → Behavior.'++export type ReadTextResult =+ | { kind: 'ok'; text: string }+ | { kind: 'missing' }+ | { kind: 'not-file' }+ | { kind: 'error' }++export type PathKind = 'dir' | 'file' | 'other' | 'missing'++export interface OpenLinkDeps {+ /** What a path is, following symlinks (a symlinked project folder is fine). Never throws. */+ statPath(p: string): Promise<{ kind: PathKind; size: number }>+ /** Read a regular file as UTF-8, at most `maxBytes + 1` bytes, from ONE open (no stat first:+ * the handle that is read is the handle that is checked, and opening never blocks on a FIFO).+ * Never throws. */+ readText(p: string, maxBytes: number): Promise<ReadTextResult>+ /** Copy a prompt into nodeterm's launch-prompt store; the stored absolute path, or null. */+ storePrompt(text: string): Promise<string | null>+ /** The workspace index's projects. */+ projects(): Promise<LinkProjectEntry[]>+ /** Is this agent's command on the login-shell PATH? `undefined` = could not tell. */+ agentInstalled(agent: string): Promise<boolean | undefined>+ /** Push to the renderer. */+ send(channel: OpenLinkChannel, payload: unknown): void+ /** Bring the window forward: the user just clicked a link. */+ raise(): void+ /** The feature flag (`settings.allowOpenLinks`), read on every link and again on accept. */+ enabled(): boolean+ /** This user's home folder: it and its ancestors are never offered as a new project. */+ homeDir(): string+ newId(): string+ now(): number+}++export type OpenLinkChannel = 'request' | 'pair' | 'notice'++interface Pending {+ prompt: OpenLinkPrompt+ request: OpenLinkRequest+ at: number+}++export interface OpenLinkService {+ /** A URL from the OS. */+ receive(url: string): void+ /** The renderer is listening: deliver what was held. */+ ready(): void+ /** The renderer went away (reload, window closed): hold again until it says ready. */+ notReady(): void+ accept(id: unknown, choice: unknown): Promise<OpenLinkAcceptResult>+ cancel(id: unknown): void+ /** Test seam. */+ pendingIds(): string[]+}++const isDir = async (deps: OpenLinkDeps, p: string): Promise<boolean> => (await deps.statPath(p)).kind === 'dir'++export function createOpenLinkService(deps: OpenLinkDeps): OpenLinkService {+ const arrivals: number[] = []+ let readyNow = false+ const held: string[] = []+ const pending = new Map<string, Pending>()++ const notice = (text: string): void => deps.send('notice', { text })++ const prune = (): void => {+ const now = deps.now()+ for (const [id, p] of pending) if (now - p.at > OPEN_LINK_PENDING_TTL_MS) pending.delete(id)+ }++ /** Validate an `open` request against the disk and the index, then hand it to the sheet. */+ const ask = async (request: OpenLinkRequest): Promise<void> => {+ if (request.cwd && !(await isDir(deps, request.cwd))) {+ notice(`Link refused: the folder ${request.cwd} does not exist.`)+ return+ }+ // project-cwd only has to exist when it would become a new project; a project's own cwd that+ // vanished is the project's problem, and the sheet still lets the human pick.+ let promptFileText: string | undefined+ if (request.promptFile) {+ const checked = await readPromptFile(deps, request.promptFile)+ if (!checked.ok) {+ notice(`Link refused: ${checked.reason}.`)+ return+ }+ promptFileText = checked.text+ }+ const entries = await deps.projects().catch(() => [] as LinkProjectEntry[])+ let resolution = resolveLinkProject(request, entries)+ // A new project is a folder the user works in: never `/`, the home folder or an ancestor of it+ // (a project's whole folder is readable by its agents, and Share-with-team refuses the same).+ if (resolution.newProjectCwd && tooBroadForProject(resolution.newProjectCwd, deps.homeDir())) {+ const { newProjectCwd: _broad, ...rest } = resolution+ resolution = rest+ }+ if (resolution.newProjectCwd && !(await isDir(deps, resolution.newProjectCwd))) {+ const { newProjectCwd: _drop, ...rest } = resolution+ resolution = rest+ }+ const agentMissing = request.agent === 'terminal' ? false : (await deps.agentInstalled(request.agent)) === false+ prune()+ // Bounded: the oldest unanswered request goes first.+ while (pending.size >= OPEN_LINK_PENDING_MAX) {+ const oldest = pending.keys().next().value as string+ pending.delete(oldest)+ }+ const id = deps.newId()+ const prompt: OpenLinkPrompt = {+ id,+ agent: request.agent,+ ...(request.cwd ? { cwd: request.cwd } : {}),+ ...(request.prompt ? { prompt: request.prompt } : {}),+ ...(request.promptFile ? { promptFile: request.promptFile, promptFileText } : {}),+ ...(request.title ? { title: request.title } : {}),+ ...(request.source ? { source: request.source } : {}),+ resolution,+ ...(agentMissing ? { agentMissing: true } : {})+ }+ pending.set(id, { prompt, request, at: deps.now() })+ deps.send('request', prompt)+ deps.raise()+ }++ const dispatch = (url: string): void => {+ if (!deps.enabled()) {+ notice(OPEN_LINKS_OFF_NOTICE)+ // The user clicked something and must see why nothing opened (rate-limited like any link).+ deps.raise()+ return+ }+ const parsed = parseNodetermLink(url)+ if (!parsed.ok) {+ notice(`Link refused: ${parsed.reason}.`)+ return+ }+ const link = parsed.link+ if (link.kind !== 'open') {+ deps.send('pair', { kind: link.kind, url: link.url })+ deps.raise()+ return+ }+ void ask(link.request).catch((e) => notice(`Link refused: ${e instanceof Error ? e.message : String(e)}.`))+ }++ return {+ receive(url) {+ const now = deps.now()+ while (arrivals.length && now - arrivals[0] >= OPEN_LINK_RATE.windowMs) arrivals.shift()+ if (arrivals.length >= OPEN_LINK_RATE.max) {+ // Said once per burst would be nicer, but a toast per dropped link is still bounded by+ // the renderer's own notice slot (one strip, replaced).+ if (readyNow) notice('Too many nodeterm links in a minute — this one was ignored.')+ return+ }+ arrivals.push(now)+ if (!readyNow) {+ if (held.length < OPEN_LINK_HELD_MAX) held.push(url)+ return+ }+ dispatch(url)+ },+ ready() {+ readyNow = true+ const queued = held.splice(0)+ for (const url of queued) dispatch(url)+ },+ notReady() {+ readyNow = false+ },+ async accept(id, choice) {+ prune()+ if (typeof id !== 'string') return { ok: false, reason: 'Unknown link request.' }+ const p = pending.get(id)+ if (!p) return { ok: false, reason: 'This link request has expired. Click the link again.' }+ // Single use, whatever happens next.+ pending.delete(id)+ // Switched off while the sheet was up: the switch wins.+ if (!deps.enabled()) return { ok: false, reason: 'Links from other apps were turned off.' }+ const c = (choice ?? {}) as OpenLinkChoice+ if (typeof c !== 'object') return { ok: false, reason: 'Invalid choice.' }+ const title = normalizeLinkTitle(c.title)+ if (title === null) return { ok: false, reason: 'The title is not valid.' }+ const { resolution } = p.prompt++ let projectId: string | undefined+ let newProjectCwd: string | undefined+ let projectCwd: string | undefined+ if (c.newProject === true) {+ if (!resolution.newProjectCwd || c.projectId !== undefined) {+ return { ok: false, reason: 'That project was not offered.' }+ }+ newProjectCwd = resolution.newProjectCwd+ projectCwd = newProjectCwd+ } else {+ const hit = resolution.candidates.find((x) => x.id === c.projectId)+ if (!hit) return { ok: false, reason: 'That project was not offered.' }+ // Still in the index, still offerable (it may have been removed or handed off since).+ const now = (await deps.projects().catch(() => [] as LinkProjectEntry[])).find((e) => e.id === hit.id)+ if (!now || now.ssh || now.handedOff) return { ok: false, reason: 'That project is no longer available.' }+ // The sheet showed the folder from when the link arrived; a project moved since then would+ // run the node somewhere the human never saw.+ const shown = hit.cwd ? comparablePath(hit.cwd) : undefined+ const current = now.cwd ? comparablePath(now.cwd) : undefined+ if (shown !== current) {+ return { ok: false, reason: "That project's folder changed after the link arrived. Click the link again." }+ }+ projectId = hit.id+ projectCwd = now.cwd+ }++ const cwd = p.request.cwd ?? projectCwd+ if (cwd && !(await isDir(deps, cwd))) return { ok: false, reason: `The folder ${cwd} no longer exists.` }++ let promptFile: string | undefined+ if (p.request.promptFile) {+ const read = await readPromptFile(deps, p.request.promptFile)+ if (!read.ok) return { ok: false, reason: `Could not open: ${read.reason}.` }+ const text = read.text+ if (text !== p.prompt.promptFileText) {+ return { ok: false, reason: 'The prompt file changed after the link arrived. Click the link again to review it.' }+ }+ const stored = await deps.storePrompt(text)+ if (!stored) return { ok: false, reason: 'Could not store the prompt.' }+ promptFile = stored+ }++ return {+ ok: true,+ open: {+ agent: p.request.agent,+ ...(projectId ? { projectId } : {}),+ ...(newProjectCwd ? { newProjectCwd } : {}),+ ...(cwd ? { cwd } : {}),+ ...(p.request.prompt ? { prompt: p.request.prompt } : {}),+ ...(promptFile ? { promptFile } : {}),+ ...(title ? { title } : {})+ }+ }+ },+ cancel(id) {+ if (typeof id === 'string') pending.delete(id)+ },+ pendingIds: () => [...pending.keys()]+ }+}++/** The prompt file's text, or a sentence saying why not. */+async function readPromptFile(+ deps: OpenLinkDeps,+ path: string+): Promise<{ ok: true; text: string } | { ok: false; reason: string }> {+ const no = (reason: string) => ({ ok: false as const, reason })+ const read = await deps.readText(path, OPEN_LINK_LIMITS.promptFile)+ if (read.kind === 'missing') return no(`the prompt file ${path} does not exist`)+ if (read.kind === 'not-file') return no(`the prompt file ${path} is not a regular file`)+ if (read.kind === 'error') return no(`the prompt file ${path} could not be read`)+ const text = read.text+ if (new TextEncoder().encode(text).length > OPEN_LINK_LIMITS.promptFile) {+ return no('the prompt file is larger than 64 KB')+ }+ // eslint-disable-next-line no-control-regex+ if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(text)) {+ return no('the prompt file contains control characters')+ }+ // The same rule as an inline prompt: nothing the sheet would not show (bidi overrides, zero-width+ // and TAG characters, C1).+ if (hasHiddenText(text)) return no('the prompt file contains invisible or direction-changing characters')+ if (!text.trim()) return no('the prompt file is empty')+ return { ok: true, text }+}++/** `/`, the home folder, or an ancestor of it. */+export function tooBroadForProject(folder: string, home: string): boolean {+ const f = comparablePath(folder)+ if (f === '/' || /^[A-Za-z]:\/?$/.test(f)) return true+ return !!home && pathWithin(home, f)+}diff --git a/src/main/window-raise.guard.test.ts b/src/main/window-raise.guard.test.tsindex 6cf845f5b..7b25c5361 100644--- a/src/main/window-raise.guard.test.ts+++ b/src/main/window-raise.guard.test.ts@@ -56,7 +56,7 @@ const ALLOWED = new Map<string, { calls: number; why: string }>([{calls: 18,why:- '3 second-instance restore/show/focus (the user launched the app again); 1 first-paint ' ++ '3 raiseForUserLaunch restore/show/focus (the user launched the app again, or clicked a nodeterm:// link — a link reaches us as a second launch or open-url); 1 first-paint ' +'show (once, never on — #737); 4 file-drop IPC restore/show/app.focus(steal)/focus, now ' +'sender-guarded (a real drop, and macOS does not activate a drop destination by itself); ' +'3 notification-CLICK restore/show/focus — the one legitimate exception, a tap; 1 ' +diff --git a/src/preload/index.ts b/src/preload/index.tsindex df707d48c..ada8b43c6 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -4,6 +4,7 @@ import { IPC } from '../shared/ipc'import type { AlertSoundKind } from '../shared/alert-sound'import { resolveUiScale } from '../shared/ui-scale'import type { RecentConversationsRequest } from '../shared/recent-conversations'+import type { OpenLinkChoice, OpenLinkPrompt } from '../shared/open-link'import type {CanvasMutation,CanvasState,@@ -852,6 +853,16 @@ const api: NodeTerminalApi = {// report that never arrives costs the terminal-first policy, not the app's shortcuts.setTerminalFocused: (focused: boolean) => ipcRenderer.send(IPC.uiTerminalFocus, focused)},+ // `nodeterm://` links (main/open-link.ts). `ready` tells main to deliver links that arrived+ // before the renderer was listening (a link that cold-started the app).+ openLink: {+ ready: () => ipcRenderer.send(IPC.openLinkReady),+ onRequest: subscribe<[OpenLinkPrompt]>(IPC.openLinkRequest),+ onPair: subscribe<[{ kind: 'pair' | 'join'; url: string }]>(IPC.openLinkPair),+ onNotice: subscribe<[{ text: string }]>(IPC.openLinkNotice),+ accept: (id: string, choice: OpenLinkChoice) => ipcRenderer.invoke(IPC.openLinkAccept, { id, choice }),+ cancel: (id: string) => ipcRenderer.send(IPC.openLinkCancel, id)+ },onMarkdownToggle: subscribe(IPC.appToggleMarkdown),onCloseNode: subscribe(IPC.appCloseNode),onZoomActualSize: subscribe<[ZoomActualSizeModifiers?]>(IPC.appZoomActualSize),diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex d7cc878b6..8bfa2c9f1 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -553,6 +553,16 @@ export function buildStubApi(): Omit<// renderer's own dispatcher (`keyDispatchContextFor`), which reads focus directly.setTerminalFocused: noop},+ // Deliberate degrade: `nodeterm://` links are an OS URL-scheme registration, which only the+ // desktop app has. Nothing ever fires here; accept refuses.+ openLink: {+ ready: noop,+ onRequest: noopUnsub,+ onPair: noopUnsub,+ onNotice: noopUnsub,+ accept: U('openLink.accept'),+ cancel: noop+ },// REAL, not a stub: a browser tab has no main process to intercept ⌘/Ctrl+M, so the chord is// matched by a window keydown listener here (bindings, terminal-first stand-down and focus all// read live — see markdown-toggle-key.ts, including why macOS Chrome never delivers ⌘M).diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex a128d17bc..e68a5064f 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -554,9 +554,14 @@ import {AGENT_CONFIG,BUILTIN_AGENT_IDS,resolvePermissionMode,+ hasPermissionMode,+ PERMISSION_MODE_LABELS,type AgentId,type AgentPermissionMode} from '@shared/agents/config'+import { comparablePath, type OpenLinkAcceptResult, type OpenLinkChoice, type OpenLinkPrompt } from '@shared/open-link'+import { OpenLinkSheet } from '../components/OpenLinkSheet'+import { NEW_PROJECT_KEY, nextSheetAction, type LinkPermissionView } from '../lib/openLinkSheet'import { withPermissionMode } from '@shared/agents/approval-mode'import { promptFilePathError } from '@shared/agents/launch'import { encodeUtf8Base64, launchPromptFor } from '../lib/promptSpill'@@ -993,6 +998,10 @@ interface HostedMountOpts {/** What the agent-control handler's `reply` accepts, for helpers that build one outside it. */type ControlReply = { ok: boolean; message?: string; result?: unknown; error?: string }+/** An accepted `nodeterm://open` link, as main answered it (prompt possibly spilled to a file). */+type LinkOpen = Extract<OpenLinkAcceptResult, { ok: true }>['open']+/** An accepted link waiting for its project to load is dropped after this (see pendingLinkRef). */+const PENDING_LINK_MAX_MS = 30_000/** The confirm dialogs, named so their setters can be wrapped in a synchronous open-guard (see* `confirmFlags`): ONE confirm at a time, decided at call time rather than at the next render. */@@ -1712,6 +1721,11 @@ export function Canvas() {const pendingFocusRef = useRef<string | null>(null)// "Open recent": a conversation to resume once the project it belongs to is on the canvas.const pendingResumeRef = useRef<{ projectId: string; conv: RecentConversation } | null>(null)+ // A `nodeterm://open` link the human accepted: the node to create once its project is on the canvas.+ // `at`: a link that has not landed within PENDING_LINK_MAX_MS is dropped, never created later+ // out of context (e.g. on the next load of that project, hours on).+ const pendingLinkRef = useRef<{ projectId: string; open: LinkOpen; at: number } | null>(null)+ const linkCreateRef = useRef<(open: LinkOpen) => void>(() => {})// One-shot: the next active-project load keeps the CURRENT camera instead of applying the// project's saved viewport. Set by reloadActiveProject (in-place external-change reload).const preserveViewportRef = useRef(false)@@ -3375,6 +3389,12 @@ export function Canvas() {pendingResumeRef.current = nullresumeCreateRef.current(pendingResume.conv)}+ // Finish a `nodeterm://open` link that had to land on this project first.+ const pendingLink = pendingLinkRef.current+ if (pendingLink && pendingLink.projectId === project.id) {+ pendingLinkRef.current = null+ if (Date.now() - pendingLink.at < PENDING_LINK_MAX_MS) linkCreateRef.current(pendingLink.open)+ }// Consume a cross-project focus request (notification click on a background node).const pending = pendingFocusRef.currentif (pending) {@@ -5357,7 +5377,9 @@ export function Canvas() {initialCommand?: string,groupId?: string,/** Force the working directory (e.g. a Source Control action running in a worktree scope). */- cwdOverride?: string+ cwdOverride?: string,+ /** A title for the node (a `nodeterm://open` link's `title`). */+ title?: string) => {// Live read + epoch guard: same rule as addAgentNode (issue #443) — a menu closure built// under the previous project must not root a terminal in that project's folder.@@ -5388,7 +5410,8 @@ export function Canvas() {// passing `project?.ssh` straight through.const ssh = nodeSshFor(project?.ssh, cwdOverride)setNodes((ns) => {- const node = createTerminalNode(ns.length, cwd, center ?? emptyNodePos(), initialCommand, ssh)+ const made = createTerminalNode(ns.length, cwd, center ?? emptyNodePos(), initialCommand, ssh)+ const node = title ? { ...made, data: { ...made.data, title } } : madereturn [...ns, groupId ? parentInto(node, groupId) : node]})markDirty()@@ -6465,7 +6488,15 @@ export function Canvas() {// `awaitSetupGroup` holds the launch for that worktree frame's setup script (the issue card's// "Start with agent in a new worktree" opens the agent in the same tick as the frame) — the// same `PendingLaunch` hold a control open into a preparing frame gets (`setupHoldGroup`).- extra?: { issueRef?: IssueRef; awaitSetupGroup?: string }+ extra?: {+ issueRef?: IssueRef+ awaitSetupGroup?: string+ // A `nodeterm://open` link (main/open-link.ts), every value already checked by main: the+ // folder the node runs in, its title, and a first prompt stored as a file (`--prompt-file`).+ cwd?: string+ title?: string+ promptFile?: string+ }): { node: CanvasNode; placed: CanvasNode; projectId: string } | undefined => {// Resolve the target project LIVE, at click time — never from this callback's render// closure. Menu onClick closures outlive the render that built them (`setMenu` freezes@@ -6482,7 +6513,7 @@ export function Canvas() {return}const project = useProjects.getState().getProject(targetProjectId)- const cwd = cwdForNewNodeIn(groupId) ?? project?.cwd+ const cwd = extra?.cwd ?? cwdForNewNodeIn(groupId) ?? project?.cwd// Codex accounts (S6) resolve through their OWN fail-closed gate: an explicitly picked account// that is missing/hostile/unconnected is REFUSED here rather than silently downgraded to the// system login (Property 4). Claude keeps its project-default-aware resolver. The factory@@ -6544,10 +6575,14 @@ export function Canvas() {// Same funnel as the account above: the active project owns the node, so its own// `.nodeterm/settings.json` launch command layers over the global one.targetProjectId,- model+ model,+ extra?.promptFile)const issueRef = normalizeIssueRef(extra?.issueRef)- const bound = issueRef ? { ...created, data: { ...created.data, issueRef } } : created+ const titled = extra?.title+ ? { ...created, data: { ...created.data, title: extra.title, titleAuto: false } }+ : created+ const bound = issueRef ? { ...titled, data: { ...titled.data, issueRef } } : titledconst node = extra?.awaitSetupGroup ? queueControlLaunch(bound, [], extra.awaitSetupGroup) : bound// Parented HERE, not inside the updater: the updater runs at render time, and a render that// a zustand write flushes first (SyncLane, skipping this DefaultLane update) mirrors@@ -17638,6 +17673,208 @@ export function Canvas() {[resumeContext, travelToNode, resumeWhenLanded, reopenProject, switchProject, openOrAdoptFolder])+ // ── `nodeterm://` links (main/open-link.ts, components/OpenLinkSheet.tsx) ──────────────────────+ // Main validates a link and asks; the sheet shows exactly what will open and where; main re-checks+ // the human's choice and answers with the final open, which is created here like any new node.+ const [linkSheet, setLinkSheet] = useState<{ req: OpenLinkPrompt; touched: boolean; shownAt: number } | null>(null)+ const linkSheetRef = useRef(linkSheet)+ linkSheetRef.current = linkSheet+ // "Open <folder> as a new project" ADOPTS that folder's committed .nodeterm/project.json, whose+ // permission mode then applies. The sheet must show that mode, so the folder is probed when the+ // sheet appears; `project: undefined` = still reading.+ // The ref is the value (callbacks read it); the state only re-renders the sheet when it lands.+ const linkProbeRef = useRef<{ reqId: string; project: Project | null | undefined } | null>(null)+ const [, setLinkProbe] = useState(linkProbeRef.current)++ /** Create the accepted node on the canvas on screen (which is the link's project by now). */+ const createFromLink = useCallback(+ (open: LinkOpen): void => {+ const center = viewCenter()+ if (open.agent === 'terminal') {+ addTerminal(center, undefined, undefined, open.cwd, open.title)+ return+ }+ const made = addAgentNode(open.agent, center, undefined, undefined, open.prompt, {+ ...(open.cwd ? { cwd: open.cwd } : {}),+ ...(open.title ? { title: open.title } : {}),+ ...(open.promptFile ? { promptFile: open.promptFile } : {})+ })+ if (made) goToNode(made.placed)+ },+ [viewCenter, addTerminal, addAgentNode, goToNode]+ )+ useEffect(() => {+ linkCreateRef.current = createFromLink+ })++ const runLinkOpen = useCallback(+ async (accepted: Extract<OpenLinkAcceptResult, { ok: true }>['open'], shownMode?: string): Promise<void> => {+ // A long inline prompt goes to a file the pane's shell reads (#706) — decided BEFORE landing,+ // so no await sits between "this project is on screen" and the node's creation.+ let open: LinkOpen = accepted+ if (accepted.prompt && accepted.agent !== 'terminal') {+ const p = await launchPromptFor(+ { prompt: accepted.prompt, localFs: true },+ { saveUpload: (name, data) => api.files.saveUpload(name, data), encodeBase64: encodeUtf8Base64 }+ )+ open = { ...accepted, prompt: p.prompt, promptFile: p.promptFile ?? accepted.promptFile }+ }+ setWelcomeOpen(false)+ let projectId = accepted.projectId+ if (accepted.newProjectCwd) {+ const folder = comparablePath(accepted.newProjectCwd)+ await openOrAdoptFolder(accepted.newProjectCwd)+ projectId = useProjects+ .getState()+ .projects.find((p) => !p.ssh && !p.remote && p.cwd && comparablePath(p.cwd) === folder)?.id+ }+ const project = projectId ? useProjects.getState().getProject(projectId) : undefined+ if (!projectId || !project) {+ setNotice({ kind: 'error', text: 'Could not open the link: its project is no longer available.' })+ return+ }+ // The sheet showed a permission mode; the session must start in that one. A project file that+ // changed in between (a pull, an adopted folder that differs from the probe) refuses.+ if (shownMode !== undefined && accepted.agent !== 'terminal' && hasPermissionMode(accepted.agent)) {+ const now = PERMISSION_MODE_LABELS[projectPermissionMode(project, accepted.agent)]+ if (now !== shownMode) {+ setNotice({+ kind: 'error',+ text: `Did not open the link: the project's permission mode is now "${now}", not the "${shownMode}" the sheet showed. Click the link again.`+ })+ return+ }+ }+ if (projectId === useProjects.getState().activeProjectId && canCreateOnCanvas(nodesProjectIdRef.current, projectId)) {+ createFromLink(open)+ return+ }+ pendingLinkRef.current = { projectId, open, at: Date.now() }+ if (project.closed) {+ const ok = await reopenProject(projectId)+ if (!ok && pendingLinkRef.current?.open === open) pendingLinkRef.current = null+ } else switchProject(projectId)+ },+ [api, openOrAdoptFolder, createFromLink, reopenProject, switchProject]+ )++ const linkPermissionLabel = useCallback(+ (key: string | null): LinkPermissionView | null => {+ const req = linkSheetRef.current?.req+ const agent = req?.agent+ if (!req || !agent || agent === 'terminal' || !hasPermissionMode(agent)) return null+ let project: Project | undefined+ if (key === NEW_PROJECT_KEY) {+ const probe = linkProbeRef.current+ if (!probe || probe.reqId !== req.id || probe.project === undefined) {+ return { label: 'Checking the folder…', bypass: false, pending: true }+ }+ project = probe.project ?? undefined+ } else if (key) {+ project = useProjects.getState().getProject(key)+ }+ const mode = projectPermissionMode(project, agent)+ return { label: PERMISSION_MODE_LABELS[mode], bypass: mode === 'bypassPermissions' }+ },+ []+ )+ const acceptLink = useCallback(+ async (choice: OpenLinkChoice): Promise<string | null> => {+ const cur = linkSheetRef.current+ if (!cur) return null+ const shown = linkPermissionLabel(choice.newProject ? NEW_PROJECT_KEY : (choice.projectId ?? null))+ if (shown?.pending) return 'Still reading the folder — try again in a moment.'+ let res: OpenLinkAcceptResult+ try {+ res = await window.nodeTerminal.openLink.accept(cur.req.id, choice)+ } catch (err) {+ return `Could not open: ${stripIpcPrefix(err instanceof Error ? err.message : String(err))}`+ }+ // Main forgets a request on its first answer, so a refusal closes the sheet too.+ setLinkSheet(null)+ if (!res.ok) {+ setNotice({ kind: 'error', text: `Could not open the link: ${res.reason}` })+ return null+ }+ void runLinkOpen(res.open, shown?.label).catch((err: unknown) =>+ setNotice({ kind: 'error', text: `Could not open the link: ${err instanceof Error ? err.message : String(err)}` })+ )+ return null+ },+ [runLinkOpen, linkPermissionLabel]+ )++ const cancelLink = useCallback(() => {+ const cur = linkSheetRef.current+ if (cur) window.nodeTerminal.openLink.cancel(cur.req.id)+ setLinkSheet(null)+ }, [])++ const linkAccountLabel = useCallback((key: string | null): string | null => {+ if (linkSheetRef.current?.req.agent !== 'claude') return null+ const project = key && key !== NEW_PROJECT_KEY ? useProjects.getState().getProject(key) : undefined+ const accounts = useSettings.getState().settings.claudeAccounts ?? []+ const id = resolveNewNodeAccount(undefined, project, accounts)+ return id ? (accounts.find((a) => a.id === id)?.label ?? null) : null+ }, [])++ useEffect(() => {+ const ol = window.nodeTerminal.openLink+ const unRequest = ol.onRequest((req) => {+ const cur = linkSheetRef.current+ const action = nextSheetAction(cur, Date.now())+ if (action === 'drop') {+ ol.cancel(req.id)+ setNotice({ kind: 'info', text: 'Another nodeterm link arrived while one is open — it was ignored.' })+ return+ }+ if (action === 'replace' && cur) ol.cancel(cur.req.id)+ const sheet = { req, touched: false, shownAt: Date.now() }+ linkSheetRef.current = sheet+ setLinkSheet(sheet)+ const folder = req.resolution.newProjectCwd+ if (folder) {+ const probe = { reqId: req.id, project: undefined }+ linkProbeRef.current = probe+ setLinkProbe(probe)+ void api.workspace+ .probeFolder(folder)+ .catch(() => null)+ .then((project) => {+ if (linkProbeRef.current?.reqId !== req.id) return+ const done = { reqId: req.id, project }+ linkProbeRef.current = done+ setLinkProbe(done)+ })+ }+ })+ // Pair / join links go to the existing flows, which have their own approval (the SAS compare).+ // Pre-filled, never auto-accepted: the human presses OK first.+ const unPair = ol.onPair(({ kind, url }) => {+ void (async () => {+ const code = (+ await promptDialog({+ message:+ kind === 'join'+ ? 'A link asks to join a hosted team. Check the code, then connect:'+ : "A link carries a host's pairing code. Check it, then connect:",+ initialValue: url,+ confirmLabel: 'Connect'+ })+ )?.trim()+ if (code) void connectOffer(code)+ })()+ })+ const unNotice = ol.onNotice(({ text }) => setNotice({ kind: 'error', text }))+ // Listening: main delivers anything that arrived first (a link that launched the app).+ ol.ready()+ return () => {+ unRequest()+ unPair()+ unNotice()+ }+ }, [connectOffer, api])+const recentActionFor = useCallback((conv: RecentConversation): { label: string; disabled?: string } => {const plan = planResume(conv, resumeContext())@@ -19088,6 +19325,22 @@ export function Canvas() {)}{remoteDialogOpen && <RemoteAccessDialog onClose={() => setRemoteDialogOpen(false)} />}+ {linkSheet && (+ <OpenLinkSheet+ key={linkSheet.req.id}+ request={linkSheet.req}+ activeProjectId={activeProjectId}+ permissionLabel={linkPermissionLabel}+ accountLabel={linkAccountLabel}+ onTouched={() => {+ if (linkSheetRef.current && !linkSheetRef.current.touched) {+ setLinkSheet({ ...linkSheetRef.current, touched: true })+ }+ }}+ onOpen={acceptLink}+ onCancel={cancelLink}+ />+ )}{shareProjectId && (<ShareTeamDialogdiff --git a/src/renderer/components/OpenLinkSheet.test.tsx b/src/renderer/components/OpenLinkSheet.test.tsxnew file mode 100644index 000000000..f3a259f05--- /dev/null+++ b/src/renderer/components/OpenLinkSheet.test.tsx@@ -0,0 +1,171 @@+// @vitest-environment jsdom+//+// The `nodeterm://open` confirm sheet. A link can come from any web page, so what is asserted is+// safety-shaped: Open is disabled for the first second, Enter never opens, the prompt and the+// unverified source are on screen, Escape cancels, and the answer is a CHOICE (project + title),+// never a path or a prompt.+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import type { OpenLinkPrompt } from '@shared/open-link'+import { OpenLinkSheet } from './OpenLinkSheet'+import { resetDialogStack } from './dialog-stack'+import { OPEN_LINK_ARM_MS } from '../lib/openLinkSheet'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++let root: Root+let host: HTMLDivElement+beforeEach(() => {+ vi.useFakeTimers()+ resetDialogStack()+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+ vi.useRealTimers()+})++const request = (over: Partial<OpenLinkPrompt> = {}): OpenLinkPrompt => ({+ id: 'r1',+ agent: 'claude',+ prompt: 'Review PR #12',+ source: 'my-tool',+ title: 'Review: billing',+ resolution: {+ candidates: [+ { id: 'api', name: 'asilo-api', cwd: '/dev/api', closed: false },+ { id: 'flutter', name: 'doc-flutter', cwd: '/dev/flutter', closed: true }+ ],+ preselectId: 'api'+ },+ ...over+})++function mount(req = request(), permission: { label: string; bypass: boolean; pending?: boolean } = { label: 'Auto', bypass: false }) {+ const onOpen = vi.fn(async () => null)+ const onCancel = vi.fn()+ const onTouched = vi.fn()+ act(() => {+ root.render(+ <OpenLinkSheet+ request={req}+ activeProjectId="flutter"+ permissionLabel={() => permission}+ accountLabel={() => null}+ onTouched={onTouched}+ onOpen={onOpen}+ onCancel={onCancel}+ />+ )+ })+ return { onOpen, onCancel, onTouched }+}++const button = (label: string) => [...document.querySelectorAll('button')].find((b) => b.textContent === label) as HTMLButtonElement+const text = () => document.body.textContent ?? ''+/** A pointer click: `detail` is the click count, 0 for a keyboard activation. */+const pointerClick = (el: Element) => el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }))+const key = (target: EventTarget, init: KeyboardEventInit) => {+ const e = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })+ act(() => {+ target.dispatchEvent(e)+ })+ return e+}++describe('OpenLinkSheet', () => {+ it('shows the prompt, the unverified source, the project and the permission mode', () => {+ mount()+ expect(text()).toContain('Open a Claude Code session?')+ expect(text()).toContain('my-tool')+ expect(text()).toContain('not verified')+ expect(text()).toContain('Review PR #12')+ expect(text()).toContain('/dev/api')+ expect(text()).toContain('Auto')+ expect((document.querySelector('#open-link-project') as HTMLSelectElement).value).toBe('api')+ })++ it('keeps Open disabled for the first second, then opens on a click with the choice only', async () => {+ const { onOpen } = mount()+ expect(button('Open').disabled).toBe(true)+ act(() => {+ vi.advanceTimersByTime(OPEN_LINK_ARM_MS)+ })+ expect(button('Open').disabled).toBe(false)+ await act(async () => {+ pointerClick(button('Open'))+ })+ expect(onOpen).toHaveBeenCalledWith({ projectId: 'api', title: 'Review: billing' })+ })++ it('never opens on Enter', () => {+ const { onOpen } = mount()+ act(() => {+ vi.advanceTimersByTime(OPEN_LINK_ARM_MS + 10)+ })+ button('Open').focus()+ const e = key(button('Open'), { key: 'Enter' })+ expect(e.defaultPrevented).toBe(true)+ expect(onOpen).not.toHaveBeenCalled()+ })++ it('never opens on a keyboard activation of the focused button (Space)', async () => {+ const { onOpen } = mount()+ act(() => {+ vi.advanceTimersByTime(OPEN_LINK_ARM_MS)+ })+ await act(async () => {+ button('Open').click() // detail 0, what Space on a focused button dispatches+ })+ expect(onOpen).not.toHaveBeenCalled()+ })++ it('warns when the project runs without permission prompts, and waits for a pending probe', () => {+ mount(request(), { label: 'Bypass permissions', bypass: true })+ expect(text()).toContain('without asking for permission')+ act(() => root.unmount())+ root = createRoot(host)+ mount(request(), { label: 'Checking the folder…', bypass: false, pending: true })+ act(() => {+ vi.advanceTimersByTime(OPEN_LINK_ARM_MS)+ })+ expect(button('Open').disabled).toBe(true)+ })++ it('shows how long the prompt is', () => {+ mount()+ expect(text()).toContain('1 line · 13 B')+ })++ it('cancels on Escape once armed, never on a held key', () => {+ const { onCancel } = mount()+ act(() => {+ vi.advanceTimersByTime(OPEN_LINK_ARM_MS)+ })+ key(window, { key: 'Escape', repeat: true })+ expect(onCancel).not.toHaveBeenCalled()+ key(window, { key: 'Escape' })+ expect(onCancel).toHaveBeenCalledTimes(1)+ })++ it('reports a touch, so a second link does not replace an edited sheet', () => {+ const { onTouched } = mount()+ const sel = document.querySelector('#open-link-project') as HTMLSelectElement+ act(() => {+ sel.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))+ })+ expect(onTouched).toHaveBeenCalled()+ })++ it('offers no Open when there is no project to open it in', () => {+ mount(request({ resolution: { candidates: [], preselectId: null } }))+ act(() => {+ vi.advanceTimersByTime(OPEN_LINK_ARM_MS)+ })+ expect(button('Open').disabled).toBe(true)+ })+})diff --git a/src/renderer/components/OpenLinkSheet.tsx b/src/renderer/components/OpenLinkSheet.tsxnew file mode 100644index 000000000..c071b6c00--- /dev/null+++ b/src/renderer/components/OpenLinkSheet.tsx@@ -0,0 +1,236 @@+// The `nodeterm://open` confirm sheet. A link proves nothing about who sent it, so this sheet is the+// whole of its authority: the human sees exactly what will open, where, with which prompt, and picks+// the project before anything is created (main/open-link.ts re-checks the answer).+//+// Key rules, the same as every dialog raised on someone else's behalf (components/confirm-key):+// - Enter NEVER opens, and neither does Space on a focused Open: only a pointer click does, and Open+// stays disabled for OPEN_LINK_ARM_MS so a click or key already on its way when the link arrived+// cannot approve it.+// - Escape cancels, once armed and never on a held key. Focus starts on Cancel.+import { useEffect, useRef, useState } from 'react'+import { createPortal } from 'react-dom'+import type { OpenLinkChoice, OpenLinkPrompt } from '@shared/open-link'+import { AGENT_CONFIG, type BuiltinAgentId } from '@shared/agents/config'+import { CONFIRM_ARM_MS } from './confirm-key'+import { useDialogStack } from './dialog-stack'+import {+ NEW_PROJECT_KEY,+ OPEN_LINK_ARM_MS,+ choiceFor,+ cwdOutsideProject,+ initialProjectKey,+ projectNoteText,+ promptSizeText,+ sheetCwd,+ type LinkPermissionView+} from '../lib/openLinkSheet'++export interface OpenLinkSheetProps {+ request: OpenLinkPrompt+ activeProjectId: string | null+ /** The permission mode the session would start in for that picker value (null = not shown). */+ permissionLabel(key: string | null): LinkPermissionView | null+ /** The managed account it would run under (null = not shown). */+ accountLabel(key: string | null): string | null+ /** Any interaction: from now on a second link does not replace this sheet. */+ onTouched(): void+ /** Resolves null on success, else a sentence to show. */+ onOpen(choice: OpenLinkChoice): Promise<string | null>+ onCancel(): void+}++export function agentTitle(agent: OpenLinkPrompt['agent']): string {+ if (agent === 'terminal') return 'a terminal'+ return `a ${AGENT_CONFIG[agent as BuiltinAgentId]?.label ?? agent} session`+}++export function OpenLinkSheet(props: OpenLinkSheetProps): React.JSX.Element {+ const { request: req, activeProjectId, permissionLabel, accountLabel, onTouched, onOpen, onCancel } = props+ const [key, setKey] = useState<string | null>(() => initialProjectKey(req, activeProjectId))+ const [title, setTitle] = useState(req.title ?? '')+ const [armed, setArmed] = useState(false)+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const isTop = useDialogStack()+ const mountedAtRef = useRef(Date.now())+ const cancelRef = useRef(onCancel)+ cancelRef.current = onCancel++ useEffect(() => {+ const t = setTimeout(() => setArmed(true), OPEN_LINK_ARM_MS)+ return () => clearTimeout(t)+ }, [])++ useEffect(() => {+ const onKey = (e: KeyboardEvent): void => {+ if (e.key !== 'Escape' || !isTop()) return+ e.preventDefault()+ if (e.repeat || Date.now() - mountedAtRef.current < CONFIRM_ARM_MS) return+ cancelRef.current()+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [isTop])++ const touch = (): void => onTouched()+ const cwd = sheetCwd(req, key)+ const outside = cwdOutsideProject(req, key)+ const note = projectNoteText(req)+ const mode = permissionLabel(key)+ const account = accountLabel(key)+ const prompt = req.prompt ?? req.promptFileText+ const { candidates, newProjectCwd } = req.resolution++ const open = async (): Promise<void> => {+ const choice = choiceFor(key, title)+ if (!choice || busy) return+ setBusy(true)+ setError(null)+ const err = await onOpen(choice)+ // On success the sheet is unmounted by its owner; on failure it stays with the reason.+ if (err) {+ setError(err)+ setBusy(false)+ }+ }++ return createPortal(+ <div className="confirm-overlay" role="dialog" aria-modal="true" aria-label="Open from a link">+ <div+ className="confirm open-link"+ onPointerDown={touch}+ // Enter answers nothing here — capture phase, so the browser's own activation of a focused+ // button does not turn it into a click either.+ onKeyDownCapture={(e) => {+ if (e.key === 'Enter' && !(e.target instanceof HTMLTextAreaElement)) e.preventDefault()+ touch()+ }}+ >+ <div className="open-link__title">Open {agentTitle(req.agent)}?</div>+ <div className="open-link__source">+ {req.source ? (+ <>+ from <strong>{req.source}</strong> — this label comes from the link and is not verified+ </>+ ) : (+ 'from a nodeterm:// link — check what it opens before you accept'+ )}+ </div>++ <div className="open-link__body">+ <label className="open-link__label" htmlFor="open-link-project">+ Project+ </label>+ <select+ id="open-link-project"+ className="confirm__input open-link__field"+ value={key ?? ''}+ onChange={(e) => {+ touch()+ setKey(e.target.value || null)+ }}+ disabled={busy}+ >+ {!key && <option value="">No project available</option>}+ {candidates.map((c) => (+ <option key={c.id} value={c.id}>+ {c.name}+ {c.closed ? ' (closed)' : ''}+ {c.id === activeProjectId ? ' (on screen)' : ''}+ </option>+ ))}+ {newProjectCwd && <option value={NEW_PROJECT_KEY}>Open {newProjectCwd} as a new project</option>}+ </select>+ {note && <p className="open-link__note">{note}</p>}++ <div className="open-link__label">Working directory</div>+ <div className="open-link__value">{cwd ?? 'Home folder (the project has no folder)'}</div>+ {outside && (+ <p className="open-link__warn">This folder is outside the project's folder.</p>+ )}++ <label className="open-link__label" htmlFor="open-link-title">+ Title+ </label>+ <input+ id="open-link-title"+ className="confirm__input open-link__field"+ value={title}+ maxLength={80}+ placeholder="Default title"+ onChange={(e) => {+ touch()+ setTitle(e.target.value)+ }}+ disabled={busy}+ />++ {req.agent !== 'terminal' && (+ <>+ <div className="open-link__label">+ Prompt{req.promptFile ? ` (from ${req.promptFile})` : ''}+ </div>+ {prompt ? (+ <>+ <div className="open-link__muted open-link__size">{promptSizeText(prompt)} — scroll to read all of it</div>+ <pre className="open-link__prompt" tabIndex={0}>+ {prompt}+ </pre>+ </>+ ) : (+ <div className="open-link__value open-link__muted">No prompt — the session starts empty.</div>+ )}+ </>+ )}++ {mode && (+ <>+ <div className="open-link__label">Permission mode</div>+ <div className="open-link__value">+ {mode.pending ? mode.label : `${mode.label} (this project's default)`}+ </div>+ {mode.bypass && (+ <p className="open-link__warn">+ This project runs agents without asking for permission. The prompt above would run+ with no approval step.+ </p>+ )}+ </>+ )}+ {account && (+ <>+ <div className="open-link__label">Account</div>+ <div className="open-link__value">{account}</div>+ </>+ )}+ {req.agentMissing && (+ <p className="open-link__warn">+ {AGENT_CONFIG[req.agent as BuiltinAgentId]?.launchCmd ?? req.agent} was not found on this+ machine's PATH; the session may fail to start.+ </p>+ )}+ {error && <p className="open-link__error">{error}</p>}+ </div>++ <div className="confirm__actions">+ <button className="confirm__btn" autoFocus onClick={onCancel} disabled={busy}>+ Cancel+ </button>+ <button+ className="confirm__btn primary"+ onClick={(e) => {+ // detail 0 = a keyboard activation (Space/Enter on the focused button): click only.+ if (e.detail === 0) return+ void open()+ }}+ disabled={!armed || busy || !key || !!mode?.pending}+ title={!key ? 'There is no project to open it in.' : undefined}+ >+ Open+ </button>+ </div>+ </div>+ </div>,+ document.body+ )+}diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsxindex c49d3b03c..a6170b724 100644--- a/src/renderer/components/TabBar.tsx+++ b/src/renderer/components/TabBar.tsx@@ -674,6 +674,19 @@ export function TabBar({>Project settings…</button>+ {/* The id a `nodeterm://open?project=<id>` link names (another app's config maps its+ repositories to these ids). A relay tab's id belongs to the host, which a link here+ cannot open. */}+ {!menuProject.remote && (+ <button+ onClick={() => {+ window.nodeTerminal.clipboard.writeText(menuProject.id)+ closeMenu()+ }}+ >+ Copy project id+ </button>+ )}<buttononClick={() => {onCloseProject(menuProject.id)diff --git a/src/renderer/components/settings/sections/BehaviorSection.openLinks.test.tsx b/src/renderer/components/settings/sections/BehaviorSection.openLinks.test.tsxnew file mode 100644index 000000000..9da7fa385--- /dev/null+++ b/src/renderer/components/settings/sections/BehaviorSection.openLinks.test.tsx@@ -0,0 +1,46 @@+// @vitest-environment jsdom+//+// Settings → Behavior "Allow nodeterm:// links" is a desktop OS URL scheme. The Server Edition+// registers no scheme and its bridge stub refuses every link, so a browser tab must not offer a+// switch that does nothing — neither as a row nor as a settings-search hit.+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const flags = vi.hoisted(() => ({ browser: false }))+vi.mock('@renderer/bridge/runtime', () => ({ isBrowserRuntime: () => flags.browser }))++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++let root: Root+let host: HTMLElement++beforeEach(() => {+ vi.resetModules()+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+})++async function renderSection(): Promise<string> {+ const { BehaviorSection } = await import('./BehaviorSection')+ act(() => root.render(<BehaviorSection isActive />))+ return host.textContent ?? ''+}++describe('Allow nodeterm:// links row', () => {+ it('is offered on the desktop', async () => {+ flags.browser = false+ expect(await renderSection()).toContain('Allow nodeterm:// links')+ })++ it('is hidden in a Server Edition browser tab', async () => {+ flags.browser = true+ expect(await renderSection()).not.toContain('Allow nodeterm:// links')+ })+})diff --git a/src/renderer/components/settings/sections/BehaviorSection.tsx b/src/renderer/components/settings/sections/BehaviorSection.tsxindex 0befc0398..fc4fd2fe3 100644--- a/src/renderer/components/settings/sections/BehaviorSection.tsx+++ b/src/renderer/components/settings/sections/BehaviorSection.tsx@@ -56,6 +56,10 @@ const ROWS = {title: 'Remember the canvas lock',keywords: ['lock', 'canvas', 'view', 'pan', 'zoom', 'freeze', 'remember', 'restart', 'persist']},+ openLinks: {+ title: 'Allow nodeterm:// links',+ keywords: ['link', 'url', 'scheme', 'deep link', 'nodeterm://', 'open', 'other apps', 'protocol', 'external']+ },mdPreview: {title: 'Open Markdown in preview',keywords: ['markdown', 'md', 'preview', 'render', 'editor', 'docs', 'readme', 'file']@@ -105,7 +109,12 @@ const ROWS = {// The background-close row only exists for a desktop window off macOS, so search must not offer// it anywhere else. Decided once: neither the platform nor the runtime changes under a live page.const SHOW_BACKGROUND_CLOSE = backgroundCloseRowVisible(isMacPlatform(), isBrowserRuntime())-const ENTRIES = Object.values(ROWS).filter((r) => SHOW_BACKGROUND_CLOSE || r !== ROWS.backgroundClose)+// nodeterm:// links are a desktop OS URL scheme: the Server Edition registers none and its bridge+// stub refuses every link, so the switch would do nothing in a browser tab.+const SHOW_OPEN_LINKS = !isBrowserRuntime()+const ENTRIES = Object.values(ROWS).filter(+ (r) => (SHOW_BACKGROUND_CLOSE || r !== ROWS.backgroundClose) && (SHOW_OPEN_LINKS || r !== ROWS.openLinks)+)export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.Element {const settings = useSettings((s) => s.settings)@@ -304,6 +313,21 @@ export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.}/></SearchableRow>+ {SHOW_OPEN_LINKS && (+ <SearchableRow {...ROWS.openLinks}>+ <FieldRow+ label="Allow nodeterm:// links"+ description="Lets other apps, scripts and web pages ask nodeterm to open one agent or terminal node, or pre-fill a pairing code. Every link shows a confirm sheet first and opens nothing until you click Open. Off: links are ignored."+ control={+ <Switch+ checked={settings.allowOpenLinks}+ onChange={(v) => update({ allowOpenLinks: v })}+ ariaLabel="Allow nodeterm:// links"+ />+ }+ />+ </SearchableRow>+ )}<SearchableRow {...ROWS.mdPreview}><FieldRowlabel="Open Markdown in preview"diff --git a/src/renderer/lib/openLinkSheet.test.ts b/src/renderer/lib/openLinkSheet.test.tsnew file mode 100644index 000000000..9c346dc23--- /dev/null+++ b/src/renderer/lib/openLinkSheet.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from 'vitest'+import type { OpenLinkPrompt } from '@shared/open-link'+import {+ NEW_PROJECT_KEY,+ choiceFor,+ cwdOutsideProject,+ initialProjectKey,+ OPEN_LINK_ARM_MS,+ nextSheetAction,+ projectNoteText,+ promptSizeText,+ sheetCwd+} from './openLinkSheet'++const base = (over: Partial<OpenLinkPrompt> = {}, res: Partial<OpenLinkPrompt['resolution']> = {}): OpenLinkPrompt => ({+ id: 'r1',+ agent: 'claude',+ ...over,+ resolution: {+ candidates: [+ { id: 'a', name: 'A', cwd: '/dev/a', closed: false },+ { id: 'b', name: 'B', cwd: '/dev/b', closed: true },+ { id: 'c', name: 'C', closed: false }+ ],+ preselectId: null,+ ...res+ }+})++describe('initialProjectKey', () => {+ it('prefers main\'s suggestion', () => {+ expect(initialProjectKey(base({}, { preselectId: 'b' }), 'a')).toBe('b')+ })+ it('falls back to the project on screen', () => {+ expect(initialProjectKey(base(), 'c')).toBe('c')+ })+ it('does not fall back to the screen when the link named a project we could not use', () => {+ expect(initialProjectKey(base({}, { note: 'not-found' }), 'c')).toBe('a')+ expect(initialProjectKey(base({}, { note: 'no-match', newProjectCwd: '/x' }), 'c')).toBe(NEW_PROJECT_KEY)+ })+ it('falls back to the new-project row, then the first candidate, then nothing', () => {+ expect(initialProjectKey(base({}, { newProjectCwd: '/x' }), null)).toBe(NEW_PROJECT_KEY)+ expect(initialProjectKey(base(), 'gone')).toBe('a')+ expect(initialProjectKey(base({}, { candidates: [] }), null)).toBeNull()+ })+})++describe('cwd display', () => {+ it('uses the link cwd, else the project\'s, else the new folder', () => {+ expect(sheetCwd(base({ cwd: '/dev/a/x' }), 'b')).toBe('/dev/a/x')+ expect(sheetCwd(base(), 'b')).toBe('/dev/b')+ expect(sheetCwd(base({}, { newProjectCwd: '/n' }), NEW_PROJECT_KEY)).toBe('/n')+ expect(sheetCwd(base(), 'c')).toBeUndefined()+ })+ it('warns when the link cwd is outside the chosen project', () => {+ expect(cwdOutsideProject(base({ cwd: '/dev/a/x' }), 'a')).toBe(false)+ expect(cwdOutsideProject(base({ cwd: '/dev/a/x' }), 'b')).toBe(true)+ expect(cwdOutsideProject(base({ cwd: '/dev/a/x' }), 'c')).toBe(true)+ expect(cwdOutsideProject(base(), 'b')).toBe(false)+ })+})++describe('choiceFor / notes / replacement', () => {+ it('builds the wire choice', () => {+ expect(choiceFor('a', ' T ')).toEqual({ projectId: 'a', title: 'T' })+ expect(choiceFor(NEW_PROJECT_KEY, '')).toEqual({ newProject: true })+ expect(choiceFor(null, 'x')).toBeNull()+ })+ it('explains a named project it could not use', () => {+ expect(projectNoteText(base({}, { note: 'unsupported' }))).toContain('SSH')+ expect(projectNoteText(base())).toBeNull()+ })+ it('replaces only a brand-new untouched sheet', () => {+ expect(nextSheetAction(null, 0)).toBe('show')+ expect(nextSheetAction({ touched: false, shownAt: 1000 }, 1500)).toBe('replace')+ expect(nextSheetAction({ touched: true, shownAt: 1000 }, 1500)).toBe('drop')+ // Shown long enough to be read: a page cannot swap it under a reader who fires no event.+ expect(nextSheetAction({ touched: false, shownAt: 1000 }, 1000 + OPEN_LINK_ARM_MS)).toBe('drop')+ })+ it('sizes a prompt', () => {+ expect(promptSizeText('a')).toBe('1 line · 1 B')+ expect(promptSizeText('a\n'.repeat(1000))).toBe('1001 lines · 2.0 KB')+ })+})diff --git a/src/renderer/lib/openLinkSheet.ts b/src/renderer/lib/openLinkSheet.tsnew file mode 100644index 000000000..0621729a0--- /dev/null+++ b/src/renderer/lib/openLinkSheet.ts@@ -0,0 +1,101 @@+// The `nodeterm://open` confirm sheet's decisions, pure (components/OpenLinkSheet.tsx renders them,+// canvas/Canvas.tsx owns the sheet's lifetime). Main already resolved the candidates; nothing here+// can widen them — the sheet only ever answers with one of them or "new project".++import type { LinkProjectCandidate, OpenLinkChoice, OpenLinkPrompt } from '@shared/open-link'+import { pathWithin } from '@shared/open-link'++/** The picker's value: a candidate id, or the "open the link's folder as a new project" row. */+export const NEW_PROJECT_KEY = '__new-project__'++/**+ * The preselection, in order: main's suggestion; else the project on screen when it is offerable;+ * else the new-project row when offered; else the first candidate. Null only when nothing at all+ * can be offered (the Open button then stays disabled with the reason).+ */+export function initialProjectKey(req: OpenLinkPrompt, activeProjectId: string | null | undefined): string | null {+ const { candidates, preselectId, newProjectCwd } = req.resolution+ if (preselectId && candidates.some((c) => c.id === preselectId)) return preselectId+ // A link that named a project we could not use says so in the sheet; falling back to the+ // project on screen there would read as "it found your project".+ const named = req.resolution.note === 'not-found' || req.resolution.note === 'unsupported' || req.resolution.note === 'no-match'+ if (!named && activeProjectId && candidates.some((c) => c.id === activeProjectId)) return activeProjectId+ if (newProjectCwd) return NEW_PROJECT_KEY+ return candidates[0]?.id ?? null+}++export function candidateFor(req: OpenLinkPrompt, key: string | null): LinkProjectCandidate | undefined {+ return key && key !== NEW_PROJECT_KEY ? req.resolution.candidates.find((c) => c.id === key) : undefined+}++/** Where the node will run, as the sheet shows it — the same rule main applies on accept. */+export function sheetCwd(req: OpenLinkPrompt, key: string | null): string | undefined {+ if (req.cwd) return req.cwd+ if (key === NEW_PROJECT_KEY) return req.resolution.newProjectCwd+ return candidateFor(req, key)?.cwd+}++/** The link's cwd is outside the chosen project's folder (or the project has none). */+export function cwdOutsideProject(req: OpenLinkPrompt, key: string | null): boolean {+ if (!req.cwd || key === NEW_PROJECT_KEY) return false+ const c = candidateFor(req, key)+ if (!c) return false+ return !c.cwd || !pathWithin(req.cwd, c.cwd)+}++/** The sentence under the picker when the link named a project we could not use. */+export function projectNoteText(req: OpenLinkPrompt): string | null {+ switch (req.resolution.note) {+ case 'not-found':+ return 'The link named a project that is not on this machine. Pick one below.'+ case 'unsupported':+ return 'The link named an SSH project, which links cannot open yet. Pick another below.'+ case 'no-match':+ return 'No project uses the folder the link named. Pick one below.'+ default:+ return null+ }+}++export function choiceFor(key: string | null, title: string): OpenLinkChoice | null {+ if (!key) return null+ const t = title.trim()+ return key === NEW_PROJECT_KEY+ ? { newProject: true, ...(t ? { title: t } : {}) }+ : { projectId: key, ...(t ? { title: t } : {}) }+}++/** How long the Open button stays disabled after the sheet appears: a click or key already on its+ * way when a link arrived must not approve it. */+export const OPEN_LINK_ARM_MS = 1000++/**+ * A second link while a sheet is up. It replaces the sheet only while that sheet is brand new (shown+ * for less than the arm time) and untouched — a double-fired link, a redirect. After that the human+ * may be reading it (reading fires no event), and a page could otherwise swap the request under+ * someone who has already decided, so the newcomer is dropped.+ */+export function nextSheetAction(+ current: { touched: boolean; shownAt: number } | null,+ now: number+): 'show' | 'replace' | 'drop' {+ if (!current) return 'show'+ return !current.touched && now - current.shownAt < OPEN_LINK_ARM_MS ? 'replace' : 'drop'+}++/** "12 lines · 1.4 KB" — so a long prompt cannot pass for a short one in a scrolled box. */+export function promptSizeText(text: string): string {+ const lines = text.split('\n').length+ const bytes = new TextEncoder().encode(text).length+ const size = bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`+ return `${lines} ${lines === 1 ? 'line' : 'lines'} · ${size}`+}++/** What the sheet says about the permission mode the session would start in. */+export interface LinkPermissionView {+ label: string+ /** The mode runs tools without asking. */+ bypass: boolean+ /** Still reading the folder's committed project file (a new project): Open waits. */+ pending?: boolean+}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 5a0bfb4eb..44ba26424 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -12830,6 +12830,77 @@ button.pull-checks__name {.confirm.share-team {width: 480px;}++/* ---- nodeterm://open confirm sheet (components/OpenLinkSheet.tsx; reuses the .confirm shell) ---- */+.confirm.open-link {+ width: 520px;+}+.open-link__title {+ flex: 0 0 auto;+ font-size: 14px;+ font-weight: 600;+ color: var(--text);+}+.open-link__source {+ flex: 0 0 auto;+ margin: 2px 0 12px;+ font-size: 12px;+ color: var(--muted);+ overflow-wrap: anywhere;+}+.open-link__body {+ flex: 1 1 auto;+ min-height: 0;+ overflow-y: auto;+ margin-bottom: 14px;+}+.open-link__label {+ display: block;+ margin: 0 0 4px;+ font-size: 11px;+ font-weight: 600;+ color: var(--muted);+}+.open-link__field {+ margin-bottom: 10px;+}+.open-link__value {+ margin: 0 0 10px;+ font-size: 12px;+ color: var(--text);+ overflow-wrap: anywhere;+}+.open-link__muted {+ color: var(--muted);+}+.open-link__prompt {+ margin: 0 0 10px;+ max-height: 220px;+ overflow: auto;+ padding: 8px 10px;+ border-radius: 8px;+ border: 1px solid var(--border);+ background: rgba(var(--tint-rgb), 0.06);+ font-size: 12px;+ line-height: 1.45;+ color: var(--text);+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}+.open-link__note,+.open-link__warn {+ margin: -4px 0 10px;+ padding: 6px 8px;+ border-radius: 6px;+ font-size: 12px;+ color: var(--text);+ background: color-mix(in srgb, var(--state-warning) 12%, transparent);+}+.open-link__error {+ margin: 0 0 6px;+ font-size: 12px;+ color: var(--danger);+}.share-team__title {flex: 0 0 auto;margin: 0 0 10px;diff --git a/src/shared/host-control.ts b/src/shared/host-control.tsindex 23eadd37d..73745e8ba 100644--- a/src/shared/host-control.ts+++ b/src/shared/host-control.ts@@ -68,7 +68,11 @@ export const HOST_ONLY_CHANNEL_PREFIXES: readonly string[] = ['watchLink:',// Agent-integration consent status: paths in the host's home it kept or wrote. The consent itself// is in settings (already host-only).- 'integrations:'+ 'integrations:',+ // `nodeterm://` links: a link clicked on THIS machine opens a node here after THIS machine's user+ // approves it. Raw ipcMain handlers (no peer reaches them); listed so a move onto the platform+ // table cannot quietly open them.+ 'open-link:']export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 670f0bd83..b1a03725c 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -673,6 +673,15 @@ export const IPC = {remoteHostPeerPendingCleared: 'remote:host:peer-pending-cleared',remoteHostApprove: 'remote:host:approve',remotePhoneApprove: 'remote:phone:approve',+ // `nodeterm://` links (desktop only, raw ipcMain, main-window sender only — see main/open-link.ts).+ // main → renderer: an `open` link to confirm, a pair/join link to route, a refusal to toast.+ openLinkRequest: 'open-link:request',+ openLinkPair: 'open-link:pair',+ openLinkNotice: 'open-link:notice',+ // renderer → main: listening (deliver held links), the human's choice, a dismissal.+ openLinkReady: 'open-link:ready',+ openLinkAccept: 'open-link:accept',+ openLinkCancel: 'open-link:cancel',remoteHostReject: 'remote:host:reject',// Host canvas mirror: renderer pushes its serialized active-project canvas to main;// main pushes a client's mutation back to the host renderer to apply.diff --git a/src/shared/open-link.test.ts b/src/shared/open-link.test.tsnew file mode 100644index 000000000..374dd2a8b--- /dev/null+++ b/src/shared/open-link.test.ts@@ -0,0 +1,269 @@+import { describe, expect, it } from 'vitest'+import {+ isAcceptableAbsolutePath,+ nodetermUrlFromArgv,+ normalizeLinkTitle,+ parseNodetermLink,+ pathWithin,+ resolveLinkProject,+ type LinkProjectEntry,+ type OpenLinkRequest+} from './open-link'++const open = (q: string) => parseNodetermLink(`nodeterm://open?${q}`)+const req = (q: string): OpenLinkRequest => {+ const r = open(q)+ if (!r.ok || r.link.kind !== 'open') throw new Error(`expected ok: ${JSON.stringify(r)}`)+ return r.link.request+}+const reason = (q: string): string => {+ const r = open(q)+ if (r.ok) throw new Error(`expected refusal for ${q}`)+ return r.reason+}++describe('parseNodetermLink — open', () => {+ it('parses every param', () => {+ expect(+ req(+ 'agent=claude&project=p1&cwd=%2FUsers%2Fme%2Frepo&prompt=hello%20there&title=Review%20%2312&source=my-tool'+ )+ ).toEqual({+ agent: 'claude',+ project: 'p1',+ cwd: '/Users/me/repo',+ prompt: 'hello there',+ title: 'Review #12',+ source: 'my-tool'+ })+ })++ it('accepts project-cwd and prompt-file', () => {+ expect(req('agent=codex&project-cwd=/a/b&prompt-file=/tmp/x.md')).toEqual({+ agent: 'codex',+ projectCwd: '/a/b',+ promptFile: '/tmp/x.md'+ })+ })++ it('treats + as a space and %2B as a plus', () => {+ expect(req('agent=claude&prompt=a+b%2Bc').prompt).toBe('a b+c')+ })++ it('decodes unicode and keeps newlines in a prompt', () => {+ expect(req('agent=claude&prompt=caf%C3%A9%0Anext%20line%09tab').prompt).toBe('café\nnext line\ttab')+ })++ it('accepts a trailing slash on the host and an uppercase scheme', () => {+ expect(parseNodetermLink('nodeterm://open/?agent=claude').ok).toBe(true)+ expect(parseNodetermLink('NODETERM://open?agent=claude').ok).toBe(true)+ })++ it('accepts a terminal with no prompt', () => {+ expect(req('agent=terminal&cwd=/x')).toEqual({ agent: 'terminal', cwd: '/x' })+ })++ it('drops empty optional values instead of keeping blanks', () => {+ expect(req('agent=claude&prompt=%20%20&title=&source=')).toEqual({ agent: 'claude' })+ })++ it.each([+ ['', 'which agent'],+ ['agent=', 'which agent'],+ ['agent=bash', 'not an agent'],+ ['agent=claude&count=3', 'unknown parameter "count"'],+ ['agent=claude&run-now=1', 'unknown parameter'],+ ['agent=claude&permission-mode=bypassPermissions', 'unknown parameter'],+ ['agent=claude&agent=codex', 'more than once'],+ ['agent=claude&project=a&project-cwd=/x', 'cannot be combined'],+ ['agent=claude&prompt=a&prompt-file=/x', 'cannot be combined'],+ ['agent=terminal&prompt=ls', 'cannot carry a prompt'],+ ['agent=terminal&prompt-file=/x', 'cannot carry a prompt'],+ ['agent=claude&cwd=relative/path', 'absolute path'],+ ['agent=claude&cwd=~/repo', 'absolute path'],+ ['agent=claude&cwd=/a/../b', 'absolute path'],+ ['agent=claude&prompt-file=x.md', 'absolute path'],+ ['agent=claude&project-cwd=.', 'absolute path'],+ ['agent=claude&prompt=%00', 'control characters'],+ ['agent=claude&prompt=%1B%5B2J', 'control characters'],+ ['agent=claude&title=a%0Ab', 'control characters'],+ ['agent=claude&source=my%E2%80%AEtool', 'control characters'],+ ['agent=claude&prompt=%E0%A4%A', 'not correctly encoded'],+ // Windows reads `/\\host\\share` as UNC; a pre-sheet stat would authenticate to that host.+ ['agent=claude&cwd=%2F%5Cevil.example%5Cshare', 'absolute path'],+ ['agent=claude&prompt-file=%2F%5C.%5Cpipe%5Cx', 'absolute path'],+ ['agent=claude&cwd=/net/evil.example/x', 'absolute path'],+ ['agent=claude&cwd=/Network/Servers/x', 'absolute path'],+ ['agent=claude&cwd=%2Ftmp%2Fa%E2%80%AEb', 'absolute path'],+ // ASCII smuggling: TAG characters render as nothing and a model reads them.+ ['agent=claude&prompt=hi%F3%A0%81%81%F3%A0%81%82', 'invisible'],+ ['agent=claude&prompt=a%E2%80%AEb', 'invisible'],+ ['agent=claude&prompt=a%E2%80%8Bb', 'invisible'],+ ['agent=claude&title=a%C2%ADb', 'control characters']+ ])('refuses %s', (q, why) => {+ expect(reason(q)).toContain(why)+ })++ it('enforces the size caps', () => {+ expect(reason(`agent=claude&prompt=${'a'.repeat(8 * 1024 + 1)}`)).toContain('8 KB')+ expect(req(`agent=claude&prompt=${'a'.repeat(8 * 1024)}`).prompt).toHaveLength(8192)+ // The cap is on BYTES after decoding: 3000 three-byte characters are 9000 bytes.+ expect(reason(`agent=claude&prompt=${'%E2%82%AC'.repeat(3000)}`)).toContain('8 KB')+ expect(reason(`agent=claude&title=${'t'.repeat(81)}`)).toContain('80')+ expect(req(`agent=claude&title=${'t'.repeat(80)}`).title).toHaveLength(80)+ expect(reason(`agent=claude&source=${'s'.repeat(41)}`)).toContain('40')+ expect(parseNodetermLink(`nodeterm://open?agent=claude&prompt=${'a'.repeat(60_000)}`).ok).toBe(false)+ })++ it('keeps an emoji ZWJ sequence in a prompt', () => {+ expect(req('agent=claude&prompt=%F0%9F%91%A8%E2%80%8D%F0%9F%92%BB').prompt).toBe('👨\u200d💻')+ })++ it('clips link text it echoes in a refusal', () => {+ expect(reason(`agent=claude&${'k'.repeat(500)}=1`).length).toBeLessThan(80)+ expect(reason(`agent=${'a'.repeat(500)}`).length).toBeLessThan(90)+ })++ it('refuses a fragment, other schemes, unknown hosts and non-strings', () => {+ expect(parseNodetermLink('nodeterm://open?agent=claude#x').ok).toBe(false)+ expect(parseNodetermLink('https://open?agent=claude').ok).toBe(false)+ const other = parseNodetermLink('nodeterm://delete?all=1')+ expect(other.ok ? null : other.reason).toContain('not a link nodeterm opens')+ expect(parseNodetermLink(42).ok).toBe(false)+ })+})++describe('parseNodetermLink — pair / join', () => {+ it('routes pair and join with the code intact', () => {+ expect(parseNodetermLink('nodeterm://pair?code=abc_-123')).toEqual({+ ok: true,+ link: { kind: 'pair', url: 'nodeterm://pair?code=abc_-123' }+ })+ expect(parseNodetermLink('nodeterm://join?code=xyz')).toEqual({+ ok: true,+ link: { kind: 'join', url: 'nodeterm://join?code=xyz' }+ })+ })++ it('refuses a missing code or extra params', () => {+ expect(parseNodetermLink('nodeterm://pair').ok).toBe(false)+ expect(parseNodetermLink('nodeterm://join?code=x&auto=1').ok).toBe(false)+ })+})++describe('isAcceptableAbsolutePath', () => {+ it.each([+ ['/a/b', true],+ ['/', true],+ ['C:\\Users\\me', true],+ ['C:/Users/me', true],+ ['\\\\server\\share', false],+ ['//server/share', false],+ ['a/b', false],+ ['/a/./b', false],+ ['', false]+ ])('%s → %s', (p, ok) => {+ expect(isAcceptableAbsolutePath(p)).toBe(ok)+ })+})++describe('normalizeLinkTitle', () => {+ it('trims, empties to undefined and refuses bad titles', () => {+ expect(normalizeLinkTitle(' x ')).toBe('x')+ expect(normalizeLinkTitle(' ')).toBeUndefined()+ expect(normalizeLinkTitle(undefined)).toBeUndefined()+ expect(normalizeLinkTitle(5)).toBeNull()+ expect(normalizeLinkTitle('a\nb')).toBeNull()+ expect(normalizeLinkTitle('t'.repeat(81))).toBeNull()+ })+})++describe('nodetermUrlFromArgv', () => {+ it('finds the link among electron args', () => {+ expect(nodetermUrlFromArgv(['/app/nodeterm', '--flag', 'nodeterm://open?agent=claude'])).toBe(+ 'nodeterm://open?agent=claude'+ )+ expect(nodetermUrlFromArgv(['/app/nodeterm', 'https://x'])).toBeNull()+ })+})++describe('pathWithin', () => {+ it('trims a long run of trailing slashes in linear time', () => {+ const t0 = performance.now()+ expect(pathWithin(`/repo${'/'.repeat(100_000)}`, '/repo')).toBe(true)+ expect(performance.now() - t0).toBeLessThan(200)+ })++ it('is segment-wise', () => {+ expect(pathWithin('/repo/src', '/repo')).toBe(true)+ expect(pathWithin('/repo', '/repo/')).toBe(true)+ expect(pathWithin('/repo-x', '/repo')).toBe(false)+ expect(pathWithin('/anything', '/')).toBe(true)+ })+})++describe('resolveLinkProject', () => {+ const entries: LinkProjectEntry[] = [+ { id: 'api', name: 'asilo-api', cwd: '/dev/asilo-api' },+ { id: 'api2', name: 'asilo-api copy', cwd: '/dev/asilo-api/' },+ { id: 'flutter', name: 'doc-flutter', cwd: '/dev/doc-flutter', closed: true },+ { id: 'nested', name: 'packages', cwd: '/dev/doc-flutter/packages' },+ { id: 'ssh', name: 'remote', cwd: '/srv/x', ssh: true },+ { id: 'handed', name: 'team', cwd: '/dev/team', handedOff: true },+ { id: 'inline', name: 'scratch' }+ ]+ const ids = (r: { candidates: { id: string }[] }) => r.candidates.map((c) => c.id)++ it('never offers SSH or handed-off projects', () => {+ const r = resolveLinkProject({ agent: 'claude' }, entries)+ expect(ids(r)).not.toContain('ssh')+ expect(ids(r)).not.toContain('handed')+ // open first, then closed+ expect(ids(r)).toEqual(['api', 'api2', 'nested', 'inline', 'flutter'])+ })++ it('project= hit preselects it, first', () => {+ const r = resolveLinkProject({ agent: 'claude', project: 'flutter' }, entries)+ expect(r.preselectId).toBe('flutter')+ expect(ids(r)[0]).toBe('flutter')+ expect(r.note).toBeUndefined()+ })++ it('project= miss is a note, not an error', () => {+ const r = resolveLinkProject({ agent: 'claude', project: 'nope' }, entries)+ expect(r).toMatchObject({ preselectId: null, note: 'not-found' })+ expect(r.candidates.length).toBe(5)+ })++ it('project= naming an SSH project says so', () => {+ expect(resolveLinkProject({ agent: 'claude', project: 'ssh' }, entries).note).toBe('unsupported')+ })++ it('project-cwd matches exactly, several first', () => {+ const r = resolveLinkProject({ agent: 'claude', projectCwd: '/dev/asilo-api' }, entries)+ expect(r.preselectId).toBe('api')+ expect(ids(r).slice(0, 2)).toEqual(['api', 'api2'])+ expect(r.newProjectCwd).toBeUndefined()+ })++ it('project-cwd with no match offers the folder as a new project', () => {+ const r = resolveLinkProject({ agent: 'claude', projectCwd: '/dev/portal' }, entries)+ expect(r).toMatchObject({ preselectId: null, note: 'no-match', newProjectCwd: '/dev/portal' })+ })++ it('cwd alone picks the longest owning prefix', () => {+ const r = resolveLinkProject({ agent: 'claude', cwd: '/dev/doc-flutter/packages/core' }, entries)+ expect(r.preselectId).toBe('nested')+ expect(r.newProjectCwd).toBe('/dev/doc-flutter/packages/core')+ })++ it('cwd outside every project suggests nothing but offers the folder', () => {+ const r = resolveLinkProject({ agent: 'claude', cwd: '/tmp/work' }, entries)+ expect(r.preselectId).toBeNull()+ expect(r.newProjectCwd).toBe('/tmp/work')+ })++ it('a cwd a project owns exactly is not offered as a new project', () => {+ expect(resolveLinkProject({ agent: 'claude', cwd: '/dev/asilo-api' }, entries).newProjectCwd).toBeUndefined()+ })+})diff --git a/src/shared/open-link.ts b/src/shared/open-link.tsnew file mode 100644index 000000000..b32d8b6ab--- /dev/null+++ b/src/shared/open-link.ts@@ -0,0 +1,424 @@+// `nodeterm://` LINKS — the parser. Pure: no electron, no fs (main does the checks that need a disk).+//+// An app outside nodeterm (a review tool, a script, a bookmark) has no node identity, so canvas control+// refuses it by design. A link does not weaken that: it proves NOTHING about who sent it — any web+// page can build one. It only FILLS IN a form, and the human approves every `open` link in a confirm+// sheet before anything is created. So this parser is strict on shape and size, and every value it+// returns is treated as hostile text by everyone downstream:+//+// - unknown params, a param given twice, an over-cap value, a relative path → the whole link is+// refused (a typo in a link is a refusal the caller can see, never a silently dropped option);+// - none of canvas control's power flags exist here (count, group, after, run-now, model, issue,+// permission mode): a link opens ONE node in its project's default permission mode, and can never+// ask for a looser one;+// - `source` is a display label only. Nothing may branch on it.+//+// `nodeterm://pair?code=…` and `nodeterm://join?code=…` are recognised and handed back verbatim so+// the app can route them to its existing pairing / join flows, which have their own approval.+// Design: docs/superpowers/specs/2026-10-13-open-link-design.md.++import { BUILTIN_AGENT_IDS, type BuiltinAgentId } from './agents/config'++export const OPEN_LINK_SCHEME = 'nodeterm:'++/** The agents a link may open: the builtins, plus a plain terminal. */+export type OpenLinkAgent = BuiltinAgentId | 'terminal'++/** Caps, after decoding. Prompt and paths in UTF-8 bytes, labels in code points. */+export const OPEN_LINK_LIMITS = {+ /** The whole raw URL. Larger than every cap below combined after %-encoding, small enough that+ * nothing pathological reaches the decoder. */+ url: 48 * 1024,+ prompt: 8 * 1024,+ /** `prompt-file` content, checked by main when the file is read. */+ promptFile: 64 * 1024,+ path: 4096,+ title: 80,+ source: 40,+ projectId: 200,+ /** A pairing offer / join code (base64url JSON). */+ code: 8 * 1024+} as const++export interface OpenLinkRequest {+ agent: OpenLinkAgent+ /** A project id from the workspace index. */+ project?: string+ /** Absolute path: the project whose cwd is exactly this. */+ projectCwd?: string+ /** Absolute path: where the node runs. Defaults to the chosen project's cwd. */+ cwd?: string+ /** The agent's first message (≤ 8 KB). */+ prompt?: string+ /** Absolute path to a file holding the first message, read by main on accept. */+ promptFile?: string+ title?: string+ /** UNVERIFIED display label. */+ source?: string+}++export type ParsedLink =+ | { kind: 'open'; request: OpenLinkRequest }+ | { kind: 'pair' | 'join'; url: string }++export type ParseLinkResult = { ok: true; link: ParsedLink } | { ok: false; reason: string }++const OPEN_PARAMS = ['agent', 'project', 'project-cwd', 'cwd', 'prompt', 'prompt-file', 'title', 'source'] as const+type OpenParam = (typeof OPEN_PARAMS)[number]++const refuse = (reason: string): ParseLinkResult => ({ ok: false, reason })++const utf8Bytes = (s: string): number => new TextEncoder().encode(s).length+const codePoints = (s: string): number => Array.from(s).length++// C0 (except tab/newline/CR), DEL and C1 — never legitimate in a link value. A prompt keeps tab and+// newlines (a multi-line brief); every other value refuses those too.+// eslint-disable-next-line no-control-regex+const CONTROL_EXCEPT_WS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/+// eslint-disable-next-line no-control-regex+const ANY_CONTROL = /[\u0000-\u001f\u007f-\u009f]/+// Bidi and zero-width formatting controls: a label must render as what it says.+const FORMAT_CONTROL = /[\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/+// Text a human cannot see but a model reads: every format character (bidi overrides, zero-width+// characters, Unicode TAG characters U+E0000–E007F — "ASCII smuggling"), plus C1. ZWJ (U+200D) is+// allowed, so an emoji sequence in a prompt survives. One character class, no backtracking.+const HIDDEN_TEXT = /[\u0080-\u009f]|(?!\u200d)\p{Cf}/u++/** Would part of this text be invisible or reordered in the sheet? Shared with main's prompt-file+ * check, so the inline prompt and a file's text follow one rule. */+export function hasHiddenText(s: string): boolean {+ return HIDDEN_TEXT.test(s)+}++/** A refusal echoes link text: keep it short (the whole link may be 48 KB). */+const clip = (s: string): string => {+ const cps = Array.from(s)+ return cps.length > 40 ? `${cps.slice(0, 40).join('')}…` : s+}++/** `+` is a space (form encoding: what `URLSearchParams` and most link builders emit), then %-decode.+ * A malformed escape refuses rather than passing the raw text through. */+function decodeValue(raw: string): string | null {+ try {+ return decodeURIComponent(raw.replace(/\+/g, ' '))+ } catch {+ return null+ }+}++/**+ * Absolute on THIS machine's dialects: POSIX `/…`, or a Windows drive path `C:\…` / `C:/…`.+ * Refused: relative paths, `~` (the shell's, not ours), UNC `\\server\share` (a read there reaches+ * another machine over SMB), and any `.`/`..` segment — an absolute path never needs one, and+ * refusing it keeps "the path the sheet shows" equal to "the path that is opened".+ *+ * A POSIX-form path may not contain a backslash: Windows reads `/\host\share` as the UNC path+ * `\\host\share`, and main stats a link's paths before the sheet appears, so that alone would+ * make Windows connect (and authenticate) to another machine. For the same reason the macOS+ * automount roots `/net` and `/Network` are refused. Hidden or reordering characters are refused so+ * the path on screen is the path opened.+ */+export function isAcceptableAbsolutePath(p: string): boolean {+ if (!p || utf8Bytes(p) > OPEN_LINK_LIMITS.path || ANY_CONTROL.test(p) || hasHiddenText(p)) return false+ if (/^\/(?:net|network)(?:\/|$)/i.test(p)) return false+ const posix = p.startsWith('/') && !p.startsWith('//') && !p.includes('\\')+ const win = /^[A-Za-z]:[\\/]/.test(p)+ if (!posix && !win) return false+ const segments = (win ? p.slice(3) : p.slice(1)).split(/[\\/]/)+ return !segments.some((s) => s === '.' || s === '..')+}++function isOpenLinkAgent(a: string): a is OpenLinkAgent {+ return a === 'terminal' || (BUILTIN_AGENT_IDS as readonly string[]).includes(a)+}++/** Split the query into decoded pairs. Refuses a duplicate key and a malformed escape. Empty+ * segments (`a=1&&b=2`, a trailing `&`) are ignored. */+function readQuery(query: string): Map<string, string> | string {+ const out = new Map<string, string>()+ for (const part of query.split('&')) {+ if (!part) continue+ const eq = part.indexOf('=')+ const rawKey = eq === -1 ? part : part.slice(0, eq)+ const rawVal = eq === -1 ? '' : part.slice(eq + 1)+ const key = decodeValue(rawKey)+ const val = decodeValue(rawVal)+ if (key === null || val === null) return 'it is not correctly encoded'+ if (out.has(key)) return `"${key}" is given more than once`+ out.set(key, val)+ }+ return out+}++/** Parse a `nodeterm://` URL. Never throws. */+export function parseNodetermLink(input: unknown): ParseLinkResult {+ if (typeof input !== 'string') return refuse('the link is not text')+ const url = input.trim()+ if (url.length > OPEN_LINK_LIMITS.url) return refuse('the link is too long')+ if (url.slice(0, OPEN_LINK_SCHEME.length + 2).toLowerCase() !== `${OPEN_LINK_SCHEME}//`) {+ return refuse('it is not a nodeterm:// link')+ }+ if (url.includes('#')) return refuse('it has a fragment (#)')+ const rest = url.slice(OPEN_LINK_SCHEME.length + 2)+ const q = rest.indexOf('?')+ // `nodeterm://open?…` and `nodeterm://open/?…` both name the host `open`.+ const host = (q === -1 ? rest : rest.slice(0, q)).replace(/\/$/, '').toLowerCase()+ const query = q === -1 ? '' : rest.slice(q + 1)++ if (host === 'pair' || host === 'join') {+ const params = readQuery(query)+ if (typeof params === 'string') return refuse(`the ${host} link: ${params}`)+ for (const key of params.keys()) {+ if (key !== 'code') return refuse(`the ${host} link has an unknown parameter "${clip(key)}"`)+ }+ const code = params.get('code')+ if (!code) return refuse(`the ${host} link has no code`)+ if (code.length > OPEN_LINK_LIMITS.code || ANY_CONTROL.test(code)) return refuse(`the ${host} code is not valid`)+ // Rebuilt from the decoded code so the existing decoders see the canonical prefix form.+ return { ok: true, link: { kind: host, url: `nodeterm://${host}?code=${code}` } }+ }+ if (host !== 'open') return refuse(host ? `nodeterm://${host} is not a link nodeterm opens` : 'it names no action')++ const params = readQuery(query)+ if (typeof params === 'string') return refuse(params)+ for (const key of params.keys()) {+ if (!(OPEN_PARAMS as readonly string[]).includes(key)) return refuse(`unknown parameter "${clip(key)}"`)+ }+ const get = (k: OpenParam): string | undefined => params.get(k)++ const agent = get('agent')+ if (!agent) return refuse('it does not say which agent to open (agent=)')+ if (!isOpenLinkAgent(agent)) return refuse(`"${clip(agent)}" is not an agent nodeterm can open`)++ const request: OpenLinkRequest = { agent }++ const project = get('project')+ const projectCwd = get('project-cwd')+ if (project !== undefined && projectCwd !== undefined) {+ return refuse('"project" and "project-cwd" cannot be combined')+ }+ if (project !== undefined) {+ if (!project || project.length > OPEN_LINK_LIMITS.projectId || ANY_CONTROL.test(project) || FORMAT_CONTROL.test(project) || hasHiddenText(project)) {+ return refuse('"project" is not a valid project id')+ }+ request.project = project+ }+ if (projectCwd !== undefined) {+ if (!isAcceptableAbsolutePath(projectCwd)) return refuse('"project-cwd" must be an absolute path')+ request.projectCwd = projectCwd+ }++ const cwd = get('cwd')+ if (cwd !== undefined) {+ if (!isAcceptableAbsolutePath(cwd)) return refuse('"cwd" must be an absolute path')+ request.cwd = cwd+ }++ const prompt = get('prompt')+ const promptFile = get('prompt-file')+ if (prompt !== undefined && promptFile !== undefined) {+ return refuse('"prompt" and "prompt-file" cannot be combined')+ }+ if ((prompt !== undefined || promptFile !== undefined) && agent === 'terminal') {+ // Typing text into a shell is running a command, not sending a message.+ return refuse('a terminal link cannot carry a prompt')+ }+ if (prompt !== undefined) {+ if (utf8Bytes(prompt) > OPEN_LINK_LIMITS.prompt) return refuse('"prompt" is longer than 8 KB (use prompt-file)')+ if (CONTROL_EXCEPT_WS.test(prompt)) return refuse('"prompt" contains control characters')+ if (hasHiddenText(prompt)) return refuse('"prompt" contains invisible or direction-changing characters')+ if (prompt.trim()) request.prompt = prompt+ }+ if (promptFile !== undefined) {+ if (!isAcceptableAbsolutePath(promptFile)) return refuse('"prompt-file" must be an absolute path')+ request.promptFile = promptFile+ }++ const title = get('title')+ if (title !== undefined) {+ if (codePoints(title) > OPEN_LINK_LIMITS.title) return refuse('"title" is longer than 80 characters')+ if (ANY_CONTROL.test(title) || FORMAT_CONTROL.test(title) || hasHiddenText(title)) return refuse('"title" contains control characters')+ if (title.trim()) request.title = title.trim()+ }++ const source = get('source')+ if (source !== undefined) {+ if (codePoints(source) > OPEN_LINK_LIMITS.source) return refuse('"source" is longer than 40 characters')+ if (ANY_CONTROL.test(source) || FORMAT_CONTROL.test(source) || hasHiddenText(source)) return refuse('"source" contains control characters')+ if (source.trim()) request.source = source.trim()+ }++ return { ok: true, link: { kind: 'open', request } }+}++/** A title the human edited in the sheet, checked again by main: one line, ≤ 80, no controls.+ * Empty / whitespace = no title. Returns null when it is not acceptable. */+export function normalizeLinkTitle(raw: unknown): string | undefined | null {+ if (raw === undefined || raw === null) return undefined+ if (typeof raw !== 'string') return null+ const t = raw.trim()+ if (!t) return undefined+ if (codePoints(t) > OPEN_LINK_LIMITS.title || ANY_CONTROL.test(t) || FORMAT_CONTROL.test(t) || hasHiddenText(t)) return null+ return t+}++/** The first `nodeterm://` URL in a process argv (Windows/Linux deliver a clicked link that way:+ * on first launch in `process.argv`, afterwards in `second-instance`'s argv). */+export function nodetermUrlFromArgv(argv: readonly string[]): string | null {+ for (const a of argv) {+ if (typeof a === 'string' && a.slice(0, OPEN_LINK_SCHEME.length + 2).toLowerCase() === `${OPEN_LINK_SCHEME}//`) {+ return a+ }+ }+ return null+}++// ─── Choosing the project ────────────────────────────────────────────────────────────────────────++/** A project as main's workspace index knows it — the only source of candidates (the renderer is+ * the more attackable half and may only pick among what main offered). */+export interface LinkProjectEntry {+ id: string+ name: string+ cwd?: string+ closed?: boolean+ /** SSH projects are out of scope for v1. */+ ssh?: boolean+ /** Handed to a hosted team: reopening it asks first everywhere else, so a link never offers it. */+ handedOff?: boolean+}++export interface LinkProjectCandidate {+ id: string+ name: string+ cwd?: string+ closed: boolean+}++export type LinkProjectNote =+ /** `project=<id>` names nothing in the index. */+ | 'not-found'+ /** `project=<id>` names an SSH project (or one handed to a team). */+ | 'unsupported'+ /** `project-cwd=` matched no project. */+ | 'no-match'++export interface LinkProjectResolution {+ /** Every project the sheet may offer, preselected / matching ones first. */+ candidates: LinkProjectCandidate[]+ /** The suggestion; null = none (the sheet falls back to the active project if offerable). */+ preselectId: string | null+ note?: LinkProjectNote+ /** "Open <folder> as a new project", offered when no project owns that exact folder. */+ newProjectCwd?: string+}++/** Comparable form of a path: separators unified, no trailing separator (root kept). */+export function comparablePath(p: string): string {+ const s = p.replace(/\\/g, '/')+ // A scan, not /\/+$/: that regex is quadratic on a run of slashes.+ let end = s.length+ while (end > 1 && s.charCodeAt(end - 1) === 47) end--+ return s.slice(0, end)+}++/** Is `child` the folder `dir` or inside it — segment-wise, so `/repo-x` is not inside `/repo`. */+export function pathWithin(child: string, dir: string): boolean {+ const c = comparablePath(child)+ const d = comparablePath(dir)+ if (c === d) return true+ return c.startsWith(d.endsWith('/') ? d : `${d}/`)+}++export function resolveLinkProject(req: OpenLinkRequest, entries: readonly LinkProjectEntry[]): LinkProjectResolution {+ const offerable = entries.filter((e) => !e.ssh && !e.handedOff)+ const toCandidate = (e: LinkProjectEntry): LinkProjectCandidate => ({+ id: e.id,+ name: e.name,+ ...(e.cwd ? { cwd: e.cwd } : {}),+ closed: !!e.closed+ })+ // Open projects before closed ones; otherwise index order.+ const ordered = [...offerable.filter((e) => !e.closed), ...offerable.filter((e) => e.closed)]+ const front = (first: LinkProjectEntry[]): LinkProjectCandidate[] => {+ const ids = new Set(first.map((e) => e.id))+ return [...first, ...ordered.filter((e) => !ids.has(e.id))].map(toCandidate)+ }++ const folder = req.cwd ?? req.projectCwd+ const ownsFolder = folder+ ? offerable.some((e) => e.cwd && comparablePath(e.cwd) === comparablePath(folder))+ : true+ const newProjectCwd = folder && !ownsFolder ? folder : undefined+ const withNew = (r: LinkProjectResolution): LinkProjectResolution =>+ newProjectCwd ? { ...r, newProjectCwd } : r++ if (req.project !== undefined) {+ const hit = entries.find((e) => e.id === req.project)+ if (!hit) return withNew({ candidates: front([]), preselectId: null, note: 'not-found' })+ if (hit.ssh || hit.handedOff) return withNew({ candidates: front([]), preselectId: null, note: 'unsupported' })+ return withNew({ candidates: front([hit]), preselectId: hit.id })+ }++ if (req.projectCwd !== undefined) {+ const want = comparablePath(req.projectCwd)+ const matches = ordered.filter((e) => e.cwd && comparablePath(e.cwd) === want)+ if (!matches.length) return withNew({ candidates: front([]), preselectId: null, note: 'no-match' })+ return withNew({ candidates: front(matches), preselectId: matches[0].id })+ }++ if (req.cwd !== undefined) {+ let best: LinkProjectEntry | null = null+ for (const e of ordered) {+ if (!e.cwd || !pathWithin(req.cwd, e.cwd)) continue+ if (!best || comparablePath(e.cwd).length > comparablePath(best.cwd as string).length) best = e+ }+ if (best) return withNew({ candidates: front([best]), preselectId: best.id })+ }+ return withNew({ candidates: front([]), preselectId: null })+}++// ─── The wire between main and the sheet ─────────────────────────────────────────────────────────++/** What main sends the renderer for an `open` link, every path already checked by main. */+export interface OpenLinkPrompt {+ id: string+ agent: OpenLinkAgent+ cwd?: string+ prompt?: string+ /** The `prompt-file` path, and its content as main read it for display (re-read on accept). */+ promptFile?: string+ promptFileText?: string+ title?: string+ source?: string+ resolution: LinkProjectResolution+ /** The agent's command was not found on the login-shell PATH. A warning, not a refusal: a launch+ * command override can make the bare binary irrelevant. */+ agentMissing?: boolean+}++/** The human's answer. Only a choice among what main offered: never a path, never a prompt. */+export interface OpenLinkChoice {+ /** One of `resolution.candidates`, or omitted with `newProject`. */+ projectId?: string+ /** Open `resolution.newProjectCwd` as a new project. */+ newProject?: boolean+ title?: string+}++/** Main's verdict on a choice: the final, re-checked open. */+export type OpenLinkAcceptResult =+ | {+ ok: true+ open: {+ agent: OpenLinkAgent+ projectId?: string+ newProjectCwd?: string+ cwd?: string+ prompt?: string+ /** A copy of the prompt file under nodeterm's own launch-prompt store. */+ promptFile?: string+ title?: string+ }+ }+ | { ok: false; reason: string }diff --git a/src/shared/types.ts b/src/shared/types.tsindex 3a9e74018..ae783de0f 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1955,6 +1955,13 @@ export interface Settings {* the lock is one person's view state. Machine-local on Desktop; in the Server Edition this* setting is the server's while the lock is per browser profile. */rememberCanvasLock: boolean+ /** Whether `nodeterm://` links from other apps are handled (docs/superpowers/specs/+ * 2026-10-13-open-link-design.md). OFF by default: a link can come from any web page, script+ * or app, so taking them is something a person turns on. On, a `nodeterm://open` link shows a+ * confirm sheet and opens ONE agent or terminal node only after a click; `nodeterm://pair` and+ * `nodeterm://join` pre-fill the code prompt. Off, a link opens nothing and a notice says where+ * to turn it on. Machine-local (settings.json); read by main on every link. */+ allowOpenLinks: boolean/** Open Markdown files (.md, .markdown, …) in rendered preview instead of the code editor.* Only picks the view an editor node OPENS in — the node's Preview/Edit toggle (and the* markdown-toggle chord) still switches either way. Default ON since the release after@@ -2408,6 +2415,7 @@ export const DEFAULT_SETTINGS: Settings = {focusZoomToNode: true,offerCloseProjectOnLastSession: false,rememberCanvasLock: false,+ allowOpenLinks: false,openMarkdownPreview: true,openMarkdownPreviewMigrated: true,terminalMiddleClickPaste: false,@@ -4336,6 +4344,22 @@ export interface TriggersApi {): Promise<{ outcome: 'fired' | 'missed' | 'failed' | 'queued'; detail?: string }>}+/** `nodeterm://` links (see main/open-link.ts, @shared/open-link). */+export interface OpenLinkApi {+ /** The renderer is listening: main delivers any link that arrived before (a cold start). */+ ready(): void+ /** An `open` link for the confirm sheet. */+ onRequest(listener: (req: import('./open-link').OpenLinkPrompt) => void): () => void+ /** A `pair` / `join` link: route to the existing pairing / join flow, never auto-accept. */+ onPair(listener: (link: { kind: 'pair' | 'join'; url: string }) => void): () => void+ /** A refused or dropped link, as one sentence for a toast. */+ onNotice(listener: (n: { text: string }) => void): () => void+ /** The human's choice; main re-checks it and answers with the final open. */+ accept(id: string, choice: import('./open-link').OpenLinkChoice): Promise<import('./open-link').OpenLinkAcceptResult>+ /** The sheet was dismissed (or replaced): forget the request. */+ cancel(id: string): void+}+export interface NodeTerminalApi {pty: PtyApiworkspace: WorkspaceApi@@ -4400,6 +4424,9 @@ export interface NodeTerminalApi {pairing: PairingApipresence: PresenceApishortcuts: ShortcutsApi+ /** `nodeterm://` links clicked outside the app. Desktop only (the Server Edition has no URL+ * scheme: its stub never fires and refuses accept). */+ openLink: OpenLinkApi/** Fires when the user presses Cmd/Ctrl+M (toggle markdown view). Returns unsubscribe. */onMarkdownToggle(listener: () => void): () => void/** Fires when the user presses Cmd/Ctrl+W (close selected node). Returns unsubscribe. */