WIP VI improve UX [snapshot task 2]
This commit is contained in:
1 parent
a73b3075b6
commit
8665d04f2c
6 files changed
+95
-66
No files matched your search
@@ -33,6 +33,10 @@
|
||||
- Upgrade connection/session framing to v3 with per-file identifiers. Both peers
|
||||
must update; v2 codes are rejected before connection setup.
|
||||
- New device identity private keys are non-extractable.
|
||||
- Replace the receive-storage choice with a single **Accept file** button that
|
||||
treats every file size the same: stream to Downloads where supported, else
|
||||
use the native save picker, else buffer up to 64 MiB in memory and hand it
|
||||
to Downloads automatically on completion.
|
||||
|
||||
### Removed
|
||||
|
||||
|
||||
@@ -53,14 +53,16 @@ remain available. Up to 100 connection slots are supported.
|
||||
confirm before the app sends the filename, size, MIME metadata, or contents.
|
||||
On later connections, a remembered device’s fresh proof can replace manual
|
||||
comparison (see Remembered devices below).
|
||||
4. The receiver sees the filename and size and explicitly accepts the file.
|
||||
On the hosted app (HTTPS or localhost), **Receive as download** shows the incoming file size and streams into the browser's download manager using a same-origin service worker.
|
||||
It requires transferable streams and service-worker support; Chromium and
|
||||
Brave have been tested with 120 MiB files. Allow the download and keep the
|
||||
receiving tab open. File contents are not uploaded to the web host.
|
||||
**Choose destination & receive to disk** remains available with a supported
|
||||
native file picker. **Receive in memory** retains its 64 MiB cap. Even capped
|
||||
memory downloads may be too large on a memory-constrained device.
|
||||
4. The receiver sees the filename and size and clicks **Accept file**. Files of
|
||||
every size stream into the browser's download manager using a same-origin
|
||||
service worker (HTTPS or localhost). This requires transferable streams and
|
||||
service-worker support; Chromium and Brave have been tested with 120 MiB
|
||||
files. Allow the download and keep the receiving tab open. File contents are
|
||||
not uploaded to the web host. Without streaming support, the browser's native
|
||||
save picker asks where to write the file. Without either, files up to 64 MiB
|
||||
are buffered in memory and handed to Downloads on completion (**Save again**
|
||||
repeats this); larger files cannot be received. Even capped memory transfers
|
||||
may be too large on a memory-constrained device.
|
||||
5. The sender waits for a receipt acknowledgment. For disk transfers, the receiver
|
||||
sends this only after its writable stream closes successfully; for streaming
|
||||
downloads, after handing all bytes to the browser; for memory transfers,
|
||||
@@ -80,10 +82,9 @@ rejects an incoming offer and lets the sender's queue continue.
|
||||
|
||||
**Disconnect** ends the entire session, drops waiting files and aborts unfinished
|
||||
disk writes. To cancel an already active transfer, disconnect; cancelling only an
|
||||
active file is not supported. Completed memory downloads remain available after
|
||||
disconnect. Save a previous memory download before accepting another file;
|
||||
acceptance replaces it. **Reset** discards the memory download and returns to
|
||||
setup. Before connecting, Send/Receive chooses who starts the connection. Once
|
||||
active file is not supported. A completed memory transfer stays available via **Save again** after
|
||||
disconnect, until the next acceptance replaces it. **Reset** discards it and
|
||||
returns to setup. Before connecting, Send/Receive chooses who starts the connection. Once
|
||||
verified, these controls navigate to the sending and receiving sections without
|
||||
reconnecting. The initial receiver can click **Send**, then **Add files to send**.
|
||||
|
||||
|
||||
+41
-32
@@ -106,7 +106,10 @@ async function page(url = origin) {
|
||||
// Background tabs otherwise skip focus/blur events, which the name editor relies on.
|
||||
await call('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId);
|
||||
await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${installBrowserContext.toString()})()` }, sessionId);
|
||||
if (streaming) await call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.showSaveFilePicker = undefined;' }, sessionId);
|
||||
// The native picker would block headless runs; simulateSlowDisk installs a test double where needed.
|
||||
await call('Page.addScriptToEvaluateOnNewDocument', { source: 'window.showSaveFilePicker = undefined;' }, sessionId);
|
||||
// Without streaming downloads the app falls back to memory, whose bytes the default checks read in-page.
|
||||
if (!streaming) await call('Page.addScriptToEvaluateOnNewDocument', { source: "Object.defineProperty(navigator, 'serviceWorker', { value: undefined });" }, sessionId);
|
||||
if (turn) await call('Page.addScriptToEvaluateOnNewDocument', { source: `(${forceRelay.toString()})(${JSON.stringify(transport)})` }, sessionId);
|
||||
await call('Page.navigate', { url }, sessionId);
|
||||
for (let n = 0; n < 100; n++) {
|
||||
@@ -180,7 +183,26 @@ async function connect(sender: string, receiver: string, size: number, changedId
|
||||
}
|
||||
}
|
||||
}
|
||||
async function verifySavedFile(path: string, size: number) {
|
||||
const deadline = Date.now() + 30000;
|
||||
while (true) {
|
||||
try { if ((await stat(path)).size === size) break; } catch {}
|
||||
if (Date.now() > deadline) throw new Error('Browser did not finish saving the download.');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
let bytes = 0;
|
||||
for await (const chunk of createReadStream(path)) {
|
||||
assert.ok((chunk as Buffer).every(byte => byte === 123), 'Downloaded bytes must match');
|
||||
bytes += (chunk as Buffer).length;
|
||||
}
|
||||
assert.equal(bytes, size);
|
||||
await rm(path);
|
||||
}
|
||||
try {
|
||||
// Received files land in the throwaway profile instead of the user's Downloads.
|
||||
const downloads = join(profile, 'downloads');
|
||||
await mkdir(downloads);
|
||||
await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads });
|
||||
if (connections) {
|
||||
const sender = await page(), receiver = await page(origin.replace('127.0.0.1', 'localhost'));
|
||||
const selectConnection = (session: string, name: string) => evaluate(session, (name: string) => {
|
||||
@@ -219,7 +241,7 @@ try {
|
||||
await click(sender, 'Add connection');
|
||||
await wait(sender, () => document.querySelector('.title-line h1')?.textContent === 'Con 2');
|
||||
assert.equal(await evaluate(sender, () => !!document.querySelector('.fingerprint')), false);
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => document.querySelector('.connection-link .connection-preview')?.textContent === 'browser-test.bin');
|
||||
assert.equal(await evaluate(sender, () => document.querySelectorAll('.activity-item').length), 0, 'Hidden session activity must stay in its own slot');
|
||||
await selectConnection(sender, 'Work laptop');
|
||||
@@ -227,7 +249,7 @@ try {
|
||||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(item => item.textContent)), fingerprints);
|
||||
await evaluate(sender, () => window.__hellcon.chooseFile(1234, 'after-switch.bin'));
|
||||
await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('after-switch.bin'));
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => document.querySelectorAll('.activity-item').length === 2);
|
||||
const received = await evaluate(receiver, async () => {
|
||||
const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer());
|
||||
@@ -322,9 +344,6 @@ try {
|
||||
console.log('PASS: removal can be cancelled, persists across reload, closes cached sessions in other tabs, and replaces the last slot with a fresh Con 1.');
|
||||
assert.deepEqual(browserErrors, []);
|
||||
} else if (streaming) {
|
||||
const downloads = join(profile, 'downloads');
|
||||
await mkdir(downloads);
|
||||
await call('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads });
|
||||
const sender = await page(), receiver = await page();
|
||||
await click(receiver, 'Receive');
|
||||
for (const size of [0, 1024 * 1024 + 7, 120 * 1024 * 1024]) {
|
||||
@@ -334,23 +353,10 @@ try {
|
||||
await wait(receiver, () => !!document.querySelector('.incoming'));
|
||||
}
|
||||
assert.equal(await evaluate(receiver, () => typeof window.showSaveFilePicker), 'undefined');
|
||||
await click(receiver, `Receive as download (${size === 0 ? '0 B' : (size / 1024 ** 2).toFixed(1) + ' MiB'})`);
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
assert.match(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), /Check Downloads/);
|
||||
const destination = join(downloads, 'browser-test.bin');
|
||||
const deadline = Date.now() + 30000;
|
||||
while (true) {
|
||||
try { if ((await stat(destination)).size === size) break; } catch {}
|
||||
if (Date.now() > deadline) throw new Error('Browser did not finish saving the download.');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
let bytes = 0;
|
||||
for await (const chunk of createReadStream(destination)) {
|
||||
assert.ok((chunk as Buffer).every(byte => byte === 123), 'Downloaded bytes must match');
|
||||
bytes += (chunk as Buffer).length;
|
||||
}
|
||||
assert.equal(bytes, size);
|
||||
await rm(destination);
|
||||
await verifySavedFile(join(downloads, 'browser-test.bin'), size);
|
||||
console.log(`PASS: hosted app streams ${size} bytes to a real browser download without the native save picker; exact file bytes verified.`);
|
||||
}
|
||||
assert.deepEqual(browserErrors, []);
|
||||
@@ -367,7 +373,7 @@ try {
|
||||
await connect(sender, receiver, 2 * 1024 * 1024 + 7);
|
||||
await checkAccessibility(sender, 'Send during transfer');
|
||||
await checkAccessibility(receiver, 'Receive before accepting a file');
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
await checkAccessibility(sender, 'Send after transfer');
|
||||
await checkAccessibility(receiver, 'Receive after transfer');
|
||||
@@ -378,6 +384,8 @@ try {
|
||||
return { length: bytes.length, valid: bytes.every(b => b === 123) };
|
||||
});
|
||||
assert.deepEqual(data, { length: 2 * 1024 * 1024 + 7, valid: true });
|
||||
assert.match(await evaluate(receiver, () => window.__hellcon.element('[role=status]').textContent), /Check Downloads/);
|
||||
await verifySavedFile(join(downloads, 'browser-test.bin'), 2 * 1024 * 1024 + 7);
|
||||
await wait(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value.includes('pairs='));
|
||||
const diagnostics = await evaluate(sender, () => window.__hellcon.element<HTMLTextAreaElement>('#connection-diagnostics').value);
|
||||
assert.match(diagnostics, /local code: host=\d+/);
|
||||
@@ -385,7 +393,7 @@ try {
|
||||
assert.match(diagnostics, /requestsSent=/);
|
||||
assert.match(diagnostics, /transfer done/);
|
||||
assert.doesNotMatch(diagnostics, /browser-test\.bin|a=candidate:|a=ice-pwd:|a=fingerprint:|\.local\b/);
|
||||
console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt.');
|
||||
console.log('PASS: real two-page WebRTC flow; full fingerprints; no metadata before both confirmations; exact file and receipt; memory fallback saves to Downloads automatically.');
|
||||
console.log('PASS: invalid offers can be replaced; invalid answers can be corrected without losing the live offer.');
|
||||
const originalFingerprints = await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent));
|
||||
for (const size of [0, 4097]) {
|
||||
@@ -395,7 +403,7 @@ try {
|
||||
assert.equal(await evaluate(receiver, () => window.__hellcon.element<HTMLAnchorElement>('a.download').href), previousDownload);
|
||||
assert.equal(await evaluate(sender, () => window.__hellcon.element('[role=status]').textContent), 'Waiting for the receiver to accept the file…');
|
||||
assert.deepEqual(await evaluate(sender, () => [...document.querySelectorAll('.fp-row code')].map(e => e.textContent)), originalFingerprints);
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
const next = await evaluate(receiver, async () => {
|
||||
const link = window.__hellcon.element<HTMLAnchorElement>('a.download');
|
||||
@@ -424,8 +432,8 @@ try {
|
||||
await wait(receiver, () => !!document.querySelector('.incoming'));
|
||||
await click(receiver, 'Decline file');
|
||||
await wait(receiver, () => document.querySelector('.incoming')?.textContent?.includes('queued.bin'));
|
||||
await click(sender, 'Receive in memory (up to 64 MiB)');
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(sender, 'Accept file');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => document.querySelector<HTMLAnchorElement>('a.download')?.download === 'return.bin');
|
||||
await wait(receiver, () => document.querySelector<HTMLAnchorElement>('a.download')?.download === 'queued.bin');
|
||||
for (const [session, size] of [[sender, 8193], [receiver, 1024]] as const) {
|
||||
@@ -446,7 +454,7 @@ try {
|
||||
console.log('PASS: Reset restores the ready state on both sides.');
|
||||
await evaluate(receiver, simulateSlowDisk);
|
||||
await connect(sender, receiver, 2 * 1024 * 1024);
|
||||
await click(receiver, 'Choose destination & receive to disk');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(receiver, () => !!window.__hellcon.releaseWrite);
|
||||
await evaluate(sender, () => window.__hellcon.chooseFile(1024, 'pending-at-disconnect.bin'));
|
||||
assert.equal(await evaluate(sender, () => !!document.querySelector('ul[aria-label="Files waiting to send"]')), true);
|
||||
@@ -459,8 +467,9 @@ try {
|
||||
console.log('PASS: privacy-safe candidate/check diagnostics remain available after completion and failure.');
|
||||
console.log('PASS: Disconnect closes the connection and aborts the receiver’s pending disk write.');
|
||||
await click(sender, 'Reset'); await click(receiver, 'Reset');
|
||||
await evaluate(receiver, () => { window.showSaveFilePicker = undefined; });
|
||||
await connect(sender, receiver, 2048);
|
||||
await click(receiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(receiver, 'Accept file');
|
||||
await wait(sender, () => window.__hellcon.element('[role=status]').textContent?.includes('confirmed the complete file'));
|
||||
console.log('PASS: fresh code exchange after a failed transfer succeeds without reloading either page.');
|
||||
if (!turn) {
|
||||
@@ -490,7 +499,7 @@ try {
|
||||
await wait(session, () => !!document.querySelector('.device-settings code'));
|
||||
}
|
||||
await checkAccessibility(identitySender, 'remembered identity');
|
||||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(identityReceiver, 'Accept file');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||||
await click(identitySender, 'Disconnect');
|
||||
await wait(identityReceiver, () => [...document.querySelectorAll('button')].some(button => button.textContent === 'Reset'));
|
||||
@@ -515,7 +524,7 @@ try {
|
||||
await input(identitySender, '#answer-input', answer); await click(identitySender, 'Connect');
|
||||
await wait(identityReceiver, () => !!document.querySelector('.incoming'));
|
||||
for (const session of [identitySender, identityReceiver]) assert.ok(await evaluate(session, () => document.body.textContent?.includes('Paired device authenticated')));
|
||||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(identityReceiver, 'Accept file');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||||
const rememberedBytes = await evaluate(identityReceiver, async () => { const bytes = new Uint8Array(await (await fetch(window.__hellcon.element<HTMLAnchorElement>('a.download').href)).arrayBuffer()); return { length: bytes.length, valid: bytes.every(byte => byte === 123) }; });
|
||||
assert.deepEqual(rememberedBytes, { length: 4096, valid: true });
|
||||
@@ -542,7 +551,7 @@ try {
|
||||
await click(forgottenSide, 'Both fingerprints match — confirm');
|
||||
await wait(identityReceiver, () => !!document.querySelector('.incoming'));
|
||||
await wait(forgottenSide, () => !!document.querySelector('.device-settings code'));
|
||||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(identityReceiver, 'Accept file');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||||
await click(identitySender, 'Disconnect');
|
||||
await wait(identityReceiver, () => !document.querySelector('.incoming'));
|
||||
@@ -569,7 +578,7 @@ try {
|
||||
await click(identityReceiver, 'Create device identity');
|
||||
await wait(identityReceiver, () => !!document.querySelector('.device-settings code'));
|
||||
await connect(identitySender, identityReceiver, 512, true);
|
||||
await click(identityReceiver, 'Receive in memory (up to 64 MiB)');
|
||||
await click(identityReceiver, 'Accept file');
|
||||
await wait(identitySender, () => document.body.textContent?.includes('The receiver confirmed the complete file.'));
|
||||
assert.ok(await evaluate(identitySender, () => document.body.textContent?.includes('This device was not remembered.')));
|
||||
assert.equal(await pairedKey(identitySender), senderPaired, 'Changed identity must not replace the paired device automatically');
|
||||
|
||||
@@ -4,7 +4,7 @@ import { crossBrowserDriver } from './cross-browser-driver.ts';
|
||||
import { isRecord } from '../src/lib/validation.ts';
|
||||
import { createServer } from 'node:http';
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { readFile, mkdtemp, rm } from 'node:fs/promises';
|
||||
import { readFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { dirname, extname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { tmpdir } from 'node:os';
|
||||
@@ -52,6 +52,10 @@ let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try{
|
||||
for(const name of ['brave','firefox']){
|
||||
const profile=await mkdtemp(join(tmpdir(),'hellcon-'+name+'-'));profiles.push(profile);
|
||||
// Received files are saved automatically; keep them in the throwaway profile instead of the user's Downloads.
|
||||
const downloads=join(profile,'downloads');await mkdir(downloads);
|
||||
if(name==='brave'){await mkdir(join(profile,'Default'));await writeFile(join(profile,'Default','Preferences'),JSON.stringify({download:{default_directory:downloads,prompt_for_download:false}}));}
|
||||
else await writeFile(join(profile,'user.js'),['user_pref("browser.download.folderList", 2);','user_pref("browser.download.dir", '+JSON.stringify(downloads)+');','user_pref("browser.download.useDownloadDir", true);','user_pref("browser.download.always_ask_before_handling_new_types", false);'].join('\n'));
|
||||
const role=(name==='brave')!==reversed?'sender':'receiver';
|
||||
const args=name==='brave'?['--headless','--no-sandbox','--disable-gpu','--no-first-run','--no-default-browser-check','--user-data-dir='+profile,origin+'/?role='+role]:['--headless','--no-remote','--profile',profile,origin+'/?role='+role];
|
||||
const child=spawn(process.env[name==='brave'?'BRAVE_PATH':'FIREFOX_PATH']||'/usr/bin/'+name,args,{stdio:['ignore','ignore','pipe']});children.push(child);
|
||||
|
||||
@@ -13,6 +13,8 @@ export async function crossBrowserDriver(provider: string) {
|
||||
const role = new URL(location.href).searchParams.get('role');
|
||||
if (role !== 'sender' && role !== 'receiver') throw new Error('Invalid role');
|
||||
const { click, input, wait, element } = window.__hellcon;
|
||||
// Use the memory fallback so the received bytes can be checked in-page.
|
||||
Object.defineProperty(navigator, 'serviceWorker', { value: undefined });
|
||||
const pause = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
|
||||
const post = async (key: string, value: unknown) => fetch('/.test/' + key, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(value)});
|
||||
const get = async <K extends keyof Exchange>(key: K): Promise<Exchange[K] | null> => (await fetch('/.test/' + key)).json();
|
||||
@@ -43,7 +45,7 @@ try {
|
||||
if(fps[0]!==other[1]||fps[1]!==other[0])throw new Error('Fingerprints do not match');
|
||||
click('Both fingerprints match — confirm');
|
||||
if(role==='receiver'){
|
||||
await stage('waiting for metadata');await wait(()=>document.querySelector('.incoming'));click('Receive in memory (up to 64 MiB)');
|
||||
await stage('waiting for metadata');await wait(()=>document.querySelector('.incoming'));click('Accept file');
|
||||
await stage('receiving');await wait(()=>document.querySelector('a.download'));
|
||||
await wait(()=>get('senderResult'));
|
||||
await pause(250);
|
||||
|
||||
@@ -73,9 +73,15 @@ const iceEndpoint = import.meta.env.VITE_ICE_ENDPOINT || '';
|
||||
const defaultStun = import.meta.env.VITE_STUN_URL || '';
|
||||
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
|
||||
const managedCredentials = ref<IceOptions | null>(null);
|
||||
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
|
||||
const canStreamDownload = supportsStreamingDownload();
|
||||
const streamedDownload = ref(false);
|
||||
// Every size is received the same way: streamed to Downloads where supported, otherwise
|
||||
// through the native save picker, otherwise buffered in memory (capped) and saved on completion.
|
||||
const receiveMethod = computed(() => {
|
||||
if (!incoming.value) return null;
|
||||
if (supportsStreamingDownload()) return 'download';
|
||||
if (typeof window.showSaveFilePicker === 'function') return 'disk';
|
||||
return incoming.value.size <= MEMORY_LIMIT ? 'memory' : null;
|
||||
});
|
||||
const savedToDisk = ref(false);
|
||||
let active: Session | null = null;
|
||||
let copyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const busy = computed(() => !['idle', 'closed', 'done', 'session-ready'].includes(step.value));
|
||||
@@ -87,10 +93,10 @@ const status = computed(() => ({
|
||||
'answer-ready': 'Send your answer back, then compare both full fingerprints.',
|
||||
verification: verified.value ? 'Waiting for the connection and your peer’s verification…' : 'Compare both full fingerprints before confirming.',
|
||||
'waiting-accept': 'Waiting for the receiver to accept the file…',
|
||||
'choose-storage': 'Choose how to receive this file.',
|
||||
'choose-storage': 'Accept or decline this file.',
|
||||
sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…',
|
||||
'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…',
|
||||
done: lastDirection.value === 'send' ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : streamedDownload.value ? 'File handed to your browser. Check Downloads for the final save result.' : 'File saved to disk.'),
|
||||
done: lastDirection.value === 'send' ? 'The receiver confirmed the complete file.' : (savedToDisk.value ? 'File saved to disk.' : 'File handed to your browser. Check Downloads for the final save result.'),
|
||||
closed: props.sending
|
||||
? 'Create a new code, then ask the receiver for a new answer. Previous codes cannot reopen a closed connection.'
|
||||
: 'Ask the sender for a new code and paste it above. Previous codes cannot reopen a closed connection.',
|
||||
@@ -100,6 +106,11 @@ function revokeDownload() {
|
||||
if (downloadUrl.value) URL.revokeObjectURL(downloadUrl.value);
|
||||
downloadUrl.value = ''; downloadName.value = '';
|
||||
}
|
||||
function saveDownload() {
|
||||
const link = document.createElement('a');
|
||||
link.href = downloadUrl.value; link.download = downloadName.value;
|
||||
document.body.append(link); link.click(); link.remove();
|
||||
}
|
||||
function dispose() {
|
||||
const old = active;
|
||||
if (old) {
|
||||
@@ -128,7 +139,7 @@ function reset(keepNetwork = false) {
|
||||
identityStatus.value = ''; pairing.value = ''; rememberPeer.value = false;
|
||||
fps.value = incoming.value = null;
|
||||
verified.value = copied.value = choosing.value = false;
|
||||
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; streamedDownload.value = false;
|
||||
progress.value = 0; receiveProgress.value = 0; step.value = 'idle'; savedToDisk.value = false;
|
||||
sendState.value = receiveState.value = null; outgoing.value = null;
|
||||
}
|
||||
function fail(session: Session, err: unknown) {
|
||||
@@ -194,7 +205,7 @@ function attach(session: Session, channel: RTCDataChannel) {
|
||||
session.diagnostics.record(`transfer ${direction} ${state}`);
|
||||
if (state === 'done') session.diagnostics.record('transfer done');
|
||||
if (direction === 'send') { sendState.value = state; outgoing.value = meta; if (state === 'waiting-accept') progress.value = 0; }
|
||||
else { receiveState.value = state; if (state === 'choose-storage' && meta.name) { incoming.value = meta; receiveProgress.value = 0; streamedDownload.value = false; } }
|
||||
else { receiveState.value = state; if (state === 'choose-storage' && meta.name) { incoming.value = meta; receiveProgress.value = 0; savedToDisk.value = false; } }
|
||||
},
|
||||
onProgress: (direction, bytes, size) => {
|
||||
if (active !== session) return;
|
||||
@@ -206,7 +217,7 @@ function attach(session: Session, channel: RTCDataChannel) {
|
||||
if (direction === 'send') progress.value = 100; else receiveProgress.value = 100;
|
||||
remember(direction, meta, 'complete');
|
||||
void session.diagnostics.capture();
|
||||
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; }
|
||||
if (blob) { revokeDownload(); downloadUrl.value = URL.createObjectURL(blob); downloadName.value = meta.name; saveDownload(); }
|
||||
},
|
||||
onDecline: (direction, meta) => {
|
||||
if (active !== session) return;
|
||||
@@ -357,9 +368,9 @@ function verify() {
|
||||
session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
|
||||
session.transfer?.verify();
|
||||
}
|
||||
async function acceptFile(destination: 'disk' | 'memory' | 'download') {
|
||||
const session = active;
|
||||
if (!session?.transfer || !incoming.value || choosing.value || receiveState.value !== 'choose-storage') return;
|
||||
async function acceptFile() {
|
||||
const session = active, destination = receiveMethod.value;
|
||||
if (!session?.transfer || !incoming.value || !destination || choosing.value || receiveState.value !== 'choose-storage') return;
|
||||
choosing.value = true; error.value = '';
|
||||
let writable: FileDestination | undefined;
|
||||
try {
|
||||
@@ -374,7 +385,7 @@ async function acceptFile(destination: 'disk' | 'memory' | 'download') {
|
||||
if (active !== session) { await writable.abort(); return; }
|
||||
}
|
||||
revokeDownload();
|
||||
streamedDownload.value = destination === 'download';
|
||||
savedToDisk.value = destination === 'disk';
|
||||
session.diagnostics.record(`storage ${destination}`);
|
||||
session.transfer.accept(writable);
|
||||
} catch (err) {
|
||||
@@ -392,7 +403,7 @@ async function copy() {
|
||||
} catch { if (active === session) error.value = 'Clipboard unavailable. Select and copy the code manually.'; }
|
||||
}
|
||||
function stateLabel(state: TransferState | null) {
|
||||
return state ? ({ verification: 'Connecting', 'waiting-accept': 'Waiting for acceptance', 'choose-storage': 'Choose where to save', sending: 'Sending', receiving: 'Receiving', saving: 'Saving', 'awaiting-receipt': 'Waiting for receipt', done: 'Complete', closed: 'Cancelled' })[state] : 'Declined';
|
||||
return state ? ({ verification: 'Connecting', 'waiting-accept': 'Waiting for acceptance', 'choose-storage': 'Awaiting acceptance', sending: 'Sending', receiving: 'Receiving', saving: 'Saving', 'awaiting-receipt': 'Waiting for receipt', done: 'Complete', closed: 'Cancelled' })[state] : 'Declined';
|
||||
}
|
||||
function formatBytes(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
@@ -457,16 +468,14 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<button :disabled="choosing" @click="declineFile">Decline file</button>
|
||||
<p>{{ incoming.name }} — {{ formatBytes(incoming.size) }}</p>
|
||||
<p class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p>
|
||||
<button v-if="canStreamDownload" class="primary" :disabled="choosing" @click="acceptFile('download')">Receive as download ({{ formatBytes(incoming.size) }})</button>
|
||||
<p v-if="canStreamDownload" class="status">Allow the browser download and keep this page open until the transfer finishes. Check Downloads for the final save result.</p>
|
||||
<button v-if="canSaveToDisk" class="primary" :disabled="choosing" @click="acceptFile('disk')">Choose destination & receive to disk</button>
|
||||
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile('memory')">Receive in memory (up to 64 MiB)</button>
|
||||
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk && !canStreamDownload" class="error">This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.</p>
|
||||
<button v-if="receiveMethod" class="primary" :disabled="choosing" @click="acceptFile">Accept file</button>
|
||||
<p v-if="receiveMethod === 'disk'" class="status">Your browser asks where to save this file. Keep this page open until the transfer finishes.</p>
|
||||
<p v-else-if="receiveMethod" class="status">Your browser downloads this file. Allow the download and keep this page open until the transfer finishes.</p>
|
||||
<p v-else class="error">This browser cannot receive files over 64 MiB. Use a browser with streaming-download or file-system saving support, or send a smaller file.</p>
|
||||
</div>
|
||||
<p v-if="incoming && receiveState !== 'choose-storage'" class="status">Receiving: {{ incoming.name }} — {{ stateLabel(receiveState) }} ({{ receiveProgress }}%)</p>
|
||||
<div v-if="incoming" class="progress" role="progressbar" :aria-valuenow="receiveProgress" aria-valuemin="0" aria-valuemax="100" aria-label="Receiving progress"><div :style="{ width: receiveProgress + '%' }"></div></div>
|
||||
<div v-if="downloadUrl" class="file-chip"><span>{{ downloadName }}</span><a class="download" :href="downloadUrl" :download="downloadName">Save file</a></div>
|
||||
<p v-if="downloadUrl && receiveState === 'choose-storage'" class="status">Save the previous file before accepting this one. Accepting replaces its memory download.</p>
|
||||
<div v-if="downloadUrl" class="file-chip"><span>{{ downloadName }}</span><a class="download" :href="downloadUrl" :download="downloadName">Save again</a></div>
|
||||
</section>
|
||||
<p class="status" role="status">{{ status }}</p>
|
||||
<p v-if="error" class="error" role="alert">{{ error }}</p>
|
||||
|
||||
Reference in new issue
Block a user