From 3b299b33e9a7b3e9ebe9d9da2d0bf0aa03fa0b2c Mon Sep 17 00:00:00 2001 From: LukeParkerDev <10430890+Hona@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:59:50 +1000 Subject: [PATCH 1/2] fix(desktop): open projects and new sessions from opencode:// links again --- .../app/src/runtime/platform/platform.tsx | 6 ++ .../app/src/shell/deep-links/deep-links.ts | 58 ++++++++++++++++ .../app/src/shell/deep-links/machine.test.ts | 67 +++++++++++++++++++ packages/app/src/shell/deep-links/machine.ts | 67 +++++++++++++++++++ packages/app/src/shell/shell.tsx | 3 + packages/desktop/src/main/index.ts | 2 + packages/desktop/src/main/lifecycle/index.ts | 12 +++- .../src/main/lifecycle/launch-links.ts | 28 ++++++++ packages/desktop/src/renderer/env.d.ts | 3 - .../desktop/src/renderer/platform/index.ts | 2 + .../src/renderer/startup/deep-links.test.ts | 35 ++++++++++ .../src/renderer/startup/deep-links.ts | 37 ++++++++-- 12 files changed, 309 insertions(+), 11 deletions(-) create mode 100644 packages/app/src/shell/deep-links/deep-links.ts create mode 100644 packages/app/src/shell/deep-links/machine.test.ts create mode 100644 packages/app/src/shell/deep-links/machine.ts create mode 100644 packages/desktop/src/main/lifecycle/launch-links.ts create mode 100644 packages/desktop/src/renderer/startup/deep-links.test.ts diff --git a/packages/app/src/runtime/platform/platform.tsx b/packages/app/src/runtime/platform/platform.tsx index d0a8b168f6cb..a2e1ec8366a6 100644 --- a/packages/app/src/runtime/platform/platform.tsx +++ b/packages/app/src/runtime/platform/platform.tsx @@ -69,6 +69,12 @@ type PlatformBase = { /** Resolve the native source path for a desktop File. */ getPathForFile?(file: File): string + /** + * Observe `opencode://` links opened with the app (desktop only). Links that arrived before the first listener + * are delivered to it at once. + */ + onDeepLinks?(listener: (urls: string[]) => void): () => void + /** Observe native drag cancellation that does not reach the renderer event loop. */ onDragCancel?(callback: () => void): () => void diff --git a/packages/app/src/shell/deep-links/deep-links.ts b/packages/app/src/shell/deep-links/deep-links.ts new file mode 100644 index 000000000000..7024dad6313b --- /dev/null +++ b/packages/app/src/shell/deep-links/deep-links.ts @@ -0,0 +1,58 @@ +import { createEffect, createMemo, onCleanup, untrack } from "solid-js" +import { usePlatform } from "@/runtime/platform/platform" +import { ServerConnection, useServers } from "@/runtime/server/registry" +import { useGlobal } from "@/runtime/server/runtime" +import { useTabs } from "@/shell/tabs/tabs" +import { INITIAL_DEEP_LINK_STATE, transitionDeepLinks, type DeepLinkEffect, type DeepLinkEvent } from "./machine" + +/** Opens the `opencode://` links the desktop app receives, for as long as the shell lives. */ +export function useDeepLinks() { + const platform = usePlatform() + const servers = useServers() + const global = useGlobal() + const tabs = useTabs() + + const own = createMemo(() => servers.list.find(ServerConnection.builtin)) + + // The app's own server can open projects: connected, with its project list loaded. + const ready = createMemo(() => { + const conn = own() + const ctx = conn && global.serverCtx(ServerConnection.key(conn)) + + return !!ctx && ctx.sdk.connection.status() === "connected" && ctx.sync.project.ready() + }) + + const machine = { state: INITIAL_DEEP_LINK_STATE } + + const dispatch = (event: DeepLinkEvent) => { + const next = transitionDeepLinks(machine.state, event) + machine.state = next.state + next.effects.forEach(run) + } + + // A project that can't be added shows the server's error (`projects.add`); one that can opens in a new session. + const run = (effect: DeepLinkEffect) => { + const conn = untrack(own) + const ctx = conn && untrack(() => global.serverCtx(ServerConnection.key(conn))) + + if (!conn || !ctx) return + const server = ServerConnection.key(conn) + + void ctx.projects.add(effect.link.directory).then((project) => { + if (!project) return + + const prompt = effect.link.type === "new-session" ? effect.link.prompt : undefined + + void tabs.newDraft({ server, directory: project.worktree }, prompt) + }) + } + + createEffect(() => { + const event: DeepLinkEvent = ready() ? { type: "server.ready" } : { type: "server.lost" } + untrack(() => dispatch(event)) + }) + + const stop = platform.onDeepLinks?.((urls) => dispatch({ type: "links.received", urls })) + + if (stop) onCleanup(stop) +} diff --git a/packages/app/src/shell/deep-links/machine.test.ts b/packages/app/src/shell/deep-links/machine.test.ts new file mode 100644 index 000000000000..6f2c1a15bdce --- /dev/null +++ b/packages/app/src/shell/deep-links/machine.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, test } from "bun:test" +import { INITIAL_DEEP_LINK_STATE, parseDeepLink, transitionDeepLinks, type DeepLinkEvent } from "./machine" + +const project = `opencode://open-project?directory=${encodeURIComponent("C:\\work\\api")}` + +const session = `opencode://new-session?directory=%2Frepo&prompt=${encodeURIComponent("fix the build")}` + +describe("deep links", () => { + test.each([ + { url: project, link: { type: "open-project", directory: "C:\\work\\api" } }, + { url: "opencode://open-project?directory=/repo", link: { type: "open-project", directory: "/repo" } }, + { url: session, link: { type: "new-session", directory: "/repo", prompt: "fix the build" } }, + { + url: "opencode://new-session?directory=/repo", + link: { type: "new-session", directory: "/repo", prompt: undefined }, + }, + { url: "opencode://open-project", link: undefined }, + { url: "opencode://open-project?directory=%2Frepo%0A", link: undefined }, + { url: "opencode://console/authorized?window=a", link: undefined }, + { url: "https://open-project?directory=/repo", link: undefined }, + { url: "opencode://open-project/%E0%A4%A%", link: undefined }, + ])("reads $url", ({ url, link }) => { + expect(parseDeepLink(url)).toEqual(link) + }) + + test("a link that started the app waits for the app's server, then each opens in order", () => { + const events: DeepLinkEvent[] = [ + { type: "links.received", urls: [project, "opencode://console/authorized?window=a"] }, + { type: "server.lost" }, + { type: "links.received", urls: [session] }, + { type: "server.ready" }, + ] + + const result = events.reduce( + (acc, event) => { + const next = transitionDeepLinks(acc.state, event) + + return { state: next.state, opened: [...acc.opened, ...next.effects.map((effect) => effect.link.directory)] } + }, + { state: INITIAL_DEEP_LINK_STATE, opened: new Array() }, + ) + + expect(result.opened).toEqual(["C:\\work\\api", "/repo"]) + expect(result.state).toEqual({ type: "ready" }) + }) + + test("while the server is ready a link opens at once, and after it drops links wait again", () => { + const ready = transitionDeepLinks(INITIAL_DEEP_LINK_STATE, { type: "server.ready" }).state + const opened = transitionDeepLinks(ready, { type: "links.received", urls: [project] }) + + expect(opened.state).toBe(ready) + expect(opened.effects).toEqual([{ type: "open", link: { type: "open-project", directory: "C:\\work\\api" } }]) + + const lost = transitionDeepLinks(ready, { type: "server.lost" }).state + const waiting = transitionDeepLinks(lost, { type: "links.received", urls: [project] }) + + expect(waiting.effects).toEqual([]) + expect(waiting.state).toEqual({ type: "waiting", queued: [{ type: "open-project", directory: "C:\\work\\api" }] }) + }) + + test("a link the app doesn't open changes nothing", () => { + const next = transitionDeepLinks(INITIAL_DEEP_LINK_STATE, { type: "links.received", urls: ["opencode://other"] }) + + expect(next.state).toBe(INITIAL_DEEP_LINK_STATE) + expect(next.effects).toEqual([]) + }) +}) diff --git a/packages/app/src/shell/deep-links/machine.ts b/packages/app/src/shell/deep-links/machine.ts new file mode 100644 index 000000000000..73baeac11b81 --- /dev/null +++ b/packages/app/src/shell/deep-links/machine.ts @@ -0,0 +1,67 @@ +// `opencode://` links opened with the desktop app. Both open on the app's own server, the one on this computer: +// - `open-project?directory=` opens the folder as a project, in a new session. +// - `new-session?directory=&prompt=` does the same with the prompt typed in, not sent. +// A link that arrives before that server can open projects (one that started the app) waits for it. + +export type DeepLink = + | { readonly type: "open-project"; readonly directory: string } + | { readonly type: "new-session"; readonly directory: string; readonly prompt: string | undefined } + +export type DeepLinkState = + | { readonly type: "waiting"; readonly queued: readonly DeepLink[] } + | { readonly type: "ready" } + +export type DeepLinkEvent = + | { readonly type: "links.received"; readonly urls: readonly string[] } + | { readonly type: "server.ready" } + | { readonly type: "server.lost" } + +export type DeepLinkEffect = { readonly type: "open"; readonly link: DeepLink } + +export type DeepLinkTransition = { readonly state: DeepLinkState; readonly effects: readonly DeepLinkEffect[] } + +export const INITIAL_DEEP_LINK_STATE: DeepLinkState = { type: "waiting", queued: [] } + +const READY: DeepLinkState = { type: "ready" } + +export function transitionDeepLinks(state: DeepLinkState, event: DeepLinkEvent): DeepLinkTransition { + if (event.type === "links.received") { + const links = event.urls.flatMap((url) => parseDeepLink(url) ?? []) + + if (links.length === 0) return { state, effects: [] } + + if (state.type === "ready") return { state, effects: links.map(open) } + + return { state: { type: "waiting", queued: [...state.queued, ...links] }, effects: [] } + } + + if (event.type === "server.ready") { + if (state.type === "ready") return { state, effects: [] } + + return { state: READY, effects: state.queued.map(open) } + } + + if (state.type === "waiting") return { state, effects: [] } + + return { state: INITIAL_DEEP_LINK_STATE, effects: [] } +} + +export function parseDeepLink(value: string): DeepLink | undefined { + if (!URL.canParse(value)) return + const url = new URL(value) + + if (url.protocol !== "opencode:") return + const directory = url.searchParams.get("directory") + + if (!directory || /[\u0000-\u001f\u007f]/.test(directory)) return + + if (url.hostname === "open-project") return { type: "open-project", directory } + + if (url.hostname !== "new-session") return + + return { type: "new-session", directory, prompt: url.searchParams.get("prompt") || undefined } +} + +function open(link: DeepLink): DeepLinkEffect { + return { type: "open", link } +} diff --git a/packages/app/src/shell/shell.tsx b/packages/app/src/shell/shell.tsx index fdad7ee44b89..5f9d2ed8ec66 100644 --- a/packages/app/src/shell/shell.tsx +++ b/packages/app/src/shell/shell.tsx @@ -8,6 +8,7 @@ import { Titlebar } from "@/shell/titlebar/titlebar" import { usePlatform } from "@/runtime/platform/platform" import { ToastRegion } from "@/shell/notifications/toast" import { createTipToasts } from "@/tips/model" +import { useDeepLinks } from "@/shell/deep-links/deep-links" import { UploadToastHost } from "@/composer/attachments/uploads" import { useSettingsSurface } from "@/settings/surface" import { useSettings } from "@/settings/model" @@ -46,6 +47,8 @@ export default function Layout(props: ParentProps) { createTipToasts() + useDeepLinks() + const [state, setState] = createStore<{ tabsWidth: number tabsMount: HTMLElement | undefined diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts index 1f7bb4e80c53..f8e109610a0a 100644 --- a/packages/desktop/src/main/index.ts +++ b/packages/desktop/src/main/index.ts @@ -2,6 +2,7 @@ import { marks } from "./lifecycle/marks" import { app } from "electron" import { acquireApplicationLock, configureApplication } from "./lifecycle/configure" +import { captureLaunchLinks } from "./lifecycle/launch-links" import { startSidecarProbe } from "./service/sidecar-probe" import { registerStorageSnapshotHandler } from "./storage/snapshot" import { createEarlyWindow, earlyWindowClosed } from "./windows/early" @@ -15,6 +16,7 @@ import { registerRendererScheme } from "./windows/scheme" configureApplication() if (acquireApplicationLock()) { + captureLaunchLinks() registerRendererScheme() // Window first, then the bundle: starting the import before ready delays ready itself, because the // module graph evaluates on the same thread Chromium needs to finish initialising. diff --git a/packages/desktop/src/main/lifecycle/index.ts b/packages/desktop/src/main/lifecycle/index.ts index 7c106d3c0ecf..f8ad68533157 100644 --- a/packages/desktop/src/main/lifecycle/index.ts +++ b/packages/desktop/src/main/lifecycle/index.ts @@ -4,6 +4,7 @@ import { app, BrowserWindow } from "electron" import type { Event } from "electron" import { Context, Effect, Layer } from "effect" import { DeepLinks } from "../deep-links" +import { deepLinkArguments, takeLaunchLinks } from "./launch-links" import { DesktopLogging, scoped } from "../native/logging" import { DesktopStorage } from "../storage" import { safeWebContentsOrigin } from "../windows/state" @@ -103,7 +104,7 @@ const runtime = Layer.effect( const deepLinks = yield* DeepLinks.make(focusWindow) const secondInstance = (_event: Event, argv: string[]) => { - const urls = argv.filter((arg) => arg.startsWith("opencode://")) + const urls = deepLinkArguments(argv) if (urls.length) { runFork(Effect.logInfo("deep link received via second-instance", { urls })) @@ -167,6 +168,15 @@ const runtime = Layer.effect( app.on("render-process-gone", renderProcessGone) process.on("SIGINT", signal) process.on("SIGTERM", signal) + + // The router waits for a window to be ready, so the links the app was started with open once one is. + const launched = takeLaunchLinks() + + if (launched.length) { + runFork(Effect.logInfo("deep link received at launch", { urls: launched })) + deepLinks.receive(launched) + } + yield* Effect.addFinalizer(() => Effect.sync(() => { app.off("second-instance", secondInstance) diff --git a/packages/desktop/src/main/lifecycle/launch-links.ts b/packages/desktop/src/main/lifecycle/launch-links.ts new file mode 100644 index 000000000000..9b5708a89cf5 --- /dev/null +++ b/packages/desktop/src/main/lifecycle/launch-links.ts @@ -0,0 +1,28 @@ +import { app } from "electron" +import type { Event } from "electron" + +// The `opencode://` links the app was started with, held until the deep-link router takes them. Windows and Linux +// pass a link on the command line; macOS sends `open-url` while the app finishes launching, before the router's own +// listener exists. +const pending: string[] = [] + +const early = (event: Event, url: string) => { + event.preventDefault() + pending.push(url) +} + +export function captureLaunchLinks() { + pending.push(...deepLinkArguments(process.argv)) + app.on("open-url", early) +} + +/** The links the app was started with; later ones reach the router's own listener. */ +export function takeLaunchLinks() { + app.off("open-url", early) + + return pending.splice(0) +} + +export function deepLinkArguments(argv: readonly string[]) { + return argv.filter((arg) => arg.startsWith("opencode://")) +} diff --git a/packages/desktop/src/renderer/env.d.ts b/packages/desktop/src/renderer/env.d.ts index ba7836cbfe30..9d0cc322d103 100644 --- a/packages/desktop/src/renderer/env.d.ts +++ b/packages/desktop/src/renderer/env.d.ts @@ -7,8 +7,5 @@ declare global { interface Window { electron: ElectronNative - __OPENCODE__?: { - deepLinks?: string[] - } } } diff --git a/packages/desktop/src/renderer/platform/index.ts b/packages/desktop/src/renderer/platform/index.ts index 7b6ede015897..b3b3fc7367f9 100644 --- a/packages/desktop/src/renderer/platform/index.ts +++ b/packages/desktop/src/renderer/platform/index.ts @@ -4,6 +4,7 @@ import { setPinchZoomEnabled, setZoomLevel, webviewZoom, zoomLevel } from "../wi import { windowFullscreen } from "../window/fullscreen" import { DragCancelEvent } from "../../shared/ipc-transport" import { createPluginBridge } from "../plugins" +import { onDeepLinks } from "../startup/deep-links" import { createDesktopFiles } from "./files" import { createDesktopMenuAction } from "./menu" import { createDesktopNotify } from "./notifications" @@ -45,6 +46,7 @@ export function createDesktopPlatform(api: ElectronAPI, windowState: DesktopWind setPinchZoomEnabled, getSpellcheckEnabled: () => api.getSpellcheckEnabled(), setSpellcheckEnabled: (enabled) => api.setSpellcheckEnabled(enabled), + onDeepLinks, onDragCancel: (callback) => { window.addEventListener(DragCancelEvent, callback) diff --git a/packages/desktop/src/renderer/startup/deep-links.test.ts b/packages/desktop/src/renderer/startup/deep-links.test.ts new file mode 100644 index 000000000000..144614fb5673 --- /dev/null +++ b/packages/desktop/src/renderer/startup/deep-links.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from "bun:test" +import type { ElectronAPI } from "../api-types" +import { onDeepLinks, startDeepLinks } from "./deep-links" + +describe("renderer deep links", () => { + test("links that reach the window before the app listens are delivered to its first listener once", () => { + const acknowledged: number[] = [] + const deliveries: Array<(delivery: { attempt: number; urls: string[] }) => void> = [] + + const api: Pick = { + onDeepLink: (cb) => { + deliveries.push(cb) + + return () => {} + }, + acknowledgeDeepLinks: (attempt) => acknowledged.push(attempt), + readyDeepLinks: () => {}, + } + + startDeepLinks(api) + deliveries.forEach((deliver) => deliver({ attempt: 1, urls: ["opencode://open-project?directory=/a"] })) + + const first: string[][] = [] + const second: string[][] = [] + const stop = onDeepLinks((urls) => first.push(urls)) + onDeepLinks((urls) => second.push(urls)) + deliveries.forEach((deliver) => deliver({ attempt: 2, urls: ["opencode://open-project?directory=/b"] })) + stop() + deliveries.forEach((deliver) => deliver({ attempt: 3, urls: ["opencode://open-project?directory=/c"] })) + + expect(acknowledged).toEqual([1, 2, 3]) + expect(first).toEqual([["opencode://open-project?directory=/a"], ["opencode://open-project?directory=/b"]]) + expect(second).toEqual([["opencode://open-project?directory=/b"], ["opencode://open-project?directory=/c"]]) + }) +}) diff --git a/packages/desktop/src/renderer/startup/deep-links.ts b/packages/desktop/src/renderer/startup/deep-links.ts index b056bbd18d6e..a2d52d26cdcc 100644 --- a/packages/desktop/src/renderer/startup/deep-links.ts +++ b/packages/desktop/src/renderer/startup/deep-links.ts @@ -1,20 +1,43 @@ import type { ElectronAPI } from "../api-types" -const deepLinkEvent = "opencode:deep-link" +type Listener = (urls: string[]) => void + +// Links that arrived before the app listened, and the app's listeners. +const pending: string[] = [] + +const listeners = new Set() // Main sends each link to one renderer at a time and forgets it once acknowledged, so a reload or a new window // never handles it again. -export function startDeepLinks(api: ElectronAPI) { +export function startDeepLinks(api: Pick) { api.onDeepLink((delivery) => { - emitDeepLinks(delivery.urls) + deliver(delivery.urls) api.acknowledgeDeepLinks(delivery.attempt) }) api.readyDeepLinks() } -function emitDeepLinks(urls: string[]) { +/** Follows the links opened with the app; the ones that came before the first listener reach it at once. */ +export function onDeepLinks(listener: Listener) { + listeners.add(listener) + + const queued = pending.splice(0) + + if (queued.length) listener(queued) + + return () => { + listeners.delete(listener) + } +} + +function deliver(urls: string[]) { if (urls.length === 0) return - window.__OPENCODE__ ??= {} - window.__OPENCODE__.deepLinks = [...(window.__OPENCODE__.deepLinks ?? []), ...urls] - window.dispatchEvent(new CustomEvent(deepLinkEvent, { detail: { urls } })) + + if (listeners.size === 0) { + pending.push(...urls) + + return + } + + listeners.forEach((listener) => listener(urls)) } From d85a18db46e7afa5a7873caaa848781c0820c440 Mon Sep 17 00:00:00 2001 From: LukeParkerDev <10430890+Hona@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:02:14 +1000 Subject: [PATCH 2/2] fix(app): open queued opencode:// links one after another, in order --- packages/app/src/shell/deep-links/deep-links.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/app/src/shell/deep-links/deep-links.ts b/packages/app/src/shell/deep-links/deep-links.ts index 7024dad6313b..89a491867c7c 100644 --- a/packages/app/src/shell/deep-links/deep-links.ts +++ b/packages/app/src/shell/deep-links/deep-links.ts @@ -30,6 +30,9 @@ export function useDeepLinks() { next.effects.forEach(run) } + // Each link opens after the one before it, so the tabs open in the order the links came and the last one is in front. + const opening = { last: Promise.resolve() } + // A project that can't be added shows the server's error (`projects.add`); one that can opens in a new session. const run = (effect: DeepLinkEffect) => { const conn = untrack(own) @@ -38,13 +41,17 @@ export function useDeepLinks() { if (!conn || !ctx) return const server = ServerConnection.key(conn) - void ctx.projects.add(effect.link.directory).then((project) => { + opening.last = opening.last.then(async () => { + const project = await ctx.projects.add(effect.link.directory) + if (!project) return const prompt = effect.link.type === "new-session" ? effect.link.prompt : undefined - void tabs.newDraft({ server, directory: project.worktree }, prompt) + await tabs.newDraft({ server, directory: project.worktree }, prompt) }) + // A tab that failed to open must not stop the links after it. + opening.last = opening.last.catch(() => undefined) } createEffect(() => {