@livx.cc/appwrap 0.54.0 → 0.56.0

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.
Files changed (70) hide show
  1. package/package.json +5 -4
  2. package/runtime/app/main-page.ts +0 -2
  3. package/runtime/app/shell/capabilities.manifest.ts +27 -92
  4. package/runtime/app/shell/config.ts +4 -0
  5. package/runtime/app/shell/env.ts +8 -1
  6. package/runtime/app/shell/handlers.ts +2 -2
  7. package/runtime/tests/bridge-response-delivery.test.ts +10 -1
  8. package/runtime/tests/env-scheme.test.ts +50 -0
  9. package/scripts/stage-assets.mjs +1 -1
  10. package/src/cli.ts +424 -621
  11. package/src/config.ts +8 -1
  12. package/src/handlers.ts +1 -1
  13. package/src/packs.ts +174 -0
  14. package/src/testing.ts +173 -0
  15. package/templates/module-pack/README.md +44 -0
  16. package/templates/module-pack/handler.ts +9 -0
  17. package/templates/module-pack/manifest.ts +27 -0
  18. package/templates/module-pack/native-src/__MODULE_NAME__/.gitkeep +0 -0
  19. package/runtime/app/shell/billing-offer.ts +0 -54
  20. package/runtime/app/shell/handlers-billing.ts +0 -662
  21. package/runtime/app/shell/handlers-health.ts +0 -178
  22. package/runtime/app/shell/handlers-widget.ts +0 -97
  23. package/runtime/modules-native/billing/App_Resources/iOS/src/AppwrapManageSubscriptions.swift +0 -44
  24. package/runtime/modules-native/health/App_Resources/Android/src/main/java/cc/livx/appwrap/HealthConnectBridge.kt +0 -74
  25. package/runtime/modules-native/widget/App_Resources/Android/src/main/java/cc/livx/appwrap/AppwrapWidgetProvider.kt +0 -118
  26. package/runtime/modules-native/widget/App_Resources/Android/src/main/res/drawable/appwrap_badge_bg.xml +0 -9
  27. package/runtime/modules-native/widget/App_Resources/Android/src/main/res/layout/appwrap_widget.xml +0 -123
  28. package/runtime/modules-native/widget/App_Resources/Android/src/main/res/values/appwrap_widget_colors.xml +0 -10
  29. package/runtime/modules-native/widget/App_Resources/Android/src/main/res/values/appwrap_widget_styles.xml +0 -67
  30. package/runtime/modules-native/widget/App_Resources/Android/src/main/res/values-night/appwrap_widget_colors.xml +0 -9
  31. package/runtime/modules-native/widget/App_Resources/Android/src/main/res/xml/appwrap_widget_info.xml +0 -17
  32. package/runtime/modules-native/widget/App_Resources/iOS/extensions/AppwrapWidget/AppwrapWidget.entitlements +0 -10
  33. package/runtime/modules-native/widget/App_Resources/iOS/extensions/AppwrapWidget/AppwrapWidget.swift +0 -275
  34. package/runtime/modules-native/widget/App_Resources/iOS/extensions/AppwrapWidget/Info.plist +0 -25
  35. package/runtime/modules-native/widget/App_Resources/iOS/extensions/AppwrapWidget/extension.json +0 -9
  36. package/runtime/modules-native/widget/App_Resources/iOS/src/AppwrapWidgetReload.swift +0 -18
  37. package/runtime/tests/billing-offer.test.ts +0 -61
  38. package/runtime-desktop/autotest/index.html +0 -77
  39. package/runtime-desktop/bridge-shim/build.sh +0 -9
  40. package/runtime-desktop/bridge-shim/content-entry.ts +0 -87
  41. package/runtime-desktop/bridge-shim/shim.ts +0 -132
  42. package/runtime-desktop/chrome/appwrap-browser-chrome.html +0 -185
  43. package/runtime-desktop/crates/webview-control/Cargo.lock +0 -330
  44. package/runtime-desktop/crates/webview-control/Cargo.toml +0 -28
  45. package/runtime-desktop/crates/webview-control/examples/host_harness.rs +0 -362
  46. package/runtime-desktop/crates/webview-control/src/embedded.rs +0 -138
  47. package/runtime-desktop/crates/webview-control/src/lib.rs +0 -100
  48. package/runtime-desktop/crates/webview-control/src/popup.rs +0 -522
  49. package/runtime-desktop/crates/webview-control/src/profiles.rs +0 -57
  50. package/runtime-desktop/crates/webview-control/src/wkwebview_backend.rs +0 -558
  51. package/runtime-desktop/src-tauri/Cargo.lock +0 -5474
  52. package/runtime-desktop/src-tauri/Cargo.toml +0 -45
  53. package/runtime-desktop/src-tauri/build.rs +0 -3
  54. package/runtime-desktop/src-tauri/capabilities/default.json +0 -6
  55. package/runtime-desktop/src-tauri/icons/icon.png +0 -0
  56. package/runtime-desktop/src-tauri/shell_config.json +0 -10
  57. package/runtime-desktop/src-tauri/src/biometrics_mac.rs +0 -138
  58. package/runtime-desktop/src-tauri/src/bridge_mac.rs +0 -424
  59. package/runtime-desktop/src-tauri/src/browser_tab.rs +0 -804
  60. package/runtime-desktop/src-tauri/src/main.rs +0 -1228
  61. package/runtime-desktop/src-tauri/src/notifications_mac.rs +0 -202
  62. package/runtime-desktop/src-tauri/src/oauth_mac.rs +0 -139
  63. package/runtime-desktop/src-tauri/src/plugin_host.rs +0 -522
  64. package/runtime-desktop/src-tauri/src/popup_mac.rs +0 -5
  65. package/runtime-desktop/src-tauri/src/push_mac.rs +0 -193
  66. package/runtime-desktop/src-tauri/src/server.rs +0 -156
  67. package/runtime-desktop/src-tauri/src/sidecar.rs +0 -398
  68. package/runtime-desktop/src-tauri/tauri.conf.json +0 -14
  69. package/src/desktop.ts +0 -300
  70. package/src/plugin/host.ts +0 -242
