Skip to content

AI-native design editor. Open-source Figma alternative.

feat(cloud): open Cloud links in the desktop app (#1072)

Danila Poyarkovc402e004302e
diff --git a/changes/1069/added.md b/changes/1069/added.md
index 28a1b3a50..b19ad1d53 100644
--- a/changes/1069/added.md
+++ b/changes/1069/added.md
@@ -1 +1 @@
-- OpenPencil Cloud is ready to self-host, and to try before the hosted service opens: open the editor with `?cloud=preview`, or follow an invitation, to keep documents on your team's server and edit them together. Connect a server in **Settings → Cloud**, which also holds the hosted service's waitlist: email and password sign in, and create an account, right in the dialog, while Google, Apple, and two-step sign-in finish in the browser. Home lists the server's workspaces and the documents shared with you, every account starts with a workspace of its own and can create team workspaces whose admins invite people by email as admins, editors, or viewers and delete them once they are empty, **New design** creates in the place Home shows, **File → Save to…** saves the open document straight to the only workspace or bucket it can go to and asks only when there are several, **File → Browse files…** opens Home where you left it, and a status beside the name appears when the document is offline, couldn't save, changed in two places, with the choice to keep both versions, or is view only. Opening a Cloud document joins its live room, so everyone with it open sees edits and cursors as they happen while one editor saves for all. **Share** invites people by email and turns on a link that opens the document for guests, within what the workspace's plan allows. The server, its relay, and its pages for signing in, account security, and administration are in `@open-pencil/cloud`.
+- OpenPencil Cloud is ready to self-host, and to try before the hosted service opens: open the editor with `?cloud=preview`, or follow an invitation, to keep documents on your team's server and edit them together. Connect a server in **Settings → Cloud**, which also holds the hosted service's waitlist: email and password sign in, and create an account, right in the dialog, while Google, Apple, and two-step sign-in finish in the browser. Home lists the server's workspaces and the documents shared with you, every account starts with a workspace of its own and can create team workspaces whose admins invite people by email as admins, editors, or viewers and delete them once they are empty, **New design** creates in the place Home shows, **File → Save to…** saves the open document straight to the only workspace or bucket it can go to and asks only when there are several, **File → Browse files…** opens Home where you left it, and a status beside the name appears when the document is offline, couldn't save, changed in two places, with the choice to keep both versions, or is view only. Opening a Cloud document joins its live room, so everyone with it open sees edits and cursors as they happen while one editor saves for all. **Share** invites people by email and turns on a link that opens the document for guests, within what the workspace's plan allows; on a computer, the web editor offers to open invitations and shared links in the desktop app. The server, its relay, and its pages for signing in, account security, and administration are in `@open-pencil/cloud`.
diff --git a/desktop/AGENTS.md b/desktop/AGENTS.md
index 65fa03ab8..51c0ee40f 100644
--- a/desktop/AGENTS.md
+++ b/desktop/AGENTS.md
@@ -15,4 +15,5 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j
- Run `bun run generate:icons --target desktop` before direct Cargo checks; native icons are generated, not committed.
- `build_fig_file` performs `.fig` export on desktop; the browser path uses fflate (`packages/fig/AGENTS.md`).
- The embedded WebDriver plugin compiles only with the `native-test` Cargo feature and must never be enabled in development or production binaries. Native tests use `bun run test:native` (`tests/AGENTS.md`).
-- `openpencil://` links are parsed in `desktop/src/deep_link.rs`: `open` queues files through `take_pending_open`, `join` queues validated room IDs through `take_pending_rooms`; second launches forward their link arguments through the single-instance handler (`deep_link` unit tests).
+- The editor opens external links through the `open_external_url` command, which allows only `http`, `https`, and `mailto`; native-test builds record them for `take_native_test_opened_urls` instead of launching a browser (`opener` unit tests, `tests/e2e/native/cloud-links.spec.ts`).
+- `openpencil://` links are parsed in `desktop/src/deep_link.rs`: `open` queues files through `take_pending_open`, `join` queues validated room IDs through `take_pending_rooms`, `cloud` queues Cloud invitations and shared links (UUID, hex secret, `http(s)` server) through `take_pending_cloud_links`; second launches forward their link arguments through the single-instance handler (`deep_link` unit tests).
diff --git a/desktop/src/deep_link.rs b/desktop/src/deep_link.rs
index 23b920c4f..44fb2f8ff 100644
--- a/desktop/src/deep_link.rs
+++ b/desktop/src/deep_link.rs
@@ -14,11 +14,30 @@ pub struct DeepLinkJoin {
pub room: String,
}
+/// An OpenPencil Cloud invitation or a document shared by link, from
+/// `openpencil://cloud/<invitations|share>/<id>?server=<url>#<secret>`: the same path, server, and
+/// secret as the web link on the server's editor address.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+pub struct CloudLink {
+ pub kind: CloudLinkKind,
+ pub id: String,
+ pub server: String,
+ pub secret: String,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum CloudLinkKind {
+ Invitations,
+ Share,
+}
+
#[derive(Debug, PartialEq, Eq)]
pub enum DeepLink {
Open(DeepLinkOpen),
Join(DeepLinkJoin),
OAuth(OAuthCallback),
+ Cloud(CloudLink),
}
#[derive(Debug, PartialEq, Eq)]
@@ -30,6 +49,7 @@ pub enum DeepLinkError {
BadExtension,
BadRoom,
BadOAuthProvider,
+ BadCloudLink,
}
/// Room IDs are 32 lowercase base36 characters (`ROOM_ID_LENGTH` and `ROOM_ID_CHARS` in
@@ -51,6 +71,9 @@ pub fn parse_deep_link(url: &Url) -> Result<DeepLink, DeepLinkError> {
"oauth" => parse_oauth_url(url)
.map(DeepLink::OAuth)
.ok_or(DeepLinkError::BadOAuthProvider),
+ "cloud" => parse_cloud_url(url)
+ .map(DeepLink::Cloud)
+ .ok_or(DeepLinkError::BadCloudLink),
action => Err(DeepLinkError::UnknownAction(action.to_string())),
}
}
@@ -65,6 +88,54 @@ fn parse_join_url(url: &Url) -> Result<DeepLinkJoin, DeepLinkError> {
Ok(DeepLinkJoin { room })
}
+/// Invitation and share IDs are UUIDs, and their secrets 32 to 128 hex characters (the Cloud
+/// sharing contract); the server must be an `http` or `https` address without credentials.
+fn parse_cloud_url(url: &Url) -> Option<CloudLink> {
+ let mut segments = url.path_segments()?;
+ let kind = match segments.next()? {
+ "invitations" => CloudLinkKind::Invitations,
+ "share" => CloudLinkKind::Share,
+ _ => return None,
+ };
+ let id = segments.next().filter(|id| is_uuid(id))?.to_owned();
+ if segments.next().is_some() {
+ return None;
+ }
+ let secret = url
+ .fragment()
+ .filter(|secret| is_secret(secret))?
+ .to_owned();
+ let server = url
+ .query_pairs()
+ .find(|(key, _)| key == "server")
+ .and_then(|(_, value)| Url::parse(&value).ok())
+ .filter(|server| {
+ matches!(server.scheme(), "http" | "https")
+ && server.host_str().is_some()
+ && server.username().is_empty()
+ && server.password().is_none()
+ })?
+ .to_string();
+ Some(CloudLink {
+ kind,
+ id,
+ server,
+ secret,
+ })
+}
+
+fn is_uuid(value: &str) -> bool {
+ value.len() == 36
+ && value.bytes().enumerate().all(|(index, byte)| match index {
+ 8 | 13 | 18 | 23 => byte == b'-',
+ _ => byte.is_ascii_hexdigit(),
+ })
+}
+
+fn is_secret(value: &str) -> bool {
+ (32..=128).contains(&value.len()) && value.bytes().all(|byte| byte.is_ascii_hexdigit())
+}
+
/// An OAuth redirect relayed by the web app's callback page: `openpencil://oauth/<provider>?…`.
/// The query goes to the webview untouched; the attempt that started sign-in checks its state.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
@@ -223,6 +294,57 @@ mod tests {
assert_eq!(oauth("openpencil://open?file=a.pen"), None);
}
+ const CLOUD_ID: &str = "0b6f4f9e-3c1a-4d7e-9a52-6f1c2d3e4f50";
+ const CLOUD_SECRET: &str = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90";
+
+ fn cloud(url: &str) -> Result<DeepLink, DeepLinkError> {
+ parse_deep_link(&Url::parse(url).unwrap())
+ }
+
+ #[test]
+ fn cloud_links_carry_kind_id_server_and_secret() {
+ assert_eq!(
+ cloud(&format!(
+ "openpencil://cloud/invitations/{CLOUD_ID}?server=https%3A%2F%2Fcloud.example.com#{CLOUD_SECRET}"
+ )),
+ Ok(DeepLink::Cloud(CloudLink {
+ kind: CloudLinkKind::Invitations,
+ id: CLOUD_ID.into(),
+ server: "https://cloud.example.com/".into(),
+ secret: CLOUD_SECRET.into(),
+ }))
+ );
+ assert!(matches!(
+ cloud(&format!(
+ "openpencil://cloud/share/{CLOUD_ID}?server=http%3A%2F%2F192.168.1.20%3A3000#{CLOUD_SECRET}"
+ )),
+ Ok(DeepLink::Cloud(CloudLink {
+ kind: CloudLinkKind::Share,
+ ..
+ }))
+ ));
+ }
+
+ #[test]
+ fn cloud_links_refuse_anything_else() {
+ let server = "server=https%3A%2F%2Fcloud.example.com";
+ for url in [
+ format!("openpencil://cloud/documents/{CLOUD_ID}?{server}#{CLOUD_SECRET}"),
+ format!("openpencil://cloud/share/not-a-uuid?{server}#{CLOUD_SECRET}"),
+ format!("openpencil://cloud/share/{CLOUD_ID}/extra?{server}#{CLOUD_SECRET}"),
+ format!("openpencil://cloud/share/{CLOUD_ID}?{server}"),
+ format!("openpencil://cloud/share/{CLOUD_ID}?{server}#short"),
+ format!("openpencil://cloud/share/{CLOUD_ID}?{server}#{}", "g".repeat(64)),
+ format!("openpencil://cloud/share/{CLOUD_ID}#{CLOUD_SECRET}"),
+ format!("openpencil://cloud/share/{CLOUD_ID}?server=file%3A%2F%2F%2Fetc#{CLOUD_SECRET}"),
+ format!(
+ "openpencil://cloud/share/{CLOUD_ID}?server=https%3A%2F%2Fa%3Ab%40cloud.example.com#{CLOUD_SECRET}"
+ ),
+ ] {
+ assert_eq!(cloud(&url), Err(DeepLinkError::BadCloudLink), "{url}");
+ }
+ }
+
fn parse(s: &str) -> Result<DeepLinkOpen, DeepLinkError> {
parse_open_url(&Url::parse(s).unwrap())
}
diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs
index 5652d6582..650a2e8f7 100644
--- a/desktop/src/lib.rs
+++ b/desktop/src/lib.rs
@@ -6,6 +6,7 @@ mod fonts;
mod http;
mod menu;
mod menu_events;
+mod opener;
#[cfg(target_os = "macos")]
mod window;
@@ -48,6 +49,27 @@ struct PendingOpen(Mutex<Vec<PendingOpenFile>>);
/// Rooms from `openpencil://join` links, waiting for the frontend to open them.
struct PendingRooms(Mutex<Vec<String>>);
+/// Cloud invitations and shared links from `openpencil://cloud` links, waiting for the frontend.
+struct PendingCloudLinks(Mutex<Vec<deep_link::CloudLink>>);
+
+#[tauri::command]
+fn take_pending_cloud_links(state: tauri::State<PendingCloudLinks>) -> Vec<deep_link::CloudLink> {
+ state
+ .0
+ .lock()
+ .map(|mut pending| pending.drain(..).collect())
+ .unwrap_or_default()
+}
+
+/// Native-test builds take a link through the same path a launch or an opened URL does.
+#[cfg(feature = "native-test")]
+#[tauri::command]
+fn native_test_open_deep_link(app: tauri::AppHandle, url: String) -> Result<(), String> {
+ let url = url::Url::parse(&url).map_err(|error| error.to_string())?;
+ queue_deep_links(&app, vec![url]);
+ Ok(())
+}
+
#[tauri::command]
fn take_pending_rooms(state: tauri::State<PendingRooms>) -> Vec<String> {
state
@@ -283,6 +305,7 @@ fn queue_open_paths<R: tauri::Runtime>(app: &tauri::AppHandle<R>, paths: Vec<Pat
fn queue_deep_links<R: tauri::Runtime>(app: &tauri::AppHandle<R>, urls: Vec<url::Url>) {
let mut files = Vec::new();
let mut rooms = Vec::new();
+ let mut cloud_links = Vec::new();
for url in urls.iter().filter(|url| url.scheme() == "openpencil") {
match deep_link::parse_deep_link(url) {
Ok(deep_link::DeepLink::Open(open)) => files.push(PendingOpenFile {
@@ -291,6 +314,7 @@ fn queue_deep_links<R: tauri::Runtime>(app: &tauri::AppHandle<R>, urls: Vec<url:
deep_link: true,
}),
Ok(deep_link::DeepLink::Join(join)) => rooms.push(join.room),
+ Ok(deep_link::DeepLink::Cloud(link)) => cloud_links.push(link),
// The sign-in that opened the browser is waiting; it checks the state itself.
Ok(deep_link::DeepLink::OAuth(callback)) => {
let _ = app.emit("oauth-callback", callback);
@@ -298,12 +322,35 @@ fn queue_deep_links<R: tauri::Runtime>(app: &tauri::AppHandle<R>, urls: Vec<url:
let _ = window.set_focus();
}
}
- Err(error) => eprintln!("[deep-link] refused {url}: {error:?}"),
+ // Cloud links carry a secret in the fragment, so a refused link is not echoed.
+ Err(error) => eprintln!(
+ "[deep-link] refused {}: {error:?}",
+ url.host_str().unwrap_or("")
+ ),
}
}
queue_pending(app, files);
queue_rooms(app, rooms);
+ queue_cloud_links(app, cloud_links);
+}
+
+fn queue_cloud_links<R: tauri::Runtime>(
+ app: &tauri::AppHandle<R>,
+ links: Vec<deep_link::CloudLink>,
+) {
+ if links.is_empty() {
+ return;
+ }
+
+ if let Ok(mut pending) = app.state::<PendingCloudLinks>().0.lock() {
+ pending.extend(links);
+ }
+
+ let _ = app.emit("open-cloud-links", ());
+ if let Some(window) = app.get_webview_window("main") {
+ let _ = window.set_focus();
+ }
}
fn queue_rooms<R: tauri::Runtime>(app: &tauri::AppHandle<R>, rooms: Vec<String>) {
@@ -344,7 +391,9 @@ pub fn run() {
#[cfg(feature = "native-test")]
{
- builder = builder.plugin(tauri_plugin_wdio_webdriver::init());
+ builder = builder
+ .manage(opener::OpenedExternalUrls::default())
+ .plugin(tauri_plugin_wdio_webdriver::init());
}
#[cfg(all(
@@ -365,6 +414,7 @@ pub fn run() {
.manage(ProxyHttpRequests::default())
.manage(PendingRooms(Mutex::new(Vec::new())))
.manage(NativeMenuState(Mutex::new(NativeMenuInputs::default())))
+ .manage(PendingCloudLinks(Mutex::new(Vec::new())))
.invoke_handler(tauri::generate_handler![
agents::agent_lookup,
build_fig_file,
@@ -376,6 +426,11 @@ pub fn run() {
credential_store_availability,
credential_write,
mcp_lookup,
+ #[cfg(feature = "native-test")]
+ native_test_open_deep_link,
+ opener::open_external_url,
+ #[cfg(feature = "native-test")]
+ opener::take_native_test_opened_urls,
path_matches_suffix,
list_system_fonts,
load_system_font,
@@ -388,6 +443,7 @@ pub fn run() {
take_pending_open,
take_pending_rooms,
sharing_disabled_by_env,
+ take_pending_cloud_links,
webview_version
])
.plugin(tauri_plugin_opener::init())
diff --git a/desktop/src/opener.rs b/desktop/src/opener.rs
new file mode 100644
index 000000000..19f63313d
--- /dev/null
+++ b/desktop/src/opener.rs
@@ -0,0 +1,79 @@
+use url::Url;
+
+/// Links the editor sends to the system browser or mail app. Anything else, such as `file:` or
+/// another app's scheme, is refused rather than handed to the operating system.
+const EXTERNAL_SCHEMES: [&str; 3] = ["http", "https", "mailto"];
+
+fn external_url(url: &str) -> Result<Url, String> {
+ let parsed = Url::parse(url).map_err(|_| "The link is not a valid address".to_owned())?;
+ if EXTERNAL_SCHEMES.contains(&parsed.scheme()) {
+ Ok(parsed)
+ } else {
+ Err("The link does not open in a browser".to_owned())
+ }
+}
+
+/// Native-test builds record the links they would open, so a test can read the sign-in address
+/// without a browser window opening on the machine running it.
+#[cfg(feature = "native-test")]
+#[derive(Default)]
+pub struct OpenedExternalUrls(pub std::sync::Mutex<Vec<String>>);
+
+#[cfg(not(feature = "native-test"))]
+#[tauri::command]
+pub fn open_external_url<R: tauri::Runtime>(
+ app: tauri::AppHandle<R>,
+ url: String,
+) -> Result<(), String> {
+ use tauri_plugin_opener::OpenerExt;
+
+ let url = external_url(&url)?;
+ app.opener()
+ .open_url(url.as_str(), None::<&str>)
+ .map_err(|error| error.to_string())
+}
+
+#[cfg(feature = "native-test")]
+#[tauri::command]
+pub fn open_external_url(
+ state: tauri::State<OpenedExternalUrls>,
+ url: String,
+) -> Result<(), String> {
+ let url = external_url(&url)?;
+ state
+ .0
+ .lock()
+ .map_err(|_| "Native test opener state is unavailable".to_owned())?
+ .push(url.into());
+ Ok(())
+}
+
+#[cfg(feature = "native-test")]
+#[tauri::command]
+pub fn take_native_test_opened_urls(state: tauri::State<OpenedExternalUrls>) -> Vec<String> {
+ state
+ .0
+ .lock()
+ .map(|mut urls| urls.drain(..).collect())
+ .unwrap_or_default()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::external_url;
+
+ #[test]
+ fn opens_web_and_mail_links_only() {
+ assert!(external_url("https://cloud.example.com/cloud/device?user_code=ABCD").is_ok());
+ assert!(external_url("http://192.168.1.20:3000/account").is_ok());
+ assert!(external_url("mailto:[email protected]").is_ok());
+ for url in [
+ "file:///etc/passwd",
+ "openpencil://open?file=a.pen",
+ "javascript:alert(1)",
+ "not a link",
+ ] {
+ assert!(external_url(url).is_err(), "{url}");
+ }
+ }
+}
diff --git a/packages/cloud/src/client/index.ts b/packages/cloud/src/client/index.ts
index 77f65ff3a..7bf404eb4 100644
--- a/packages/cloud/src/client/index.ts
+++ b/packages/cloud/src/client/index.ts
@@ -1,5 +1,5 @@
export { cloudEditorReturnURL, cloudSignInURL } from './auth/navigation'
-export { cloudRedirectPath, cloudShareURL } from './links'
+export { cloudDesktopLinkURL, cloudRedirectPath, cloudShareURL, type CloudLinkKind } from './links'
export {
CloudAPIError,
createCloudAPIClient,
diff --git a/packages/cloud/src/client/links.ts b/packages/cloud/src/client/links.ts
index b1a0c5f52..92070cd10 100644
--- a/packages/cloud/src/client/links.ts
+++ b/packages/cloud/src/client/links.ts
@@ -19,6 +19,25 @@ export function cloudShareURL(
return url.href
}
+/** The two kinds of Cloud link that carry a secret: invitations and documents shared by link. */
+export type CloudLinkKind = 'invitations' | 'share'
+
+/**
+ * The desktop app's form of a Cloud link, `openpencil://cloud/<kind>/<id>?server=…#secret`, which
+ * `desktop/src/deep_link.rs` validates before the editor sees it.
+ */
+export function cloudDesktopLinkURL(
+ kind: CloudLinkKind,
+ id: string,
+ serverURL: string,
+ secret: string
+): string {
+ const url = new URL(`openpencil://cloud/${kind}/${encodeURIComponent(id)}`)
+ url.searchParams.set('server', serverURL)
+ url.hash = secret
+ return url.href
+}
+
/** Accept only same-origin application paths for post-authentication navigation. */
export function cloudRedirectPath(value: unknown, fallback = '/app'): string {
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) return fallback
diff --git a/packages/cloud/tests/client/links.test.ts b/packages/cloud/tests/client/links.test.ts
index b8564bfa8..b0de08b22 100644
--- a/packages/cloud/tests/client/links.test.ts
+++ b/packages/cloud/tests/client/links.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from 'bun:test'
-import { cloudRedirectPath, cloudShareURL } from '#cloud/client'
+import { cloudDesktopLinkURL, cloudRedirectPath, cloudShareURL } from '#cloud/client'
import type { CloudDiscovery } from '#cloud/contract'
const discovery: CloudDiscovery = {
@@ -44,3 +44,14 @@ test('authentication continuation stays on the issuing origin', () => {
expect(cloudRedirectPath(input)).toBe('/app')
}
})
+
+test('desktop links keep the web link path, server, and secret under the app scheme', () => {
+ const url = new URL(
+ cloudDesktopLinkURL('invitations', 'invitation-id', 'https://company.example', 'secret')
+ )
+ expect(url.protocol).toBe('openpencil:')
+ expect(url.host).toBe('cloud')
+ expect(url.pathname).toBe('/invitations/invitation-id')
+ expect(url.searchParams.get('server')).toBe('https://company.example')
+ expect(url.hash).toBe('#secret')
+})
diff --git a/packages/docs/development/cloud.md b/packages/docs/development/cloud.md
index 7acd2c9d3..97d039edb 100644
--- a/packages/docs/development/cloud.md
+++ b/packages/docs/development/cloud.md
@@ -276,3 +276,10 @@ before they have anything to put in it.
says whether it is for a document or a workspace, so one link format, one email path, and one
editor dialog cover both, and the desktop app's link handling needs no new kind. Invitation
continuations through OAuth stay document-only; the editor keeps a pending invitation itself.
+
+**2026-10 · Cloud links hand off to the desktop app through `openpencil://cloud`.** Links stay web
+addresses on the server's editor, so they work for anyone; the web editor on a computer offers the
+desktop app, which gets the same path, server, and secret as `openpencil://cloud/<kind>/<id>`.
+The native side checks the ID, secret, and server before the editor sees a link. The secret is
+visible in the launch arguments to other processes on the same computer; pasting links into the
+app would avoid that at the cost of a manual step for everyone.
diff --git a/packages/docs/user-guide/openpencil-cloud.md b/packages/docs/user-guide/openpencil-cloud.md
index 1f0a9671e..427cc04cb 100644
--- a/packages/docs/user-guide/openpencil-cloud.md
+++ b/packages/docs/user-guide/openpencil-cloud.md
@@ -85,6 +85,8 @@ The server keeps only a fingerprint of each link, so a link can be copied only o
An invitation link opens OpenPencil with who invited you, to which document, and on which server. If you have never used that server, OpenPencil warns you to sign in only if you trust it. Sign in with the address the invitation was sent to; if you are signed in as someone else, choose **Use another account**. Once you accept, the document opens and stays under **Shared with you** on Home.
+Invitation and share links open in the browser. If you use the desktop app, choose **Open in the desktop app** in the invitation, or on the notice that appears after a shared document opens; your browser asks before it switches to the app.
+
## Edit Together
Opening a Cloud document joins its live session: everyone who has it open sees each other's cursors and edits as they happen. One person's app saves the document for everyone, so editing together never makes your changes conflict with someone else's.
diff --git a/packages/vue/src/i18n/locales/de/cloud/editor.json b/packages/vue/src/i18n/locales/de/cloud/editor.json
index 2135f2412..e55dcfc11 100644
--- a/packages/vue/src/i18n/locales/de/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/de/cloud/editor.json
@@ -272,5 +272,7 @@
"leaveWorkspaceShort": "Verlassen",
"deleteWorkspaceShort": "Löschen",
"workspaceNotEmpty": "Lösche oder verschiebe zuerst seine Dokumente; nur ein leerer Arbeitsbereich kann gelöscht werden.",
- "workspaceCleanupPending": "Seine gelöschten Dokumente werden noch eine Weile aufbewahrt, bevor sie endgültig verschwinden. Versuche es danach erneut."
+ "workspaceCleanupPending": "Seine gelöschten Dokumente werden noch eine Weile aufbewahrt, bevor sie endgültig verschwinden. Versuche es danach erneut.",
+ "shareOpenedInBrowser": "Im Browser geöffnet",
+ "openInDesktopApp": "In der Desktop-App öffnen"
}
diff --git a/packages/vue/src/i18n/locales/es/cloud/editor.json b/packages/vue/src/i18n/locales/es/cloud/editor.json
index 9bf5bf7bf..2adc2fa9a 100644
--- a/packages/vue/src/i18n/locales/es/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/es/cloud/editor.json
@@ -272,5 +272,7 @@
"leaveWorkspaceShort": "Salir",
"deleteWorkspaceShort": "Eliminar",
"workspaceNotEmpty": "Elimina o mueve primero sus documentos; solo se puede eliminar un espacio vacío.",
- "workspaceCleanupPending": "Sus documentos eliminados se conservan un tiempo antes de borrarse definitivamente. Vuelve a intentarlo después."
+ "workspaceCleanupPending": "Sus documentos eliminados se conservan un tiempo antes de borrarse definitivamente. Vuelve a intentarlo después.",
+ "shareOpenedInBrowser": "Abierto en el navegador",
+ "openInDesktopApp": "Abrir en la aplicación de escritorio"
}
diff --git a/packages/vue/src/i18n/locales/fr/cloud/editor.json b/packages/vue/src/i18n/locales/fr/cloud/editor.json
index 8f99dde53..dd9c30a11 100644
--- a/packages/vue/src/i18n/locales/fr/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/fr/cloud/editor.json
@@ -272,5 +272,7 @@
"leaveWorkspaceShort": "Quitter",
"deleteWorkspaceShort": "Supprimer",
"workspaceNotEmpty": "Supprimez ou déplacez d’abord ses documents ; seul un espace vide peut être supprimé.",
- "workspaceCleanupPending": "Ses documents supprimés sont conservés un temps avant de disparaître définitivement. Réessayez ensuite."
+ "workspaceCleanupPending": "Ses documents supprimés sont conservés un temps avant de disparaître définitivement. Réessayez ensuite.",
+ "shareOpenedInBrowser": "Ouvert dans le navigateur",
+ "openInDesktopApp": "Ouvrir dans l’application de bureau"
}
diff --git a/packages/vue/src/i18n/locales/it/cloud/editor.json b/packages/vue/src/i18n/locales/it/cloud/editor.json
index 681844d21..b0b03c9a6 100644
--- a/packages/vue/src/i18n/locales/it/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/it/cloud/editor.json
@@ -272,5 +272,7 @@
"leaveWorkspaceShort": "Esci",
"deleteWorkspaceShort": "Elimina",
"workspaceNotEmpty": "Prima elimina o sposta i suoi documenti; si può eliminare solo un’area vuota.",
- "workspaceCleanupPending": "I suoi documenti eliminati vengono conservati per un po’ prima di sparire del tutto. Riprova dopo."
+ "workspaceCleanupPending": "I suoi documenti eliminati vengono conservati per un po’ prima di sparire del tutto. Riprova dopo.",
+ "shareOpenedInBrowser": "Aperto nel browser",
+ "openInDesktopApp": "Apri nell’app desktop"
}
diff --git a/packages/vue/src/i18n/locales/ja/cloud/editor.json b/packages/vue/src/i18n/locales/ja/cloud/editor.json
index 085011f81..955ff0215 100644
--- a/packages/vue/src/i18n/locales/ja/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/ja/cloud/editor.json
@@ -269,5 +269,7 @@
"leaveWorkspaceShort": "退出",
"deleteWorkspaceShort": "削除",
"workspaceNotEmpty": "先にドキュメントを削除するか移動してください。削除できるのは空のワークスペースだけです。",
- "workspaceCleanupPending": "削除されたドキュメントは完全に消えるまでしばらく保管されます。その後にもう一度お試しください。"
+ "workspaceCleanupPending": "削除されたドキュメントは完全に消えるまでしばらく保管されます。その後にもう一度お試しください。",
+ "shareOpenedInBrowser": "ブラウザーで開きました",
+ "openInDesktopApp": "デスクトップアプリで開く"
}
diff --git a/packages/vue/src/i18n/locales/pl/cloud/editor.json b/packages/vue/src/i18n/locales/pl/cloud/editor.json
index 9453b047a..56f331d53 100644
--- a/packages/vue/src/i18n/locales/pl/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/pl/cloud/editor.json
@@ -275,5 +275,7 @@
"leaveWorkspaceShort": "Opuść",
"deleteWorkspaceShort": "Usuń",
"workspaceNotEmpty": "Najpierw usuń lub przenieś jego dokumenty; usunąć można tylko pusty obszar.",
- "workspaceCleanupPending": "Usunięte dokumenty są jeszcze przez jakiś czas przechowywane. Spróbuj ponownie później."
+ "workspaceCleanupPending": "Usunięte dokumenty są jeszcze przez jakiś czas przechowywane. Spróbuj ponownie później.",
+ "shareOpenedInBrowser": "Otwarto w przeglądarce",
+ "openInDesktopApp": "Otwórz w aplikacji na komputer"
}
diff --git a/packages/vue/src/i18n/locales/ru/cloud/editor.json b/packages/vue/src/i18n/locales/ru/cloud/editor.json
index c8dd03a95..b9b44b2ce 100644
--- a/packages/vue/src/i18n/locales/ru/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/ru/cloud/editor.json
@@ -275,5 +275,7 @@
"leaveWorkspaceShort": "Покинуть",
"deleteWorkspaceShort": "Удалить",
"workspaceNotEmpty": "Сначала удалите или перенесите его документы: удалить можно только пустое пространство.",
- "workspaceCleanupPending": "Удалённые документы ещё какое-то время хранятся, прежде чем исчезнуть окончательно. Попробуйте позже."
+ "workspaceCleanupPending": "Удалённые документы ещё какое-то время хранятся, прежде чем исчезнуть окончательно. Попробуйте позже.",
+ "shareOpenedInBrowser": "Открыто в браузере",
+ "openInDesktopApp": "Открыть в приложении для компьютера"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json
index 5949c442e..aa4ba3c4f 100644
--- a/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json
+++ b/packages/vue/src/i18n/locales/zh-cn/cloud/editor.json
@@ -269,5 +269,7 @@
"leaveWorkspaceShort": "退出",
"deleteWorkspaceShort": "删除",
"workspaceNotEmpty": "请先删除或移走其中的文档;只能删除空的工作区。",
- "workspaceCleanupPending": "已删除的文档会保留一段时间后才彻底清除。请在那之后再试。"
+ "workspaceCleanupPending": "已删除的文档会保留一段时间后才彻底清除。请在那之后再试。",
+ "shareOpenedInBrowser": "已在浏览器中打开",
+ "openInDesktopApp": "在桌面应用中打开"
}
diff --git a/packages/vue/src/i18n/messages/cloud/editor.ts b/packages/vue/src/i18n/messages/cloud/editor.ts
index 7cb47866c..41765965d 100644
--- a/packages/vue/src/i18n/messages/cloud/editor.ts
+++ b/packages/vue/src/i18n/messages/cloud/editor.ts
@@ -323,7 +323,9 @@ export const cloudMessageDefaults = {
syncOffline: 'Offline — changes are saved on this device',
syncConflict: 'Edited elsewhere too — choose which version to keep',
syncError: 'Could not upload changes',
- shareLinkFailed: 'This link doesn’t open a document. Ask for a new one.'
+ shareLinkFailed: 'This link doesn’t open a document. Ask for a new one.',
+ shareOpenedInBrowser: 'Opened in the browser',
+ openInDesktopApp: 'Open in the desktop app'
} as const
export const cloudMessages = i18n('cloud', cloudMessageDefaults)
diff --git a/src/app/cloud/invitations/flow.ts b/src/app/cloud/invitations/flow.ts
index 51f57dcc5..e83c61fc9 100644
--- a/src/app/cloud/invitations/flow.ts
+++ b/src/app/cloud/invitations/flow.ts
@@ -2,7 +2,7 @@ import { useSessionStorage } from '@vueuse/core'
import * as v from 'valibot'
import { computed, ref, shallowRef } from 'vue'
-import { CloudAPIError, createCloudAPIClient } from '@open-pencil/cloud/client'
+import { CloudAPIError, cloudDesktopLinkURL, createCloudAPIClient } from '@open-pencil/cloud/client'
import type { AcceptedInvitation, InvitationPreview } from '@open-pencil/cloud/contract'
import { openHomeLocation } from '@/app/shell/menu/navigation'
@@ -115,6 +115,15 @@ export function resumeCloudInvitation(): void {
void checkCloudInvitation()
}
+/** Hands the invitation to the desktop app; the dialog stays in case the app isn't installed. */
+export function openCloudInvitationInDesktop(): void {
+ const invitation = pending.value
+ if (!invitation) return
+ globalThis.location.assign(
+ cloudDesktopLinkURL('invitations', invitation.id, invitation.server, invitation.token)
+ )
+}
+
export function dismissCloudInvitation(): void {
stored.value = null
cloudInvitationOpen.value = false
diff --git a/src/app/cloud/links.ts b/src/app/cloud/links.ts
new file mode 100644
index 000000000..d14b6376c
--- /dev/null
+++ b/src/app/cloud/links.ts
@@ -0,0 +1,91 @@
+import * as v from 'valibot'
+
+import { cloudDesktopLinkURL, type CloudLinkKind } from '@open-pencil/cloud/client'
+import { cloudMessages, useViewportKind } from '@open-pencil/vue'
+
+import { toast } from '@/app/shell/ui'
+import { isTauri } from '@/app/tauri/env'
+import { bindDesktopLinkQueue } from '@/app/tauri/link-queue'
+import { IS_BROWSER } from '@/constants'
+
+import { beginCloudInvitation } from './invitations/flow'
+import { openCloudShareLink } from './sharing/link'
+
+/**
+ * An invitation, `/cloud/invitations/:id?server=…#token`, or a document shared by link,
+ * `/cloud/share/:id?server=…#secret`. The desktop app gets the same link as
+ * `openpencil://cloud/<kind>/<id>?server=…#secret`.
+ */
+export type CloudLink = { kind: CloudLinkKind; id: string; server: string; secret: string }
+
+const CLOUD_LINK_PATH = /^\/cloud\/(invitations|share)\/([^/]+)$/
+
+/** Desktop events and commands for `openpencil://cloud` links (`desktop/src/lib.rs`). */
+const CLOUD_LINKS_EVENT = 'open-cloud-links'
+const TAKE_PENDING_CLOUD_LINKS = 'take_pending_cloud_links'
+
+const cloudLinkSchema = v.object({
+ kind: v.picklist(['invitations', 'share']),
+ id: v.string(),
+ server: v.string(),
+ secret: v.string()
+})
+
+/** The Cloud link a web address carries, if it is one. */
+export function readCloudLink(url: URL): CloudLink | null {
+ const [, kind, id] = url.pathname.match(CLOUD_LINK_PATH) ?? []
+ const server = url.searchParams.get('server')
+ const secret = url.hash.slice(1)
+ if ((kind !== 'invitations' && kind !== 'share') || !id || !server || !secret) return null
+ try {
+ return { kind, id: decodeURIComponent(id), server, secret }
+ } catch {
+ // A broken escape such as `%E0` is no link; it must not stop the app from starting.
+ return null
+ }
+}
+
+/** Hands a Cloud link to the desktop app; the browser asks before it opens the app. */
+export function openCloudLinkInDesktop(link: CloudLink): void {
+ globalThis.location.assign(cloudDesktopLinkURL(link.kind, link.id, link.server, link.secret))
+}
+
+/** The web editor offers the desktop app on computers; phones have none to offer. */
+export function canOfferDesktopApp(): boolean {
+ return IS_BROWSER && !isTauri() && !useViewportKind().isMobile.value
+}
+
+/** Opens an invitation's dialog, or a shared document as a guest. */
+export async function openCloudLink(link: CloudLink): Promise<void> {
+ if (link.kind === 'invitations') {
+ beginCloudInvitation(link.id, link.server, link.secret)
+ return
+ }
+ const messages = cloudMessages.get()
+ try {
+ await openCloudShareLink({ shareId: link.id, server: link.server, secret: link.secret })
+ } catch {
+ toast.error(messages.shareLinkFailed)
+ return
+ }
+ if (canOfferDesktopApp()) {
+ toast.info(messages.shareOpenedInBrowser, {
+ label: messages.openInDesktopApp,
+ run: () => openCloudLinkInDesktop(link)
+ })
+ }
+}
+
+/**
+ * Opens the Cloud links the desktop app received, at startup and while running. The native side
+ * validates each link before it gets here.
+ */
+export function bindDesktopCloudLinks(): Promise<() => void> {
+ return bindDesktopLinkQueue({
+ event: CLOUD_LINKS_EVENT,
+ command: TAKE_PENDING_CLOUD_LINKS,
+ schema: cloudLinkSchema,
+ label: 'Cloud link',
+ open: openCloudLink
+ })
+}
diff --git a/src/app/cloud/sessions/startup.ts b/src/app/cloud/sessions/startup.ts
index 8fde03fcd..3f00b4069 100644
--- a/src/app/cloud/sessions/startup.ts
+++ b/src/app/cloud/sessions/startup.ts
@@ -1,51 +1,28 @@
-import { cloudMessages } from '@open-pencil/vue'
-
-import { toast } from '@/app/shell/ui'
-
import { checkCloudAvailability } from '../availability'
import { cloudSignedIn } from '../connect/flow'
-import { beginCloudInvitation, resumeCloudInvitation } from '../invitations/flow'
+import { resumeCloudInvitation } from '../invitations/flow'
+import { bindDesktopCloudLinks, openCloudLink, readCloudLink } from '../links'
import { cloudServers, findCloudServer } from '../servers/store'
-import { openCloudShareLink } from '../sharing/link'
import { refreshCloudConnection } from './connection'
import { takePendingCloudSignIn } from './sign-in'
-const CLOUD_LINK_PATH = /^\/cloud\/(invitations|share)\/([^/]+)$/
-
-/**
- * A Cloud link this tab was opened with: an invitation, `/cloud/invitations/:id?server=…#token`,
- * or a document shared by link, `/cloud/share/:id?server=…#secret`.
- */
-function readCloudLink() {
- const url = new URL(globalThis.location.href)
- const [, kind, id] = url.pathname.match(CLOUD_LINK_PATH) ?? []
- const server = url.searchParams.get('server')
- const secret = url.hash.slice(1)
- if (!kind || !id || !server || !secret) return null
- return { kind, id: decodeURIComponent(id), server, secret }
-}
-
/**
* Checks every known server once the app starts, finishes a sign-in this tab left for the
- * server's pages to do, and opens an invitation or a shared link the tab was opened with. The
- * link's secret is taken out of the address at once.
+ * server's pages to do, and opens an invitation or a shared link the tab was opened with, or the
+ * desktop app was sent. The link's secret is taken out of the address at once.
*/
export async function startCloudSessions(options: {
/** Leaves a Cloud link's address, so its secret is not kept in history. */
leaveLinkAddress(): Promise<unknown>
}): Promise<void> {
void checkCloudAvailability(globalThis.location.href)
- const link = readCloudLink()
+ const link = readCloudLink(new URL(globalThis.location.href))
if (link) await options.leaveLinkAddress()
const pending = takePendingCloudSignIn()
await Promise.all(cloudServers.value.map((server) => refreshCloudConnection(server)))
const server = pending ? findCloudServer(pending) : null
if (server) cloudSignedIn.value = { serverId: server.id }
- if (link?.kind === 'invitations') beginCloudInvitation(link.id, link.server, link.secret)
- else resumeCloudInvitation()
- if (link?.kind === 'share') {
- await openCloudShareLink({ shareId: link.id, server: link.server, secret: link.secret }).catch(
- () => toast.error(cloudMessages.get().shareLinkFailed)
- )
- }
+ if (link?.kind !== 'invitations') resumeCloudInvitation()
+ if (link) await openCloudLink(link)
+ await bindDesktopCloudLinks()
}
diff --git a/src/app/collab/room/links.ts b/src/app/collab/room/links.ts
index 1f49d996d..fc56a32c0 100644
--- a/src/app/collab/room/links.ts
+++ b/src/app/collab/room/links.ts
@@ -1,13 +1,11 @@
import * as v from 'valibot'
-import { isTauri } from '@/app/tauri/env'
+import { bindDesktopLinkQueue } from '@/app/tauri/link-queue'
/** Desktop events and commands for `openpencil://join?room=<id>` links (`desktop/src/lib.rs`). */
export const ROOM_LINKS_EVENT = 'open-room-links'
const TAKE_PENDING_ROOMS = 'take_pending_rooms'
-const pendingRoomsSchema = v.array(v.string())
-
export function roomLinkURL(roomId: string): string {
return `openpencil://join?room=${encodeURIComponent(roomId)}`
}
@@ -16,19 +14,12 @@ export function roomLinkURL(roomId: string): string {
* Opens the rooms of `openpencil://join` links the desktop app received, at startup and while
* running. The native side validates each room ID; `open` validates it again before joining.
*/
-export async function bindDesktopRoomLinks(open: (roomId: string) => void): Promise<() => void> {
- if (!isTauri()) return () => undefined
- const [{ invoke }, { listen }] = await Promise.all([
- import('@tauri-apps/api/core'),
- import('@tauri-apps/api/event')
- ])
- async function drain() {
- const rooms = v.parse(pendingRoomsSchema, await invoke<unknown>(TAKE_PENDING_ROOMS))
- for (const roomId of rooms) open(roomId)
- }
- const stop = await listen(ROOM_LINKS_EVENT, () => {
- void drain().catch((error: unknown) => console.error('[Room link]', error))
+export function bindDesktopRoomLinks(open: (roomId: string) => void): Promise<() => void> {
+ return bindDesktopLinkQueue({
+ event: ROOM_LINKS_EVENT,
+ command: TAKE_PENDING_ROOMS,
+ schema: v.string(),
+ label: 'Room link',
+ open
})
- await drain()
- return stop
}
diff --git a/src/app/shell/ui.ts b/src/app/shell/ui.ts
index b2ecb421b..acb97561b 100644
--- a/src/app/shell/ui.ts
+++ b/src/app/shell/ui.ts
@@ -82,7 +82,8 @@ function trim() {
/** Toast-driven work keeps its toast open until progress clears or the work ends. */
export function toastDuration(entry: Toast): number {
if (entry.progress) return 0
- return entry.variant === 'error' ? ERROR_TOAST_DURATION : TOAST_DURATION
+ // A toast that offers an action stays long enough to reach it.
+ return entry.variant === 'error' || entry.action ? ERROR_TOAST_DURATION : TOAST_DURATION
}
function startProgress(
@@ -115,8 +116,8 @@ function startProgress(
}
}
-function info(message: string) {
- push(message, 'default')
+function info(message: string, action?: ToastAction) {
+ push(message, 'default', action)
}
function warning(message: string) {
@@ -160,8 +161,9 @@ export const toast = {
export async function openExternalLink(url: string) {
if (isTauri()) {
- const { openUrl } = await import('@tauri-apps/plugin-opener')
- await openUrl(url)
+ // An app command, so native tests can read the address instead of opening a browser.
+ const { invoke } = await import('@tauri-apps/api/core')
+ await invoke('open_external_url', { url })
} else {
window.open(url, '_blank')
}
diff --git a/src/app/tauri/link-queue.ts b/src/app/tauri/link-queue.ts
new file mode 100644
index 000000000..a93800c78
--- /dev/null
+++ b/src/app/tauri/link-queue.ts
@@ -0,0 +1,39 @@
+import * as v from 'valibot'
+
+import { isTauri } from '@/app/tauri/env'
+
+/**
+ * Hands the desktop app's queued links to `open`: those that arrived before the editor started,
+ * then each batch the native side announces with `event`. `command` drains the queue, and its
+ * answer is checked against `schema` before anything opens.
+ */
+export async function bindDesktopLinkQueue<T>(options: {
+ event: string
+ command: string
+ schema: v.GenericSchema<unknown, T>
+ label: string
+ open: (item: T) => unknown
+}): Promise<() => void> {
+ if (!isTauri()) return () => undefined
+ const [{ invoke }, { listen }] = await Promise.all([
+ import('@tauri-apps/api/core'),
+ import('@tauri-apps/api/event')
+ ])
+ const queue = v.array(options.schema)
+ async function drain() {
+ const items = v.parse(queue, await invoke<unknown>(options.command))
+ // The native side already emptied its queue, so one link that fails must not drop the rest.
+ for (const item of items) {
+ try {
+ await options.open(item)
+ } catch (error) {
+ console.error(`[${options.label}]`, error)
+ }
+ }
+ }
+ const stop = await listen(options.event, () => {
+ void drain().catch((error: unknown) => console.error(`[${options.label}]`, error))
+ })
+ await drain()
+ return stop
+}
diff --git a/src/components/cloud/invitation/CloudInvitationDialog.stories.ts b/src/components/cloud/invitation/CloudInvitationDialog.stories.ts
index b4058616d..314022742 100644
--- a/src/components/cloud/invitation/CloudInvitationDialog.stories.ts
+++ b/src/components/cloud/invitation/CloudInvitationDialog.stories.ts
@@ -8,8 +8,10 @@ type Args = {
state: CloudInvitationState
invitation: CloudInvitationSummary | null
account: { email: string } | null
+ offerDesktop: boolean
onAccept: () => void
onSignIn: () => void
+ onOpenInDesktop: () => void
}
const invitation: CloudInvitationSummary = {
@@ -29,15 +31,17 @@ const meta = {
state: 'ready',
invitation,
account: { email: '[email protected]' },
+ offerDesktop: false,
onAccept: fn(),
- onSignIn: fn()
+ onSignIn: fn(),
+ onOpenInDesktop: fn()
},
render: (args) => ({
components: { CloudInvitationDialog },
setup: () => ({ args }),
template: `
<div class="h-[600px]">
- <CloudInvitationDialog :open="true" :state="args.state" :invitation="args.invitation" :account="args.account" @accept="args.onAccept" @sign-in="args.onSignIn" />
+ <CloudInvitationDialog :open="true" :state="args.state" :invitation="args.invitation" :account="args.account" :offer-desktop="args.offerDesktop" @accept="args.onAccept" @sign-in="args.onSignIn" @open-in-desktop="args.onOpenInDesktop" />
</div>`
})
} satisfies Meta<Args>
@@ -74,4 +78,8 @@ export const JoinWorkspace: Story = {
}
}
}
+export const OfferDesktopApp: Story = { args: { offerDesktop: true } }
+export const OfferDesktopAppBeforeSignIn: Story = {
+ args: { state: 'sign-in', account: null, offerDesktop: true }
+}
export const Unavailable: Story = { args: { state: 'unavailable' } }
diff --git a/src/components/cloud/invitation/CloudInvitationDialog.vue b/src/components/cloud/invitation/CloudInvitationDialog.vue
index 36ce2b622..f990302d4 100644
--- a/src/components/cloud/invitation/CloudInvitationDialog.vue
+++ b/src/components/cloud/invitation/CloudInvitationDialog.vue
@@ -22,16 +22,25 @@ import type { CloudInvitationState, CloudInvitationSummary } from './types'
const {
state,
invitation = null,
- account = null
+ account = null,
+ offerDesktop = false
} = defineProps<{
state: CloudInvitationState
invitation?: CloudInvitationSummary | null
/** The account signed in to the invitation's server, if any. */
account?: { email: string } | null
+ /** The web editor on a computer can hand the invitation to the desktop app. */
+ offerDesktop?: boolean
}>()
const open = defineModel<boolean>('open', { default: false })
-const emit = defineEmits<{ accept: []; signIn: []; switchAccount: []; cancel: [] }>()
+const emit = defineEmits<{
+ accept: []
+ signIn: []
+ switchAccount: []
+ openInDesktop: []
+ cancel: []
+}>()
const ui = cloudInvitation()
const t = useCloudMessages()
@@ -78,7 +87,7 @@ const target = computed(() => {
</p>
</AppDialogBody>
- <AppDialogBody v-else-if="state === 'unavailable'">
+ <AppDialogBody v-else-if="state === 'unavailable'" data-test-id="cloud-invitation-unavailable">
<div :class="ui.unavailable()">
<span :class="ui.unavailableIcon()"><icon-lucide-mail-x class="size-4" /></span>
<p :class="ui.unavailableDescription()">
@@ -142,6 +151,16 @@ const target = computed(() => {
<AppButton variant="outline" @click="emit('cancel')">{{ common.close }}</AppButton>
</template>
<template v-else>
+ <AppButton
+ v-if="offerDesktop"
+ :class="ui.desktop()"
+ variant="ghost"
+ :disabled="state === 'accepting'"
+ @click="emit('openInDesktop')"
+ >
+ <template #leading><icon-lucide-monitor class="size-3.5" /></template>
+ {{ t.openInDesktopApp }}
+ </AppButton>
<AppButton variant="ghost" @click="emit('cancel')">{{ t.notNow }}</AppButton>
<AppButton
v-if="state === 'sign-in'"
diff --git a/src/components/cloud/invitation/CloudInvitationHost.vue b/src/components/cloud/invitation/CloudInvitationHost.vue
index a7ec0e6b7..d4020c00f 100644
--- a/src/components/cloud/invitation/CloudInvitationHost.vue
+++ b/src/components/cloud/invitation/CloudInvitationHost.vue
@@ -13,9 +13,11 @@ import {
cloudInvitationOpen,
cloudInvitationState,
dismissCloudInvitation,
+ openCloudInvitationInDesktop,
signInForCloudInvitation,
switchCloudInvitationAccount
} from '@/app/cloud/invitations/flow'
+import { canOfferDesktopApp } from '@/app/cloud/links'
import CloudInvitationDialog from './CloudInvitationDialog.vue'
@@ -49,10 +51,12 @@ watch(cloudSignedIn, () => {
:state="cloudInvitationState"
:invitation="summary"
:account="cloudInvitationAccount"
+ :offer-desktop="canOfferDesktopApp()"
@update:open="(open) => !open && dismissCloudInvitation()"
@accept="acceptCloudInvitation"
@sign-in="signInForCloudInvitation"
@switch-account="switchCloudInvitationAccount"
+ @open-in-desktop="openCloudInvitationInDesktop"
@cancel="dismissCloudInvitation"
/>
</template>
diff --git a/src/theme/cloud/invitation.ts b/src/theme/cloud/invitation.ts
index 6b1fd047d..d8072c8dd 100644
--- a/src/theme/cloud/invitation.ts
+++ b/src/theme/cloud/invitation.ts
@@ -10,6 +10,7 @@ export const cloudInvitation = tv({
documentMeta: 'mt-0.5 block truncate text-[11px] text-muted',
permission: 'shrink-0 rounded bg-panel px-1.5 py-0.5 text-[10px] font-medium text-muted',
stack: 'flex flex-col gap-3',
+ desktop: 'me-auto',
unavailable: 'flex flex-col items-center gap-3 py-4 text-center',
unavailableIcon:
'flex size-10 items-center justify-center rounded-full bg-panel-field text-muted',
diff --git a/tests/app/cloud/links.test.ts b/tests/app/cloud/links.test.ts
new file mode 100644
index 000000000..009d05a0e
--- /dev/null
+++ b/tests/app/cloud/links.test.ts
@@ -0,0 +1,43 @@
+import 'fake-indexeddb/auto'
+import { describe, expect, test } from 'bun:test'
+
+import { cloudDesktopLinkURL } from '@open-pencil/cloud/client'
+
+import { readCloudLink } from '@/app/cloud/links'
+
+const SERVER = 'https://cloud.example.com'
+
+describe('Cloud links', () => {
+ test('a web link names its kind, id, server, and secret', () => {
+ expect(
+ readCloudLink(new URL(`https://app.example.com/cloud/invitations/abc?server=${SERVER}#token`))
+ ).toEqual({ kind: 'invitations', id: 'abc', server: SERVER, secret: 'token' })
+ expect(
+ readCloudLink(new URL(`https://app.example.com/cloud/share/s%201?server=${SERVER}#secret`))
+ ).toEqual({ kind: 'share', id: 's 1', server: SERVER, secret: 'secret' })
+ })
+
+ test('other addresses and links missing a part are not Cloud links', () => {
+ for (const address of [
+ 'https://app.example.com/',
+ `https://app.example.com/cloud/documents/abc?server=${SERVER}#secret`,
+ `https://app.example.com/cloud/share/abc/more?server=${SERVER}#secret`,
+ 'https://app.example.com/cloud/share/abc#secret',
+ `https://app.example.com/cloud/share/abc?server=${SERVER}`,
+ `https://app.example.com/cloud/share/%E0%A4?server=${SERVER}#secret`
+ ]) {
+ expect(readCloudLink(new URL(address))).toBeNull()
+ }
+ })
+
+ test('the desktop form of a web link reads back as the same link', () => {
+ const web = readCloudLink(
+ new URL(`https://app.example.com/cloud/share/abc?server=${SERVER}#secret`)
+ )
+ if (!web) throw new Error('Expected a Cloud link')
+ const desktop = new URL(cloudDesktopLinkURL(web.kind, web.id, web.server, web.secret))
+ expect(desktop.href).toBe(
+ `openpencil://cloud/share/abc?server=${encodeURIComponent(SERVER)}#secret`
+ )
+ })
+})
diff --git a/tests/e2e/native/cloud-links.spec.ts b/tests/e2e/native/cloud-links.spec.ts
new file mode 100644
index 000000000..30ddcbed5
--- /dev/null
+++ b/tests/e2e/native/cloud-links.spec.ts
@@ -0,0 +1,55 @@
+import { strict as assert } from 'node:assert'
+
+import { invokeNative } from '#tests/helpers/tauri/invoke'
+
+const SIGN_IN_URL = 'https://cloud.example.test/cloud/device?user_code=ABCD-EFGH'
+const INVITATION = '0b6f4f9e-3c1a-4d7e-9a52-6f1c2d3e4f50'
+// Shaped like a share secret, 64 hex characters, and obviously not one.
+const SECRET = 'ab'.repeat(32)
+// Nothing listens on the discard port, so the invitation's server cannot be reached.
+const SERVER = 'http://127.0.0.1:9'
+
+function invitationLink(secret: string): string {
+ return `openpencil://cloud/invitations/${INVITATION}?server=${encodeURIComponent(SERVER)}#${secret}`
+}
+
+describe('native Cloud links', () => {
+ before(async () => {
+ await browser.waitUntil(
+ async () => browser.execute(() => Boolean(window.openPencil?.getStore?.())),
+ { timeout: 30_000 }
+ )
+ })
+
+ it('records browser links instead of opening a browser', async () => {
+ await invokeNative('take_native_test_opened_urls')
+ await invokeNative('open_external_url', { url: SIGN_IN_URL })
+ assert.deepEqual(await invokeNative('take_native_test_opened_urls'), [SIGN_IN_URL])
+ assert.deepEqual(await invokeNative('take_native_test_opened_urls'), [])
+ })
+
+ it('refuses to open links that are not web or mail addresses', async () => {
+ await assert.rejects(invokeNative('open_external_url', { url: 'file:///etc/hosts' }))
+ assert.deepEqual(await invokeNative('take_native_test_opened_urls'), [])
+ })
+
+ it('opens an invitation link sent to the app', async () => {
+ await invokeNative('native_test_open_deep_link', { url: invitationLink(SECRET) })
+ const dialog = await $('[role="dialog"]')
+ await dialog.waitForDisplayed({ timeout: 15_000 })
+ // The server in the link doesn't answer, so the invitation can't be used.
+ await $('[data-test-id="cloud-invitation-unavailable"]').waitForDisplayed({
+ timeout: 15_000,
+ timeoutMsg: 'The invitation dialog did not report the unreachable server'
+ })
+ await browser.keys('Escape')
+ await dialog.waitForDisplayed({ reverse: true })
+ })
+
+ it('ignores a Cloud link whose secret is malformed', async () => {
+ await invokeNative('native_test_open_deep_link', { url: invitationLink('not-a-secret') })
+ const pending = await invokeNative<unknown[]>('take_pending_cloud_links')
+ assert.deepEqual(pending, [])
+ assert.equal(await $('[role="dialog"]').isExisting(), false)
+ })
+})
diff --git a/tests/engine/app/external-link.test.ts b/tests/engine/app/external-link.test.ts
index 242ea4d31..9facb6c18 100644
--- a/tests/engine/app/external-link.test.ts
+++ b/tests/engine/app/external-link.test.ts
@@ -4,11 +4,6 @@ import { openExternalLink } from '@/app/shell/ui'
import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'
-/**
- * Tests for the browser (window.open) path only.
- * The Tauri path (dynamic import of @tauri-apps/plugin-opener) cannot be
- * exercised in bun:test since IS_TAURI evaluates to false outside Tauri.
- */
describe('openExternalLink', () => {
let mockOpen: ReturnType<typeof vi.fn>
@@ -45,10 +40,10 @@ describe('openExternalLink', () => {
expect(mockOpen).toHaveBeenCalledWith('https://example.com/docs', '_blank')
})
- test('opens links through Tauri opener when running in Tauri', async () => {
+ test('opens links through the app command when running in Tauri', async () => {
await mockTauriIPC((cmd, args) => {
- expect(cmd).toBe('plugin:opener|open_url')
- expect(args).toEqual({ url: 'https://example.com/docs', with: undefined })
+ expect(cmd).toBe('open_external_url')
+ expect(args).toEqual({ url: 'https://example.com/docs' })
return null
})