@pi-chamber/web 1.0.7 → 1.0.8-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/AgentsSurface-BmHImX8m.js +1 -0
- package/dist/assets/ChoicesArtifact-C71fGOm2.js +1 -0
- package/dist/assets/DiagramView-BZQxoiZu.js +1 -0
- package/dist/assets/{DiffView-BxW6BuOC.js → DiffView-C70pbgk-.js} +6 -6
- package/dist/assets/FileSaveConflictDialog-Cu8c3gBV.js +3 -0
- package/dist/assets/FilesView-nFJYEdRw.js +6 -0
- package/dist/assets/GitHubDetailScaffold-Jvv_tgbl.js +11 -0
- package/dist/assets/GitHubLinkPicker-BXD2ODRi.js +1 -0
- package/dist/assets/GitHubListPrimitives-BWI706F0.js +1 -0
- package/dist/assets/{GitView-DD33ngnM.js → GitView-MIDG5RYW.js} +5 -5
- package/dist/assets/{IssuesSurface-BAY_eyX5.js → IssuesSurface-uNlozeu0.js} +2 -2
- package/dist/assets/{JsonTreeView-DpXbUrAl.js → JsonTreeView-CSLsTriz.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-Cn63lAmn.js → MarkdownRendererImpl-Cs-7BfWi.js} +3 -3
- package/dist/assets/PatchDiff-axbsnbTJ.js +1 -0
- package/dist/assets/PierreDiffViewer-lwn6w_5w.js +147 -0
- package/dist/assets/PullRequestsSurface-o_AXDjbO.js +2 -0
- package/dist/assets/{SessionSwitcherContent-CscYekC1.js → SessionSwitcherContent-C4CMlcbv.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-DCBVuCoo.js +2 -0
- package/dist/assets/SessionUnreadDot-DyeIrsro.js +1 -0
- package/dist/assets/SettingsView-BHBpt2Um.js +7 -0
- package/dist/assets/{SettingsWindow-gxjULdm1.js → SettingsWindow-Cb4st5y5.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
- package/dist/assets/SubagentsArtifact-BzeMEoFP.js +1 -0
- package/dist/assets/ToolOutputDialog-BP2mOWdV.js +8 -0
- package/dist/assets/ToolPartDiffPreview-D49XBR9b.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-BrbPymTL.js → VirtualizedFileDiff-CLgDONEQ.js} +4 -4
- package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
- package/dist/assets/VisualFrame-CJrAvWSo.js +22 -0
- package/dist/assets/VisualsArtifact-DqLGgU-Q.js +1 -0
- package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-BeyKtQGB.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-G4csGiKs.js → computeVirtualFileMetrics-DmO6H8u6.js} +2 -2
- package/dist/assets/contextFileOpenGuard-DOK251YW.js +1 -0
- package/dist/assets/{fileTreeStatus-Bskhj4qT.js → fileTreeStatus-CnzR7kxA.js} +2 -2
- package/dist/assets/gitStatusPredicates-4kPg2t6j.js +1 -0
- package/dist/assets/githubLink-QvaLfNNT.js +10 -0
- package/dist/assets/{index-I2QYqABE.js → index-B2v0_mez.js} +8 -8
- package/dist/assets/index-D3F4JrPN.css +1 -0
- package/dist/assets/{index-ComwtfT4.js → index-DMX9wT1Z.js} +1 -1
- package/dist/assets/{main-DoiadX0a.js → main-BW9J3Y72.js} +2 -2
- package/dist/assets/main-BirYxac2.js +137 -0
- package/dist/assets/{markdownCore-DczkEluO.js → markdownCore-CxmcPur8.js} +2 -2
- package/dist/assets/miniChat-BRB11eEs.js +2 -0
- package/dist/assets/{mobile-BucKVm1P.js → mobile-DJZYYCuB.js} +2 -2
- package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-B6QpoPRn.js} +1 -1
- package/dist/assets/pi-session-focus-preference-PWoh3LNA.js +9 -0
- package/dist/assets/{renderDiffWithHighlighter-PL82AR81.js → renderDiffWithHighlighter-C48T6YFJ.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-N-BQdJl0.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-CYgfbA4F.js → renderFileWithHighlighter-8Kt2MyTN.js} +1 -1
- package/dist/assets/{renderMobileApp-Bp74b_Lo.js → renderMobileApp-B7cT7m5b.js} +3 -3
- package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +62 -0
- package/dist/assets/runtimeSurface-kIEoYsPP.js +1 -0
- package/dist/assets/selection-BTEdLRVK.js +1 -0
- package/dist/assets/useAppFontEffects-EcTZ_I_I.js +225 -0
- package/dist/assets/useGitHubRemoteSearch-DIBHNu8r.js +1 -0
- package/dist/assets/useSwitcherItems-DfLbfX37.js +1 -0
- package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
- package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
- package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
- package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
- package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
- package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
- package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
- package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
- package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
- package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
- package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
- package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
- package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
- package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
- package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
- package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
- package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
- package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
- package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
- package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
- package/dist/assets/{web-components-CGDpzixf.js → web-components-C_DsTJis.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -1
- package/plugins/registry.json +7 -0
- package/plugins/subagents/LICENSE +25 -0
- package/plugins/subagents/agents/planner.md +36 -0
- package/plugins/subagents/agents/reviewer.md +34 -0
- package/plugins/subagents/agents/scout.md +49 -0
- package/plugins/subagents/agents/worker.md +23 -0
- package/plugins/subagents/extension.js +631 -0
- package/plugins/subagents/extension.test.js +295 -0
- package/plugins/subagents/package.json +41 -0
- package/plugins/visuals/choices.js +168 -0
- package/plugins/visuals/extension.js +87 -0
- package/plugins/visuals/files.js +74 -0
- package/plugins/visuals/package.json +32 -0
- package/server/index.js +20 -0
- package/server/lib/github/DOCUMENTATION.md +4 -2
- package/server/lib/github/gh-cli.js +35 -9
- package/server/lib/github/gh-cli.test.js +122 -0
- package/server/lib/notifications/pi-notification-watcher.js +3 -0
- package/server/lib/notifications/pi-notification-watcher.test.js +10 -0
- package/server/lib/open-url/DOCUMENTATION.md +1 -1
- package/server/lib/pi/extension-protocol.js +54 -0
- package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
- package/server/lib/pi/routes-extension-events.test.js +115 -0
- package/server/lib/pi/routes.js +307 -5
- package/server/lib/pi/routes.test.js +296 -1
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +25 -8
- package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
- package/server/lib/pi/session-daemon/extension-config.js +719 -0
- package/server/lib/pi/session-daemon/extension-config.test.js +618 -0
- package/server/lib/pi/session-daemon/extension-controls.js +177 -0
- package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
- package/server/lib/pi/session-daemon/extension-name.js +6 -0
- package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
- package/server/lib/pi/session-daemon/extension-palette.js +146 -0
- package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
- package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
- package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
- package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
- package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
- package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
- package/server/lib/pi/session-daemon/plugin-host.js +245 -0
- package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
- package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
- package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
- package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
- package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
- package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
- package/server/lib/pi/session-daemon/session-daemon.js +568 -61
- package/server/lib/pi/session-daemon/session-daemon.test.js +164 -4
- package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
- package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
- package/server/lib/pi/session-daemon/supervisor.js +22 -3
- package/server/lib/pi/settings-store.js +14 -0
- package/server/lib/pi/settings-store.test.js +11 -0
- package/server/lib/plugins/DOCUMENTATION.md +186 -0
- package/server/lib/plugins/daemon-sync.js +78 -0
- package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
- package/server/lib/plugins/daemon-sync.test.js +96 -0
- package/server/lib/plugins/impact.js +139 -0
- package/server/lib/plugins/impact.test.js +82 -0
- package/server/lib/plugins/manifest.js +195 -0
- package/server/lib/plugins/manifest.test.js +118 -0
- package/server/lib/plugins/registry.js +59 -0
- package/server/lib/plugins/routes.js +92 -0
- package/server/lib/plugins/routes.test.js +219 -0
- package/server/lib/plugins/service.js +161 -0
- package/server/lib/plugins/store.js +261 -0
- package/server/lib/plugins/store.test.js +188 -0
- package/server/lib/plugins/visuals-extension.test.js +237 -0
- package/server/lib/server-browser/DOCUMENTATION.md +32 -7
- package/server/lib/server-browser/browser-tab.js +4 -1
- package/server/lib/server-browser/downloads.js +261 -34
- package/server/lib/server-browser/downloads.test.js +171 -0
- package/server/lib/server-browser/runtime.integration.test.js +47 -0
- package/server/lib/server-browser/runtime.js +16 -0
- package/server/lib/server-browser/server-browser.js +25 -6
- package/server/lib/tunnels/executable-search.js +5 -1
- package/server/lib/tunnels/executable-search.test.js +26 -0
- package/dist/assets/DiagramView-BB-aZobi.js +0 -1
- package/dist/assets/FileSaveConflictDialog-Bzz8FNMq.js +0 -3
- package/dist/assets/FilesView-DECxN8Z0.js +0 -6
- package/dist/assets/GitHubDetailScaffold-CWsWycRd.js +0 -11
- package/dist/assets/GitHubLinkPicker-BVYdg_e8.js +0 -1
- package/dist/assets/GitHubListPrimitives-Dlv3tC4d.js +0 -1
- package/dist/assets/PatchDiff-BklyOEHs.js +0 -1
- package/dist/assets/PierreDiffViewer-wc6cB6qw.js +0 -147
- package/dist/assets/PullRequestsSurface-BZvJkT1I.js +0 -2
- package/dist/assets/SessionSwitcherDropdown-DShvvGwC.js +0 -2
- package/dist/assets/SessionUnreadDot-CbqRq6h_.js +0 -1
- package/dist/assets/SettingsView-DcF-At5E.js +0 -6
- package/dist/assets/ToolOutputDialog-DdMIfrnK.js +0 -8
- package/dist/assets/ToolPartDiffPreview-C6Sm4eVf.js +0 -1
- package/dist/assets/contextFileOpenGuard-UU86YHgI.js +0 -1
- package/dist/assets/gitStatusPredicates-DQEO4Psc.js +0 -1
- package/dist/assets/githubLink-ByPAyFjh.js +0 -10
- package/dist/assets/index-BaLCg7tL.css +0 -1
- package/dist/assets/main-DyFfbllq.js +0 -137
- package/dist/assets/miniChat-Ck6MEZ9Q.js +0 -2
- package/dist/assets/pi-session-focus-preference-Dx0UXPoO.js +0 -9
- package/dist/assets/renderElectronMiniChatApp-Cb7s7dWl.js +0 -2
- package/dist/assets/runtimeEndpointReset-7nWYnKd4.js +0 -62
- package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
- package/dist/assets/useAppFontEffects-ZTyNwFk6.js +0 -213
- package/dist/assets/useGitHubRemoteSearch-BF3ohpsh.js +0 -1
- package/dist/assets/useSwitcherItems-BJzwyDGX.js +0 -1
|
@@ -1,75 +1,302 @@
|
|
|
1
1
|
import crypto from 'node:crypto';
|
|
2
2
|
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
|
|
5
6
|
const MAX_DOWNLOADS = 50;
|
|
7
|
+
// Progress goes to viewers at most this often per download; state changes go at once.
|
|
8
|
+
const PROGRESS_INTERVAL_MS = 250;
|
|
9
|
+
// Chrome's progress for downloads Playwright has not reported yet.
|
|
10
|
+
const MAX_UNPAIRED = 50;
|
|
11
|
+
const MAX_NAME_ATTEMPTS = 1000;
|
|
6
12
|
|
|
7
13
|
export const safeFileName = (value) => {
|
|
8
14
|
const base = path.basename(String(value || '')).replace(/[\u0000-\u001f<>:"/\\|?*]/g, '_').trim();
|
|
9
|
-
|
|
15
|
+
if (!base || base === '.' || base === '..') return 'file';
|
|
16
|
+
return base.slice(0, 200);
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** `name (1).ext`, `name (2).ext`, ... for a name that is taken. */
|
|
20
|
+
const numberedName = (filename, n) => {
|
|
21
|
+
if (n === 0) return filename;
|
|
22
|
+
const ext = path.extname(filename);
|
|
23
|
+
return `${filename.slice(0, filename.length - ext.length)} (${n})${ext}`;
|
|
10
24
|
};
|
|
11
25
|
|
|
12
26
|
/**
|
|
13
|
-
* Files pages
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
27
|
+
* Files pages download. Each is saved under its own name in a folder of a
|
|
28
|
+
* per-run directory in the system temp directory (owner-only), and offered
|
|
29
|
+
* to the viewers of the tab it came from. The newest 50 are kept. Downloads
|
|
30
|
+
* are indexed in memory only, and the temp directory is deleted on
|
|
31
|
+
* `dispose()`, so files from an earlier run are never served.
|
|
32
|
+
*
|
|
33
|
+
* Progress comes from Chrome (`Page.downloadWillBegin` and
|
|
34
|
+
* `Page.downloadProgress`, passed to `progress()`); the file comes from
|
|
35
|
+
* Playwright (`add()`). The two are paired by tab and address, in order.
|
|
36
|
+
*
|
|
37
|
+
* `broadcast(tabKey, message)` sends a message to a tab's viewers.
|
|
38
|
+
* `serverDownloadsDir()` is where Save to server copies files.
|
|
17
39
|
*/
|
|
18
|
-
export const createDownloadStore = ({
|
|
40
|
+
export const createDownloadStore = ({
|
|
41
|
+
broadcast = () => {},
|
|
42
|
+
tmpRoot = os.tmpdir(),
|
|
43
|
+
serverDownloadsDir = () => path.join(os.homedir(), 'Downloads'),
|
|
44
|
+
log = () => {},
|
|
45
|
+
} = {}) => {
|
|
19
46
|
const downloads = new Map();
|
|
20
|
-
|
|
47
|
+
// Chrome downloads not yet paired with an entry, by Chrome's guid.
|
|
48
|
+
const unpaired = new Map();
|
|
49
|
+
// Save to server in progress, by download id, shared by overlapping calls.
|
|
50
|
+
const savingToServer = new Map();
|
|
51
|
+
let dirPromise = null;
|
|
52
|
+
let disposed = false;
|
|
53
|
+
|
|
54
|
+
const ensureDir = () => {
|
|
55
|
+
dirPromise ??= fs.promises.mkdtemp(path.join(tmpRoot, 'pichamber-downloads-')).catch((error) => {
|
|
56
|
+
dirPromise = null;
|
|
57
|
+
throw error;
|
|
58
|
+
});
|
|
59
|
+
return dirPromise;
|
|
60
|
+
};
|
|
21
61
|
|
|
22
62
|
const message = (entry) => ({
|
|
23
63
|
type: 'download',
|
|
24
64
|
id: entry.id,
|
|
25
65
|
filename: entry.filename,
|
|
66
|
+
url: entry.url,
|
|
26
67
|
state: entry.state,
|
|
27
|
-
receivedBytes: entry.
|
|
28
|
-
totalBytes: entry.
|
|
68
|
+
receivedBytes: entry.receivedBytes,
|
|
69
|
+
totalBytes: entry.totalBytes,
|
|
70
|
+
path: entry.state === 'completed' ? entry.path : null,
|
|
71
|
+
savedPath: entry.savedPath,
|
|
72
|
+
startedAt: entry.startedAt,
|
|
29
73
|
});
|
|
30
74
|
|
|
75
|
+
const send = (entry) => {
|
|
76
|
+
clearTimeout(entry.progressTimer);
|
|
77
|
+
entry.progressTimer = null;
|
|
78
|
+
entry.sentAt = Date.now();
|
|
79
|
+
broadcast(entry.tabKey, message(entry));
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// In-progress updates are paced; the last one is never dropped.
|
|
83
|
+
const sendProgress = (entry) => {
|
|
84
|
+
if (entry.progressTimer) return;
|
|
85
|
+
const wait = PROGRESS_INTERVAL_MS - (Date.now() - entry.sentAt);
|
|
86
|
+
if (wait <= 0) {
|
|
87
|
+
send(entry);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
entry.progressTimer = setTimeout(() => {
|
|
91
|
+
entry.progressTimer = null;
|
|
92
|
+
if (downloads.get(entry.id) === entry && entry.state === 'inProgress') send(entry);
|
|
93
|
+
}, wait);
|
|
94
|
+
entry.progressTimer.unref?.();
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const removeFiles = (entry) => {
|
|
98
|
+
if (!entry.folder) return;
|
|
99
|
+
void fs.promises.rm(entry.folder, { recursive: true, force: true }).catch(() => {});
|
|
100
|
+
};
|
|
101
|
+
|
|
31
102
|
const evict = () => {
|
|
32
103
|
while (downloads.size > MAX_DOWNLOADS) {
|
|
33
104
|
const [oldest] = downloads.values();
|
|
34
105
|
downloads.delete(oldest.id);
|
|
35
|
-
|
|
106
|
+
clearTimeout(oldest.progressTimer);
|
|
107
|
+
// Its viewers drop the row: nothing can be saved from it any more.
|
|
108
|
+
broadcast(oldest.tabKey, { type: 'download-removed', id: oldest.id });
|
|
109
|
+
if (oldest.state === 'inProgress') void oldest.download?.cancel().catch(() => {});
|
|
110
|
+
removeFiles(oldest);
|
|
36
111
|
}
|
|
37
112
|
};
|
|
38
113
|
|
|
114
|
+
const applyProgress = (entry, update) => {
|
|
115
|
+
if (entry.state !== 'inProgress') return;
|
|
116
|
+
if (Number.isFinite(update.receivedBytes)) entry.receivedBytes = Math.max(0, update.receivedBytes);
|
|
117
|
+
if (Number.isFinite(update.totalBytes) && update.totalBytes > 0) entry.totalBytes = update.totalBytes;
|
|
118
|
+
sendProgress(entry);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const pairWithChrome = (entry) => {
|
|
122
|
+
for (const [guid, pending] of unpaired) {
|
|
123
|
+
if (pending.tabKey !== entry.tabKey || pending.url !== entry.url) continue;
|
|
124
|
+
unpaired.delete(guid);
|
|
125
|
+
entry.guid = guid;
|
|
126
|
+
applyProgress(entry, pending);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const entryForGuid = (guid) => {
|
|
132
|
+
for (const entry of downloads.values()) {
|
|
133
|
+
if (entry.guid === guid) return entry;
|
|
134
|
+
}
|
|
135
|
+
return null;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const finish = async (entry) => {
|
|
139
|
+
const { download } = entry;
|
|
140
|
+
try {
|
|
141
|
+
const failure = await download.failure();
|
|
142
|
+
if (failure) throw new Error(failure);
|
|
143
|
+
const dir = await ensureDir();
|
|
144
|
+
entry.folder = path.join(dir, entry.id);
|
|
145
|
+
await fs.promises.mkdir(entry.folder, { mode: 0o700 });
|
|
146
|
+
entry.path = path.join(entry.folder, entry.filename);
|
|
147
|
+
await download.saveAs(entry.path);
|
|
148
|
+
// saveAs copies with the process umask; a download stays owner-only.
|
|
149
|
+
await fs.promises.chmod(entry.path, 0o600);
|
|
150
|
+
const size = (await fs.promises.stat(entry.path)).size;
|
|
151
|
+
entry.receivedBytes = size;
|
|
152
|
+
entry.totalBytes = size;
|
|
153
|
+
entry.state = 'completed';
|
|
154
|
+
// Evicted or disposed while it downloaded: nothing can ask for it.
|
|
155
|
+
if (downloads.get(entry.id) !== entry || disposed) removeFiles(entry);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
entry.state = entry.cancelRequested ? 'canceled' : 'failed';
|
|
158
|
+
if (!entry.cancelRequested) log(`[server-browser] download failed: ${error?.message || error}`);
|
|
159
|
+
removeFiles(entry);
|
|
160
|
+
entry.folder = null;
|
|
161
|
+
entry.path = null;
|
|
162
|
+
} finally {
|
|
163
|
+
entry.download = null;
|
|
164
|
+
// saveAs copied it; Playwright's own copy is not needed.
|
|
165
|
+
await download.delete().catch(() => {});
|
|
166
|
+
}
|
|
167
|
+
if (downloads.get(entry.id) === entry) send(entry);
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const saveCopy = async (id) => {
|
|
171
|
+
const entry = downloads.get(id);
|
|
172
|
+
if (!entry || entry.state !== 'completed' || !entry.path) return null;
|
|
173
|
+
if (entry.savedPath && fs.existsSync(entry.savedPath)) return { path: entry.savedPath };
|
|
174
|
+
const dir = serverDownloadsDir();
|
|
175
|
+
await fs.promises.mkdir(dir, { recursive: true });
|
|
176
|
+
for (let n = 0; n < MAX_NAME_ATTEMPTS; n += 1) {
|
|
177
|
+
const target = path.join(dir, numberedName(entry.filename, n));
|
|
178
|
+
try {
|
|
179
|
+
await fs.promises.copyFile(entry.path, target, fs.constants.COPYFILE_EXCL);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (error?.code === 'EEXIST') continue;
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
entry.savedPath = target;
|
|
185
|
+
if (downloads.get(id) === entry) send(entry);
|
|
186
|
+
return { path: target };
|
|
187
|
+
}
|
|
188
|
+
throw new Error(`${entry.filename} and its numbered names are all taken in ${dir}`);
|
|
189
|
+
};
|
|
190
|
+
|
|
39
191
|
return {
|
|
40
|
-
/**
|
|
41
|
-
|
|
192
|
+
/** A Playwright download from the tab `tabKey`; saves it and tells the tab's viewers. */
|
|
193
|
+
add(tabKey, download) {
|
|
194
|
+
if (disposed) {
|
|
195
|
+
void download.cancel().catch(() => {});
|
|
196
|
+
return Promise.resolve();
|
|
197
|
+
}
|
|
42
198
|
const id = crypto.randomUUID();
|
|
43
|
-
const entry = {
|
|
199
|
+
const entry = {
|
|
200
|
+
id,
|
|
201
|
+
tabKey,
|
|
202
|
+
guid: null,
|
|
203
|
+
download,
|
|
204
|
+
url: typeof download.url === 'function' ? download.url() : '',
|
|
205
|
+
filename: safeFileName(download.suggestedFilename()),
|
|
206
|
+
state: 'inProgress',
|
|
207
|
+
receivedBytes: 0,
|
|
208
|
+
totalBytes: 0,
|
|
209
|
+
folder: null,
|
|
210
|
+
path: null,
|
|
211
|
+
savedPath: null,
|
|
212
|
+
startedAt: Date.now(),
|
|
213
|
+
cancelRequested: false,
|
|
214
|
+
progressTimer: null,
|
|
215
|
+
sentAt: 0,
|
|
216
|
+
};
|
|
44
217
|
downloads.set(id, entry);
|
|
45
218
|
evict();
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
|
|
219
|
+
pairWithChrome(entry);
|
|
220
|
+
send(entry);
|
|
221
|
+
return finish(entry);
|
|
222
|
+
},
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Chrome's view of a download in `tabKey`: `{ guid, url }` when it
|
|
226
|
+
* begins, then `{ guid, receivedBytes, totalBytes }` as it runs.
|
|
227
|
+
*/
|
|
228
|
+
progress(tabKey, update) {
|
|
229
|
+
const guid = update?.guid;
|
|
230
|
+
if (typeof guid !== 'string' || !guid) return;
|
|
231
|
+
const paired = entryForGuid(guid);
|
|
232
|
+
if (paired) {
|
|
233
|
+
applyProgress(paired, update);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const pending = unpaired.get(guid) ?? { tabKey, url: '', receivedBytes: 0, totalBytes: 0 };
|
|
237
|
+
if (typeof update.url === 'string' && update.url) pending.url = update.url;
|
|
238
|
+
if (Number.isFinite(update.receivedBytes)) pending.receivedBytes = update.receivedBytes;
|
|
239
|
+
if (Number.isFinite(update.totalBytes)) pending.totalBytes = update.totalBytes;
|
|
240
|
+
// Playwright may have reported the download first.
|
|
241
|
+
for (const entry of downloads.values()) {
|
|
242
|
+
if (entry.guid || entry.state !== 'inProgress' || entry.tabKey !== tabKey || entry.url !== pending.url || !pending.url) continue;
|
|
243
|
+
unpaired.delete(guid);
|
|
244
|
+
entry.guid = guid;
|
|
245
|
+
applyProgress(entry, pending);
|
|
246
|
+
return;
|
|
65
247
|
}
|
|
66
|
-
|
|
248
|
+
if (update.state === 'completed' || update.state === 'canceled') {
|
|
249
|
+
unpaired.delete(guid);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
unpaired.set(guid, pending);
|
|
253
|
+
while (unpaired.size > MAX_UNPAIRED) unpaired.delete(unpaired.keys().next().value);
|
|
254
|
+
},
|
|
255
|
+
|
|
256
|
+
/** Stops a download in progress. */
|
|
257
|
+
async cancel(id) {
|
|
258
|
+
const entry = downloads.get(id);
|
|
259
|
+
if (!entry || entry.state !== 'inProgress' || !entry.download) return false;
|
|
260
|
+
entry.cancelRequested = true;
|
|
261
|
+
await entry.download.cancel().catch(() => {});
|
|
262
|
+
return true;
|
|
67
263
|
},
|
|
68
264
|
|
|
69
265
|
get(id) {
|
|
70
266
|
const entry = downloads.get(id);
|
|
71
|
-
if (!entry || entry.state !== 'completed') return null;
|
|
267
|
+
if (!entry || entry.state !== 'completed' || !entry.path) return null;
|
|
72
268
|
return { path: entry.path, filename: entry.filename };
|
|
73
269
|
},
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Copies a finished download into the server's Downloads folder under
|
|
273
|
+
* its own name (numbered when taken) and returns where. A second call
|
|
274
|
+
* returns the same copy while it exists.
|
|
275
|
+
*/
|
|
276
|
+
saveToServer(id) {
|
|
277
|
+
const pending = savingToServer.get(id);
|
|
278
|
+
if (pending) return pending;
|
|
279
|
+
const saving = saveCopy(id).finally(() => savingToServer.delete(id));
|
|
280
|
+
savingToServer.set(id, saving);
|
|
281
|
+
return saving;
|
|
282
|
+
},
|
|
283
|
+
|
|
284
|
+
/** The downloads of `tabKey`, oldest first, as viewer messages. */
|
|
285
|
+
messagesFor(tabKey) {
|
|
286
|
+
return [...downloads.values()].filter((entry) => entry.tabKey === tabKey).map(message);
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
/** Cancels downloads in progress and deletes the temp directory. */
|
|
290
|
+
async dispose() {
|
|
291
|
+
disposed = true;
|
|
292
|
+
for (const entry of downloads.values()) {
|
|
293
|
+
clearTimeout(entry.progressTimer);
|
|
294
|
+
if (entry.state === 'inProgress') void entry.download?.cancel().catch(() => {});
|
|
295
|
+
}
|
|
296
|
+
downloads.clear();
|
|
297
|
+
unpaired.clear();
|
|
298
|
+
const dir = await dirPromise?.catch(() => null);
|
|
299
|
+
if (dir) await fs.promises.rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
300
|
+
},
|
|
74
301
|
};
|
|
75
302
|
};
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
6
|
+
|
|
7
|
+
import { createDownloadStore, safeFileName } from './downloads.js';
|
|
8
|
+
|
|
9
|
+
/** A Playwright download that finishes when told to. */
|
|
10
|
+
const fakeDownload = ({ url = 'https://files.example/report.pdf', filename = 'report.pdf', body = 'file body' } = {}) => {
|
|
11
|
+
let settle;
|
|
12
|
+
const finished = new Promise((resolve) => { settle = resolve; });
|
|
13
|
+
return {
|
|
14
|
+
url: () => url,
|
|
15
|
+
suggestedFilename: () => filename,
|
|
16
|
+
failure: () => finished,
|
|
17
|
+
saveAs: async (target) => fs.promises.writeFile(target, body),
|
|
18
|
+
delete: async () => {},
|
|
19
|
+
cancel: async () => settle('canceled'),
|
|
20
|
+
finish: (failure = null) => settle(failure),
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
describe('server browser downloads', () => {
|
|
25
|
+
let tmpRoot;
|
|
26
|
+
let serverDownloads;
|
|
27
|
+
let sent;
|
|
28
|
+
let store;
|
|
29
|
+
|
|
30
|
+
beforeEach(() => {
|
|
31
|
+
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'pichamber-downloads-test-'));
|
|
32
|
+
serverDownloads = path.join(tmpRoot, 'home', 'Downloads');
|
|
33
|
+
sent = [];
|
|
34
|
+
store = createDownloadStore({
|
|
35
|
+
broadcast: (key, message) => sent.push({ key, ...message }),
|
|
36
|
+
tmpRoot,
|
|
37
|
+
serverDownloadsDir: () => serverDownloads,
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
afterEach(async () => {
|
|
42
|
+
await store.dispose();
|
|
43
|
+
fs.rmSync(tmpRoot, { recursive: true, force: true });
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('keeps a finished file under its own name in the temp directory', async () => {
|
|
47
|
+
const download = fakeDownload();
|
|
48
|
+
const done = store.add('tab-a', download);
|
|
49
|
+
expect(sent.at(-1)).toMatchObject({ key: 'tab-a', state: 'inProgress', filename: 'report.pdf', path: null });
|
|
50
|
+
download.finish();
|
|
51
|
+
await done;
|
|
52
|
+
|
|
53
|
+
const last = sent.at(-1);
|
|
54
|
+
expect(last).toMatchObject({ state: 'completed', receivedBytes: 9, totalBytes: 9, savedPath: null });
|
|
55
|
+
expect(path.basename(last.path)).toBe('report.pdf');
|
|
56
|
+
expect(last.path.startsWith(tmpRoot)).toBe(true);
|
|
57
|
+
expect(fs.readFileSync(last.path, 'utf8')).toBe('file body');
|
|
58
|
+
expect(fs.statSync(last.path).mode & 0o777).toBe(0o600);
|
|
59
|
+
expect(store.get(last.id)).toEqual({ path: last.path, filename: 'report.pdf' });
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('reports Chrome progress, whichever of Chrome and Playwright reports first', async () => {
|
|
63
|
+
// Chrome first.
|
|
64
|
+
store.progress('tab-a', { guid: 'g1', url: 'https://files.example/a.zip' });
|
|
65
|
+
store.progress('tab-a', { guid: 'g1', receivedBytes: 10, totalBytes: 100, state: 'inProgress' });
|
|
66
|
+
const first = fakeDownload({ url: 'https://files.example/a.zip', filename: 'a.zip' });
|
|
67
|
+
void store.add('tab-a', first);
|
|
68
|
+
expect(sent.at(-1)).toMatchObject({ filename: 'a.zip', receivedBytes: 10, totalBytes: 100 });
|
|
69
|
+
|
|
70
|
+
// Playwright first.
|
|
71
|
+
const second = fakeDownload({ url: 'https://files.example/b.zip', filename: 'b.zip' });
|
|
72
|
+
void store.add('tab-a', second);
|
|
73
|
+
store.progress('tab-a', { guid: 'g2', url: 'https://files.example/b.zip' });
|
|
74
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
75
|
+
store.progress('tab-a', { guid: 'g2', receivedBytes: 50, totalBytes: 200, state: 'inProgress' });
|
|
76
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
77
|
+
expect(sent.filter((m) => m.filename === 'b.zip').at(-1)).toMatchObject({ receivedBytes: 50, totalBytes: 200 });
|
|
78
|
+
|
|
79
|
+
// Another tab's download at the same address is not mixed up.
|
|
80
|
+
expect(sent.filter((m) => m.filename === 'a.zip').every((m) => m.key === 'tab-a')).toBe(true);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('marks a canceled download canceled and a broken one failed', async () => {
|
|
84
|
+
const canceled = fakeDownload({ filename: 'one.bin' });
|
|
85
|
+
const canceling = store.add('tab-a', canceled);
|
|
86
|
+
const id = sent.at(-1).id;
|
|
87
|
+
expect(await store.cancel(id)).toBe(true);
|
|
88
|
+
await canceling;
|
|
89
|
+
expect(sent.at(-1)).toMatchObject({ id, state: 'canceled', path: null });
|
|
90
|
+
|
|
91
|
+
const broken = fakeDownload({ filename: 'two.bin' });
|
|
92
|
+
const breaking = store.add('tab-a', broken);
|
|
93
|
+
broken.finish('net::ERR_FAILED');
|
|
94
|
+
await breaking;
|
|
95
|
+
expect(sent.at(-1)).toMatchObject({ filename: 'two.bin', state: 'failed' });
|
|
96
|
+
expect(store.get(sent.at(-1).id)).toBeNull();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('saves a copy to the server Downloads folder, numbering a taken name', async () => {
|
|
100
|
+
fs.mkdirSync(serverDownloads, { recursive: true });
|
|
101
|
+
fs.writeFileSync(path.join(serverDownloads, 'report.pdf'), 'older');
|
|
102
|
+
const download = fakeDownload();
|
|
103
|
+
const done = store.add('tab-a', download);
|
|
104
|
+
download.finish();
|
|
105
|
+
await done;
|
|
106
|
+
const { id } = sent.at(-1);
|
|
107
|
+
|
|
108
|
+
const saved = await store.saveToServer(id);
|
|
109
|
+
expect(saved.path).toBe(path.join(serverDownloads, 'report (1).pdf'));
|
|
110
|
+
expect(fs.readFileSync(saved.path, 'utf8')).toBe('file body');
|
|
111
|
+
expect(fs.readFileSync(path.join(serverDownloads, 'report.pdf'), 'utf8')).toBe('older');
|
|
112
|
+
expect(sent.at(-1)).toMatchObject({ id, savedPath: saved.path });
|
|
113
|
+
// Saving again returns the same copy.
|
|
114
|
+
expect(await store.saveToServer(id)).toEqual(saved);
|
|
115
|
+
expect(await store.saveToServer('missing')).toBeNull();
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('replays a tab\'s downloads and deletes the temp directory on dispose', async () => {
|
|
119
|
+
const download = fakeDownload();
|
|
120
|
+
const done = store.add('tab-a', download);
|
|
121
|
+
void store.add('tab-b', fakeDownload({ filename: 'other.txt' }));
|
|
122
|
+
download.finish();
|
|
123
|
+
await done;
|
|
124
|
+
expect(store.messagesFor('tab-a').map((m) => m.filename)).toEqual(['report.pdf']);
|
|
125
|
+
const file = store.messagesFor('tab-a')[0].path;
|
|
126
|
+
await store.dispose();
|
|
127
|
+
expect(fs.existsSync(path.dirname(path.dirname(file)))).toBe(false);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('never names a file . or ..', () => {
|
|
131
|
+
expect(safeFileName('..')).toBe('file');
|
|
132
|
+
expect(safeFileName('.')).toBe('file');
|
|
133
|
+
expect(safeFileName('../../etc/passwd')).toBe('passwd');
|
|
134
|
+
expect(safeFileName('a:b?.txt')).toBe('a_b_.txt');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('shares one copy between overlapping Save to server calls', async () => {
|
|
138
|
+
const download = fakeDownload();
|
|
139
|
+
const done = store.add('tab-a', download);
|
|
140
|
+
download.finish();
|
|
141
|
+
await done;
|
|
142
|
+
const { id, path: tempPath } = sent.at(-1);
|
|
143
|
+
|
|
144
|
+
const [first, second] = await Promise.all([store.saveToServer(id), store.saveToServer(id)]);
|
|
145
|
+
expect(first).toEqual({ path: path.join(serverDownloads, 'report.pdf') });
|
|
146
|
+
expect(second).toEqual(first);
|
|
147
|
+
expect(fs.readdirSync(serverDownloads)).toEqual(['report.pdf']);
|
|
148
|
+
// The temp copy stays for Save to this device.
|
|
149
|
+
expect(fs.existsSync(tempPath)).toBe(true);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it('tells viewers when an old download is dropped', async () => {
|
|
153
|
+
const first = fakeDownload();
|
|
154
|
+
const firstDone = store.add('tab-a', first);
|
|
155
|
+
first.finish();
|
|
156
|
+
await firstDone;
|
|
157
|
+
const { id: oldestId, path: oldestPath } = sent.at(-1);
|
|
158
|
+
|
|
159
|
+
const later = [];
|
|
160
|
+
for (let n = 0; n < 50; n += 1) {
|
|
161
|
+
const download = fakeDownload({ url: `https://files.example/${n}`, filename: `file-${n}.txt` });
|
|
162
|
+
later.push(store.add('tab-a', download));
|
|
163
|
+
download.finish();
|
|
164
|
+
}
|
|
165
|
+
await Promise.all(later);
|
|
166
|
+
|
|
167
|
+
expect(sent).toContainEqual({ key: 'tab-a', type: 'download-removed', id: oldestId });
|
|
168
|
+
expect(store.get(oldestId)).toBeNull();
|
|
169
|
+
await expect.poll(() => fs.existsSync(oldestPath)).toBe(false);
|
|
170
|
+
});
|
|
171
|
+
});
|
|
@@ -87,6 +87,18 @@ describe.skipIf(!chrome?.path)('server browser over its WebSocket', () => {
|
|
|
87
87
|
if (req.url === '/second') { res.setHeader('content-type', 'text/html'); res.end('<title>Second</title><h1>second</h1>'); return; }
|
|
88
88
|
if (req.url === '/alert') { res.setHeader('content-type', 'text/html'); res.end('<script>setTimeout(() => { alert("hello there"); fetch("/after-alert"); }, 50)</script>'); return; }
|
|
89
89
|
if (req.url === '/download') { res.setHeader('content-disposition', 'attachment; filename="notes.txt"'); res.end('downloaded body'); return; }
|
|
90
|
+
if (req.url === '/slow-download') {
|
|
91
|
+
// Four chunks a quarter second apart, so progress shows between them.
|
|
92
|
+
res.setHeader('content-disposition', 'attachment; filename="slow.bin"');
|
|
93
|
+
res.setHeader('content-length', String(4 * 64 * 1024));
|
|
94
|
+
let sent = 0;
|
|
95
|
+
const timer = setInterval(() => {
|
|
96
|
+
res.write(Buffer.alloc(64 * 1024, 7));
|
|
97
|
+
sent += 1;
|
|
98
|
+
if (sent === 4) { clearInterval(timer); res.end(); }
|
|
99
|
+
}, 250);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
90
102
|
if (req.url === '/popup-to-local') { res.setHeader('content-type', 'text/html'); res.end(`<a href="http://127.0.0.1:${upstreamPort}/popup-secret" target="_blank" style="position:absolute;left:0;top:0;width:300px;height:100px">open</a>`); return; }
|
|
91
103
|
if (req.url === '/frame-public') { res.setHeader('content-type', 'text/html'); res.end(`<iframe src="http://public.example:${upstreamPort}/to-local"></iframe>`); return; }
|
|
92
104
|
if (req.url === '/to-local') { res.statusCode = 302; res.setHeader('location', `http://127.0.0.1:${upstreamPort}/secret`); res.end(); return; }
|
|
@@ -113,6 +125,8 @@ describe.skipIf(!chrome?.path)('server browser over its WebSocket', () => {
|
|
|
113
125
|
env: { ...process.env, PICHAMBER_BROWSER_NO_SANDBOX: isRoot ? '1' : (process.env.PICHAMBER_BROWSER_NO_SANDBOX ?? '') },
|
|
114
126
|
// Public-looking names for this machine, to test public pages.
|
|
115
127
|
extraChromeArgs: ['--host-resolver-rules=MAP *.example 127.0.0.1'],
|
|
128
|
+
downloadsTmpRoot: dataDir,
|
|
129
|
+
serverDownloadsDir: () => path.join(dataDir, 'Downloads'),
|
|
116
130
|
// The rule's own lookup sees them as public addresses.
|
|
117
131
|
createGuard: (options) => createNetworkGuard({ ...options, lookup: async () => [{ address: '93.184.216.34', family: 4 }] }),
|
|
118
132
|
log: (message) => logs.push(message),
|
|
@@ -286,6 +300,39 @@ describe.skipIf(!chrome?.path)('server browser over its WebSocket', () => {
|
|
|
286
300
|
const response = await fetch(`http://${base}/api/server-browser/downloads/${done.id}`);
|
|
287
301
|
expect(await response.text()).toBe('downloaded body');
|
|
288
302
|
expect(response.headers.get('content-disposition')).toContain('notes.txt');
|
|
303
|
+
expect(response.headers.get('content-length')).toBe(String('downloaded body'.length));
|
|
304
|
+
// The file waits under its own name in the per-run temp folder.
|
|
305
|
+
expect(path.basename(done.path)).toBe('notes.txt');
|
|
306
|
+
expect(done.path.startsWith(dataDir)).toBe(true);
|
|
307
|
+
|
|
308
|
+
const saved = await fetch(`http://${base}/api/server-browser/downloads/${done.id}/save-to-server`, { method: 'POST' }).then((r) => r.json());
|
|
309
|
+
expect(saved.path).toBe(path.join(dataDir, 'Downloads', 'notes.txt'));
|
|
310
|
+
expect(fs.readFileSync(saved.path, 'utf8')).toBe('downloaded body');
|
|
311
|
+
await page.waitFor((m) => m.type === 'download' && m.id === done.id && m.savedPath === saved.path, 'saved path');
|
|
312
|
+
|
|
313
|
+
// A viewer that comes later is told about the tab's downloads.
|
|
314
|
+
const later = connect('popup', '');
|
|
315
|
+
await later.waitFor((m) => m.type === 'download' && m.id === done.id && m.state === 'completed', 'replayed download');
|
|
316
|
+
later.socket.close();
|
|
317
|
+
page.socket.close();
|
|
318
|
+
}, 30_000);
|
|
319
|
+
|
|
320
|
+
it('reports download progress and cancels downloads', async () => {
|
|
321
|
+
const page = connect('slow-download', `http://127.0.0.1:${upstreamPort}/`);
|
|
322
|
+
await page.open;
|
|
323
|
+
page.send({ type: 'viewport', width: 600, height: 400, dpr: 1 });
|
|
324
|
+
await page.waitFor((m) => m.type === 'state' && m.title === 'Test page' && !m.loading, 'title');
|
|
325
|
+
page.send({ type: 'navigate', url: `http://127.0.0.1:${upstreamPort}/slow-download` });
|
|
326
|
+
const partway = await page.waitFor((m) => m.type === 'download' && m.state === 'inProgress' && m.receivedBytes > 0 && m.receivedBytes < m.totalBytes, 'progress');
|
|
327
|
+
expect(partway.totalBytes).toBe(4 * 64 * 1024);
|
|
328
|
+
const done = await page.waitFor((m) => m.type === 'download' && m.id === partway.id && m.state === 'completed', 'slow download');
|
|
329
|
+
expect(done.receivedBytes).toBe(4 * 64 * 1024);
|
|
330
|
+
|
|
331
|
+
page.send({ type: 'navigate', url: `http://127.0.0.1:${upstreamPort}/slow-download` });
|
|
332
|
+
const started = await page.waitFor((m) => m.type === 'download' && m.id !== partway.id && m.state === 'inProgress', 'second download');
|
|
333
|
+
page.send({ type: 'download-cancel', id: started.id });
|
|
334
|
+
const canceled = await page.waitFor((m) => m.type === 'download' && m.id === started.id && m.state !== 'inProgress', 'canceled');
|
|
335
|
+
expect(canceled.state).toBe('canceled');
|
|
289
336
|
page.socket.close();
|
|
290
337
|
}, 30_000);
|
|
291
338
|
|
|
@@ -119,11 +119,24 @@ export const createServerBrowserRuntime = ({
|
|
|
119
119
|
if (!download) return res.status(404).json({ error: 'Download not found' });
|
|
120
120
|
res.setHeader('Cache-Control', 'no-store');
|
|
121
121
|
res.attachment(download.filename);
|
|
122
|
+
// The size lets the device show how far its copy has come.
|
|
123
|
+
try { res.setHeader('Content-Length', String(fs.statSync(download.path).size)); } catch { /* read below fails too */ }
|
|
122
124
|
fs.createReadStream(download.path)
|
|
123
125
|
.on('error', () => { if (!res.headersSent) res.status(404).end(); else res.destroy(); })
|
|
124
126
|
.pipe(res);
|
|
125
127
|
});
|
|
126
128
|
|
|
129
|
+
// Copies a finished download into the server's Downloads folder.
|
|
130
|
+
app.post('/api/server-browser/downloads/:id/save-to-server', async (req, res) => {
|
|
131
|
+
try {
|
|
132
|
+
const saved = await browser.saveDownloadToServer(req.params.id);
|
|
133
|
+
if (!saved) return res.status(404).json({ error: 'Download not found' });
|
|
134
|
+
res.json(saved);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
res.status(500).json({ error: error?.message || 'Could not save the download on the server' });
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
|
|
127
140
|
let wsServer = new WebSocketServer({ noServer: true, maxPayload: MAX_CLIENT_MESSAGE_BYTES, perMessageDeflate: false });
|
|
128
141
|
|
|
129
142
|
wsServer.on('connection', (socket, req) => {
|
|
@@ -188,6 +201,7 @@ export const createServerBrowserRuntime = ({
|
|
|
188
201
|
case 'file-chooser':
|
|
189
202
|
await tab.respondFileChooser({ id: message.id, files: browser.takeUploads(message.uploadIds) });
|
|
190
203
|
return;
|
|
204
|
+
case 'download-cancel': await browser.cancelDownload(String(message.id || '')); return;
|
|
191
205
|
case 'inspect': {
|
|
192
206
|
const target = await tab.inspectAt(message.x, message.y);
|
|
193
207
|
if (message.pick !== true) {
|
|
@@ -232,6 +246,8 @@ export const createServerBrowserRuntime = ({
|
|
|
232
246
|
}
|
|
233
247
|
if (closed) return;
|
|
234
248
|
detach = tab.attachViewer(viewer);
|
|
249
|
+
// Downloads the tab made before this viewer came.
|
|
250
|
+
for (const download of browser.downloadMessages(key)) sendJson(download);
|
|
235
251
|
markReady();
|
|
236
252
|
})();
|
|
237
253
|
});
|