@@ -1,87 +0,0 @@
1
- // SPIKE: browser-bridge content layer for the appwrap desktop (Tauri/WKWebView) shell.
2
- // Reuses bod-browser's extension/src/content/* modules UNMODIFIED; only the transport differs:
3
- // instead of chrome.runtime messaging, each page dials a local WS to the shim (bridge-shim/shim.ts)
4
- // and answers ContentAction messages. Injected per-window via Tauri initialization_script.
5
- //
6
- // Build (from the bod-browser repo root so its tsconfig `paths` resolve shared/*):
7
- // cd ../bod-browser && bun build <this file> --outfile <appwrap>/runtime-desktop/bridge-shim/dist/content.js
8
- import type { ContentAction } from 'shared/protocol';
9
- import { advanceScroll } from '../../../bod-browser/extension/src/content/advance-scroll';
10
- import {
11
- clickElement, typeInElement, fillElement, doScroll, scrollElementIntoView, evalScript,
12
- waitForElement, hoverElement, scrollElementBy, hoverNear, sendKey,
13
- } from '../../../bod-browser/extension/src/content/actions';
14
- import {
15
- queryElements, getLinks, findButtons, clickText, queryByText, getElementValue, setElementAttribute,
16
- } from '../../../bod-browser/extension/src/content/query';
17
- import { getA11ySnapshot, queryA11y } from '../../../bod-browser/extension/src/content/a11y';
18
- import { probePage } from '../../../bod-browser/extension/src/content/probe';
19
- import { diagnosePage } from '../../../bod-browser/extension/src/content/diagnose';
20
-
21
- declare global {
22
- interface Window { __BRIDGE_LABEL?: string; __BRIDGE_PORT?: number; __BRIDGE_LOADED?: boolean }
23
- }
24
-
25
- async function handleMessage(msg: ContentAction): Promise<unknown> {
26
- switch (msg.action) {
27
- case 'getContent':
28
- return { url: location.href, title: document.title, html: document.documentElement.outerHTML, text: document.body?.innerText ?? '' };
29
- case 'getTextContent':
30
- return { url: location.href, title: document.title, text: document.body?.innerText?.slice(0, 20000) || '' };
31
- case 'query': return queryElements(msg.selector, msg.multiple);
32
- case 'click': return clickElement(msg.selector);
33
- case 'type': return typeInElement(msg.selector, msg.value, msg.mode, msg.clear);
34
- case 'fill': return fillElement(msg.selector, msg.value, msg.timeout, msg.mode, msg.clear);
35
- case 'getValue': return getElementValue(msg.selector);
36
- case 'setAttribute': return setElementAttribute(msg.selector, msg.attr, msg.value);
37
- case 'scroll': return doScroll(msg.x || 0, msg.y || 0, msg.behavior);
38
- case 'scrollIntoView': return scrollElementIntoView(msg.selector, msg.behavior);
39
- case 'eval': return evalScript(msg.script);
40
- case 'waitFor': return waitForElement(msg.selector, msg.timeout || 5000);
41
- case 'hover': return hoverElement(msg.selector);
42
- case 'scrollEl': return scrollElementBy(msg.selector, msg.deltaX || 0, msg.deltaY || 0, msg.behavior);
43
- case 'advanceScroll':
44
- return advanceScroll({ deltaY: msg.deltaY, itemSelector: msg.itemSelector, loadMoreSelector: msg.loadMoreSelector, behavior: msg.behavior });
45
- case 'getA11ySnapshot': return getA11ySnapshot(msg.root || null, msg.maxDepth || 10, msg.mode || 'full');
46
- case 'probe': return probePage(msg.goal || null);
47
- case 'diagnose': return diagnosePage();
48
- case 'queryA11y': return queryA11y(msg.role, msg.name, msg.multiple);
49
- case 'getLinks': return getLinks(msg.pattern || null, msg.scope || null);
50
- case 'clickText': return clickText(msg.text, msg.scope || null);
51
- case 'queryByText': return queryByText(msg.text, msg.scope || null);
52
- case 'findButtons': return findButtons(msg.scope || null);
53
- case 'sendKey': return sendKey(msg.selector || null, msg.key, msg.modifiers);
54
- case '_ping': return { pong: true };
55
- default:
56
- throw new Error(`Unknown action: ${(msg as ContentAction).action}`);
57
- }
58
- }
59
-
60
- (() => {
61
- // initialization_script can fire more than once per document lifecycle; guard.
62
- if (window.__BRIDGE_LOADED) return;
63
- window.__BRIDGE_LOADED = true;
64
- const label = window.__BRIDGE_LABEL || 'unknown';
65
-
66
- // Transport: WebKit blocks ws://127.0.0.1 (and plain-http beacons) from https pages as mixed
67
- // content — no loopback exemption like Chrome. So results go out via the native
68
- // WKScriptMessageHandler the shell installs (webkit.messageHandlers.bridgeShim), and commands
69
- // come in via window.__bridgeDispatch(...) evaluated by the shell (evalJs op).
70
- type WebkitHandlers = { webkit?: { messageHandlers?: { bridgeShim?: { postMessage: (s: string) => void } } } };
71
- const post = (o: Record<string, unknown>) => {
72
- try { (window as WebkitHandlers).webkit?.messageHandlers?.bridgeShim?.postMessage(JSON.stringify({ label, ...o })); } catch { /* ignore */ }
73
- };
74
-
75
- (window as unknown as { __bridgeDispatch: (m: ContentAction & { id: string }) => void }).__bridgeDispatch = (m) => {
76
- Promise.resolve()
77
- .then(() => handleMessage(m))
78
- .then(result => post({ id: m.id, result }))
79
- .catch((e: Error) => post({ id: m.id, error: e.message }));
80
- };
81
-
82
- const register = () => post({ type: 'register', url: location.href, title: document.title });
83
- register();
84
- addEventListener('DOMContentLoaded', register);
85
- addEventListener('load', register);
86
- console.log(`[BridgeDesktop:cs ${label}] loaded on ${location.href.slice(0, 80)}`);
87
- })();
@@ -1,132 +0,0 @@
1
- #!/usr/bin/env bun
2
- // SPIKE: browser-bridge "extension instance" shim for the appwrap desktop (Tauri) shell.
3
- // Speaks the UNMODIFIED bod-browser extension protocol to the bridge server (ws://localhost:9230),
4
- // backed by Tauri windows instead of Chrome tabs:
5
- // - WS client -> bridge server: hello { instanceId: 'appwrap-desktop' }, answers WsCommand.
6
- // - WS server :9236 (/page) : each Tauri window's injected content bundle dials in and
7
- // executes ContentAction messages (the DOM layer).
8
- // - TCP :9237 (line-JSON) : the Rust shell connects as 'control'; the shim asks it for
9
- // window ops (createWindow/closeWindow/navigate/screenshot).
10
- // Run: bun runtime-desktop/bridge-shim/shim.ts
11
-
12
- const SERVER_URL = process.env.BRIDGE_SERVER_URL || 'ws://localhost:9230';
13
- const INSTANCE_ID = process.env.BRIDGE_INSTANCE_ID || 'appwrap-desktop';
14
- const PAGE_PORT = Number(process.env.APPWRAP_BRIDGE_PAGE_PORT || 9236);
15
- const RUST_PORT = Number(process.env.APPWRAP_BRIDGE_RUST_PORT || 9237);
16
-
17
- const log = (m: string, ...a: unknown[]) => console.log(`[shim] ${m}`, ...a);
18
-
19
- // The transport-agnostic browser-automation PRODUCT (tab registry + bod-browser routing +
20
- // handleCommand) was lifted into the `browser-driver` package inside mcp-desktop-browser (Phase 1b).
21
- // This file is now a thin TRANSPORT shell: WS client + TCP control channel + page WS, delegating all
22
- // command handling and page-beacon parsing to the driver below. Consumed as a proper package
23
- // (`mcp-desktop-browser/browser-driver`, a file: dep in the root package.json → resolves by name,
24
- // not a fragile cross-repo relative path — the TS analogue of the crate-consumption decision).
25
- import { createBrowserDriver } from 'mcp-desktop-browser/browser-driver';
26
-
27
- // ---------------------------------------------------------------------------
28
- // Rust control channel (TCP, newline-delimited JSON)
29
- // ---------------------------------------------------------------------------
30
- type Pending = { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> };
31
- let rustSock: { write: (s: string) => void } | null = null;
32
- const rustPending = new Map<string, Pending>();
33
- let reqCounter = 0;
34
-
35
- function rustRequest(op: string, params: Record<string, unknown> = {}, timeoutMs = 15000): Promise<unknown> {
36
- if (!rustSock) return Promise.reject(new Error('Desktop shell not connected to shim (is the app running with APPWRAP_BRIDGE_JS?)'));
37
- const id = `r${++reqCounter}`;
38
- return new Promise((resolve, reject) => {
39
- const timer = setTimeout(() => { rustPending.delete(id); reject(new Error(`rust op ${op} timed out`)); }, timeoutMs);
40
- rustPending.set(id, { resolve, reject, timer });
41
- rustSock!.write(JSON.stringify({ id, op, ...params }) + '\n');
42
- });
43
- }
44
-
45
- // The product layer — driven through our transport (rustRequest) + fed page beacons via onPageMsg.
46
- const driver = createBrowserDriver({ rustRequest, log });
47
-
48
- Bun.listen({
49
- hostname: '127.0.0.1',
50
- port: RUST_PORT,
51
- socket: {
52
- open(socket) {
53
- log('rust control connected');
54
- rustSock = { write: (s) => socket.write(s) };
55
- (socket as unknown as { __buf: string }).__buf = '';
56
- },
57
- data(socket, data) {
58
- const s = socket as unknown as { __buf: string };
59
- s.__buf += data.toString();
60
- let idx: number;
61
- while ((idx = s.__buf.indexOf('\n')) >= 0) {
62
- const line = s.__buf.slice(0, idx).trim();
63
- s.__buf = s.__buf.slice(idx + 1);
64
- if (!line) continue;
65
- try {
66
- const msg = JSON.parse(line);
67
- if (msg.type === 'pageMsg') { driver.onPageMsg(String(msg.payload)); continue; }
68
- const p = rustPending.get(msg.id);
69
- if (p) {
70
- rustPending.delete(msg.id);
71
- clearTimeout(p.timer);
72
- if (msg.error) p.reject(new Error(String(msg.error)));
73
- else p.resolve(msg.result);
74
- }
75
- } catch (e) { log('bad rust line:', line.slice(0, 200), (e as Error).message); }
76
- }
77
- },
78
- close() { log('rust control disconnected'); rustSock = null; },
79
- error(_s, e) { log('rust control error:', e.message); },
80
- },
81
- });
82
-
83
- // Debug HTTP endpoint (curl a raw rust op / read page beacons)
84
- Bun.serve({
85
- hostname: '127.0.0.1',
86
- port: PAGE_PORT,
87
- async fetch(req) {
88
- const path = new URL(req.url).pathname;
89
- if (path === '/log' && req.method === 'POST') { log('page:', await req.text()); return new Response('ok'); }
90
- if (path === '/rust' && req.method === 'POST') {
91
- const body = await req.json() as Record<string, unknown>;
92
- try { return Response.json({ result: await rustRequest(String(body.op), body) }); }
93
- catch (e) { return Response.json({ error: (e as Error).message }); }
94
- }
95
- return new Response('bridge-shim debug endpoint', { status: 200 });
96
- },
97
- });
98
-
99
- // ---------------------------------------------------------------------------
100
- // Bridge server WS client (the extension background's ws.ts analogue)
101
- // ---------------------------------------------------------------------------
102
- let serverWs: WebSocket | null = null;
103
- function connectServer() {
104
- serverWs = new WebSocket(SERVER_URL);
105
- serverWs.onopen = () => {
106
- log(`connected to bridge server ${SERVER_URL} as ${INSTANCE_ID}`);
107
- serverWs!.send(JSON.stringify({ type: 'hello', userAgent: `appwrap-desktop-shell (Tauri/WKWebView; ${process.platform})`, instanceId: INSTANCE_ID, buildHash: 'appwrap-desktop-spike' }));
108
- serverWs!.send(JSON.stringify({ type: 'ping', t: Date.now() }));
109
- };
110
- serverWs.onmessage = async (ev) => {
111
- let msg: { id: string; cmd: string; params?: Record<string, unknown>; type?: string } | undefined;
112
- try {
113
- const parsed = JSON.parse(String(ev.data));
114
- if (parsed.type === 'pong' || parsed.type === 'reload' || parsed.type === 'recording_saved') return;
115
- msg = parsed;
116
- const result = await driver.handleCommand(msg!);
117
- log(`cmd=${msg!.cmd} ok`);
118
- serverWs!.send(JSON.stringify({ id: msg!.id, result }));
119
- } catch (e) {
120
- log(`cmd=${msg?.cmd} error: ${(e as Error).message}`);
121
- try { serverWs!.send(JSON.stringify({ id: msg?.id, error: (e as Error).message })); } catch { /* ignore */ }
122
- }
123
- };
124
- serverWs.onclose = () => { log('server disconnected, retrying in 3s'); setTimeout(connectServer, 3000); };
125
- serverWs.onerror = () => { /* onclose follows */ };
126
- }
127
- connectServer();
128
- setInterval(() => {
129
- if (serverWs?.readyState === WebSocket.OPEN) serverWs.send(JSON.stringify({ type: 'ping', t: Date.now() }));
130
- }, 15000);
131
-
132
- log(`page WS :${PAGE_PORT} rust control :${RUST_PORT}`);
@@ -1,185 +0,0 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width, initial-scale=1" />
6
- <title>Browser</title>
7
- <style>
8
- :root {
9
- --bar-h: 44px;
10
- --bg: #f2f2f4; --fg: #1c1c1e; --border: #d0d0d5;
11
- --field-bg: #ffffff; --field-border: #c4c4cc; --btn-hover: #e2e2e6;
12
- }
13
- @media (prefers-color-scheme: dark) {
14
- :root {
15
- --bg: #2a2a2e; --fg: #f2f2f4; --border: #444;
16
- --field-bg: #1c1c1e; --field-border: #555; --btn-hover: #3a3a40;
17
- }
18
- }
19
- * { box-sizing: border-box; }
20
- html, body { margin: 0; height: 100%; overflow: hidden;
21
- font: 13px -apple-system, system-ui, sans-serif; color: var(--fg); }
22
- /* The controlled WKWebView is a native subview covering everything below the bar; the body below
23
- the bar is never seen — only this top strip renders. */
24
- #bar {
25
- display: flex; align-items: center; gap: 6px;
26
- height: var(--bar-h); padding: 0 8px;
27
- background: var(--bg); border-bottom: 1px solid var(--border);
28
- -webkit-user-select: none; user-select: none;
29
- }
30
- button.nav {
31
- width: 30px; height: 28px; flex: none;
32
- border: none; border-radius: 6px; background: transparent; color: var(--fg);
33
- font-size: 16px; line-height: 1; cursor: default;
34
- }
35
- button.nav:hover { background: var(--btn-hover); }
36
- button.nav:active { background: var(--field-border); }
37
- #addr {
38
- flex: 1 1 auto; height: 28px; padding: 0 10px;
39
- border: 1px solid var(--field-border); border-radius: 7px;
40
- background: var(--field-bg); color: var(--fg); font-size: 13px; outline: none;
41
- }
42
- #addr:focus { border-color: #4c8bf5; }
43
- #profile, #newprof {
44
- flex: none; height: 28px; max-width: 160px;
45
- border: 1px solid var(--field-border); border-radius: 7px;
46
- background: var(--field-bg); color: var(--fg); font-size: 12px; padding: 0 4px;
47
- }
48
- #newprof:focus { border-color: #4c8bf5; outline: none; }
49
- </style>
50
- </head>
51
- <body>
52
- <div id="bar">
53
- <button class="nav" id="back" title="Back">&#8249;</button>
54
- <button class="nav" id="fwd" title="Forward">&#8250;</button>
55
- <button class="nav" id="reload" title="Reload">&#8635;</button>
56
- <input id="addr" type="text" spellcheck="false" autocomplete="off"
57
- placeholder="Enter address (e.g. 127.0.0.1:3000)" />
58
- <select id="profile" title="Profile"></select>
59
- <input id="newprof" type="text" spellcheck="false" autocomplete="off"
60
- placeholder="profile name — Enter" style="display:none" />
61
- </div>
62
- <script>
63
- (function () {
64
- // id + profile arrive via hash fragment (#id=…&profile=…) — a query (?…) breaks Tauri's App-asset
65
- // resolution. Read hash first, fall back to search for robustness.
66
- var hp = new URLSearchParams(location.hash.replace(/^#/, ''));
67
- var sp = new URLSearchParams(location.search);
68
- var id = hp.get('id') || sp.get('id') || '';
69
- var initProfile = hp.get('profile') || sp.get('profile') || 'default';
70
- function invoke(cmd, args) {
71
- var core = window.__TAURI__ && window.__TAURI__.core;
72
- if (!core) return Promise.reject(new Error('Tauri core unavailable'));
73
- return core.invoke(cmd, args || {});
74
- }
75
-
76
- var addr = document.getElementById('addr');
77
- var profileSel = document.getElementById('profile');
78
-
79
- function normalizeUrl(raw) {
80
- var s = (raw || '').trim();
81
- if (!s) return '';
82
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s) || /^about:/i.test(s)) return s;
83
- return 'https://' + s;
84
- }
85
-
86
- document.getElementById('back').addEventListener('click', function () { invoke('browser_tab_back', { id: id }); });
87
- document.getElementById('fwd').addEventListener('click', function () { invoke('browser_tab_forward', { id: id }); });
88
- document.getElementById('reload').addEventListener('click', function () { invoke('browser_tab_reload', { id: id }); });
89
-
90
- addr.addEventListener('keydown', function (e) {
91
- if (e.key !== 'Enter') return;
92
- var url = normalizeUrl(addr.value);
93
- if (url) invoke('browser_tab_navigate', { id: id, url: url });
94
- });
95
-
96
- var NEW_PROFILE = '__new__'; // sentinel option: reveal an inline input, then switch to the name
97
- var current = initProfile; // the profile actually shown (to revert the <select> on cancel)
98
- var newprof = document.getElementById('newprof');
99
-
100
- function addProfileOption(name) {
101
- if (!name) return;
102
- for (var i = 0; i < profileSel.options.length; i++) {
103
- if (profileSel.options[i].value === name) return; // already listed
104
- }
105
- var opt = document.createElement('option');
106
- opt.value = name; opt.textContent = name;
107
- profileSel.insertBefore(opt, profileSel.lastChild); // before the "+ New profile…" item
108
- }
109
-
110
- function switchProfile(name) {
111
- // Switching recreates the webview with a fresh, isolated store; the name is persisted on first
112
- // use (uuid_for) so it reappears in the list next launch.
113
- addProfileOption(name);
114
- profileSel.value = name;
115
- current = name;
116
- invoke('browser_subwindow_switch_profile', { id: id, profileId: name });
117
- }
118
-
119
- // Inline "+ New profile" flow — WKWebView has no window.prompt (no text-input panel delegate), so
120
- // reveal a small input instead of prompting. Enter commits, Escape/empty-blur cancels.
121
- function beginNewProfile() {
122
- profileSel.style.display = 'none';
123
- newprof.style.display = '';
124
- newprof.value = '';
125
- newprof.focus();
126
- }
127
- function endNewProfile(commit) {
128
- if (newprof.style.display === 'none') return; // already closed (guard double-fire)
129
- var name = (newprof.value || '').trim();
130
- newprof.style.display = 'none';
131
- profileSel.style.display = '';
132
- profileSel.value = current; // reset the sentinel selection
133
- if (commit && name && name !== current) switchProfile(name);
134
- }
135
- newprof.addEventListener('keydown', function (e) {
136
- if (e.key === 'Enter') endNewProfile(true);
137
- else if (e.key === 'Escape') endNewProfile(false);
138
- });
139
- newprof.addEventListener('blur', function () { endNewProfile(true); });
140
-
141
- profileSel.addEventListener('change', function () {
142
- var val = profileSel.value;
143
- if (val === NEW_PROFILE) { beginNewProfile(); return; }
144
- current = val;
145
- invoke('browser_subwindow_switch_profile', { id: id, profileId: val });
146
- });
147
-
148
- // Populate the profile dropdown, then append the "+ New profile…" sentinel.
149
- invoke('browser_list_profiles').then(function (profiles) {
150
- (profiles || ['default']).forEach(function (p) {
151
- var opt = document.createElement('option');
152
- opt.value = p; opt.textContent = p;
153
- profileSel.appendChild(opt);
154
- });
155
- var add = document.createElement('option');
156
- add.value = NEW_PROFILE; add.textContent = '+ New profile…';
157
- profileSel.appendChild(add);
158
- // Reflect the window's ACTUAL mounted profile (may be non-default on a restored window).
159
- addProfileOption(initProfile);
160
- profileSel.value = initProfile;
161
- }).catch(function (e) { console.error('list profiles failed', e); });
162
-
163
- // Keep the address bar in sync with the controlled webview (skip while the user is editing it).
164
- var focused = false;
165
- addr.addEventListener('focus', function () { focused = true; });
166
- addr.addEventListener('blur', function () { focused = false; });
167
- function poll() {
168
- invoke('browser_tab_current_url', { id: id }).then(function (json) {
169
- if (focused) return;
170
- try {
171
- var o = JSON.parse(json);
172
- var href = o && o.href ? o.href : '';
173
- if (href && href !== 'about:blank') addr.value = href;
174
- } catch (_) {}
175
- }).catch(function () {});
176
- }
177
- var pollTimer = setInterval(poll, 1000);
178
- poll();
179
- // Stop polling as the window unloads — a poll's current_url eval racing the native teardown blocks
180
- // the closing window (the webview is gone, so the eval never resolves). Fixes the close-hang.
181
- window.addEventListener('pagehide', function () { clearInterval(pollTimer); });
182
- })();
183
- </script>
184
- </body>
185
- </html>