From c5d45f4d085cc9d38026e87bcff6491b63a6ea7c Mon Sep 17 00:00:00 2001 From: i2cjak Date: Mon, 23 Nov 2026 18:15:12 -0500 Subject: [PATCH] mobile,host: fix file:// link parsing, bot-thread resolution, and QuickLook/download viewing --- .../dev/backplane/mobile/DataLinkGrammar.kt | 71 +++++++++++- .../java/dev/backplane/mobile/DataLinks.kt | 1 + .../java/dev/backplane/mobile/DataMarkdown.kt | 9 +- .../java/dev/backplane/mobile/DataViews.kt | 5 +- .../java/dev/backplane/mobile/Downloads.kt | 22 +++- .../java/dev/backplane/mobile/FileFetch.kt | 12 +- .../dev/backplane/mobile/FileFetchTest.kt | 5 +- .../dev/backplane/mobile/LinkGrammarTest.kt | 12 ++ mobile/ios/Backplane/DataDownloads.swift | 33 +++++- mobile/ios/Backplane/DataLinkGrammar.swift | 61 ++++++++++- mobile/ios/Backplane/DataLinks.swift | 8 +- mobile/ios/Backplane/DataMarkdown.swift | 16 +-- mobile/ios/Backplane/DataModels.swift | 8 ++ mobile/ios/Backplane/DataViews.swift | 1 + mobile/ios/Backplane/FileFetch.swift | 20 +++- mobile/ios/Tests/FileFetchTests.swift | 5 +- mobile/ios/Tests/LinkGrammarTests.swift | 7 ++ native/host/src/data/link.rs | 95 ++++++++++++---- native/host/src/data/tests.rs | 63 +++++++++++ native/host/src/files/share.rs | 103 +++++++++++++++--- native/host/src/files/share_tests.rs | 103 ++++++++++++++++++ scripts/mobile/ios-unit-tests.sh | 1 + 22 files changed, 576 insertions(+), 85 deletions(-) diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinkGrammar.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinkGrammar.kt index c4ecd77781..840d0facff 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinkGrammar.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinkGrammar.kt @@ -16,7 +16,65 @@ private val rePhone = Regex("^(?:(?:\\+\\d{1,3}[ .-]?)?(?:\\(\\d{3}\\)[ .-]?|\\d fun isPathText(t: String) = !t.startsWith("http") && !t.contains("://") && (rePath.matches(t) || reFile.matches(t) || FileFetch.shareRoute(t) != null) fun pathLink(p: String) = PATH_SCHEME + p -fun pathOf(url: String): String? = if (url.startsWith(PATH_SCHEME)) url.removePrefix(PATH_SCHEME) else null +fun pathOf(url: String): String? = if (url.startsWith(PATH_SCHEME)) url.removePrefix(PATH_SCHEME) else fileUrlPath(url) + +private fun decodePercent(s: String): String { + val out = java.io.ByteArrayOutputStream(s.length) + var i = 0 + while (i < s.length) { + val c = s[i] + if (c == '%' && i + 2 < s.length) { + val hi = s[i + 1].digitToIntOrNull(16) + val lo = s[i + 2].digitToIntOrNull(16) + if (hi != null && lo != null) { + out.write((hi shl 4) or lo) + i += 3 + continue + } + } + out.write(c.toString().toByteArray(Charsets.UTF_8)) + i++ + } + return out.toString(Charsets.UTF_8.name()) +} + +private val reLineFrag = Regex("^L\\d{1,6}(?:-L?\\d{1,6})?$") +private val reWinSlashDrive = Regex("^/[A-Za-z]:/.*") +private val reWinDrive = Regex("^[A-Za-z]:/.*") + +/** Decodes a `file://` URL into a hub filesystem path (preserving `#L` anchors, stripping other fragments/queries and `localhost`). */ +fun fileUrlPath(s: String): String? { + val t = s.trim() + if (!t.startsWith("file://", ignoreCase = true)) return null + var rest = t.substring(7) + if (rest.startsWith("localhost/")) rest = rest.removePrefix("localhost") + var anchor = "" + val hash = rest.indexOf('#') + if (hash >= 0) { + val frag = rest.substring(hash + 1) + rest = rest.substring(0, hash) + if (reLineFrag.matches(frag)) anchor = "#$frag" + } + val q = rest.indexOf('?') + if (q >= 0) rest = rest.substring(0, q) + var decoded = decodePercent(rest) + if (reWinSlashDrive.matches(decoded)) decoded = decoded.substring(1) + if (decoded.isEmpty() || !(decoded.startsWith("/") || decoded.startsWith("~/") || reWinDrive.matches(decoded))) return null + return decoded + anchor +} + +/** Converts a markdown link destination into a link target (`bppath:` for `file://` and hub paths, otherwise the URL). */ +fun linkTargetUrl(raw: String): String { + val trimmed = raw.trim() + val url = if (trimmed.startsWith("<") && trimmed.indexOf('>', 1) > 0) { + trimmed.substring(1, trimmed.indexOf('>', 1)) + } else { + trimmed.substringBefore(' ').removePrefix("<").removeSuffix(">") + } + fileUrlPath(url)?.let { return pathLink(it) } + if (isPathText(url)) return pathLink(url) + return url +} private fun boundary(s: String, i: Int) = i == 0 || s[i - 1].isWhitespace() || s[i - 1] in "([{<\"'`,;:" @@ -45,13 +103,18 @@ fun autoLink(s: String, i: Int): LinkHit? { return null } -/** An http(s):// or backplane:// address that starts at s[i] (trailing marks and an unmatched ) stay out). */ +/** An http(s)://, backplane:// or file:// address that starts at s[i] (trailing marks and an unmatched ) stay out). */ fun webLink(s: String, i: Int): LinkHit? { if (i > 0 && s[i - 1].isLetterOrDigit()) return null - if (!(s.startsWith("http://", i) || s.startsWith("https://", i) || s.startsWith("backplane://", i))) return null + val isFile = s.startsWith("file://", i, ignoreCase = true) + val isWeb = s.startsWith("http://", i, ignoreCase = true) || s.startsWith("https://", i, ignoreCase = true) + val isBp = s.startsWith("backplane://", i) + if (!(isFile || isWeb || isBp)) return null var e = i; while (e < s.length && !s[e].isWhitespace() && s[e] !in "<>\"'") e++ while (e > i && s[e - 1] in ".,;:!?)]}*_") { if (s[e - 1] == ')' && s.substring(i, e).count { it == '(' } >= s.substring(i, e).count { it == ')' }) break; e-- } - return LinkHit(e, s.substring(i, e)) + val raw = s.substring(i, e) + if (isFile) return fileUrlPath(raw)?.let { LinkHit(e, pathLink(it)) } + return LinkHit(e, raw) } /** Plain text cut into runs (text, link or null): a message that is not Markdown (a user's, a room post). */ diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinks.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinks.kt index f81be93cbb..d5d3723c81 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinks.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataLinks.kt @@ -72,6 +72,7 @@ fun DataClient.openLink(url: String, thread: String) { "project" -> LinkTarget(LinkTarget.Kind.PROJECT, r.optString("project")) "room" -> LinkTarget(LinkTarget.Kind.ROOM, r.optString("room")) "file" -> LinkTarget(LinkTarget.Kind.FILE, r.optString("thread"), r.optString("path"), r.optInt("line")) + "download" -> { MdLinks.ctx?.let { c -> Downloads.file(c, DFileLink(r.optString("path"), r.optString("name"), r.optLong("size", -1L), "download"), thread) }; null } "settings" -> LinkTarget(LinkTarget.Kind.SETTINGS, r.optString("page")) else -> { // a file the reply lists that no viewer here opens is downloaded instead diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataMarkdown.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataMarkdown.kt index b236011dd7..36148d0086 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataMarkdown.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataMarkdown.kt @@ -143,9 +143,9 @@ object MdLinks { var thread: String = "" fun open(url: String) { val c = ctx - val scheme = url.substringBefore(':', "") + val scheme = url.substringBefore(':', "").lowercase() when { - url.startsWith(PATH_SCHEME) || scheme == "backplane" || scheme == BuildConfig.URL_SCHEME -> DataClient.openLink(url, thread) + url.startsWith(PATH_SCHEME) || scheme == "backplane" || scheme == BuildConfig.URL_SCHEME.lowercase() || scheme == "file" -> DataClient.openLink(url, thread) scheme == "http" || scheme == "https" || scheme == "mailto" -> c?.let { runCatching { it.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) } } scheme == "tel" -> c?.let { runCatching { it.startActivity(android.content.Intent(android.content.Intent.ACTION_DIAL, android.net.Uri.parse(url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) } } } @@ -203,7 +203,8 @@ private fun AnnotatedString.Builder.inl(s: String, p: MdPalette, depth: Int, cx: if (e > 0) { val inner = s.substring(i + n, e).trim('`').let { if (it.startsWith(" ") && it.endsWith(" ") && it.isNotBlank()) it.trim() else it } val code: AnnotatedString.Builder.() -> Unit = { withStyle(SpanStyle(fontFamily = BpMono, color = p.code, background = p.codeBg, fontSize = 12.5.sp)) { append(inner) } } - if (isPathText(inner)) link(pathLink(inner), p) { code() } else code() + val codeTarget = fileUrlPath(inner)?.let { pathLink(it) } ?: if (isPathText(inner)) pathLink(inner) else null + if (codeTarget != null) link(codeTarget, p) { code() } else code() cx?.look?.inline(inner)?.let { piece -> appendInlineContent("cp${cx.pieces.size}", " "); cx.pieces.add(piece) } i = e + n; continue } @@ -217,7 +218,7 @@ private fun AnnotatedString.Builder.inl(s: String, p: MdPalette, depth: Int, cx: var pd = 0; var k = close + 1; var end = -1 while (k < s.length) { if (s[k] == '(') pd++ else if (s[k] == ')') { pd--; if (pd == 0) { end = k; break } }; k++ } if (end > 0) { - val url = s.substring(close + 2, end).trim().removePrefix("<").substringBefore(' ').removeSuffix(">").let { if (isPathText(it)) pathLink(it) else it } + val url = linkTargetUrl(s.substring(close + 2, end)) val label = s.substring(st + 1, close) link(url, p) { if (c == '!') append(label.ifEmpty { url }) else inl(label, p, depth + 1, cx) } i = end + 1; continue diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt index f95833e4cc..370edc9ae2 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt @@ -137,7 +137,10 @@ fun DataRoot() { Page.Home -> HomeScreen({ page = Page.Thread(it) }, { page = Page.Settings }, { page = Page.Hub(Page.Home) }, { page = Page.Folders() }, { page = Page.New(it) }, { page = Page.Swarm(it) }) { page = Page.Room(it) } is Page.Term -> { BackHandler { page = p.from }; TermFull(p.key, Msg.palette_terminal) { page = p.from } } is Page.Terms -> { BackHandler { page = p.from }; TermsScreen(p.project, { page = p.from }) { page = Page.Term(it, p) } } - is Page.Viewer -> { BackHandler { page = Page.Thread(p.id) }; DataClient.threads.firstOrNull { it.id == p.id }?.let { ViewerScreen(it, p.file, p.line) { page = Page.Thread(p.id) } } + is Page.Viewer -> { BackHandler { page = Page.Thread(p.id) } + val viewerThread = DataClient.threads.firstOrNull { it.id == p.id } + ?: if (p.file.isNotEmpty()) DThread(id = p.id, project = "", title = p.file.substringAfterLast('/'), state = "idle", updatedAt = 0L, pinned = false, settled = false, archived = false, provider = "", model = "", preview = "", waiting = 0) else null + viewerThread?.let { ViewerScreen(it, p.file, p.line) { page = Page.Thread(p.id) } } ?: Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } } // never a blank page while the thread list comes is Page.Room -> { BackHandler { page = Page.Home }; RoomScreen(p.room) { page = Page.Home } } is Page.Thread -> { BackHandler { page = p.from ?: Page.Home }; CompositionLocalProvider(LocalOpenSub provides { k -> page = Page.Sub(p.id, k) }) { ThreadScreen(p.id, { page = Page.Viewer(p.id) }, { page = Page.Hub(p) }, { page = Page.Thread(it) }, { page = Page.Settings }) { page = p.from ?: Page.Home } } } diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/Downloads.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/Downloads.kt index b44aab6e3f..6ef0063ec7 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/Downloads.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/Downloads.kt @@ -115,7 +115,11 @@ object Downloads { File(c.cacheDir, "downloads").listFiles()?.forEach { d -> if (d !in live && d.lastModified() < day) d.deleteRecursively() } } - private fun mime(name: String) = MimeTypeMap.getSingleton().getMimeTypeFromExtension(name.substringAfterLast('.', "").lowercase()) ?: "application/octet-stream" + private fun mime(name: String): String { + val ext = name.substringAfterLast('.', "").lowercase() + if (ext == "pdf") return "application/pdf" + return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) ?: "application/octet-stream" + } /** A copy in the phone's Downloads: MediaStore from Android 10, the app's own Downloads folder before it. */ private fun saveToDownloads(c: Context, f: File) { @@ -136,13 +140,21 @@ object Downloads { private fun uri(c: Context, f: File): Uri = androidx.core.content.FileProvider.getUriForFile(c, c.packageName + ".files", f) fun open(c: Context, r: DownloadRow) { val f = r.file ?: return - val i = Intent(Intent.ACTION_VIEW).setDataAndType(uri(c, f), mime(f.name)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) - runCatching { c.startActivity(Intent.createChooser(i, f.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.onFailure { DataClient.say(Msg.android_download_noapp) } + val u = uri(c, f) + val i = Intent(Intent.ACTION_VIEW).setDataAndType(u, mime(f.name)) + .apply { clipData = android.content.ClipData.newRawUri(f.name, u) } + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + val chooser = Intent.createChooser(i, f.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION) + runCatching { c.startActivity(chooser) }.onFailure { DataClient.say(Msg.android_download_noapp) } } fun send(c: Context, r: DownloadRow) { val f = r.file ?: return - val i = Intent(Intent.ACTION_SEND).setType(mime(f.name)).putExtra(Intent.EXTRA_STREAM, uri(c, f)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) - runCatching { c.startActivity(Intent.createChooser(i, f.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } + val u = uri(c, f) + val i = Intent(Intent.ACTION_SEND).setType(mime(f.name)).putExtra(Intent.EXTRA_STREAM, u) + .apply { clipData = android.content.ClipData.newRawUri(f.name, u) } + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + val chooser = Intent.createChooser(i, f.name).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION) + runCatching { c.startActivity(chooser) } } } diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/FileFetch.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/FileFetch.kt index f45f3dd12a..5477e07aa1 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/FileFetch.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/FileFetch.kt @@ -21,11 +21,17 @@ object FileFetch { /** A name safe to be a file's: no folder in it, never `.` or `..`. */ fun safeName(n: String): String { val t = n.replace('/', '_').replace('\\', '_').trim(); return if (t.isEmpty() || t == "." || t == "..") "download" else t } - /** A path as a link carries it, without the line it points at (`a.rs:12`, `a.rs:3:4`, `a.rs#L4-L9`). */ - fun bare(p: String): String = lineTail.replace(p, "") + /** A path as a link carries it, without `file://`, fragment, query, or the line it points at (`a.rs:12`, `a.rs:3:4`, `a.rs#L4-L9`). */ + fun bare(p: String): String { + val s = fileUrlPath(p)?.substringBefore('#') ?: p.trim() + return lineTail.replace(s, "") + } /** The file of [files] a tapped path names, in the message's spelling. */ - fun find(p: String, files: List): DFileLink? { val b = bare(p); return files.firstOrNull { it.path == p || it.path == b } } + fun find(p: String, files: List): DFileLink? { + val b = bare(p) + return files.firstOrNull { it.path == p || it.path == b || bare(it.path) == b } + } /** A thread of another machine (`~`) is named on the request; this hub's own thread is not. */ fun far(thread: String) = thread.contains('~') diff --git a/mobile/android/app/src/test/java/dev/backplane/mobile/FileFetchTest.kt b/mobile/android/app/src/test/java/dev/backplane/mobile/FileFetchTest.kt index 1a27472478..860b5142c5 100644 --- a/mobile/android/app/src/test/java/dev/backplane/mobile/FileFetchTest.kt +++ b/mobile/android/app/src/test/java/dev/backplane/mobile/FileFetchTest.kt @@ -11,7 +11,7 @@ import org.junit.Test // Files of the hub's machine (docs/file-links.md): which link is a file to download, its address, and how a stopped download goes on class FileFetchTest { private val tok = "0123456789abcdef0123456789abcdef0123456789abcdef" - private val files = listOf(DFileLink("/home/user/p/mfg/gerbers.zip", "gerbers.zip", 123, "download"), DFileLink("~/p/board.kicad_pcb", "board.kicad_pcb", 9, "view")) + private val files = listOf(DFileLink("/home/user/p/mfg/gerbers.zip", "gerbers.zip", 123, "download"), DFileLink("~/p/board.kicad_pcb", "board.kicad_pcb", 9, "view"), DFileLink("/home/user/p/docs/My Doc.pdf", "My Doc.pdf", 456, "view")) @Test fun sharesAreLinks() { assertEquals("/s/$tok/gerbers.zip", FileFetch.shareRoute("/s/$tok/gerbers.zip")) @@ -32,6 +32,9 @@ class FileFetchTest { @Test fun aTappedPathFindsItsFile() { assertEquals("gerbers.zip", FileFetch.find("/home/user/p/mfg/gerbers.zip", files)?.name) + assertEquals("gerbers.zip", FileFetch.find("file:///home/user/p/mfg/gerbers.zip", files)?.name) + assertEquals("My Doc.pdf", FileFetch.find("file:///home/user/p/docs/My%20Doc.pdf", files)?.name) + assertEquals("My Doc.pdf", FileFetch.find("file://localhost/home/user/p/docs/My%20Doc.pdf#page=2", files)?.name) // a link carries the line it points at; the file is the same assertEquals("board.kicad_pcb", FileFetch.find("~/p/board.kicad_pcb:12", files)?.name) assertEquals("board.kicad_pcb", FileFetch.find("~/p/board.kicad_pcb:3:4", files)?.name) diff --git a/mobile/android/app/src/test/java/dev/backplane/mobile/LinkGrammarTest.kt b/mobile/android/app/src/test/java/dev/backplane/mobile/LinkGrammarTest.kt index b2a01d2c0e..793e047dd9 100644 --- a/mobile/android/app/src/test/java/dev/backplane/mobile/LinkGrammarTest.kt +++ b/mobile/android/app/src/test/java/dev/backplane/mobile/LinkGrammarTest.kt @@ -29,4 +29,16 @@ class LinkGrammarTest { assertEquals(listOf("backplane://thread/lab~t9|backplane://thread/lab~t9"), kinds("(backplane://thread/lab~t9)")) assertEquals(listOf("backplane://conv/room%3Aabc|backplane://conv/room%3Aabc"), kinds("backplane://conv/room%3Aabc")) } + @Test fun file_urls() { + assertEquals("/home/user/proj/docs/Parts List.pdf", fileUrlPath("file:///home/user/proj/docs/Parts%20List.pdf")) + assertEquals("/home/user/proj/docs/Spec Sheet.pdf", fileUrlPath("file://localhost/home/user/proj/docs/Spec%20Sheet.pdf#page=2")) + assertEquals("/home/user/proj/src/main.rs#L40-L50", fileUrlPath("file:///home/user/proj/src/main.rs#L40-L50")) + assertEquals("/home/user/proj/docs/Parts List.pdf", pathOf("file:///home/user/proj/docs/Parts%20List.pdf")) + assertEquals("bppath:/home/user/proj/docs/My Doc (Final).pdf", linkTargetUrl("file:///home/user/proj/docs/My%20Doc%20(Final).pdf")) + assertEquals("bppath:/home/user/proj/docs/Parts List.pdf", linkTargetUrl("")) + assertEquals( + listOf("bppath:/home/user/proj/docs/Parts List.pdf|file:///home/user/proj/docs/Parts%20List.pdf"), + kinds("see file:///home/user/proj/docs/Parts%20List.pdf now"), + ) + } } diff --git a/mobile/ios/Backplane/DataDownloads.swift b/mobile/ios/Backplane/DataDownloads.swift index 4572e0c57d..b3a280041e 100644 --- a/mobile/ios/Backplane/DataDownloads.swift +++ b/mobile/ios/Backplane/DataDownloads.swift @@ -1,5 +1,6 @@ import SwiftUI import UIKit +import QuickLook // Downloads of files on the hub's machine (docs/file-links.md): a file a reply names (`/file?path=`), a share (`/s//`) or a Files row // (`/files/get`), over HTTP on the hub the app is connected to, with the device's token. Streamed into `.part` in the app's caches, never held in @@ -44,7 +45,7 @@ final class DDownloads { } guard let self, !Task.isCancelled else { return } self.tasks[key] = nil; self.put(out) - if out.state == .done, let f = out.file { DDownloads.present(f) } + if out.state == .done, let f = out.file { DDownloads.open(f) } } } @ObservationIgnored private var stopping: [String: Task] = [:] @@ -93,18 +94,39 @@ final class DDownloads { } } + private static var ql: DQuickLook? + private static func topVC() -> UIViewController? { + let top = UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.keyWindow?.rootViewController }.first + var at = top; while let p = at?.presentedViewController { at = p } + return at + } + /// Preview a finished download in QuickLook (PDFs, images, text, office files), falling back to the share sheet. + static func open(_ f: URL) { + guard QLPreviewController.canPreview(f as NSURL), let at = topVC() else { present(f); return } + let hold = DQuickLook(f); ql = hold + let vc = QLPreviewController(); vc.dataSource = hold; vc.delegate = hold + at.present(vc, animated: true) + } + /// The system's share sheet for a finished file: Save to Files, AirDrop, Open in another app. static func present(_ f: URL) { let vc = UIActivityViewController(activityItems: [f], applicationActivities: nil) - let top = UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.keyWindow?.rootViewController }.first - var at = top; while let p = at?.presentedViewController { at = p } + let at = topVC() vc.popoverPresentationController?.sourceView = at?.view if let v = at?.view { vc.popoverPresentationController?.sourceRect = CGRect(x: v.bounds.midX, y: v.bounds.maxY - 80, width: 1, height: 1) } at?.present(vc, animated: true) } + + private final class DQuickLook: NSObject, QLPreviewControllerDataSource, QLPreviewControllerDelegate { + let url: URL + init(_ url: URL) { self.url = url } + nonisolated func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 } + nonisolated func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { url as NSURL } + nonisolated func previewControllerDidDismiss(_ controller: QLPreviewController) { Task { @MainActor in DDownloads.ql = nil } } + } } -/// The downloads under way and just done, over the screen's foot: each with its progress, then Share, or the hub's words and Retry. +/// The downloads under way and just done, over the screen's foot: each with its progress, then Open & Share, or the hub's words and Retry. struct DDownloadStrip: View { var d = DDownloads.shared private func mb(_ n: Int64) -> String { n < 0 ? "?" : n < 1024 ? "\(n) B" : n < 1 << 20 ? "\(n / 1024) KB" : String(format: "%.1f MB", Double(n) / 1048576) } @@ -120,7 +142,8 @@ struct DDownloadStrip: View { Text(r.total > 0 ? Tr.android_download_of(have: mb(r.have), total: mb(r.total)) : mb(r.have)).dmono(11).foregroundStyle(BackplaneDesign.dim) Button(Tr.t("Cancel")) { d.cancel(r.id) }.buttonStyle(DButton(compact: true)).accessibilityIdentifier("download.cancel") case .done: - Button(Tr.t("Share")) { if let f = r.file { DDownloads.present(f) } }.buttonStyle(DButton(primary: true, compact: true)).accessibilityIdentifier("download.share") + Button(Tr.t("Open")) { if let f = r.file { DDownloads.open(f) } }.buttonStyle(DButton(primary: true, compact: true)).accessibilityIdentifier("download.open") + Button(Tr.t("Share")) { if let f = r.file { DDownloads.present(f) } }.buttonStyle(DButton(compact: true)).accessibilityIdentifier("download.share") Button { d.dismiss(r.id) } label: { Image(systemName: "xmark") }.buttonStyle(DButton(compact: true)).accessibilityIdentifier("download.close") case .fail: Button(Tr.t("Retry")) { d.retry(r.id) }.buttonStyle(DButton(compact: true)).accessibilityIdentifier("download.retry") diff --git a/mobile/ios/Backplane/DataLinkGrammar.swift b/mobile/ios/Backplane/DataLinkGrammar.swift index 04dbce1b4d..dbba9c3128 100644 --- a/mobile/ios/Backplane/DataLinkGrammar.swift +++ b/mobile/ios/Backplane/DataLinkGrammar.swift @@ -7,7 +7,49 @@ import Foundation /// A path written in text, as a URL the text can carry: bppath: let dPathScheme = "bppath" func dPathURL(_ p: String) -> URL? { URL(string: dPathScheme + ":" + (p.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: ":"))) ?? p)) } -func dPathFrom(_ u: URL) -> String? { u.scheme == dPathScheme ? String(u.absoluteString.dropFirst(dPathScheme.count + 1)).removingPercentEncoding : nil } +func dPathFrom(_ u: URL) -> String? { + if u.scheme == dPathScheme { return String(u.absoluteString.dropFirst(dPathScheme.count + 1)).removingPercentEncoding } + if u.scheme?.lowercased() == "file" { return dFileURLPath(u.absoluteString) } + return nil +} + +/// Decodes a `file://` URL into a hub filesystem path (preserving `#L` anchors, stripping other fragments/queries and `localhost`). +func dFileURLPath(_ s: String) -> String? { + let t = s.trimmingCharacters(in: .whitespacesAndNewlines) + guard t.count >= 7, t.prefix(7).lowercased() == "file://" else { return nil } + var rest = String(t.dropFirst(7)) + if rest.hasPrefix("localhost/") { rest = String(rest.dropFirst("localhost".count)) } + var anchor = "" + if let hash = rest.firstIndex(of: "#") { + let frag = String(rest[rest.index(after: hash)...]) + rest = String(rest[.. URL? { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + var url: String + if trimmed.hasPrefix("<"), let gt = trimmed.dropFirst().firstIndex(of: ">") { + url = String(trimmed[trimmed.index(after: trimmed.startIndex)..")) + } + if let p = dFileURLPath(url) { return dPathURL(p) } + if dIsPathText(url) { return dPathURL(url) } + return URL(string: url) ?? URL(string: url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "") +} private func rx(_ p: String) -> NSRegularExpression { try! NSRegularExpression(pattern: p) } private let reEmail = rx("^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,}$") @@ -70,17 +112,24 @@ func dLinkRuns(_ text: String) -> [(text: String, url: URL?)] { flush(); return out } -/// An http(s):// or backplane:// address that starts at s[i], to the end of its characters (trailing marks and an unmatched ) stay out). +/// An http(s)://, backplane:// or file:// address that starts at s[i], to the end of its characters (trailing marks and an unmatched ) stay out). func dWebLink(_ s: [Character], _ i: Int) -> (end: Int, url: URL)? { if i > 0, s[i - 1].isLetter || s[i - 1].isNumber { return nil } - var hit = false - for p in ["http://", "https://", "backplane://"] where i + p.count <= s.count && String(s[i..\"'".contains(s[e]) { e += 1 } while e > i, ".,;:!?)]}*_".contains(s[e - 1]) { if s[e - 1] == ")" { let seg = s[i..= seg.filter({ $0 == ")" }).count { break } } e -= 1 } - guard let u = URL(string: String(s[i.. 0 { - var url = String(s[(close + 2)..")) + let rawDest = String(s[(close + 2).. ReplyImages.Layout { #if DEBUG DataClient.shared.lastLink = url.absoluteString #endif - switch url.scheme { + switch url.scheme?.lowercased() { case "http", "https", "mailto", "tel": return .systemAction - case "backplane", AppIdentity.scheme, dPathScheme: DataClient.shared.openLink(url, thread: thread); return .handled + case "backplane", AppIdentity.scheme.lowercased(), dPathScheme, "file": DataClient.shared.openLink(url, thread: thread); return .handled default: return .discarded } } diff --git a/mobile/ios/Backplane/DataModels.swift b/mobile/ios/Backplane/DataModels.swift index 6ead57bd0d..ee0f35a428 100644 --- a/mobile/ios/Backplane/DataModels.swift +++ b/mobile/ios/Backplane/DataModels.swift @@ -272,6 +272,14 @@ struct DThread: Codable, Equatable, Identifiable, NestedThread { var memory: DMemory? // infinite context: how far its memory is written (the hub's bots/recall/progress.rs); nil for a thread without it var planMode: DPlanMode? = nil enum CodingKeys: String, CodingKey { case id, project, title, state, updatedAt, pinned, pinOrder, settled, settledAt, archived, provider, model, effort, runtime, chip, preview, waiting, parent, history, status, mark, swarm, memory, planMode } + init(id: String, project: String = "", title: String = "", state: String = "idle", updatedAt: Int = 0, pinned: Bool = false, pinOrder: Int = 0, settled: Bool = false, settledAt: Int = 0, archived: Bool = false, provider: String = "", model: String = "", effort: String = "", runtime: String = "", chip: String = "", preview: String = "", waiting: Int = 0, parent: String = "", history: Bool = false, status: String = "", mark: DMark? = nil, swarm: String = "", memory: DMemory? = nil, planMode: DPlanMode? = nil) { + self.id = id; self.project = project; self.title = title; self.state = state; self.updatedAt = updatedAt + self.pinned = pinned; self.pinOrder = pinOrder; self.settled = settled; self.settledAt = settledAt; self.archived = archived + self.provider = provider; self.model = model; self.effort = effort; self.runtime = runtime; self.chip = chip + self.preview = preview; self.waiting = waiting; self.parent = parent; self.history = history; self.status = status + self.mark = mark; self.swarm = swarm; self.memory = memory; self.planMode = planMode + } + static func stub(id: String, title: String) -> DThread { DThread(id: id, title: title) } init(from d: Decoder) throws { let c = try d.container(keyedBy: CodingKeys.self) id = c.str(.id); project = c.str(.project); title = c.str(.title); state = c.str(.state); updatedAt = c.int(.updatedAt) diff --git a/mobile/ios/Backplane/DataViews.swift b/mobile/ios/Backplane/DataViews.swift index 4144b7ec0d..5408e5c0a5 100644 --- a/mobile/ios/Backplane/DataViews.swift +++ b/mobile/ios/Backplane/DataViews.swift @@ -236,6 +236,7 @@ struct DataThreadsView: View { .navigationDestination(for: DSwarmRoute.self) { DataSwarmView(client: client, route: $0) } .navigationDestination(for: DViewerRoute.self) { r in if let t = client.threads.first(where: { $0.id == r.id }) { DataViewerView(client: client, thread: t, openFile: r.file, line: r.line) } + else if !r.file.isEmpty { DataViewerView(client: client, thread: DThread.stub(id: r.id, title: (r.file as NSString).lastPathComponent), openFile: r.file, line: r.line) } else { DLoading(text: Tr.t(client.conn == .online ? "Loading the thread…" : "Connecting to the hub…")) } // never a blank page while the thread list comes } .navigationDestination(for: DPage.self) { p in if p.name == "settings" { DataSettingsView(client: client) } else if let sub = DSettingsPage(rawValue: p.name) { DataSettingsPageView(client: client, page: sub) } else if p.name == "hub" { DataHubView(client: client) } else if p.name == "accounts" { DataAccountsView(client: client) } else if p.name == "mcp" { DataMcpView(client: client) } else { DataImprovementsView(client: client) } } diff --git a/mobile/ios/Backplane/FileFetch.swift b/mobile/ios/Backplane/FileFetch.swift index d69c5f7be9..7d114f8dff 100644 --- a/mobile/ios/Backplane/FileFetch.swift +++ b/mobile/ios/Backplane/FileFetch.swift @@ -36,10 +36,24 @@ enum FileFetch { if isShare(route) { guard shareRoute(route) != nil else { return nil }; c.percentEncodedPath = route } else { c.path = route } return c.url } - /// A path as a link carries it, without the line it points at (`a.rs:12`, `a.rs:3:4`, `a.rs#L4-L9`). - static func bare(_ p: String) -> String { lineTail.stringByReplacingMatches(in: p, range: whole(p), withTemplate: "") } + /// A path as a link carries it, without `file://`, fragment, query, or the line it points at (`a.rs:12`, `a.rs:3:4`, `a.rs#L4-L9`). + static func bare(_ p: String) -> String { + var s = p.trimmingCharacters(in: .whitespaces) + if s.count >= 7, s.prefix(7).lowercased() == "file://" { + var rest = String(s.dropFirst(7)) + if rest.hasPrefix("localhost/") { rest = String(rest.dropFirst("localhost".count)) } + if let hash = rest.firstIndex(of: "#") { rest = String(rest[.. DFileLink? { let b = bare(p); return files.first { $0.path == p || $0.path == b } } + static func find(_ p: String, in files: [DFileLink]) -> DFileLink? { + let b = bare(p) + return files.first { $0.path == p || $0.path == b || bare($0.path) == b } + } /// A thread of another machine (`~`) is named on the request; this hub's own thread is not. static func far(_ thread: String) -> Bool { thread.contains("~") } /// `/file`'s query. diff --git a/mobile/ios/Tests/FileFetchTests.swift b/mobile/ios/Tests/FileFetchTests.swift index 7019ba7b6b..533f3a4d93 100644 --- a/mobile/ios/Tests/FileFetchTests.swift +++ b/mobile/ios/Tests/FileFetchTests.swift @@ -4,7 +4,7 @@ import Foundation var failed = 0 func check(_ ok: Bool, _ what: String) { if !ok { failed += 1; print("FAIL", what) } } let tok = "0123456789abcdef0123456789abcdef0123456789abcdef" -let files = [DFileLink(path: "/home/user/p/mfg/gerbers.zip", name: "gerbers.zip", size: 123, open: "download"), DFileLink(path: "~/p/board.kicad_pcb", name: "board.kicad_pcb", size: 9, open: "view")] +let files = [DFileLink(path: "/home/user/p/mfg/gerbers.zip", name: "gerbers.zip", size: 123, open: "download"), DFileLink(path: "~/p/board.kicad_pcb", name: "board.kicad_pcb", size: 9, open: "view"), DFileLink(path: "/home/user/p/docs/My Doc.pdf", name: "My Doc.pdf", size: 456, open: "view")] func kinds(_ t: String) -> [String] { dLinkRuns(t).compactMap { run in run.url.map { u in (dPathFrom(u).map { "path:" + $0 } ?? u.absoluteString) + "|" + run.text } } } // shares @@ -25,6 +25,9 @@ check(FileFetch.safeName("a/b") == "a_b" && FileFetch.safeName("..") == "downloa // a tapped path finds its file check(FileFetch.find("/home/user/p/mfg/gerbers.zip", in: files)?.name == "gerbers.zip", "find") +check(FileFetch.find("file:///home/user/p/mfg/gerbers.zip", in: files)?.name == "gerbers.zip", "find file://") +check(FileFetch.find("file:///home/user/p/docs/My%20Doc.pdf", in: files)?.name == "My Doc.pdf", "find file:// encoded") +check(FileFetch.find("file://localhost/home/user/p/docs/My%20Doc.pdf#page=2", in: files)?.name == "My Doc.pdf", "find file:// localhost fragment") check(FileFetch.find("~/p/board.kicad_pcb:12", in: files)?.name == "board.kicad_pcb", "find with line") check(FileFetch.find("~/p/board.kicad_pcb:3:4", in: files)?.name == "board.kicad_pcb", "find with line and column") check(FileFetch.find("/home/user/p/mfg/gerbers.zip#L4-L9", in: files)?.name == "gerbers.zip", "find with anchor") diff --git a/mobile/ios/Tests/LinkGrammarTests.swift b/mobile/ios/Tests/LinkGrammarTests.swift index 54999c8e81..d1ddaab7ce 100644 --- a/mobile/ios/Tests/LinkGrammarTests.swift +++ b/mobile/ios/Tests/LinkGrammarTests.swift @@ -23,5 +23,12 @@ check(kinds("visit https://example.com/a_(b)). ok") == ["https://example.com/a_( check(kinds("(backplane://thread/lab~t9)") == ["backplane://thread/lab~t9|backplane://thread/lab~t9"], "backplane link") check(kinds("backplane://conv/room%3Aabc") == ["backplane://conv/room%3Aabc|backplane://conv/room%3Aabc"], "conv link") check(dPathFrom(dPathURL("a b/c.rs:5")!) == "a b/c.rs:5", "path url round trip") +check(dFileURLPath("file:///home/user/proj/docs/Parts%20List.pdf") == "/home/user/proj/docs/Parts List.pdf", "file url spaces") +check(dFileURLPath("file://localhost/home/user/proj/docs/Spec%20Sheet.pdf#page=2") == "/home/user/proj/docs/Spec Sheet.pdf", "file url localhost + page fragment") +check(dFileURLPath("file:///home/user/proj/src/main.rs#L40-L50") == "/home/user/proj/src/main.rs#L40-L50", "file url line anchor") +check(dPathFrom(URL(string: "file:///home/user/proj/docs/Parts%20List.pdf")!) == "/home/user/proj/docs/Parts List.pdf", "dPathFrom file URL") +check(dPathFrom(dLinkURL("file:///home/user/proj/docs/My%20Doc%20(Final).pdf")!) == "/home/user/proj/docs/My Doc (Final).pdf", "dLinkURL file:// with parens") +check(dPathFrom(dLinkURL("")!) == "/home/user/proj/docs/Parts List.pdf", "dLinkURL angle-bracket file:// with space") +check(kinds("see file:///home/user/proj/docs/Parts%20List.pdf now") == ["path:/home/user/proj/docs/Parts List.pdf|file:///home/user/proj/docs/Parts%20List.pdf"], "bare file:// in text \(kinds("see file:///home/user/proj/docs/Parts%20List.pdf now"))") if failed == 0 { print("link grammar: ok") } exit(failed == 0 ? 0 : 1) diff --git a/native/host/src/data/link.rs b/native/host/src/data/link.rs index 5e02c4893a..0a883bf8ba 100644 --- a/native/host/src/data/link.rs +++ b/native/host/src/data/link.rs @@ -63,29 +63,78 @@ pub(super) async fn resolve(hub: &Arc, p: &Value) -> Result { }; } if url.starts_with("backplane://") { return none("That link is not one this hub knows.") } - // a path in a project: against the thread's folder; a file of another project (an absolute path, a file:// address) opens in that - // project's thread (present/filelink.rs: the one given when it is that project's, else its newest), its tab chosen by the app from its name - let url = url.strip_prefix("file://").map(crate::present::filelink::url_path).unwrap_or_else(|| url.to_string()); - let (path, line) = split_line(&url); - let other = { let g = hub.model().await; use crate::present::filelink as fl; - let base = g.threads.get(th).and_then(|t| if !t.worktree.is_empty() { Some(crate::files::kicad::canonical::design_root(&t.worktree)) } else { g.projects.get(&t.project).map(|p| p.root.clone()) }).unwrap_or_default(); - fl::absolute(path, &base, &crate::plat::dirs::home_or_empty()).and_then(|a| { - let under = |r: &str| fl::under(&a, r); - let (pid, p) = g.projects.iter().filter(|(id, p)| !p.removed && !id.contains('~') && under(&p.root)).max_by_key(|(_, p)| p.root.trim_end_matches('/').len())?; - let t = if g.threads.get(th).map_or(false, |t| &t.project == pid && !t.deleted) { th.to_string() } - else { g.threads.iter().filter(|(_, t)| &t.project == pid && !t.archived && !t.deleted).max_by_key(|(i, t)| (t.activity, i.to_string())).map(|(i, _)| i.clone())? }; - Some((t, p.root.clone())) }) }; - let (th, root) = { let g = hub.model().await; - match other { Some(x) => x, None => { - if th.is_empty() { return none("There is no project to look for that file in.") } - let root = g.threads.get(th).filter(|t| !t.deleted).and_then(|t| g.projects.get(&t.project)).map(|p| p.root.clone()); - let Some(root) = root else { return none("That file is on another machine.") }; - (th.to_string(), root) } } }; - let th = th.as_str(); - let r2 = root.clone(); let pp = path.to_string(); - match tokio::task::spawn_blocking(move || inside(&r2, &pp)).await.ok().flatten() { - Some(rel) => Ok(json!({"kind":"file","thread":th,"path":rel,"line":line})), - None => none("That file is not in this project."), + // a path in a project: against the thread's folder, or any registered project / share root allowed by files::share::check + // (a file:// address or absolute path in another project, e.g. from a bot conversation, opens in that project's thread or downloads via /file) + let normalized = if let Some(rest) = url.get(..7).filter(|s| s.eq_ignore_ascii_case("file://")).map(|_| &url[7..]) { + let (before_frag, frag) = match rest.split_once('#') { + Some((a, f)) if f.starts_with('L') && f[1..].chars().next().is_some_and(|c| c.is_ascii_digit()) => (a, Some(f)), + Some((a, _)) => (a, None), + None => (rest, None), + }; + let decoded = crate::present::filelink::url_path(before_frag); + match frag { Some(f) => format!("{decoded}#{f}"), None => decoded } + } else { url.to_string() }; + let (path, line) = split_line(&normalized); + let extra = hub.setting("files.share.roots").await.unwrap_or_default(); + let home = hub.cfg.home.clone(); + let home_dir = crate::plat::dirs::home_or_empty(); + let (roots, abs_path, cands) = { + let g = hub.model().await; + use crate::present::filelink as fl; + let roots = crate::files::share::roots_of(&g, &home, &extra); + let th_root = crate::files::threadpath::resolve( + th, + |i| g.threads.get(i).map(|t| crate::files::threadpath::T { project: &t.project, worktree: &t.worktree, deleted: t.deleted }), + |i| g.projects.get(i).map(|p| crate::files::threadpath::P { root: &p.root, removed: p.removed }), + ).unwrap_or_default(); + let th_proj_root = g.threads.get(th).filter(|t| !t.deleted).and_then(|t| g.projects.get(&t.project)).filter(|p| !p.removed).map(|p| p.root.clone()).unwrap_or_default(); + let base = if !th_root.is_empty() { th_root.clone() } else { th_proj_root }; + let is_rel = !crate::plat::fs::is_abs(path) && !path.starts_with("~/"); + if is_rel && base.is_empty() { return none("There is no project to look for that file in.") } + if is_rel && path.split(['/', '\\']).any(|x| x == "..") { return none("That file is not in this project.") } + let Some(abs_path) = fl::absolute(path, &base, &home_dir) else { return none("That file is not in this project.") }; + let mut cands: Vec<(String, String)> = vec![]; + if !th.is_empty() && !th_root.is_empty() && g.threads.get(th).is_some_and(|t| !t.deleted) { + cands.push((th.to_string(), th_root)); + } + let mut projs: Vec<(&String, &crate::model::ProjectMeta)> = g.projects.iter().filter(|(id, p)| !p.removed && !id.contains('~') && !p.root.is_empty()).collect(); + projs.sort_by(|a, b| b.1.root.trim_end_matches('/').len().cmp(&a.1.root.trim_end_matches('/').len())); + for (pid, p) in projs { + let mut ts: Vec<(&String, &crate::model::ThreadMeta)> = g.threads.iter().filter(|(_, t)| !t.deleted && !t.archived && &t.project == pid).collect(); + ts.sort_by(|a, b| { + let ra = if !a.1.worktree.is_empty() { &a.1.worktree } else { &p.root }; + let rb = if !b.1.worktree.is_empty() { &b.1.worktree } else { &p.root }; + std::path::Path::new(rb).components().count().cmp(&std::path::Path::new(ra).components().count()) + .then_with(|| b.1.activity.cmp(&a.1.activity)) + .then_with(|| b.0.cmp(a.0)) + }); + for (tid, t) in ts { + if cands.iter().any(|(x, _)| x == tid) { continue } + let root = if !t.worktree.is_empty() { t.worktree.clone() } else { p.root.clone() }; + cands.push((tid.clone(), root)); + } + } + (roots, abs_path, cands) + }; + let res = tokio::task::spawn_blocking(move || -> Result { + let (real, md) = crate::files::share::check(&roots, &home, &abs_path).map_err(|e| match e { + "that file is not shared" => "That file is not shared.", + "that file is not in a project" => "That file is not in a project.", + _ => "That file is not in this project.", + })?; + let real_str = real.to_string_lossy().into_owned(); + for (cand_th, cand_root) in &cands { + if let Some(rel) = inside(cand_root, &real_str) { + return Ok(json!({"kind": "file", "thread": cand_th, "path": rel, "line": line})); + } + } + let name = real.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into()); + Ok(json!({"kind": "download", "path": real_str, "name": name, "size": md.len()})) + }).await; + match res { + Ok(Ok(v)) => Ok(v), + Ok(Err(note)) => none(note), + Err(_) => none("That file is not in this project."), } } diff --git a/native/host/src/data/tests.rs b/native/host/src/data/tests.rs index 04ae9f886f..062baad19d 100644 --- a/native/host/src/data/tests.rs +++ b/native/host/src/data/tests.rs @@ -1620,3 +1620,66 @@ fn probed_models(installed: &[&str]) -> Value { }; assert_eq!(push2["favorites"], json!([])); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn data_link_resolve_handles_bot_thread_file_urls_and_download_fallback() { + let base = crate::plat::tmp::canonical("link-bot-file"); + let proj_with_thread = base.join("proj-a"); + let proj_no_thread = base.join("proj-b"); + let proj_wt_only = base.join("proj-c"); + let wt_dir = proj_wt_only.join(".backplane/worktrees/w1"); + let outside = base.join("outside"); + for d in [proj_with_thread.join("docs"), proj_no_thread.join("docs"), wt_dir.clone(), outside.clone()] { + std::fs::create_dir_all(&d).unwrap(); + } + let pdf_a = proj_with_thread.join("docs/Parts List.pdf"); + let pdf_b = proj_no_thread.join("docs/No Thread.pdf"); + let pdf_c = proj_wt_only.join("docs/Main Only.pdf"); + std::fs::create_dir_all(proj_wt_only.join("docs")).unwrap(); + std::fs::write(&pdf_a, b"%PDF-1.4\na").unwrap(); + std::fs::write(&pdf_b, b"%PDF-1.4\nb").unwrap(); + std::fs::write(&pdf_c, b"%PDF-1.4\nc").unwrap(); + std::fs::write(proj_with_thread.join(".env"), b"SECRET=1").unwrap(); + std::fs::write(outside.join("secret.pdf"), b"%PDF-1.4\nout").unwrap(); + + let more = format!( + "{{\"$\":\"ProjectCreated\",\"id\":\"pa\",\"title\":\"A\",\"root\":{},\"at\":1700000100}}\n\ + {{\"$\":\"ProjectCreated\",\"id\":\"pb\",\"title\":\"B\",\"root\":{},\"at\":1700000101}}\n\ + {{\"$\":\"ProjectCreated\",\"id\":\"pc\",\"title\":\"C\",\"root\":{},\"at\":1700000102}}\n\ + {{\"$\":\"ThreadCreated\",\"id\":\"ta\",\"project\":\"pa\",\"title\":\"A1\",\"env\":\"local\",\"branch\":\"\",\"worktree\":\"\",\"provider\":\"claude\",\"model\":\"\",\"at\":1700000110}}\n\ + {{\"$\":\"ThreadCreated\",\"id\":\"tc_wt\",\"project\":\"pc\",\"title\":\"Cwt\",\"env\":\"worktree\",\"branch\":\"b\",\"worktree\":{},\"provider\":\"claude\",\"model\":\"\",\"at\":1700000111}}\n\ + {{\"$\":\"ThreadCreated\",\"id\":\"bot_th\",\"project\":\"\",\"title\":\"Bot\",\"env\":\"local\",\"branch\":\"\",\"worktree\":\"\",\"provider\":\"claude\",\"model\":\"\",\"at\":1700000112}}\n", + json!(proj_with_thread.to_string_lossy()), + json!(proj_no_thread.to_string_lossy()), + json!(proj_wt_only.to_string_lossy()), + json!(wt_dir.to_string_lossy()), + ); + let (_h, port) = up_with("bot-file", &more).await; + let mut ws = open(port, "&enc=json").await; + next(&mut ws).await; + + let pct_path = |p: &std::path::Path| format!("file://{}", p.to_string_lossy().replace(' ', "%20")); + + // Bot thread linking to a file in a registered project with an active non-worktree thread -> kind: "file" + let r1 = ask(&mut ws, 1, "link.resolve", json!({"url": pct_path(&pdf_a), "thread": "bot_th"})).await; + assert_eq!(r1["result"]["kind"], "file", "{r1}"); + assert_eq!(r1["result"]["thread"], "ta", "{r1}"); + assert_eq!(r1["result"]["path"], "docs/Parts List.pdf", "{r1}"); + + // Bot thread linking to a file in a registered project with NO threads -> kind: "download" + let r2 = ask(&mut ws, 2, "link.resolve", json!({"url": pct_path(&pdf_b), "thread": "bot_th"})).await; + assert_eq!(r2["result"]["kind"], "download", "{r2}"); + assert_eq!(r2["result"]["path"], pdf_b.to_string_lossy().as_ref(), "{r2}"); + assert_eq!(r2["result"]["name"], "No Thread.pdf", "{r2}"); + assert_eq!(r2["result"]["size"], 10, "{r2}"); + + // Project whose only thread is a worktree that doesn't contain the file -> kind: "download" (not a 404 viewer thread) + let r3 = ask(&mut ws, 3, "link.resolve", json!({"url": pct_path(&pdf_c), "thread": "bot_th"})).await; + assert_eq!(r3["result"]["kind"], "download", "{r3}"); + assert_eq!(r3["result"]["path"], pdf_c.to_string_lossy().as_ref(), "{r3}"); + + // Security refusals: .env inside project and file outside all projects -> kind: "none" + let r4 = ask(&mut ws, 4, "link.resolve", json!({"url": format!("file://{}/.env", proj_with_thread.to_string_lossy()), "thread": "bot_th"})).await; + assert_eq!(r4["result"]["kind"], "none", "{r4}"); + let r5 = ask(&mut ws, 5, "link.resolve", json!({"url": format!("file://{}/secret.pdf", outside.to_string_lossy()), "thread": "bot_th"})).await; + assert_eq!(r5["result"]["kind"], "none", "{r5}"); +} diff --git a/native/host/src/files/share.rs b/native/host/src/files/share.rs index c4bd791e6d..bee9c7c798 100644 --- a/native/host/src/files/share.rs +++ b/native/host/src/files/share.rs @@ -74,9 +74,19 @@ fn closed_dir(n: &str) -> bool { (l.starts_with('.') && l != ".backplane" && l != ".github") || l == "secrets" || l == "vault" || l.starts_with(".backplane-") || l == "node_modules" } -/// The request's path made into a path on this machine: `file://` dropped, `~/` expanded; None for anything relative, climbing or with a NUL. +fn strip_file_scheme(s: &str) -> Option<&str> { + s.get(..7).filter(|p| p.eq_ignore_ascii_case("file://")).map(|_| &s[7..]) +} + +/// The request's path made into a path on this machine: `file://` (with `#fragment` stripped and `%XX` decoded) dropped, `~/` expanded; None for anything relative, climbing or with a NUL. pub fn local_path(p: &str) -> Option { - let p = p.trim(); let p = p.strip_prefix("file://").unwrap_or(p); + let p = p.trim(); + let decoded; + let p = if let Some(rest) = strip_file_scheme(p) { + let rest = rest.split('#').next().unwrap_or(rest); + decoded = crate::present::filelink::url_path(rest); + decoded.as_str() + } else { p }; if p.contains('\0') || !crate::files::mimg::no_climb(p) { return None } let full = match p.strip_prefix("~/") { Some(r) => PathBuf::from(crate::plat::dirs::home_or_empty()).join(r), None => PathBuf::from(p) }; if full.is_absolute() { Some(full) } else { None } @@ -145,13 +155,12 @@ pub fn linkable(text: &str) -> Vec { g.insert(key, (Instant::now(), v.clone())); v } -fn linkable_now(text: &str) -> Vec { - let roots = roots(); if roots.is_empty() { return vec![] } - let home = HOME.read().unwrap().clone(); +pub fn linkable_with(roots: &[PathBuf], home: &Path, text: &str) -> Vec { + if roots.is_empty() { return vec![] } let mut out = vec![]; for p in candidates(text) { if out.len() >= 32 { break } - if let Ok((_, md)) = check(&roots, &home, &p) { + if let Ok((_, md)) = check(roots, home, &p) { let name = p.rsplit(['/', '\\']).next().unwrap_or(&p).to_string(); let open = if crate::files::fm::preview(&name).is_empty() { "download" } else { "view" }; out.push(json!({"path": p, "name": name, "size": md.len(), "open": open})); @@ -159,22 +168,80 @@ fn linkable_now(text: &str) -> Vec { } out } +fn linkable_now(text: &str) -> Vec { + let roots = roots(); + let home = HOME.read().unwrap().clone(); + linkable_with(&roots, &home, text) +} static HOME: LazyLock> = LazyLock::new(Default::default); -/// Every absolute or `~/` path in a text (code spans and blocks included: an agent writes paths in backticks), each once, at most 1024 chars, with -/// what a sentence puts after it (`.`, `:`, `,`, `)`) dropped. +fn push_candidate(raw: &str, out: &mut Vec) { + if out.len() >= 64 { return } + let w = raw.trim(); + let decoded; + let w = if let Some(rest) = strip_file_scheme(w) { + let rest = rest.split('#').next().unwrap_or(rest); + decoded = crate::present::filelink::url_path(rest); + decoded.as_str() + } else { w }; + let w = w.trim_end_matches(['.', ':', '!', '?']); + let w = w.split_once(":L").map_or(w, |(a, b)| if b.chars().next().map_or(false, |c| c.is_ascii_digit()) { a } else { w }); + let (w, _) = crate::data::link::split_line(w); + if w.len() < 2 || w.len() > 1024 || !(crate::plat::fs::is_abs(w) || w.starts_with("~/")) || w.ends_with('/') { return } + if !out.iter().any(|x| x == w) { out.push(w.to_string()) } +} + +/// Every absolute or `~/` path in a text (markdown links, code spans and blocks included: an agent writes paths in backticks), each once, at most +/// 1024 chars, with what a sentence puts after it (`.`, `:`, `,`, `)`) dropped. pub fn candidates(text: &str) -> Vec { - let sep = |c: char| c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | '`' | '"' | '\'' | ',' | ';' | '|' | '*'); let mut out: Vec = vec![]; - for w in text.split(sep) { - let w = w.strip_prefix("file://").unwrap_or(w); - let w = w.trim_end_matches(['.', ':', '!', '?']); - let w = w.split_once(":L").map_or(w, |(a, b)| if b.chars().next().map_or(false, |c| c.is_ascii_digit()) { a } else { w }); - // a `path:line` reference - let w = match w.rsplit_once(':') { Some((a, b)) if !b.is_empty() && b.bytes().all(|c| c.is_ascii_digit()) => a, _ => w }; - if w.len() < 2 || w.len() > 1024 || !(crate::plat::fs::is_abs(w) || w.starts_with("~/")) || w.ends_with('/') { continue } - if !out.iter().any(|x| x == w) { out.push(w.to_string()) } - if out.len() >= 64 { break } + let mut skip: Vec<(usize, usize)> = vec![]; + // Pass 1: standard markdown links `[label](dest)` (including balanced `()` and `<...>` inside dest, e.g. `%20` or `(Final)`). + let b = text.as_bytes(); + let mut i = 0; + while i < b.len() && out.len() < 64 { + if b[i] == b'\\' { i = (i + 2).min(b.len()); continue } + if b[i] == b'[' { + let mut d = 0usize; let mut j = i; let mut close = None; + while j < b.len() { + if b[j] == b'\\' { j = (j + 2).min(b.len()); continue } + if b[j] == b'[' { d += 1 } + else if b[j] == b']' { d -= 1; if d == 0 { close = Some(j); break } } + j += 1; + } + if let Some(c) = close.filter(|&c| c + 1 < b.len() && b[c + 1] == b'(') { + let mut pd = 0usize; let mut k = c + 1; let mut end = None; + while k < b.len() { + if b[k] == b'\\' { k = (k + 2).min(b.len()); continue } + if b[k] == b'(' { pd += 1 } + else if b[k] == b')' { pd -= 1; if pd == 0 { end = Some(k); break } } + k += 1; + } + if let Some(e) = end { + let inner = text[c + 2..e].trim(); + let dest = if let Some(after) = inner.strip_prefix('<') { + after.split_once('>').map(|(u, _)| u).unwrap_or(after) + } else { + inner.split_whitespace().next().unwrap_or("") + }; + push_candidate(dest, &mut out); + skip.push((c + 1, e + 1)); + i = e + 1; + continue; + } + } + } + i += 1; + } + // Pass 2: bare, backticked, and parenthesized paths in running text outside matched markdown `(dest)` spans. + let sep = |c: char| c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | '`' | '"' | '\'' | ',' | ';' | '|' | '*'); + let mut pos = 0; + for (s, e) in skip.into_iter().chain(std::iter::once((text.len(), text.len()))) { + for w in text[pos..s].split(sep) { + if out.len() >= 64 { break } + push_candidate(w, &mut out); + } + pos = e; } out } diff --git a/native/host/src/files/share_tests.rs b/native/host/src/files/share_tests.rs index 6e97c3dbb0..c0db8358a7 100644 --- a/native/host/src/files/share_tests.rs +++ b/native/host/src/files/share_tests.rs @@ -177,3 +177,106 @@ fn s(p: &Path) -> String { p.to_string_lossy().into_owned() } std::fs::remove_file(d.join("shares-v1.json")).unwrap(); assert!(mutate(&d, |v| v.len()).is_ok(), "no store yet is an empty list"); } + +#[test] fn file_urls_and_markdown_links_extract_decode_and_check_safely() { + let t = concat!( + "See [Parts_List.pdf](file:///home/user/proj/docs/Parts_List.pdf) and ", + "[My Doc](file:///home/user/proj/docs/My%20Doc%20(Final).pdf) and ", + "[Ref](file://localhost/home/user/proj/docs/Spec%20Sheet.pdf#page=2) and ", + "file:///home/user/proj/src/main.rs#L10-L20 and /home/user/proj/src/lib.rs:12:3" + ); + assert_eq!( + candidates(t), + vec![ + "/home/user/proj/docs/Parts_List.pdf", + "/home/user/proj/docs/My Doc (Final).pdf", + "/home/user/proj/docs/Spec Sheet.pdf", + "/home/user/proj/src/main.rs", + "/home/user/proj/src/lib.rs", + ] + ); + + let d = tmp("fileurl"); + let (proj, home, out) = (d.join("proj"), d.join("home"), d.join("out")); + std::fs::create_dir_all(proj.join("docs")).unwrap(); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(&out).unwrap(); + let pdf = proj.join("docs/My Doc (Final).pdf"); + std::fs::write(&pdf, b"%PDF-1.4\n").unwrap(); + std::fs::write(proj.join(".env"), b"SECRET=1").unwrap(); + std::fs::write(out.join("outside.pdf"), b"%PDF-1.4\n").unwrap(); + let roots = vec![proj.clone()]; + + let encoded_url = format!("file://{}/docs/My%20Doc%20(Final).pdf#page=2", s(&proj)); + let localhost_url = format!("file://localhost{}/docs/My%20Doc%20(Final).pdf", s(&proj)); + assert_eq!(local_path(&encoded_url), Some(pdf.clone())); + assert_eq!(local_path(&localhost_url), Some(pdf.clone())); + assert!(check(&roots, &home, &encoded_url).is_ok()); + assert!(check(&roots, &home, &localhost_url).is_ok()); + + // Security refusals: traversal, NUL, secret, outside project + assert!(local_path(&format!("file://{}/docs/%2e%2e/.env", s(&proj))).is_none()); + assert!(local_path(&format!("file://{}/docs/a%00b.pdf", s(&proj))).is_none()); + assert_eq!(check(&roots, &home, &format!("file://{}/.env", s(&proj))).unwrap_err(), "that file is not shared"); + assert_eq!(check(&roots, &home, &format!("file://{}/outside.pdf", s(&out))).unwrap_err(), "that file is not in a project"); + + // linkable_with picks up markdown file:// PDF as view and drops .env / outside files + let msg = format!( + "[My Doc]({}) and [env](file://{}/.env) and [out](file://{}/outside.pdf)", + encoded_url, s(&proj), s(&out) + ); + let links = linkable_with(&roots, &home, &msg); + assert_eq!(links, vec![json!({ + "path": s(&pdf), + "name": "My Doc (Final).pdf", + "size": 9, + "open": "view" + })]); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn serve_file_serves_project_pdf_by_path_and_file_url() { + let d = tmp("serve-file"); + let (proj, home, out) = (d.join("proj"), d.join("home"), d.join("out")); + std::fs::create_dir_all(proj.join("docs")).unwrap(); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(&out).unwrap(); + let pdf = proj.join("docs/Parts List.pdf"); + std::fs::write(&pdf, b"%PDF-1.4\nhello").unwrap(); + std::fs::write(proj.join(".env"), b"SECRET=1").unwrap(); + std::fs::write(out.join("out.pdf"), b"%PDF-1.4\n").unwrap(); + + std::fs::write(home.join("events.jsonl"), format!("{{\"$\":\"ProjectCreated\",\"id\":\"p1\",\"title\":\"proj\",\"root\":{},\"at\":1700000000}}\n", serde_json::Value::from(s(&proj)))).unwrap(); + let cfg = crate::hub::Cfg { home: home.clone(), version: "0.14.0".into(), commit: "c".into(), listen: "x".into(), os: "linux".into(), arch: "x64".into() }; + let hub = Hub::start(cfg, Arc::new(crate::presenter::Canned { reply: json!({}) })).await.unwrap(); + refresh(&hub).await; + + let split = |v: &[u8]| { + let i = v.windows(4).position(|w| w == b"\r\n\r\n").unwrap(); + (String::from_utf8_lossy(&v[..i]).into_owned(), v[i + 4..].to_vec()) + }; + let fetch = |target: String| { + let hub = hub.clone(); + async move { + let mut out_buf = Vec::new(); + let req = Req::new("GET", &target, Default::default()); + serve_file(&hub, &mut out_buf, Who::Native, &req).await.unwrap(); + out_buf + } + }; + + let enc = |v: &str| crate::md::refs::pct(v).replace("%2F", "/"); + let (h1, b1) = split(&fetch(format!("/file?path={}", enc(&s(&pdf)))).await); + assert!(h1.starts_with("HTTP/1.1 200 OK") && h1.contains("Content-Type: application/pdf"), "{h1}"); + assert_eq!(b1, b"%PDF-1.4\nhello"); + + let file_url = format!("file://{}", enc(&s(&pdf))); + let (h2, b2) = split(&fetch(format!("/file?path={}", crate::md::refs::pct(&file_url))).await); + assert!(h2.starts_with("HTTP/1.1 200 OK") && h2.contains("Content-Type: application/pdf"), "{h2}"); + assert_eq!(b2, b"%PDF-1.4\nhello"); + + let (h3, _) = split(&fetch(format!("/file?path={}", crate::md::refs::pct(&s(&proj.join(".env"))))).await); + assert!(h3.starts_with("HTTP/1.1 403"), "{h3}"); + + let (h4, _) = split(&fetch(format!("/file?path={}", crate::md::refs::pct(&s(&out.join("out.pdf"))))).await); + assert!(h4.starts_with("HTTP/1.1 403"), "{h4}"); +} diff --git a/scripts/mobile/ios-unit-tests.sh b/scripts/mobile/ios-unit-tests.sh index 9193b9f93b..c6c4a570d0 100755 --- a/scripts/mobile/ios-unit-tests.sh +++ b/scripts/mobile/ios-unit-tests.sh @@ -45,6 +45,7 @@ run reply-images ReplyImagesTests.swift "" ReplyImages.swift run reply-draft ReplyDraftTests.swift "" ReplyDraft.swift run viewer-rail ViewerRailTests.swift "" ViewerRail.swift run hub-restart HubRestartTests.swift "" HubRestart.swift +run link-grammar LinkGrammarTests.swift "" DataLinkGrammar.swift run file-fetch FileFetchTests.swift "" FileFetch.swift DataLinkGrammar.swift run plan-floorplanner PlanFloorplannerTests.swift "" PlanFloorplannerModel.swift sh "$ROOT/scripts/mobile/ios-outbox-test.sh" && echo "ok outbox"