Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 55 additions & 12 deletions web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <a download>.
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();
Expand Down Expand Up @@ -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";
Expand Down
2 changes: 1 addition & 1 deletion web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ <h2>Send</h2>
<p><input type="text" id="send-addr" size="40" placeholder="tc…"></p>
<p><input type="file" id="send-file">
<button id="send-btn" disabled>Send file</button></p>
<p><textarea id="send-text" rows="4" placeholder="…or type text to send"></textarea></p>
<p><textarea id="send-text" rows="4" dir="auto" placeholder="…or type text to send"></textarea></p>
<p><button id="send-text-btn" disabled>Send text</button></p>
<p id="send-progress"></p>
</section>
Expand Down
110 changes: 110 additions & 0 deletions web/wasm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Loading