From 2a838bc35eb68050c9050a85294923b47125df15 Mon Sep 17 00:00:00 2001 From: "Dr. Mohammed Lubbad" Date: Mon, 30 Nov 2026 18:56:10 +0300 Subject: [PATCH] web: fall back to Blob download without showSaveFilePicker and survive picker cancel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Clicking "Save incoming file…" in the browser app unconditionally called showSaveFilePicker, which caused two issues: 1. Safari (macOS/iOS) and Firefox do not implement showSaveFilePicker, so clicking "Save incoming file…" threw ReferenceError, closed conn, left both action buttons disabled, and lost the incoming transfer. Fall back to buffering the stream into a Blob and triggering an when showSaveFilePicker is absent. 2. Where showSaveFilePicker is supported, canceling the save dialog throws AbortError before any bytes have been read from conn (while the sender is still stalled on TCP backpressure), yet the catch handler closed conn and left the buttons disabled. Re-enable the buttons and keep conn open on AbortError so the user can retry or choose "Show as text". Also set dir="auto" on #send-text and .recv-text so right-to-left text renders with natural paragraph direction. Updates #4 Signed-off-by: Dr. Mohammed Lubbad --- web/app.js | 67 +++++++++++++++++++++++------ web/index.html | 2 +- web/wasm_test.go | 110 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 166 insertions(+), 13 deletions(-) diff --git a/web/app.js b/web/app.js index 41a1be205..229288686 100644 --- a/web/app.js +++ b/web/app.js @@ -167,30 +167,72 @@ function onConnection(conn) { const progress = document.createElement("span"); li.append(btn, " ", textBtn, " ", progress); $("incoming").append(li); - const chose = () => { - btn.disabled = true; - textBtn.disabled = true; + const setButtonsDisabled = (disabled) => { + btn.disabled = disabled; + textBtn.disabled = disabled; }; textBtn.onclick = () => { - chose(); + setButtonsDisabled(true); receiveText(conn, li, progress); }; btn.onclick = async () => { - chose(); + setButtonsDisabled(true); + if (typeof globalThis.showSaveFilePicker === "function") { + let handle; + try { + // Pick the destination before reading from conn: the pull-based + // conn.read means the sender stalls on TCP backpressure while + // the user chooses a file, so canceling the picker leaves the + // unread stream intact for another attempt. + handle = await globalThis.showSaveFilePicker({ suggestedName: "tailcat-download" }); + } catch (err) { + if (err && err.name === "AbortError") { + setButtonsDisabled(false); + return; + } + conn.close(); + progress.textContent = "failed: " + err.message; + window.tcTest.errors.push(String(err)); + return; + } + try { + const w = await handle.createWritable(); + let n = 0; + for (let chunk; (chunk = await conn.read()) !== null; ) { + await w.write(chunk); + n += chunk.length; + progress.textContent = `${n} bytes`; + } + await w.close(); + conn.close(); + progress.textContent = `done, ${n} bytes`; + } catch (err) { + conn.close(); + progress.textContent = "failed: " + err.message; + window.tcTest.errors.push(String(err)); + } + return; + } + // Safari and Firefox do not implement showSaveFilePicker; buffer + // the incoming stream into a Blob and trigger an . try { - // Stream to disk. The pull-based conn.read means the sender - // stalls on TCP backpressure while the user picks a file, and - // while the disk keeps up; nothing is buffered in memory. - const handle = await showSaveFilePicker({ suggestedName: "tailcat-download" }); - const w = await handle.createWritable(); + const chunks = []; let n = 0; for (let chunk; (chunk = await conn.read()) !== null; ) { - await w.write(chunk); + chunks.push(chunk); n += chunk.length; progress.textContent = `${n} bytes`; } - await w.close(); conn.close(); + const url = URL.createObjectURL(new Blob(chunks, { type: "application/octet-stream" })); + const a = document.createElement("a"); + a.href = url; + a.download = "tailcat-download"; + a.style.display = "none"; + document.body.append(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 60_000); progress.textContent = `done, ${n} bytes`; } catch (err) { conn.close(); @@ -221,6 +263,7 @@ async function receiveText(conn, li, progress) { const text = new TextDecoder().decode(all); const box = document.createElement("code"); box.className = "recv-text"; + box.dir = "auto"; box.textContent = text; const copyBtn = document.createElement("button"); copyBtn.textContent = "Copy"; diff --git a/web/index.html b/web/index.html index 1049a41b1..fa477f6a3 100644 --- a/web/index.html +++ b/web/index.html @@ -52,7 +52,7 @@

Send

-

+

