Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

feat: allow opening the packaged URL on every launch

youxi7984ff150b3ef78
diff --git a/AGENTS.md b/AGENTS.md
index 02079564..ea180974 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -119,6 +119,7 @@ Oracles per row live under `tests/unit/` (for example `event-link-guard.test.js`
- New user-visible CLI surface (a new flag, alias, subcommand, or extra help variant) needs a stated justification before implementation: name the user problem and why an existing flag, config key, or default cannot cover it, then get maintainer sign-off. Prefer quieter defaults over new options; never split help output into parallel variants.
- Window/runtime options with platform-sensitive behavior include `--incognito`, `--new-window`, `--min-width`, `--min-height`, `--maximize`, multi-window behavior, notification click handling, and Linux/Wayland WebKit compositing defaults.
- `--incognito` intentionally trades persistence for clean private sessions; be careful around login, cookies, local storage, and WeChat-style WebView detection.
+- Web apps restore the main window's last URL by default. `--no-restore-last-url` / config `restoreLastUrl: false` disables both reading and saving that URL without changing cookie or local-storage persistence. Legacy native configs missing `restore_last_url` default to true. Startup and close/exit persistence share `WindowConfig::remembers_last_url`, which excludes incognito sessions and local pages. Verify with `cargo test --lib` and `node tests/integration/last-url.mjs` (real macOS WebView).
- Windows `--password-autosave` is opt-in and disabled in private windows. Every window creation must apply both true and false through `ICoreWebView2Settings4::SetIsPasswordAutosaveEnabled`; do not treat the false case as a no-op. Legacy configs default to false. This controls new save/update prompts, not existing password autofill or general autofill, and does not share an Edge or Chrome profile. Keep the native bool, CLI/config surface, and both language docs consistent; cover all four requested/private combinations and the missing-field default in the `config.rs` Rust tests, and keep `tests/unit/password-autosave.test.ts` asserting that both values reach the native call.
- `--new-window` and `--multi-window` do not bypass every provider policy. Google OAuth and similar embedded-WebView restrictions may still require a normal browser or native client.
- macOS Basic Auth keeps only an enablement boolean in CLI/config. Usernames and passwords are runtime-only input for the target host and session; never put them in CLI arguments, config, generated artifacts, logs, or persistence. Native dialog changes need a real macOS smoke covering the icon, button alignment, label/input baselines, field width, and outer margins; compile and unit tests do not prove the layout.
diff --git a/bin/defaults.ts b/bin/defaults.ts
index fa0aae0a..c73d37eb 100644
--- a/bin/defaults.ts
+++ b/bin/defaults.ts
@@ -41,6 +41,7 @@ export const DEFAULT_PAKE_OPTIONS: PakeCliOptions = {
installerLanguage: 'en-US',
hideOnClose: undefined, // Platform-specific: true for macOS, false for others
incognito: false,
+ restoreLastUrl: true,
passwordAutosave: false,
wasm: false,
enableDragDrop: false,
diff --git a/bin/helpers/cli-program.ts b/bin/helpers/cli-program.ts
index ec689f63..6a67efad 100644
--- a/bin/helpers/cli-program.ts
+++ b/bin/helpers/cli-program.ts
@@ -180,6 +180,14 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
.hideHelp(),
)
.addOption(new Option('--title <string>', 'Window title').hideHelp())
+ .addOption(
+ new Option(
+ '--no-restore-last-url',
+ 'Open the packaged URL on launch while keeping cookies and storage',
+ )
+ .default(DEFAULT.restoreLastUrl)
+ .hideHelp(),
+ )
.addOption(
new Option('--incognito', 'Launch app in incognito/private mode')
.default(DEFAULT.incognito)
diff --git a/bin/helpers/merge.ts b/bin/helpers/merge.ts
index b7d774c1..657ee004 100644
--- a/bin/helpers/merge.ts
+++ b/bin/helpers/merge.ts
@@ -54,6 +54,7 @@ export function buildWindowConfigOverrides(
disabled_web_shortcuts: options.disabledWebShortcuts,
hide_on_close: platformHideOnClose,
incognito: options.incognito,
+ restore_last_url: options.restoreLastUrl,
password_autosave: options.passwordAutosave,
title: options.title,
enable_wasm: options.wasm,
diff --git a/bin/types.ts b/bin/types.ts
index 8e0428a6..40cf020e 100644
--- a/bin/types.ts
+++ b/bin/types.ts
@@ -104,6 +104,9 @@ export interface PakeCliOptions {
// Launch app in incognito/private mode, default false
incognito: boolean;
+ // Restore the last main-window URL on launch, default true
+ restoreLastUrl: boolean;
+
// Enable native WebView2 password-save prompts on Windows, default false
passwordAutosave: boolean;
@@ -195,6 +198,7 @@ export interface WindowConfig {
activation_shortcut: string;
hide_on_close: boolean;
incognito: boolean;
+ restore_last_url: boolean;
password_autosave: boolean;
title?: string;
enable_wasm: boolean;
diff --git a/dist/cli.js b/dist/cli.js
index dc0b266c..e846d055 100644
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -944,6 +944,7 @@ function buildWindowConfigOverrides(options, platform = asSupportedPlatform(proc
disabled_web_shortcuts: options.disabledWebShortcuts,
hide_on_close: platformHideOnClose,
incognito: options.incognito,
+ restore_last_url: options.restoreLastUrl,
password_autosave: options.passwordAutosave,
title: options.title,
enable_wasm: options.wasm,
@@ -3537,6 +3538,7 @@ const DEFAULT_PAKE_OPTIONS = {
installerLanguage: 'en-US',
hideOnClose: undefined, // Platform-specific: true for macOS, false for others
incognito: false,
+ restoreLastUrl: true,
passwordAutosave: false,
wasm: false,
enableDragDrop: false,
@@ -3705,6 +3707,9 @@ ${green('|_| \\__,_|_|\\_\\___| can turn any webpage into a desktop app with
})
.hideHelp())
.addOption(new Option('--title <string>', 'Window title').hideHelp())
+ .addOption(new Option('--no-restore-last-url', 'Open the packaged URL on launch while keeping cookies and storage')
+ .default(DEFAULT_PAKE_OPTIONS.restoreLastUrl)
+ .hideHelp())
.addOption(new Option('--incognito', 'Launch app in incognito/private mode')
.default(DEFAULT_PAKE_OPTIONS.incognito)
.hideHelp())
diff --git a/docs/cli-usage.md b/docs/cli-usage.md
index e3504be3..09f7f3e4 100644
--- a/docs/cli-usage.md
+++ b/docs/cli-usage.md
@@ -444,6 +444,14 @@ Set the window title bar text. macOS shows no title if not specified; Windows/Li
--title "Google Translate"
```
+#### [no-restore-last-url]
+
+Web apps restore the main window's last URL by default. Use this option to open the packaged URL on every launch while keeping cookies, local storage, and login sessions. In a `--config` JSON file, set `"restoreLastUrl": false`. Incognito sessions and local pages do not restore URLs.
+
+```shell
+pake https://www.rememberthemilk.com --name RememberTheMilk --no-restore-last-url
+```
+
#### [incognito]
Launch the application in incognito/private browsing mode. Default is `false`. When enabled, the webview will run in private mode, which means it won't store cookies, local storage, or browsing history. This is useful for privacy-sensitive applications.
diff --git a/docs/cli-usage_CN.md b/docs/cli-usage_CN.md
index ad484747..2a077474 100644
--- a/docs/cli-usage_CN.md
+++ b/docs/cli-usage_CN.md
@@ -444,6 +444,14 @@ pake https://github.com --name GitHub --show-system-tray --start-to-tray
--title "音乐播放器"
```
+#### [no-restore-last-url]
+
+网页应用默认恢复主窗口上次打开的网址,使用此选项后每次启动都打开打包时的地址,仍保留 Cookie、Local Storage 和登录状态,使用 `--config` 时在 JSON 中设置 `"restoreLastUrl": false`,无痕模式和本地页面不恢复网址。
+
+```shell
+pake https://www.rememberthemilk.com --name RememberTheMilk --no-restore-last-url
+```
+
#### [incognito]
以无痕模式启动应用,默认为 `false`,启用后不保留 Cookie、Local Storage 和历史记录,适用于注重隐私或临时登录场景。
diff --git a/schema/pake.schema.json b/schema/pake.schema.json
index dea7bd84..5dcff2e4 100644
--- a/schema/pake.schema.json
+++ b/schema/pake.schema.json
@@ -154,6 +154,11 @@
"type": "boolean",
"description": "Hide the window on close instead of exiting. Defaults to true on macOS, false elsewhere."
},
+ "restoreLastUrl": {
+ "type": "boolean",
+ "description": "Restore the last main-window URL on launch. Set false to open the packaged URL while keeping cookies and storage. Ignored in incognito mode and for local pages.",
+ "default": true
+ },
"incognito": {
"type": "boolean",
"description": "Launch in incognito/private mode (no persisted cookies or storage).",
diff --git a/src-tauri/src/app/config.rs b/src-tauri/src/app/config.rs
index 3f271ccb..5ef17d88 100644
--- a/src-tauri/src/app/config.rs
+++ b/src-tauri/src/app/config.rs
@@ -26,6 +26,8 @@ pub struct WindowConfig {
pub activation_shortcut: String,
pub hide_on_close: bool,
pub incognito: bool,
+ #[serde(default = "default_restore_last_url")]
+ pub restore_last_url: bool,
#[serde(default)]
pub password_autosave: bool,
pub title: Option<String>,
@@ -54,6 +56,10 @@ fn default_zoom() -> u32 {
100
}
+fn default_restore_last_url() -> bool {
+ true
+}
+
#[cfg(any(windows, test))]
impl WindowConfig {
pub fn password_autosave_enabled(&self) -> bool {
@@ -62,6 +68,10 @@ impl WindowConfig {
}
impl WindowConfig {
+ pub fn remembers_last_url(&self) -> bool {
+ self.restore_last_url && self.url_type == "web" && !self.incognito
+ }
+
/// The overlay title bar (`hide_title_bar`) keeps precedence, so existing
/// configs behave exactly as before.
pub fn title_bar_follows_page(&self) -> bool {
@@ -199,6 +209,36 @@ mod tests {
config
}
+ #[test]
+ fn last_url_restoration_defaults_on_and_preserves_private_and_local_exclusions() {
+ let mut window = config_for("https://example.com").windows.remove(0);
+ let mut legacy = serde_json::to_value(&window).unwrap();
+ legacy.as_object_mut().unwrap().remove("restore_last_url");
+ let legacy: WindowConfig = serde_json::from_value(legacy.clone()).unwrap();
+ assert!(legacy.restore_last_url);
+ assert!(legacy.remembers_last_url());
+
+ for enabled in [false, true] {
+ for incognito in [false, true] {
+ for url_type in ["web", "local"] {
+ window.restore_last_url = enabled;
+ window.incognito = incognito;
+ window.url_type = url_type.into();
+ assert_eq!(
+ window.remembers_last_url(),
+ enabled && !incognito && url_type == "web"
+ );
+ }
+ }
+ }
+
+ let mut disabled = serde_json::to_value(legacy).unwrap();
+ disabled["restore_last_url"] = false.into();
+ let disabled: WindowConfig = serde_json::from_value(disabled).unwrap();
+ assert!(!disabled.remembers_last_url());
+ assert!(!disabled.incognito);
+ }
+
#[test]
fn password_autosave_is_opt_in_and_disabled_in_private_windows() {
let mut window = config_for("https://example.com").windows.remove(0);
diff --git a/src-tauri/src/app/window.rs b/src-tauri/src/app/window.rs
index 02720a26..7d4add98 100644
--- a/src-tauri/src/app/window.rs
+++ b/src-tauri/src/app/window.rs
@@ -431,10 +431,7 @@ fn build_window(
))
})?;
- let restored_url = if label == "pake"
- && window_config.url_type == "web"
- && !window_config.incognito
- {
+ let restored_url = if label == "pake" && window_config.remembers_last_url() {
match app.path().app_data_dir() {
Ok(directory) => match crate::util::read_last_url(&directory.join("last-url.txt")) {
Ok(url) => url,
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 7dbdcdb0..51e45a4f 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -306,8 +306,7 @@ pub fn run_app() {
let show_system_tray = pake_config.show_system_tray();
let hide_on_close = pake_config.windows[0].hide_on_close;
- let remember_url =
- pake_config.windows[0].url_type == "web" && !pake_config.windows[0].incognito;
+ let remember_url = pake_config.windows[0].remembers_last_url();
let activation_shortcut = pake_config.windows[0].activation_shortcut.clone();
let init_fullscreen = pake_config.windows[0].fullscreen;
let start_to_tray = pake_config.windows[0].start_to_tray && show_system_tray; // Only valid when tray is enabled
diff --git a/tests/integration/last-url.mjs b/tests/integration/last-url.mjs
new file mode 100644
index 00000000..627fbe6d
--- /dev/null
+++ b/tests/integration/last-url.mjs
@@ -0,0 +1,171 @@
+// Real macOS WebView coverage for URL restoration and persistent login data.
+import assert from "node:assert/strict";
+import fs from "node:fs/promises";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+
+if (process.platform !== "darwin") {
+ throw new Error("This native URL restoration fixture requires macOS.");
+}
+const repo = process.cwd();
+const root = await fs.mkdtemp(path.join(os.tmpdir(), "pake-last-url-"));
+const identifier = `com.pake.last-url-probe-${process.pid}`;
+const dataDir = path.join(
+ os.homedir(),
+ "Library/Application Support",
+ identifier,
+);
+const lastUrl = path.join(dataDir, "last-url.txt");
+const reports = [];
+let phase = "seed";
+let app;
+const server = http.createServer(async (request, response) => {
+ if (request.url === "/report") {
+ let body = "";
+ for await (const chunk of request) body += chunk;
+ reports.push(JSON.parse(body));
+ response.end("ok");
+ return;
+ }
+ response.setHeader("Content-Type", "text/html");
+ response.end(`<!doctype html><title>Pake URL restoration probe</title><script>
+ (async () => {
+ const phase = ${JSON.stringify(phase)};
+ if (phase === "seed" && location.pathname === "/") {
+ localStorage.setItem("session", "retained");
+ document.cookie = "session=retained; Max-Age=3600; Path=/";
+ location.href = "/task";
+ return;
+ }
+ if (phase === "disabled" && location.pathname === "/") {
+ await fetch("/report", {method:"POST", body:JSON.stringify({
+ phase, path:location.pathname, storage:localStorage.getItem("session"),
+ cookie:document.cookie
+ })});
+ location.href = "/other";
+ return;
+ }
+ await fetch("/report", {method:"POST", body:JSON.stringify({
+ phase, path:location.pathname, storage:localStorage.getItem("session"),
+ cookie:document.cookie
+ })});
+ await new Promise(resolve => setTimeout(resolve, 300));
+ await window.__TAURI__.core.invoke("plugin:window|close", {label:"pake"});
+ })();
+ </script>`);
+});
+server.listen(0, "127.0.0.1");
+await once(server, "listening");
+const origin = `http://127.0.0.1:${server.address().port}`;
+
+try {
+ const fixture = path.join(root, "fixture");
+ await fs.mkdir(fixture);
+ await fs.cp(path.join(repo, "src-tauri"), path.join(fixture, "src-tauri"), {
+ recursive: true,
+ filter: (file) => {
+ const relative = path.relative(path.join(repo, "src-tauri"), file);
+ return (
+ !["target", ".pake", "gen", ".cargo"].includes(
+ relative.split(path.sep)[0],
+ ) && !relative.startsWith(path.join("permissions", "autogenerated"))
+ );
+ },
+ });
+ await fs.copyFile(
+ path.join(repo, "rust-toolchain.toml"),
+ path.join(fixture, "rust-toolchain.toml"),
+ );
+ await fs.mkdir(path.join(fixture, "dist"));
+ await fs.writeFile(path.join(fixture, "dist/index.html"), "URL fixture");
+ const log = await fs.open(path.join(root, "build.log"), "w");
+ console.log("Building native URL restoration fixture...");
+ const compiler = spawn(
+ "cargo",
+ ["build", "--locked", "--features", "runtime-template"],
+ {
+ cwd: path.join(fixture, "src-tauri"),
+ env: {
+ ...process.env,
+ CARGO_TARGET_DIR: path.join(repo, "src-tauri/target"),
+ },
+ stdio: ["ignore", log.fd, log.fd],
+ },
+ );
+ const [code] = await once(compiler, "exit");
+ await log.close();
+ if (code !== 0) {
+ console.error(await fs.readFile(path.join(root, "build.log"), "utf8"));
+ throw new Error(`Native fixture build failed with exit code ${code}`);
+ }
+
+ const contents = path.join(root, "Probe.app/Contents");
+ const executable = path.join(contents, "MacOS/pake");
+ const runtime = path.join(contents, "Resources/pake-runtime");
+ await fs.mkdir(path.dirname(executable), { recursive: true });
+ await fs.mkdir(runtime, { recursive: true });
+ await fs.copyFile(path.join(repo, "src-tauri/target/debug/pake"), executable);
+ await fs.chmod(executable, 0o755);
+ await fs.writeFile(
+ path.join(runtime, "app.json"),
+ JSON.stringify({ identifier, productName: "PakeUrlProbe" }),
+ );
+ const config = JSON.parse(
+ await fs.readFile(path.join(repo, "src-tauri/pake.json")),
+ );
+ config.windows[0].url = origin + "/";
+ config.windows[0].hide_on_close = false;
+ config.system_tray.macos = false;
+ const run = async (nextPhase, enabled) => {
+ phase = nextPhase;
+ if (enabled === undefined) delete config.windows[0].restore_last_url;
+ else config.windows[0].restore_last_url = enabled;
+ await fs.writeFile(path.join(runtime, "pake.json"), JSON.stringify(config));
+ app = spawn(executable, [], { stdio: "ignore" });
+ const timer = setTimeout(() => app.kill("SIGKILL"), 45_000);
+ const [exitCode] = await once(app, "exit");
+ clearTimeout(timer);
+ assert.equal(exitCode, 0, `native app failed during ${phase}`);
+ };
+
+ await run("seed", undefined);
+ assert.equal(await fs.readFile(lastUrl, "utf8"), origin + "/task");
+ await run("restored", true);
+ assert.equal(reports.find((r) => r.phase === "restored")?.path, "/task");
+ const saved = await fs.readFile(lastUrl, "utf8");
+ await run("disabled", false);
+ await run("disabled-relaunch", false);
+ assert.equal(
+ await fs.readFile(lastUrl, "utf8"),
+ saved,
+ "opt-out must not save a new URL",
+ );
+ assert.deepEqual(
+ reports.filter((r) => r.phase === "disabled").map((r) => r.path),
+ ["/", "/other"],
+ );
+ assert.equal(reports.find((r) => r.phase === "disabled-relaunch")?.path, "/");
+ for (const report of reports) {
+ assert.equal(report.storage, "retained", `${report.phase}: local storage`);
+ assert.match(
+ report.cookie,
+ /(?:^|; )session=retained(?:;|$)/,
+ `${report.phase}: cookie`,
+ );
+ }
+ console.log(
+ "Native URL restoration passed: legacy/default restore, opt-out launch and save, persistent cookies and local storage.",
+ );
+} finally {
+ if (app && app.exitCode === null && app.signalCode === null) {
+ const exited = once(app, "exit");
+ app.kill("SIGKILL");
+ await exited;
+ }
+ server.close();
+ await fs.rm(dataDir, { recursive: true, force: true });
+ console.log(`Native fixture and build log: ${root}`);
+}
diff --git a/tests/unit/__snapshots__/merge-window-options.test.ts.snap b/tests/unit/__snapshots__/merge-window-options.test.ts.snap
index 77f7836b..1c44b63e 100644
--- a/tests/unit/__snapshots__/merge-window-options.test.ts.snap
+++ b/tests/unit/__snapshots__/merge-window-options.test.ts.snap
@@ -24,6 +24,7 @@ exports[`buildWindowConfigOverrides > matches the default snapshot on Linux 1`]
"new_window": false,
"password_autosave": false,
"resizable": true,
+ "restore_last_url": true,
"start_to_tray": false,
"title": undefined,
"width": 1200,
@@ -55,6 +56,7 @@ exports[`buildWindowConfigOverrides > matches the default snapshot on Windows 1`
"new_window": false,
"password_autosave": false,
"resizable": true,
+ "restore_last_url": true,
"start_to_tray": false,
"title": undefined,
"width": 1200,
@@ -86,6 +88,7 @@ exports[`buildWindowConfigOverrides > matches the default snapshot on macOS 1`]
"new_window": false,
"password_autosave": false,
"resizable": true,
+ "restore_last_url": true,
"start_to_tray": false,
"title": undefined,
"width": 1200,
diff --git a/tests/unit/cli-options.test.ts b/tests/unit/cli-options.test.ts
index 32104ace..96577d5e 100644
--- a/tests/unit/cli-options.test.ts
+++ b/tests/unit/cli-options.test.ts
@@ -1,4 +1,4 @@
-import { InvalidArgumentError } from 'commander';
+import { Command, InvalidArgumentError } from 'commander';
import { describe, expect, it } from 'vitest';
import { getCliProgram } from '../../bin/helpers/cli-program.js';
import { validateNumberInput } from '../../bin/utils/validate.js';
@@ -6,6 +6,22 @@ import { validateNumberInput } from '../../bin/utils/validate.js';
describe('CLI options', () => {
const program = getCliProgram();
+ it.each([{ args: [] }, { args: ['--no-restore-last-url'] }])(
+ 'keeps URL restoration on by default and parses the opt-out: $args',
+ ({ args }) => {
+ const option = program.options.find(
+ (item) => item.long === '--no-restore-last-url',
+ );
+ expect(option).toBeDefined();
+ const command = new Command().addOption(option!);
+ command.parse(args, { from: 'user' });
+ expect(command.opts().restoreLastUrl).toBe(args.length === 0);
+ expect(command.getOptionValueSource('restoreLastUrl')).toBe(
+ args.length === 0 ? 'default' : 'cli',
+ );
+ },
+ );
+
it('shows meta options in help', () => {
const help = program.helpInformation();
diff --git a/tests/unit/config-file.test.ts b/tests/unit/config-file.test.ts
index 247cb341..f65d2c61 100644
--- a/tests/unit/config-file.test.ts
+++ b/tests/unit/config-file.test.ts
@@ -100,6 +100,22 @@ describe('loadConfigFile', () => {
expect(loaded.options.downloadDir).toBe('~/Documents/My App');
});
+ it.each([false, true])(
+ 'loads restoreLastUrl=%s from config',
+ async (enabled) => {
+ const configPath = await writeConfig({ restoreLastUrl: enabled });
+ const loaded = await loadConfigFile(configPath, validKeys);
+ expect(loaded.options.restoreLastUrl).toBe(enabled);
+ },
+ );
+
+ it('rejects a non-boolean restoreLastUrl', async () => {
+ const configPath = await writeConfig({ restoreLastUrl: 'false' });
+ await expect(loadConfigFile(configPath, validKeys)).rejects.toMatchObject({
+ code: 'INVALID_INPUT',
+ });
+ });
+
it.each([false, true])(
'loads passwordAutosave=%s from config',
async (enabled) => {
diff --git a/tests/unit/merge-window-options.test.ts b/tests/unit/merge-window-options.test.ts
index 28d7c6e5..8ad0ce41 100644
--- a/tests/unit/merge-window-options.test.ts
+++ b/tests/unit/merge-window-options.test.ts
@@ -12,6 +12,17 @@ function makeOptions(overrides: Partial<PakeAppOptions> = {}): PakeAppOptions {
}
describe('buildWindowConfigOverrides', () => {
+ it.each(['darwin', 'win32', 'linux'] as const)(
+ 'disables URL restoration without enabling private mode on %s',
+ (platform) => {
+ expect(
+ buildWindowConfigOverrides(
+ makeOptions({ restoreLastUrl: false }),
+ platform,
+ ),
+ ).toMatchObject({ restore_last_url: false, incognito: false });
+ },
+ );
it.each([false, true])(
'forwards password autosave=%s to native config',
(enabled) => {