diff --git a/web/wasm_test.go b/web/wasm_test.go index bbf7fdb04..45a508bd4 100644 --- a/web/wasm_test.go +++ b/web/wasm_test.go @@ -541,3 +541,113 @@ func TestBrowserReceivesTextUI(t *testing.T) { } checkPageErrors(t, runCtx) } + +// TestBrowserSaveFileCancelAndFallback verifies two browser UI paths +// on an incoming connection: canceling showSaveFilePicker leaves the +// unread stream open and re-enables the action buttons, and browsers +// without showSaveFilePicker (Safari, Firefox) fall back to saving a +// Blob download cleanly. +func TestBrowserSaveFileCancelAndFallback(t *testing.T) { + bin := preflight(t) + dm := integration.RunDERPAndSTUN(t, mkLogf(t, "derpstun"), "127.0.0.1") + srv := newWebServer(t, dm) + + browserCtx := launchChrome(t, bin) + runCtx, cancelRun := context.WithTimeout(browserCtx, 120*time.Second) + t.Cleanup(cancelRun) + + var gotAddr bool + var addr string + if err := chromedp.Run(runCtx, + chromedp.Navigate(srv.URL+"/?mode=listen"), + chromedp.Poll("window.tcTest && window.tcTest.listenAddr !== null", &gotAddr, + chromedp.WithPollingTimeout(90*time.Second)), + chromedp.Evaluate("window.tcTest.listenAddr", &addr), + ); err != nil { + t.Fatalf("chromedp run: %v", err) + } + if !gotAddr || !strings.HasPrefix(addr, "tc") { + t.Fatalf("browser listener never produced an address (gotAddr=%v addr=%q)", gotAddr, addr) + } + + cl := &tailcat.Client{ + Server: tailcat.Addr(addr), + Logf: mkLogf(t, "client"), + DERPMapURL: srv.URL + "/derpmap.json", + } + t.Cleanup(func() { cl.Close() }) + + ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) + defer cancel() + for { + pctx, pcancel := context.WithTimeout(ctx, 5*time.Second) + _, err := cl.Ping(pctx) + pcancel() + if err == nil { + break + } + if ctx.Err() != nil { + t.Fatalf("Ping never succeeded: %v", err) + } + } + + data := make([]byte, 128<<10) + rand.Read(data) + wantSum := sha256.Sum256(data) + + conn, err := cl.DialTCPPort(ctx, 1) + if err != nil { + t.Fatalf("DialTCPPort: %v", err) + } + writeDone := make(chan error, 1) + go func() { + if _, err := conn.Write(data); err != nil { + writeDone <- err + return + } + writeDone <- conn.(interface{ CloseWrite() error }).CloseWrite() + }() + + const saveBtn = `//button[text()="Save incoming file…"]` + var reenabled, blobDone bool + var blobHex string + if err := chromedp.Run(runCtx, + chromedp.WaitVisible(saveBtn), + // 1. Simulate canceling the save picker before any read occurs. + chromedp.Evaluate(`window.showSaveFilePicker = async () => { throw new DOMException("User canceled", "AbortError"); }; true`, nil), + chromedp.Click(saveBtn), + chromedp.Poll(`document.evaluate('`+saveBtn+`', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.disabled === false`, &reenabled, + chromedp.WithPollingTimeout(10*time.Second)), + // 2. Simulate Safari/Firefox (no showSaveFilePicker) and capture the Blob passed to URL.createObjectURL. + chromedp.Evaluate(`(() => { + delete window.showSaveFilePicker; + window.__savedBlobSha256 = null; + URL.createObjectURL = (blob) => { + blob.arrayBuffer().then(async (buf) => { + const digest = await crypto.subtle.digest("SHA-256", buf); + window.__savedBlobSha256 = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join(""); + }); + return "blob:test-noop"; + }; + HTMLAnchorElement.prototype.click = function() {}; + return true; + })()`, nil), + chromedp.Click(saveBtn), + chromedp.Poll(`window.__savedBlobSha256 !== null`, &blobDone, + chromedp.WithPollingTimeout(60*time.Second)), + chromedp.Evaluate(`window.__savedBlobSha256`, &blobHex), + ); err != nil { + t.Fatalf("chromedp run: %v", err) + } + + if err := <-writeDone; err != nil { + t.Fatalf("sender write/CloseWrite: %v", err) + } + if _, err := io.Copy(io.Discard, conn); err != nil { + t.Fatalf("reading to EOF: %v", err) + } + if want := hex.EncodeToString(wantSum[:]); blobHex != want { + t.Errorf("fallback blob sha256 = %s; want %s", blobHex, want) + } + checkPageErrors(t, runCtx) +}