A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.

9 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-browser.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-browser.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-browser.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 toolbar: Back and Forward are greyed out when there's nowhere to go cc08c7a 1 week, 2 days ago History
chrome.html · 162.1 KB · 2410 lines
1<!doctype html>
2<html>
3 <head>
4 <meta charset="utf-8" />
5 <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data:" />
6 <title>dbbasic-browser</title>
7 <style>
8 * { box-sizing: border-box; }
9 html, body { margin: 0; height: 100%; font: 13px -apple-system, system-ui, sans-serif; }
10 body { display: flex; flex-direction: column; background: #1e1e22; color: #e8e8ea; }
11 #bar { display: flex; align-items: center; gap: 8px; padding: 8px 10px; background: #26262b; border-bottom: 1px solid #000; }
12 #url { flex: 1; padding: 7px 12px; border-radius: 7px; border: 1px solid #3a3a40; background: #131316; color: #e8e8ea; font-size: 13px; }
13 #back, #fwd, #reload { min-width: 36px; height: 32px; display: inline-flex; align-items: center; justify-content: center; font-size: 17px; line-height: 1; }
14 #url:focus { outline: none; border-color: #5b8cff; }
15 #zoomBtn { padding: 6px 9px; font-size: 12px; font-variant-numeric: tabular-nums; color: #b9c6ff; }
16 #zoomBtn[hidden] { display: none; }
17 .btn { padding: 7px 10px; border-radius: 7px; border: 1px solid #3a3a40; background: #131316; color: #e8e8ea; cursor: pointer; white-space: nowrap; }
18 .btn:hover { background: #1c1c20; }
19 .btn:disabled { opacity: 0.35; cursor: default; }
20 .btn:disabled:hover { background: #131316; }
21 .btn .ico { width: 16px; height: 16px; vertical-align: -3px; flex-shrink: 0; }
22 .btn.on { background: #23324e; border-color: #3a5a9a; color: #cde0ff; }
23 #inspectBtn { position: relative; }
24 #inspectCount { position: absolute; top: -6px; right: -6px; background: #5b8cff; color: #fff; border-radius: 999px; font-size: 10px; min-width: 16px; height: 16px; padding: 0 4px; display: none; align-items: center; justify-content: center; }
25 #meter { font-variant-numeric: tabular-nums; padding: 6px 10px; border-radius: 7px; background: #10240f; color: #7ee787; border: 1px solid #1c4a1a; white-space: nowrap; }
26 #meter.zero { background: #131316; color: #8a8a90; border-color: #2a2a30; }
27 #bal { font-variant-numeric: tabular-nums; padding: 6px 10px; border-radius: 7px; background: #131316; color: #8a8a90; border: 1px solid #2a2a30; white-space: nowrap; cursor: pointer; }
28 #bal.funded { color: #cde0ff; border-color: #3a5a9a; }
29 #bal:hover { background: #1c1c20; }
30 #mbal { font-variant-numeric: tabular-nums; padding: 6px 10px; border-radius: 7px; background: #131316; color: #8a8a90; border: 1px solid #2a2a30; white-space: nowrap; }
31 #mbal.earning { color: #7ee787; border-color: #1c4a1a; }
32 .txlink { color: #7aa2ff; cursor: pointer; text-decoration: underline; }
33 #main { flex: 1; display: flex; min-height: 0; }
34 #findBar { position: absolute; top: 8px; right: 18px; z-index: 15; display: none; align-items: center; gap: 6px; padding: 6px 8px; background: #1e1e24; border: 1px solid #3a3a40; border-radius: 9px; box-shadow: 0 8px 28px rgba(0,0,0,.5); }
35 #findBar.open { display: flex; }
36 #findIn { width: 230px; padding: 6px 9px; border-radius: 6px; border: 1px solid #3a3a40; background: #131316; color: #e8e8ea; font-size: 13px; }
37 #findIn:focus { outline: none; border-color: #5b8cff; }
38 #findBar.none #findIn { border-color: #8a3a3a; }
39 #findCount { min-width: 74px; text-align: right; color: #9a9aa2; font-size: 12px; font-variant-numeric: tabular-nums; }
40 #findBar .btn { padding: 4px 9px; }
41 #pages { flex: 1; position: relative; min-width: 0; }
42 /* Inactive tabs stay full-size (so pages lay out correctly) but are hidden. */
43 .pg { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: #fff; }
44 .pg.hidden { visibility: hidden; pointer-events: none; }
45 #tabbar { display: flex; align-items: flex-end; gap: 4px; padding: 6px 10px 0; background: #1a1a1e; }
46 #tabs { display: flex; gap: 2px; min-width: 0; overflow: hidden; }
47 /* width (not just flex-basis) so the container is sized from 200px, not from the full title text */
48 .tab { display: flex; align-items: center; gap: 6px; flex: 0 1 200px; width: 200px; min-width: 72px; padding: 6px 6px 6px 12px; border-radius: 8px 8px 0 0; background: #202024; color: #8a8a90; cursor: pointer; user-select: none; }
49 .tab:hover { background: #232328; }
50 .tab.on { background: #26262b; color: #e8e8ea; }
51 .tab .tt { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
52 :root { --throb-accent: #5b8cff; --throb-ok: #7ee787; --throb-fail: #ff8a8a; }
53 .tab .th { flex: none; width: 16px; height: 16px; display: flex; align-items: center; justify-content: center; color: #7ee787; font-size: 11px; }
54 .th svg { width: 16px; height: 16px; display: block; }
55 .fav { width: 16px; height: 16px; display: block; object-fit: contain; }
56 #omni .or .ic .fav { display: inline-block; vertical-align: -3px; }
57 #bmPanel .bm .h .fav { display: inline-block; width: 12px; height: 12px; vertical-align: -2px; margin-right: 5px; }
58 .tab:not(.on) .th svg { opacity: .8; }
59 #sbar { flex: none; display: flex; align-items: center; gap: 6px; height: 28px; padding: 0 8px; background: #26262b; border-top: 1px solid #000; font-size: 12px; color: #c8c8ce; }
60 #histBtn.paused { color: #f0c674; }
61 #histBtn.off { color: #8a8a90; }
62 #plugBtn { max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
63 #viewBtns { display: contents; }
64 .viewBtn { display: inline-flex; align-items: center; gap: 2px; white-space: nowrap; }
65 #plugBtn.applied { color: #9fd8a8; }
66 #plugBtn.unapplied { color: #8a8a90; }
67 #plugBtn.offer { color: #8ab4ff; }
68 #sbar .btn, #sbar #bal, #sbar #mbal, #sbar #meter, #sbar #ctlChip { padding: 2px 9px; border-radius: 5px; font-size: 12px; line-height: 18px; }
69 #sbar #meter::before { content: "Paid "; opacity: .75; }
70 #sbar #mbal::before { content: "Merchant "; opacity: .75; }
71 #sbar #inspectCount { position: static; display: inline-flex; margin-left: 5px; vertical-align: 1px; }
72 #sleft { flex: 1; min-width: 0; display: flex; align-items: center; }
73 #status { display: none; align-items: center; gap: 7px; min-width: 0; }
74 #status.show { display: flex; }
75 #cn { display: none; padding: 2px 9px; background: #7a1f1f; color: #fff; border-radius: 5px; font-size: 12px; font-weight: 600; white-space: nowrap; }
76 #cn.show { display: block; }
77 #link { display: none; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
78 #link.show { display: block; }
79 #link.show + #status { display: none; } /* a link you point at is shown instead of the page's status, as it always was */
80 #link .k { font-weight: 600; margin-right: 6px; }
81 #link.same { color: #8fd19e; } /* same site: green */
82 #link.other { color: #f0c674; } /* another site: amber */
83 #status .ic { flex: none; width: 16px; height: 16px; }
84 #status .ic svg { width: 16px; height: 16px; display: block; }
85 #status .tx { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-variant-numeric: tabular-nums; }
86 .tab .x { opacity: .55; border-radius: 4px; padding: 0 5px; line-height: 16px; }
87 .tab .x:hover { background: #3a3a40; opacity: 1; }
88 #newTab { margin-bottom: 3px; padding: 2px 9px; }
89 #ctlChip { padding: 6px 10px; border-radius: 7px; background: #2a1f0a; color: #f0c674; border: 1px solid #5a4514; white-space: nowrap; font-size: 12px; }
90 #keyBtn { position: relative; }
91 #keyDot { position: absolute; top: -3px; right: -3px; width: 9px; height: 9px; border-radius: 50%; background: #55555c; border: 2px solid #26262b; }
92 #keyBtn.unlocked #keyDot { background: #7ee787; }
93 #offerbar { display: none; align-items: center; gap: 8px; padding: 7px 12px; background: #1a2033; border-bottom: 1px solid #2a3a66; color: #cde0ff; font-size: 12px; flex-wrap: wrap; }
94 #offerbar.show { display: flex; }
95 #offerbar .msg { flex: 1; min-width: 160px; }
96 #offerbar .msg b { color: #fff; font-weight: 600; }
97 .sbtn { padding: 4px 10px; border-radius: 6px; border: 1px solid #3a5a9a; background: #23324e; color: #cde0ff; cursor: pointer; font-size: 12px; }
98 .sbtn:hover { background: #2b3d5e; }
99 .sbtn.quiet { background: transparent; border-color: #3a3a40; color: #9a9aa2; }
100 #vaultPanel { position: fixed; top: 84px; right: 10px; width: 350px; max-height: calc(100vh - 100px); overflow: auto; z-index: 20; background: #1e1e24; border: 1px solid #3a3a40; border-radius: 10px; box-shadow: 0 10px 40px rgba(0,0,0,.55); padding: 12px; display: none; }
101 #vaultPanel.open { display: block; }
102 #vaultPanel h4 { margin: 0 0 8px; font-size: 13px; display: flex; align-items: center; gap: 8px; }
103 #vaultPanel h4 .sp { flex: 1; }
104 #vaultPanel .sec { margin: 12px 0 4px; color: #7a7a82; font-size: 10px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; }
105 #vaultPanel input { width: 100%; padding: 6px 9px; margin: 3px 0; border-radius: 6px; border: 1px solid #3a3a40; background: #131316; color: #e8e8ea; font-size: 12px; }
106 #vaultPanel input:focus { outline: none; border-color: #5b8cff; }
107 #vaultPanel .row2 { display: flex; gap: 6px; align-items: center; }
108 #vaultPanel .hint { color: #8a8a90; font-size: 11.5px; line-height: 1.5; margin: 4px 0; }
109 #vaultPanel .err { color: #ff9a9a; font-size: 11.5px; margin: 4px 0; }
110 .cred { display: flex; align-items: center; gap: 6px; padding: 6px 8px; margin: 3px 0; background: #17171b; border: 1px solid #2a2a30; border-radius: 7px; }
111 .cred .who { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
112 .cred .who small { display: block; color: #7a7a82; font-size: 10.5px; overflow: hidden; text-overflow: ellipsis; }
113 .cred .x { cursor: pointer; opacity: .5; padding: 0 4px; } .cred .x:hover { opacity: 1; color: #ff9a9a; }
114 /* ---- bookmarks ---- */
115 #starBtn { min-width: 34px; }
116 #starBtn.saved { color: #f0c674; --icon-accent: #f0c674; }
117 #starBtn.site { color: #f0c674; box-shadow: inset 0 0 0 1px #8a6a1a; } /* this page is not saved, another on the same site is */
118 #omni { position: fixed; z-index: 30; background: #1e1e24; border: 1px solid #3a3a40; border-radius: 9px; box-shadow: 0 12px 40px rgba(0,0,0,.6); padding: 5px; display: none; font-size: 13px; max-height: 70vh; overflow: auto; }
119 #omni.open { display: block; }
120 #omni .or { display: flex; align-items: baseline; gap: 9px; padding: 6px 9px; border-radius: 6px; cursor: pointer; color: #e8e8ea; white-space: nowrap; overflow: hidden; }
121 #omni .or.sel { background: #2f3a52; }
122 #omni .or .ic { width: 18px; text-align: center; flex: none; color: #9a9aa2; }
123 #omni .or .tt { overflow: hidden; text-overflow: ellipsis; }
124 #omni .or .u { color: #8a8a90; font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; flex: 1; min-width: 0; }
125 #omni .or .k { color: #9cc3ff; font-size: 11px; flex: none; margin-left: auto; }
126 #omni .of { color: #6f6f76; font-size: 11px; padding: 6px 9px 3px; border-top: 1px solid #2c2c32; margin-top: 4px; display: flex; gap: 8px; }
127 #omni .of a { color: #8fb3e8; cursor: pointer; }
128 #omni .or[data-kind="notice"] { color: #f0c674; cursor: default; white-space: normal; }
129 #omni .or[data-kind="notice"].link { cursor: pointer; }
130 #omni .or .p { color: #f08a7a; font-size: 11.5px; }
131 #chatLog .cmd { background: #15201a; border: 1px solid #24402c; border-radius: 9px; padding: 8px 10px; font-size: 12.5px; color: #d8e8dc; max-width: 96%; }
132 #chatLog .cmd .typed { font: 12px/1.4 ui-monospace, Menlo, monospace; color: #9cc3ff; word-break: break-word; }
133 #chatLog .cmd .s { color: #e8e8ea; margin-top: 3px; word-break: break-word; }
134 #chatLog .cmd a, .note a { color: #9cc3ff; cursor: pointer; text-decoration: underline; margin-left: 6px; }
135 #chatLog .cmd ol { margin: 6px 0 0; padding-left: 20px; } #chatLog .cmd li { margin: 2px 0; word-break: break-word; }
136 #chatLog .cmd li a { margin-left: 0; } #chatLog .cmd li .g { color: #8a8a90; font-size: 10.5px; text-transform: uppercase; letter-spacing: .03em; margin-right: 6px; }
137 #chatLog .cmd details { margin-top: 6px; } #chatLog .cmd summary { color: #8a8a90; cursor: pointer; font-size: 11.5px; }
138 #chatLog .cmd pre { margin: 4px 0 0; max-height: 260px; overflow: auto; white-space: pre-wrap; word-break: break-word; color: #c8c8cc; font: 11.5px/1.45 ui-monospace, Menlo, monospace; }
139 #bmPanel { position: fixed; top: 84px; right: 10px; width: 420px; max-height: calc(100vh - 100px); overflow: auto; z-index: 20; background: #1e1e24; border: 1px solid #3a3a40; border-radius: 10px; box-shadow: 0 10px 40px rgba(0,0,0,.55); padding: 12px; display: none; font-size: 12.5px; }
140 #bmPanel.open { display: block; }
141 #bmPanel h4 { margin: 0 0 4px; font-size: 13px; display: flex; align-items: center; gap: 8px; }
142 #bmPanel h4 .sp { flex: 1; }
143 #bmPanel .sub { color: #8a8a90; font-size: 11px; margin-bottom: 8px; }
144 #bmPanel input { width: 100%; box-sizing: border-box; padding: 6px 9px; margin: 2px 0 8px; border-radius: 6px; border: 1px solid #3a3a40; background: #131316; color: #e8e8ea; font-size: 12px; }
145 #bmPanel .bm { display: block; padding: 6px 4px; border-radius: 6px; cursor: pointer; }
146 #bmPanel .bm:hover { background: #26262b; }
147 #bmPanel .bm .t { color: #e8e8ea; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
148 #bmPanel .tabs2 { display: flex; gap: 6px; margin: 0 0 8px; }
149 #bmPanel .tabs2 button.on { background: #23324e; border-color: #3a5a9a; color: #cde0ff; }
150 #bmPanel .bm .s { color: #9a9aa2; font-size: 11px; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
151 #bmPanel .bm .h { color: #7a7a82; font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
152 #bmPanel .note { color: #8a8a90; font-size: 11.5px; line-height: 1.5; padding: 6px 2px; }
153 #bmPanel .err { color: #ff9a9a; font-size: 11.5px; padding: 4px 2px; }
154 #plugPanel { position: fixed; top: 84px; right: 10px; width: 420px; max-height: calc(100vh - 100px); overflow: auto; z-index: 20; background: #1e1e24; border: 1px solid #3a3a40; border-radius: 10px; box-shadow: 0 10px 40px rgba(0,0,0,.55); padding: 12px; display: none; font-size: 12.5px; }
155 #plugPanel.open { display: block; }
156 #plugPanel h4 { margin: 0 0 4px; font-size: 13px; display: flex; align-items: center; gap: 8px; }
157 #plugPanel h4 .sp { flex: 1; }
158 #plugPanel .sub, #plugPanel .note { color: #8a8a90; font-size: 11.5px; line-height: 1.5; margin: 4px 0 8px; }
159 #plugPanel .err { color: #ff9a9a; font-size: 11.5px; margin: 4px 0; }
160 #plugPanel .row2 { display: flex; gap: 6px; align-items: center; margin: 4px 0 8px; }
161 #plugPanel input[type=text] { flex: 1; min-width: 0; padding: 6px 9px; border-radius: 6px; border: 1px solid #3a3a40; background: #131316; color: #e8e8ea; font-size: 12px; }
162 #plugPanel input[type=text]:focus { outline: none; border-color: #5b8cff; }
163 #plugPanel .pl { padding: 8px 6px; border-radius: 6px; border: 1px solid #2c2c32; margin: 6px 0; }
164 #plugPanel .pl .t { color: #e8e8ea; display: flex; gap: 8px; align-items: center; }
165 #plugPanel .pl .t b { flex: 1; font-weight: 600; }
166 #plugPanel .pl .h { color: #8a8a90; font-size: 11px; margin-top: 3px; overflow-wrap: anywhere; }
167 #plugPanel .ask { border-color: #3a5a9a; background: #1b2233; }
168 #plugPanel a { color: #8ab4ff; text-decoration: none; }
169 #plugPanel a:hover { text-decoration: underline; }
170 #plugPanel label.sw { display: flex; gap: 6px; align-items: center; color: #c8c8cc; font-size: 12px; margin: 4px 0; }
171 /* ---- resource status ---- */
172 #resBtn { font-variant-numeric: tabular-nums; white-space: nowrap; }
173 #resBtn.warn { color: #f0c674; border-color: #5a4514; background: #2a1f0a; }
174 #resPanel { position: fixed; bottom: 36px; right: 10px; width: 420px; max-height: calc(100vh - 130px); overflow: auto; z-index: 20; background: #1e1e24; border: 1px solid #3a3a40; border-radius: 10px; box-shadow: 0 10px 40px rgba(0,0,0,.55); padding: 12px; display: none; font-size: 12px; }
175 #resPanel.open { display: block; }
176 #dlPanel { position: fixed; bottom: 36px; right: 10px; width: 440px; max-height: calc(100vh - 130px); overflow: auto; z-index: 20; background: #1e1e24; border: 1px solid #3a3a40; border-radius: 10px; box-shadow: 0 10px 40px rgba(0,0,0,.55); padding: 12px; display: none; font-size: 12px; }
177 #dlPanel.open { display: block; }
178 #dlPanel h4 { margin: 0 0 6px; font-size: 13px; display: flex; align-items: center; gap: 8px; }
179 #dlPanel h4 .sp { flex: 1; }
180 #dlPanel .empty { color: #8a8a90; line-height: 1.5; padding: 8px 2px; }
181 #dlPanel .dl { padding: 7px 2px; border-bottom: 1px solid #2a2a30; }
182 #dlPanel .dl .t1 { display: flex; align-items: center; gap: 6px; }
183 #dlPanel .dl .nm { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #e8e8ea; }
184 #dlPanel .dl a.nm { color: #8ab4ff; cursor: pointer; text-decoration: none; }
185 #dlPanel .dl a.nm:hover { text-decoration: underline; }
186 #dlPanel .dl.gone .nm { color: #8a8a90; text-decoration: line-through; }
187 #dlPanel .dl .t2 { color: #8a8a90; font-size: 11px; margin-top: 3px; font-variant-numeric: tabular-nums; }
188 #dlPanel .dl .t2 .bad { color: #ff9a9a; }
189 #dlPanel .dl .bar { height: 4px; border-radius: 2px; background: #131316; margin: 5px 0 2px; overflow: hidden; }
190 #dlPanel .dl .bar i { display: block; height: 100%; background: #5b8cff; }
191 #dlPanel .sbtn { padding: 3px 8px; font-size: 11px; }
192 #resPanel h4 { margin: 0 0 6px; font-size: 13px; display: flex; align-items: center; gap: 8px; }
193 #resPanel h4 .sp { flex: 1; }
194 #resPanel .sec { margin: 12px 0 4px; color: #7a7a82; font-size: 10px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; }
195 #resPanel .tot { color: #c8c8ce; line-height: 1.6; }
196 #resPanel .trow { padding: 6px 0; border-bottom: 1px solid #2a2a30; }
197 #resPanel .trow .t1 { display: flex; align-items: center; gap: 6px; }
198 #resPanel .trow .nm { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #e8e8ea; }
199 #resPanel .trow .mb { color: #c8c8ce; font-variant-numeric: tabular-nums; }
200 #resPanel .trow.hot .mb { color: #f0c674; font-weight: 700; }
201 #resPanel .bar { height: 4px; border-radius: 2px; background: #131316; margin: 4px 0 3px; overflow: hidden; }
202 #resPanel .bar i { display: block; height: 100%; background: #5b8cff; }
203 #resPanel .trow.hot .bar i { background: #f0c674; }
204 #resPanel .t2 { color: #8a8a90; font-size: 11px; }
205 #resPanel .hint { color: #8a8a90; font-size: 11px; line-height: 1.5; margin-top: 8px; }
206 /* ---- assistant chat panel ---- */
207 #chat { width: 380px; flex: none; background: #17171b; border-left: 1px solid #000; display: none; flex-direction: column; min-height: 0; }
208 #chat.open { display: flex; }
209 #chatHead { display: flex; align-items: center; gap: 6px; padding: 9px 12px; border-bottom: 1px solid #2a2a30; font-weight: 600; }
210 #chatHead .sub { color: #8a8a90; font-weight: 400; font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1 1 0; min-width: 0; }
211 #chatHead > span:first-child, #chatHead .sbtn { flex-shrink: 0; }
212 #chatHead select { flex: 0 1 auto; min-width: 0; }
213 #chatMode { max-width: 96px; }
214 #chatModel { max-width: 140px; text-overflow: ellipsis; }
215 #chatHead select { background: #131316; color: #c8c8ce; border: 1px solid #2a2a30; border-radius: 6px; font-size: 11px; padding: 2px 4px; }
216 #chatConn { padding: 6px 12px; border-bottom: 1px solid #2a2a30; display: flex; flex-direction: column; gap: 4px; font-size: 12px; }
217 #chatConn:empty { display: none; }
218 #chatConn .cn { display: flex; align-items: center; gap: 8px; color: #9a9aa2; }
219 #chatConn .cn .nm { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
220 #chatConn .cn .dot { width: 8px; height: 8px; border-radius: 50%; background: #55555c; flex: none; }
221 #chatConn .cn.on { color: #c8c8ce; } #chatConn .cn.on .dot { background: #7ee787; }
222 #chatConn .cn.wait .dot { background: #f0c674; }
223 #chatConn .er { color: #ff9a9a; font-size: 11.5px; line-height: 1.4; }
224 #chatLog { flex: 1; overflow: auto; padding: 10px; display: flex; flex-direction: column; gap: 8px; min-height: 0; }
225 #chatLog .m { padding: 8px 10px; border-radius: 9px; white-space: pre-wrap; word-break: break-word; line-height: 1.45; font-size: 13px; }
226 #chatLog .u { background: #23324e; color: #e8f0ff; align-self: flex-end; max-width: 92%; }
227 #chatLog .a { background: #1e1e24; border: 1px solid #2a2a30; color: #e8e8ea; max-width: 96%; }
228 #chatLog .step { color: #8a8a90; font-size: 11.5px; padding: 0 4px; font-family: ui-monospace, Menlo, monospace; word-break: break-word; }
229 #chatLog .step.ok { color: #7ee787; } #chatLog .step.bad { color: #ff9a9a; }
230 #chatLog .note { color: #8a8a90; font-size: 11.5px; text-align: center; padding: 2px 6px; }
231 #chatLog .ask { background: #1a2033; border: 1px solid #3a5a9a; border-radius: 9px; padding: 9px 10px; font-size: 12.5px; color: #cde0ff; }
232 #chatLog .ask.danger { background: #2a1f0a; border-color: #8a6a1a; color: #f4dca0; }
233 #chatLog .ask .what { margin: 4px 0 8px; color: #fff; word-break: break-word; white-space: pre-wrap; max-height: 260px; overflow-y: auto; }
234 #chatLog .m.a a { color: #8ab4ff; text-decoration: underline; cursor: pointer; word-break: break-all; }
235 #chatLog .step { white-space: pre-wrap; }
236 #chatLog .ask .tag { font-size: 10.5px; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; opacity: .85; }
237 #chatLog .ask .row2 { display: flex; gap: 6px; }
238 #chatLog .ask.done { opacity: .6; } #chatLog .ask.done .row2 { display: none; }
239 #chatEmpty { color: #6a6a72; padding: 22px 12px; text-align: center; font-size: 12px; line-height: 1.7; }
240 #chatForm { display: flex; gap: 6px; padding: 8px 10px 4px; border-top: 1px solid #2a2a30; }
241 #chatIn { flex: 1; resize: none; height: 54px; padding: 7px 9px; border-radius: 8px; border: 1px solid #3a3a40; background: #131316; color: #e8e8ea; font: inherit; font-size: 13px; }
242 #chatIn:focus { outline: none; border-color: #5b8cff; }
243 #chatPriv { color: #6a6a72; font-size: 10.5px; padding: 0 12px 8px; line-height: 1.4; }
244 #inspector { width: 400px; flex: none; background: #17171b; border-left: 1px solid #000; display: none; flex-direction: column; }
245 #inspector.open { display: flex; }
246 #insHead { display: flex; align-items: center; gap: 6px; padding: 10px 12px; border-bottom: 1px solid #2a2a30; font-weight: 600; }
247 #insHead .sub { color: #8a8a90; font-weight: 400; font-size: 12px; margin-left: auto; }
248 .insTab { border: 1px solid #2a2a30; background: #131316; color: #8a8a90; font-size: 11px; padding: 3px 9px; border-radius: 6px; cursor: pointer; font-weight: 600; }
249 .insTab.on { background: #23324e; border-color: #3a5a9a; color: #cde0ff; }
250 .histrow { display: flex; align-items: center; gap: 8px; padding: 8px 11px; background: #1e1e24; border: 1px solid #2a2a30; border-radius: 8px; }
251 .histrow .t { color: #7a7a82; font-variant-numeric: tabular-nums; font-size: 11px; white-space: nowrap; }
252 .histrow .h { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, Menlo, monospace; font-size: 11px; color: #c8c8ce; }
253 .histrow .p { font-variant-numeric: tabular-nums; }
254 #histTotal { padding: 8px 11px; color: #8a8a90; font-size: 12px; border-bottom: 1px solid #2a2a30; }
255 #insList { overflow: auto; padding: 8px; display: flex; flex-direction: column; gap: 8px; }
256 #insEmpty { color: #6a6a72; padding: 24px 12px; text-align: center; font-size: 12px; line-height: 1.6; }
257 .row { background: #1e1e24; border: 1px solid #2a2a30; border-radius: 9px; overflow: hidden; }
258 .row > .top { display: flex; align-items: center; gap: 8px; padding: 9px 11px; cursor: pointer; }
259 .row .path { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: ui-monospace, Menlo, monospace; font-size: 11.5px; color: #c8c8ce; }
260 .row .price { font-variant-numeric: tabular-nums; color: #e8e8ea; }
261 .pill { font-size: 10.5px; padding: 2px 8px; border-radius: 999px; white-space: nowrap; }
262 .pill.paid { background: #10240f; color: #7ee787; }
263 .pill.quoted { background: #201a0a; color: #f0c674; }
264 .pill.prompt { background: #1a2033; color: #9ab4ff; }
265 .pill.refused { background: #241010; color: #ff9a9a; }
266 .detail { display: none; border-top: 1px solid #2a2a30; padding: 9px 11px; font-size: 11.5px; }
267 .row.open .detail { display: block; }
268 .detail dl { display: grid; grid-template-columns: 96px 1fr; gap: 3px 10px; margin: 0; }
269 .detail dt { color: #7a7a82; }
270 .detail dd { margin: 0; font-family: ui-monospace, Menlo, monospace; font-size: 11px; word-break: break-all; color: #cdcdd3; }
271 .detail dd.warn { color: #f0c674; }
272 .detail .step { margin: 8px 0 2px; color: #8a8a90; font-weight: 600; letter-spacing: .03em; text-transform: uppercase; font-size: 10px; }
273 #toast { position: fixed; right: 14px; bottom: 40px; display: flex; flex-direction: column; gap: 6px; z-index: 10; }
274 .note { padding: 8px 12px; border-radius: 8px; font-size: 12px; box-shadow: 0 4px 16px rgba(0,0,0,.4); animation: in .15s ease-out; }
275 .note.paid { background: #10240f; color: #7ee787; border: 1px solid #1c4a1a; }
276 .note.quoted { background: #201a0a; color: #f0c674; border: 1px solid #4a3a12; }
277 .note.skipped { background: #241010; color: #ff9a9a; border: 1px solid #4a1a1a; }
278 #bar .lbl { margin-left: 3px; }
279 @media (max-width: 1100px) { #bar .lbl { display: none; } }
280 @keyframes in { from { opacity: 0; transform: translateY(6px); } }
281 </style>
282 </head>
283 <body>
284 <div id="tabbar">
285 <div id="tabs"></div>
286 <button class="btn" id="newTab" title="New tab (⌘T)" aria-label="New tab"><!--icon:new-tab--></button>
287 </div>
288 <div id="bar">
289 <button class="btn" id="back" aria-label="Back"><!--icon:back--></button>
290 <button class="btn" id="fwd" aria-label="Forward"><!--icon:forward--></button>
291 <button class="btn" id="reload" title="Reload (⌘R)" aria-label="Reload"></button>
292 <input id="url" placeholder="Search askrobots.com or enter a URL — http(s) requests are x402 pay-aware" spellcheck="false" />
293 <button class="btn" id="zoomBtn" hidden title="This site is zoomed. Click for actual size (⌘0); ⌘+ and ⌘− change it." aria-label="Page zoom"></button>
294 <button class="btn" id="keepBtn" title="Keep a copy of this page (what is on screen and its text) and close the tab"><!--icon:keep--><span class="lbl"> Keep</span></button>
295 <button class="btn" id="starBtn" title="Save this page to your askrobots bookmarks (one click)"><!--icon:save--><span class="lbl"> Save</span></button>
296 <button class="btn" id="galleryBtn" title="Open the local x402 test gallery (http://127.0.0.1:8899/) — start it with: node apps/browser/demo/x402-demo-server.mjs"><!--icon:tests--> x402 tests</button>
297 <button class="btn" id="tourBtn" title="Guided tour of the demo gallery"><!--icon:tour--> Tour</button>
298 <button class="btn" id="bmBtn" title="Your bookmarks (askrobots links)"><!--icon:bookmarks--><span class="lbl"> Bookmarks</span></button>
299 <button class="btn" id="chatBtn" title="Assistant chat (⌘J)"><!--icon:chat--><span class="lbl"> Chat</span></button>
300 <button class="btn" id="readerBtn" title="AI Reader — a clean reading view with a TL;DR (⌘⇧R)"><!--icon:reader--><span class="lbl"> Reader</span></button>
301 <button class="btn" id="keyBtn" title="Passwords"><!--icon:passwords--><span class="lbl"> Passwords</span><span id="keyDot"></span></button>
302 </div>
303 <div id="offerbar"></div>
304 <div id="vaultPanel"></div>
305 <div id="resPanel"></div>
306 <div id="dlPanel" role="dialog" aria-label="Downloads"></div>
307 <div id="bmPanel"></div>
308 <div id="plugPanel"></div>
309 <div id="main">
310 <div id="pages">
311 <div id="findBar" role="search">
312 <input id="findIn" placeholder="Find in page" aria-label="Find in page" spellcheck="false" />
313 <span id="findCount" aria-live="polite"></span>
314 <button class="btn" id="findPrev" title="Previous match (⌘⇧G or ⇧Enter)" aria-label="Previous match">↑</button>
315 <button class="btn" id="findNext" title="Next match (⌘G or Enter)" aria-label="Next match">↓</button>
316 <button class="btn" id="findClose" title="Close (Esc)" aria-label="Close find">✕</button>
317 </div>
318 </div>
319 <div id="chat">
320 <div id="chatHead">
321 <span>Assistant</span>
322 <span class="sub" id="chatSub"></span>
323 <select id="chatModel" title="Which model the assistant uses. Smarter models make fewer mistakes and cost more: 20× means about twenty times Haiku's cost per message. The reader's summaries keep their own model." aria-label="Assistant model" hidden></select>
324 <select id="chatMode" title="Ask: every action waits for your OK. Auto: only risky ones do (submitting, pressing Enter, opening a site that is not open).">
325 <option value="ask">Ask first</option>
326 <option value="auto">Auto (risky asks)</option>
327 </select>
328 <button class="sbtn quiet" id="chatClear" title="Start a new conversation">New</button>
329 <button class="sbtn quiet" id="chatClose" title="Close (⌘J)">✕</button>
330 </div>
331 <div id="chatConn"></div>
332 <div id="chatLog"></div>
333 <div id="chatForm">
334 <textarea id="chatIn" placeholder="Ask about this page, or tell me what to do…" spellcheck="true"></textarea>
335 <button class="sbtn" id="chatSend">Send</button>
336 </div>
337 <div id="chatPriv"></div>
338 </div>
339 <div id="inspector">
340 <div id="insHead">
341 <span>x402</span>
342 <button class="insTab on" id="tabPage">this page</button>
343 <button class="insTab" id="tabSession">session</button>
344 <span class="sub" id="insSub">this page</span>
345 </div>
346 <div id="insList"><div id="insEmpty">No x402 activity yet.<br />Load a page that returns 402 Payment Required — every challenge, decision, and payment shows up here.</div></div>
347 </div>
348 </div>
349 <!-- The status bar: what the page is doing on the left; what the browser is spending (memory, money) on the right. -->
350 <div id="sbar">
351 <div id="sleft"><div id="link"></div><div id="status"><span class="ic"></span><span class="tx"></span></div></div>
352 <div id="cn">Caller network ON · this browser fetches nothing itself</div>
353 <div id="ctlChip" style="display:none"></div>
354 <button class="btn" id="dlBtn" title="Downloads, and pages saved as PDF (⌘⇧J)">Downloads</button>
355 <button class="btn" id="plugBtn">Plugins</button>
356 <span id="viewBtns"></span>
357 <button class="btn" id="histBtn" style="display:none" title="History: the pages you visit are kept on your askrobots account, so you can find one later. Click to pause or resume."></button>
358 <button class="btn" id="resBtn" title="What the browser is using: memory, CPU, data, disk">Memory …</button>
359 <button class="btn" id="inspectBtn" title="x402 inspector: every payment request, decision and payment"><!--icon:x402--> x402<span id="inspectCount">0</span></button>
360 <div id="bal" class="chip" title="Your wallet USDC on Base Sepolia — click to copy address">◈ —</div>
361 <div id="mbal" title="Merchant wallet — live payments land here" style="display:none">🏪 —</div>
362 <button class="btn" id="refundBtn" title="Refund merchant → you" style="display:none">Refund</button>
363 <button class="btn" id="fundBtn" title="Copy address + open the faucet">Fund</button>
364 <div id="meter" class="zero" title="Total paid this session">$0.00</div>
365 </div>
366 <div id="toast"></div>
367
368 <script>
369 const $ = (id) => document.getElementById(id);
370 const urlInput = $("url");
371 let omniEditing = false; // true while you are typing in the address bar (pages loading meanwhile do not overwrite it)
372
373 // ---- tabs ------------------------------------------------------------
374 // One <webview> per tab. Each tab owns its inspector rows so payment history
375 // follows the page that caused it, not whichever tab happens to be in front.
376 const tabs = [];
377 let active = null;
378 let nextTabId = 1;
379 let rows = new Map(); // alias for the active tab's inspector rows
380 const owners = new Map(); // resource URL -> tab that triggered it
381
382 const shown = (u) => (u && !u.startsWith("about:") && !u.startsWith("data:") && !u.startsWith("dbb-reader:") ? u : "");
383
384 function newTab(url, activate = true) {
385 const wv = document.createElement("webview");
386 wv.className = "pg hidden";
387 wv.setAttribute("src", "about:blank");
388 wv.setAttribute("allowpopups", ""); // main's windowOpenHandler turns these into tabs
389 if (window.x402.webviewPreload) wv.setAttribute("preload", window.x402.webviewPreload);
390 const tab = { id: nextTabId++, wv, wcId: null, url: "", title: "", rows: new Map(), userClosed: false, paid: false, ready: false, pending: null, loading: false, saveOffer: null, fillOffer: null, waiters: [], navSeen: false,
391 el: null, reader: null, aiBusy: null, net: { reqs: new Map() }, lastActivity: 0, stats: { requests: 0, bytes: 0, hosts: new Set(), redirects: [], answered: 0, errorStatus: 0, cancelled: 0, failures: [], statusExamples: [] }, redirect: null, settledUntil: 0, failed: null, netError: null, thState: null, thText: "", find: { open: false, text: "", count: "" } };
392
393 // Navigate only once the webview is really ready — setting src at creation
394 // races its own init and can leave us stranded on about:blank.
395 wv.addEventListener("dom-ready", () => {
396 tab.ready = true;
397 try { tab.wcId = wv.getWebContentsId(); } catch {}
398 syncTabs(); // the automation API addresses pages by this id: publish it the moment it exists
399 if (tab.pending) { const p = tab.pending; tab.pending = null; wv.src = p; }
400 if (tab.focusWhenReady) { tab.focusWhenReady = false; focusPage(tab); }
401 });
402 wv.addEventListener("ipc-message", (e) => { if (e.channel === "link-hover") { tab.hoverLink = typeof e.args[0] === "string" ? e.args[0] : null; if (tab === active) paintLink(); } });
403 // ⌘← / ⌘→ pressed in the page (and not used by it): back and forward, like the buttons.
404 wv.addEventListener("ipc-message", (e) => { if (e.channel === "nav-key" && tab === active) $(e.args[0] === "forward" ? "fwd" : "back").click(); });
405 wv.addEventListener("ipc-message", (e) => {
406 if (e.channel !== "page-cmd" || tab !== active) return;
407 if (PAGE_CMDS.has(e.args[0])) pageCmd(e.args[0], "page");
408 else if (e.args[0] === "downloads" && !samePress("downloads", "page")) setDl(!dlOpen);
409 });
410 wv.addEventListener("did-start-loading", () => { tab.loading = true; refreshThrobber(tab); syncTabs(); if (tab === active) paintReload(); });
411 wv.addEventListener("did-fail-load", (e) => {
412 if (!e.isMainFrame || e.errorCode === -3) return; // -3 = aborted (a newer navigation replaced it)
413 tab.failed = { code: e.errorCode, desc: tab.netError || String(e.errorDescription || "").replace(/^net::/, "") };
414 refreshThrobber(tab);
415 });
416 wv.addEventListener("did-stop-loading", () => {
417 tab.loading = false;
418 refreshThrobber(tab);
419 if (tab === active) paintReload();
420 syncTabs();
421 if (tab.navSeen && tab.waiters.length) { // automation is waiting for this navigation to finish
422 const ws = tab.waiters; tab.waiters = [];
423 for (const w of ws) w({ loaded: true });
424 }
425 });
426 // Reset this tab's inspector when navigation STARTS — the page's payment events
427 // fire during the load, so resetting on did-navigate (after) would wipe them.
428 wv.addEventListener("did-start-navigation", (e) => {
429 if (e.isMainFrame) { tab.hoverLink = null; if (tab === active) paintLink(); } // the page we were pointing into is going away
430 if (!e.isMainFrame || e.isInPlace) return;
431 if (e.url.startsWith("chrome-error:")) return; // Chromium's own error page: keep the failure that caused it
432 if (e.url !== "about:blank") tab.navSeen = true;
433 if (shown(e.url)) tab.url = e.url;
434 tab.rows.clear();
435 tab.paid = false;
436 tab.failed = null; tab.netError = null; tab.redirect = null; tab.settledUntil = 0;
437 tab.lastActivity = Date.now(); // a navigation starting is network activity (it restarts the quiet clock)
438 // Requests that predate this navigation belong to the page we're leaving. Chromium doesn't tell
439 // our handler they were abandoned, so drop them here (the small margin keeps the new page's own
440 // first request, whose net event can race this one).
441 for (const [id, r] of tab.net.reqs) if (r.t0 < Date.now() - 150) tab.net.reqs.delete(id);
442 refreshThrobber(tab);
443 tab.userClosed = false; // new page — allow auto-open again
444 if (tab.find.count) { tab.find.count = ""; tab.find.none = false; if (tab === active) paintFind(); } // the matches were on the page we left
445 tab.fillOffer = null; // a save offer deliberately survives: login → redirect → "save?"
446 if (tab.saveOffer) { // …but not into a different site
447 let same = false;
448 try { same = new URL(e.url).origin === tab.saveOffer.origin; } catch {}
449 if (!same && shown(e.url)) { window.x402.vault.dismiss(tab.wcId); tab.saveOffer = null; }
450 }
451 renderTabs();
452 if (tab === active) renderOffer();
453 if (tab === active) renderInspector();
454 });
455 const onNav = (e) => {
456 if (tab === active) paintNav();
457 if (!shown(e.url)) return;
458 tab.url = e.url;
459 if (tab === active && !omniEditing) urlInput.value = e.url;
460 };
461 wv.addEventListener("did-navigate", onNav);
462 wv.addEventListener("did-navigate-in-page", (e) => { if (e.isMainFrame) onNav(e); });
463 for (const ev of ["dom-ready", "did-stop-loading"]) wv.addEventListener(ev, () => { if (tab === active) paintNav(); });
464 wv.addEventListener("page-title-updated", (e) => { tab.title = e.title; renderTabs(); });
465 wv.addEventListener("found-in-page", (e) => {
466 const r = e.result || {};
467 if (typeof r.matches !== "number") return;
468 tab.find.count = r.matches ? (r.activeMatchOrdinal || 1) + " of " + r.matches : "No matches";
469 tab.find.none = !r.matches;
470 if (tab === active) paintFind();
471 });
472 // a new page under an open find bar: look again once it has loaded
473 wv.addEventListener("did-stop-loading", () => { if (tab.find.open && tab.find.text && tab.find.loadedFor !== tab.url) { tab.find.loadedFor = tab.url; findRun(tab, 0); } });
474
475 $("pages").appendChild(wv);
476 tabs.push(tab);
477 if (url) tab.opening = true; // switchTo runs before go(): don't take it for an empty tab and focus the address bar
478 if (activate) switchTo(tab); else renderTabs();
479 tab.opening = false;
480 if (url) go(url, tab);
481 return tab;
482 }
483
484 // Give the keyboard to the page (space scrolls or pauses it), as other browsers do when a link opens a tab or you
485 // switch to one. Not while you are typing in the browser's own fields (⌘T focuses the address bar on purpose).
486 function focusPage(tab) {
487 if (tab !== active) return;
488 const a = document.activeElement;
489 if (a && a !== tab.wv && a.matches && a.matches("input, textarea, select, [contenteditable]")) return;
490 if (!tab.ready) { tab.focusWhenReady = true; return; }
491 try { tab.wv.focus(); } catch {}
492 }
493
494 function switchTo(tab) {
495 active = tab;
496 for (const t of tabs) t.wv.classList.toggle("hidden", t !== tab);
497 rows = tab.rows;
498 setUrlBar(tab);
499 renderTabs();
500 refreshThrobber(tab);
501 paintReload();
502 paintZoom();
503 paintNav();
504 renderInspector();
505 renderOffer();
506 if (vaultPanelOpen) renderVaultPanel();
507 paintFind();
508 if (!tab.url && !tab.opening) urlInput.focus();
509 else focusPage(tab);
510 }
511
512 // ---- find in page: the page's own find, per tab; nothing leaves the machine ----
513 const findBar = $("findBar"), findIn = $("findIn");
514 function paintFind() {
515 const f = active ? active.find : { open: false };
516 findBar.classList.toggle("open", !!f.open);
517 if (!f.open) return;
518 if (document.activeElement !== findIn) findIn.value = f.text;
519 $("findCount").textContent = f.text ? f.count : "";
520 findBar.classList.toggle("none", !!(f.text && f.none));
521 }
522 // dir 0: a new search for what is typed; 1 / -1: the next or previous match of it
523 function findRun(tab, dir) {
524 const q = tab.find.text;
525 if (!q) { try { tab.wv.stopFindInPage("clearSelection"); } catch {} tab.find.count = ""; tab.find.none = false; if (tab === active) paintFind(); return; }
526 if (dir === 0) tab.find.loadedFor = tab.url;
527 try { tab.wv.findInPage(q, { forward: dir !== -1, findNext: dir === 0 }); } catch {}
528 }
529 function openFind() {
530 if (!active) return;
531 active.find.open = true;
532 paintFind();
533 findIn.value = active.find.text;
534 findIn.focus(); findIn.select();
535 if (active.find.text) findRun(active, 0);
536 }
537 function closeFind() {
538 if (!active || !active.find.open) return;
539 active.find.open = false;
540 try { active.wv.stopFindInPage("keepSelection"); } catch {}
541 paintFind();
542 try { active.wv.focus(); } catch {}
543 }
544 function findStep(dir) {
545 if (!active) return;
546 if (!active.find.open || !active.find.text) return openFind();
547 findRun(active, dir);
548 }
549 findIn.addEventListener("input", () => { if (!active) return; active.find.text = findIn.value; findRun(active, 0); });
550 findIn.addEventListener("keydown", (e) => {
551 if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); findStep(e.shiftKey ? -1 : 1); }
552 else if (e.key === "Escape") { e.preventDefault(); closeFind(); }
553 });
554 $("findNext").onclick = () => findStep(1);
555 $("findPrev").onclick = () => findStep(-1);
556 $("findClose").onclick = () => closeFind();
557
558 function closeTab(tab) {
559 const i = tabs.indexOf(tab);
560 if (i < 0) return;
561 tab.wv.remove();
562 tabs.splice(i, 1);
563 if (tabs.length === 0) return void openNewTab(); // never leave the window tab-less
564 if (active === tab) switchTo(tabs[Math.min(i, tabs.length - 1)]);
565 else renderTabs();
566 }
567
568 function cycleTab(dir) {
569 if (tabs.length < 2) return;
570 switchTo(tabs[(tabs.indexOf(active) + dir + tabs.length) % tabs.length]);
571 }
572
573 // The address bar shows where a reader view came from, never the data: URL it is built on.
574 function setUrlBar(t) { if (typeof paintPlugBtn === "function") paintPlugBtn(); if (omniEditing && document.activeElement === urlInput && t === active) return; /* never overwrite what you are typing */ urlInput.value = t.reader ? "📖 Reader · " + t.reader : t.url; if (typeof paintStar === "function") paintStar(); }
575
576 function tabLabel(t) {
577 if (t.reader) return "📖 " + (t.title || hostOf(t.reader));
578 if (t.title) return t.title;
579 try { return new URL(t.url).host; } catch { return t.url ? t.url : "New Tab"; }
580 }
581
582 // The strip is reconciled, not rebuilt: replacing a tab's node would restart its throbber's
583 // SMIL clock on every title or state change.
584 // ---- site icons: data: URLs from the main process (favicons.ts), by host. Nothing is loaded from a site here. ----
585 const favicons = new Map();
586 function iconFor(url) {
587 if (!url || !/^https?:/i.test(url)) return null;
588 try { return favicons.get(new URL(url).hostname.toLowerCase()) || null; } catch { return null; }
589 }
590 function favImg(src) { const i = document.createElement("img"); i.className = "fav"; i.alt = ""; i.src = src; i.draggable = false; return i; }
591 function faviconsChanged() { renderTabs(); if (omni.classList.contains("open")) omniRender(); if (bmOpen) renderBm(); }
592 if (window.x402.favicons) {
593 window.x402.favicons.all().then((all) => { for (const [h, i] of Object.entries(all || {})) favicons.set(h, i); faviconsChanged(); }).catch(() => {});
594 window.x402.favicons.onUpdate((u) => { if (!u || !u.host) return; if (u.icon) favicons.set(u.host, u.icon); else favicons.delete(u.host); faviconsChanged(); });
595 }
596
597 function makeTabEl(t) {
598 const el = document.createElement("div");
599 el.className = "tab";
600 const th = document.createElement("span"); th.className = "th";
601 const tt = document.createElement("span"); tt.className = "tt";
602 const x = document.createElement("span"); x.className = "x"; x.textContent = "×";
603 x.onclick = (e) => { e.stopPropagation(); closeTab(t); };
604 el.append(th, tt, x);
605 el.onclick = () => switchTo(t);
606 el.onauxclick = (e) => { if (e.button === 1) closeTab(t); };
607 return el;
608 }
609
610 function renderTabs() {
611 const bar = $("tabs");
612 const keep = new Set();
613 for (const t of tabs) {
614 if (!t.el) t.el = makeTabEl(t);
615 keep.add(t.el);
616 t.el.classList.toggle("on", t === active);
617 t.el.title = t.thText || t.url || "New Tab";
618 t.el.querySelector(".tt").textContent = tabLabel(t);
619 if (t.el.parentNode !== bar) bar.appendChild(t.el);
620 paintThrobber(t.el.querySelector(".th"), t.thState, t.paid, iconFor(t.url));
621 }
622 for (const el of [...bar.children]) if (!keep.has(el)) el.remove();
623 document.title = active ? tabLabel(active) + " — dbbasic-browser" : "dbbasic-browser";
624 syncTabs();
625 }
626
627 // ---- what is this tab doing? (throbbers + status line) -------------------------------------
628 // Driven by REAL signals only: the webview's load events, per-request progress from our own
629 // transport (request out, headers in, bytes, redirect, error), and the x402 engine's events.
630 // DNS/TCP/TLS are invisible to us (they happen inside Chromium), so they show as "waiting".
631 const THROBBERS = /*__THROBBERS__*/ {};
632 // Toolbar icons (assets/icons/svg), inlined at build time like the throbbers. Our own constant markup, never page text.
633 const ICONS = /*__ICONS__*/ {};
634 function iconEl(name) { const t = document.createElement("template"); t.innerHTML = ICONS[name] || ""; return t.content.firstChild || document.createTextNode(""); }
635 // Downloads are not tied to one tab: the status line shows the most recent active one, whichever tab is in front.
636 const downloads = new Map();
637 function downloadStatus() {
638 const active = [...downloads.values()].filter((d) => d.state === "progressing" || d.state === "paused");
639 if (!active.length) return null;
640 const d = active[active.length - 1];
641 const of = d.total > 0 ? " of " + fmtBytes(d.total) : "";
642 const more = active.length > 1 ? " (+" + (active.length - 1) + " more)" : "";
643 return { state: "receiving", text: "⬇ Downloading " + d.name + " — " + fmtBytes(d.received) + of + more };
644 }
645 const SLOW_MS = 6000;
646 // Default: follow the OS "Reduce motion" setting. View ▸ Loading Animations can override it
647 // (Always / Never) for anyone who wants to.
648 const reducedMotionMQ = matchMedia("(prefers-reduced-motion: reduce)");
649 let motionMode = "system";
650 try { motionMode = localStorage.getItem("dbb.motion") || "system"; } catch {}
651 const animating = () => motionMode === "always" || (motionMode === "system" && !reducedMotionMQ.matches);
652 function applyMotion() {
653 for (const svg of document.querySelectorAll(".th svg, #status .ic svg")) {
654 if (animating()) svg.unpauseAnimations && svg.unpauseAnimations();
655 else svg.pauseAnimations && svg.pauseAnimations();
656 }
657 }
658 function setMotionMode(m) {
659 if (!["always", "system", "never"].includes(m)) return;
660 motionMode = m;
661 try { localStorage.setItem("dbb.motion", m); } catch {}
662 window.x402.reportMotion(m); // so the View menu's radio check follows
663 applyMotion();
664 }
665 reducedMotionMQ.addEventListener("change", applyMotion);
666 window.x402.reportMotion(motionMode);
667 const fmtBytes = (n) => (n < 1024 ? n + " B" : n < 1048576 ? (n / 1024).toFixed(0) + " KB" : (n / 1048576).toFixed(1) + " MB");
668
669 function computeState(tab) {
670 const now = Date.now();
671 const reqs = [...tab.net.reqs.values()];
672 const host = hostOf(tab.url) || (reqs[0] && hostOf(reqs[0].url)) || "";
673 const rows = [...tab.rows.values()];
674 const price = (r) => (r.quote ? r.quote.price : "");
675 if (tab.failed) {
676 if (/INTERNET_DISCONNECTED|NETWORK_CHANGED/.test(tab.failed.desc)) return { state: "offline", text: "You're offline" };
677 return { state: "failed", text: "Couldn't load " + (host || "the page") + ": " + (tab.failed.desc || "error") };
678 }
679 if (tab.aiBusy) return { state: "summarizing", text: "Summarizing with " + tab.aiBusy + "…" };
680 const pend = rows.find((r) => r.decision === "prompt" && !r.outcome);
681 if (pend) return { state: "pay-pending", text: price(pend) + " payment needed on " + hostOf(pend.resource) + " — waiting for your approval" };
682 const paying = rows.find((r) => r.decision === "allow" && !r.outcome);
683 if (paying) return { state: "pay-paying", text: "Paying " + price(paying) + " to " + hostOf(paying.resource) + "…" };
684 if (tab.settledUntil > now) {
685 const paid = rows.filter((r) => r.outcome === "paid").pop();
686 return { state: "pay-settled", text: "Paid " + (paid ? price(paid) : "") + " ✓" };
687 }
688 if (tab.loading) { // network phases only mean something while the page is loading
689 if (/\.within\.website/.test(tab.url) || reqs.some((r) => r.url.includes(".within.website"))) {
690 return { state: "challenge", text: "Checking your browser with " + host + " (a short proof of work)…" };
691 }
692 if (tab.redirect && tab.redirect.until > now) return { state: "redirecting", text: "Redirecting to " + tab.redirect.to };
693 const waiting = reqs.filter((r) => r.phase === "waiting");
694 if (waiting.length) {
695 const age = now - Math.min(...waiting.map((r) => r.t0));
696 const secs = (age / 1000).toFixed(age >= 10000 ? 0 : 1);
697 const h = hostOf(waiting[0].url);
698 return age > SLOW_MS ? { state: "slow", text: "Still waiting for " + h + "… " + secs + "s" } : { state: "waiting", text: "Waiting for " + h + "… " + secs + "s" };
699 }
700 const recv = reqs.filter((r) => r.phase === "receiving");
701 if (recv.length) return { state: "receiving", text: "Receiving from " + hostOf(recv[0].url) + "… " + fmtBytes(recv.reduce((a, r) => a + (r.bytes || 0), 0)) };
702 return { state: "connecting", text: "Connecting to " + host + "…" };
703 }
704 return { state: null, text: "" };
705 }
706
707 function paintThrobber(slot, state, paid, icon) {
708 const key = state || (paid ? "paid" : icon ? "icon:" + icon.length + ":" + icon.slice(-24) : "");
709 if (slot.dataset.k === key) return; // same state: leave the node alone so its animation keeps running
710 slot.dataset.k = key;
711 slot.textContent = "";
712 if (state && THROBBERS[state]) {
713 slot.innerHTML = THROBBERS[state]; // trusted: our own SVGs, inlined at build time
714 const svg = slot.firstElementChild;
715 if (!animating() && svg && svg.pauseAnimations) svg.pauseAnimations();
716 } else if (paid) slot.textContent = "⚡";
717 else if (icon) slot.appendChild(favImg(icon));
718 }
719
720 // The address of the link under the pointer, in the status area, coloured by whether it stays on this site.
721 // (Approximation: same host, or same last two labels — three for names like example.co.uk.)
722 const siteOf = (host) => { const p = host.split("."); const n = p.length >= 3 && p[p.length - 1].length === 2 && p[p.length - 2].length <= 3 ? 3 : 2; return p.slice(-n).join("."); };
723 function sameSite(a, b) {
724 try { const x = new URL(a), y = new URL(b); return x.hostname === y.hostname || (/^https?:$/.test(x.protocol) && /^https?:$/.test(y.protocol) && siteOf(x.hostname) === siteOf(y.hostname)); } catch { return false; }
725 }
726 function paintLink() {
727 const el = $("link"), href = active && active.hoverLink;
728 if (!href) { el.className = ""; el.textContent = ""; return; }
729 let cur = ""; try { cur = active.wv.getURL(); } catch {}
730 const same = sameSite(href, cur);
731 el.className = "show " + (same ? "same" : "other");
732 const k = document.createElement("span"); k.className = "k"; k.textContent = same ? "● this site" : "↗ other site"; // not colour alone
733 el.replaceChildren(k, document.createTextNode(href));
734 el.title = href;
735 }
736
737 function refreshThrobber(tab) {
738 const { state, text } = computeState(tab);
739 const changed = tab.thState !== state;
740 tab.thState = state;
741 tab.thText = text;
742 if (tab.el) paintThrobber(tab.el.querySelector(".th"), state, tab.paid, iconFor(tab.url));
743 if (tab === active) {
744 const st = $("status");
745 const dl = state ? null : downloadStatus(); // the tab's own state wins; otherwise show a download in progress
746 const shownState = state || (dl && dl.state);
747 st.classList.toggle("show", !!shownState);
748 if (shownState) { paintThrobber(st.querySelector(".ic"), shownState, false); st.querySelector(".tx").textContent = state ? text : dl.text; }
749 }
750 if (tab === active) paintLink(); // keep the link bar clear of the status line
751 if (changed) syncTabs();
752 }
753 setInterval(() => { for (const t of tabs) { for (const [id, r] of t.net.reqs) if (Date.now() - r.last > (r.caller ? 130000 : 20000)) t.net.reqs.delete(id); refreshThrobber(t); } }, 250);
754
755 // A response that is held open on purpose: an event stream, or a body gone quiet with no Content-Length.
756 // A finished page can hold one open, so these must not count as "still loading" (see settle.ts).
757 const STREAM_IDLE_MS = 1000;
758 const isEventStream = (r) => /text\/event-stream/i.test(r.contentType || "");
759 const isLongLived = (r, now) => r.phase === "receiving" && (isEventStream(r) || (r.total == null && now - r.last > STREAM_IDLE_MS));
760
761 // An address without its query or fragment (those can hold tokens), cut short: enough to name what failed.
762 const addrOnly = (u) => String(u || "").split(/[?#]/)[0].slice(0, 200);
763 window.x402.onNetEvent((e) => {
764 if (e.type === "start") owners.delete(e.url); // a new request begins a new lifecycle
765 const tab = ownerOf(e.url);
766 const reqs = tab.net.reqs;
767 const now = Date.now();
768 if (e.type === "start") {
769 reqs.set(e.id, { url: e.url, t0: now, last: now, phase: "waiting", bytes: 0 });
770 tab.stats.requests++;
771 try { tab.stats.hosts.add(new URL(e.url).host); } catch {}
772 tab.lastActivity = now;
773 } else {
774 const r = reqs.get(e.id);
775 if (!r) return;
776 // Progress on an event stream is not "the page is still loading": it must not reset the quiet clock.
777 if (!(e.type === "progress" && isEventStream(r))) tab.lastActivity = now;
778 r.last = now;
779 if (e.type === "caller") r.caller = true; // parked: waiting on a caller-supplied network layer
780 else if (e.type === "headers") {
781 r.phase = "receiving"; r.total = e.total; r.contentType = e.contentType;
782 r.answered = true; tab.stats.answered++; // a response arrived (what the status was is counted apart)
783 if (e.status >= 400) { r.errStatus = true; tab.stats.errorStatus++; if (tab.stats.statusExamples.length < 10) tab.stats.statusExamples.push({ url: addrOnly(r.url), status: e.status }); }
784 }
785 else if (e.type === "progress") r.bytes = e.bytes;
786 else if (e.type === "redirect") { tab.stats.answered++; reqs.delete(e.id); tab.redirect = { to: e.location, until: now + 700 }; tab.stats.redirects.push({ status: e.status, to: e.location }); }
787 else if (e.type === "end") { reqs.delete(e.id); tab.stats.bytes += e.bytes || 0; }
788 else if (e.type === "error") {
789 // A request that ends in an error is a failure, even if its response had started (then it is not also "answered").
790 if (r.answered) { tab.stats.answered--; if (r.errStatus) tab.stats.errorStatus--; }
791 if (e.error === "aborted") tab.stats.cancelled++; // the page itself gave up on it
792 else if (tab.stats.failures.length < 500) tab.stats.failures.push({ kind: e.failureKind || null, error: String(e.error || "").replace(/^net::/, "").slice(0, 120), url: addrOnly(r.url) });
793 reqs.delete(e.id); tab.netError = String(e.error || "").replace(/^net::/, ""); }
794 }
795 refreshThrobber(tab);
796 });
797
798 // Mirror tab state to main so the automation API can address tabs by id.
799 function syncTabs() {
800 window.x402.syncTabs(tabs.map((t) => ({ id: t.id, wcId: t.wcId, url: t.url, title: t.title, active: t === active, loading: t.loading, state: t.thState })));
801 }
802
803 // ---- automation (see control.ts) ---------------------------------------
804 // Resolves when the NEXT navigation in this tab finishes (or times out).
805 function waitLoad(tab, ms = 30000) {
806 return new Promise((resolve) => {
807 tab.navSeen = false;
808 const timer = setTimeout(() => { tab.waiters = tab.waiters.filter((w) => w !== done); resolve({ timeout: true }); }, ms);
809 const done = (r) => { clearTimeout(timer); resolve(r); };
810 tab.waiters.push(done);
811 });
812 }
813 async function tabReady(tab) {
814 for (let i = 0; i < 100 && tab.wcId == null; i++) await new Promise((r) => setTimeout(r, 50));
815 return tab.wcId != null;
816 }
817 const summary = (t, extra) => ({ id: t.id, wcId: t.wcId, url: t.url, title: t.title, ...extra });
818 let peekBack = null;
819 window.x402.onControl(async (op, a) => {
820 const tab = a.id != null ? tabs.find((t) => t.id === a.id) : null;
821 if (a.id != null && !tab) throw new Error("no such tab: " + a.id);
822 switch (op) {
823 case "tab.new": {
824 const t = newTab(null, a.activate !== false);
825 if (a.reader) t.reader = String(a.reader);
826 await tabReady(t);
827 if (a.url) { const w = waitLoad(t); go(a.url, t); if (a.wait) return summary(t, await w); }
828 return summary(t, {});
829 }
830 case "tab.close": closeTab(tab); return { closed: a.id };
831 case "tab.activate": switchTo(tab); return summary(tab, {});
832 // Card view's "More posts": show the tab being read while it scrolls (a hidden page doesn't load more), then
833 // go back to the tab that asked.
834 case "tab.peek": {
835 const t = tabs.find((x) => x.wcId === a.wcId);
836 if (a.on) { peekBack = active; if (t) switchTo(t); }
837 else if (peekBack && tabs.includes(peekBack)) { switchTo(peekBack); peekBack = null; }
838 return { ok: !!t };
839 }
840 case "tab.goto": {
841 if (a.wait === "start") {
842 // Return once the navigation has actually BEGUN (not finished), so a settle that follows can't run
843 // against the page we are leaving.
844 tab.navSeen = false;
845 go(a.url, tab);
846 for (let i = 0; i < 250 && !tab.navSeen; i++) await new Promise((r) => setTimeout(r, 20));
847 return summary(tab, {});
848 }
849 const w = waitLoad(tab); go(a.url, tab); return summary(tab, a.wait ? await w : {});
850 }
851 case "tab.back": { const w = waitLoad(tab); tab.wv.goBack(); return summary(tab, a.wait ? await w : {}); }
852 case "tab.forward": { const w = waitLoad(tab); tab.wv.goForward(); return summary(tab, a.wait ? await w : {}); }
853 case "tab.reload": { const w = waitLoad(tab); tab.wv.reload(); return summary(tab, a.wait ? await w : {}); }
854 case "tab.waitLoad": return summary(tab, await waitLoad(tab, a.ms || 15000));
855 case "tab.netState": {
856 // What the network layer sees for this tab right now, for "has the page finished loading?" (settle.ts)
857 const now = Date.now();
858 const rows = [...tab.rows.values()];
859 const pay = rows.some((x) => x.decision === "prompt" && !x.outcome) ? "pending" : rows.some((x) => x.outcome === "skipped" || (x.decision === "deny" && !x.outcome)) ? "refused" : null;
860 return {
861 url: tab.url, title: tab.title, state: tab.thState, pay,
862 inFlight: [...tab.net.reqs.values()].map((x) => ({ url: x.url, phase: x.phase, ageMs: now - x.t0, longLived: isLongLived(x, now) })),
863 sinceActivityMs: now - (tab.lastActivity || now),
864 stats: { requests: tab.stats.requests, bytes: tab.stats.bytes, hosts: [...tab.stats.hosts], redirects: tab.stats.redirects, answered: tab.stats.answered, errorStatus: tab.stats.errorStatus, cancelled: tab.stats.cancelled, failures: tab.stats.failures, statusExamples: tab.stats.statusExamples },
865 };
866 }
867 default: throw new Error("unknown op " + op);
868 }
869 });
870 window.x402.onControlStatus(({ port }) => {
871 const c = $("ctlChip");
872 c.style.display = "";
873 c.textContent = "🤖 :" + port;
874 c.title = "Automation API is listening on 127.0.0.1:" + port + " - this browser can be remote-controlled";
875 });
876
877 // A new tab opens the homepage (askrobots.com by default), like any browser's new-tab page.
878 // The automation API's tabs.new stays blank unless given a url, so scripts get a clean slate.
879 function openNewTab() {
880 const t = newTab(window.x402.homepage || null);
881 urlInput.focus();
882 urlInput.select();
883 return t;
884 }
885 $("newTab").onclick = () => openNewTab();
886
887 // AI Reader: a clean reading view of the active page with a TL;DR on top. The text is read in the page
888 // and the view is built in the main process; this document never touches page content or API keys.
889 async function openReader() {
890 if (!active || active.wcId == null || !active.url) { toast("skipped", "Open a web page first"); return; }
891 const r = await window.x402.reader.open({ wcId: active.wcId });
892 if (!r.ok) toast("skipped", "📖 " + (r.message || "Couldn't open the reader"), 5000);
893 }
894 $("readerBtn").onclick = () => openReader();
895 // Card view: the page's posts as dense cards in a new tab (X for now). The page is scrolled while it is read.
896 let cardsBusy = false;
897 async function openCards(plugin) {
898 if (!active || active.wcId == null || !active.url) { toast("skipped", "Open a web page first"); return; }
899 if (cardsBusy) return;
900 cardsBusy = true;
901 try {
902 const r = await window.x402.cards.open({ wcId: active.wcId, plugin });
903 if (!r.ok) toast("skipped", "▦ " + (r.message || "Couldn't make a card view"), 5000);
904 else if (r.promoted) toast("quoted", "▦ " + r.posts + " posts as cards · " + r.promoted + " promoted hidden", 4000);
905 } finally { cardsBusy = false; }
906 }
907
908 // Which tab does a payment event belong to? Events carry only a resource URL, so:
909 // reuse the earlier mapping; else among loading tabs prefer the one on the same
910 // origin, then the active one; else fall back to the active tab.
911 function ownerOf(resource) {
912 const prior = owners.get(resource);
913 if (prior && tabs.includes(prior)) return prior;
914 let origin = "";
915 try { origin = new URL(resource).origin; } catch {}
916 const loading = tabs.filter((t) => t.loading);
917 const sameOrigin = loading.find((t) => { try { return new URL(t.url).origin === origin; } catch { return false; } });
918 const t = sameOrigin || (loading.includes(active) ? active : loading[0]) || active;
919 owners.set(resource, t);
920 return t;
921 }
922
923
924 // ---- assistant chat ------------------------------------------------------------------------------
925 // Everything shown here that came from a model or a page is put in with textContent, never as HTML.
926 const chatEl = $("chat"), chatLog = $("chatLog"), chatIn = $("chatIn");
927 let chatOpen = false, chatBusy = false, chatSeen = 0, chatInfo = null;
928 const askCards = new Map();
929 const chatPush = (cls, text, parent = chatLog) => {
930 const d = document.createElement("div");
931 d.className = cls;
932 d.textContent = text;
933 parent.appendChild(d);
934 chatLog.scrollTop = chatLog.scrollHeight;
935 return d;
936 };
937 // Web addresses in the assistant's replies become links that open in a new tab (https only; the text stays text).
938 function linkify(el, text) {
939 let at = 0;
940 for (const m of text.matchAll(/https:\/\/[^\s<>"'`]+/g)) {
941 const url = m[0].replace(/[.,;:!?)\]]+$/, "");
942 el.append(text.slice(at, m.index));
943 const a = document.createElement("a"); a.href = url; a.textContent = url; a.title = "Open in a new tab";
944 a.onclick = (ev) => { ev.preventDefault(); newTab(url); };
945 el.append(a);
946 at = m.index + url.length;
947 }
948 el.append(text.slice(at));
949 chatLog.scrollTop = chatLog.scrollHeight;
950 }
951 function chatSetBusy(b) {
952 chatBusy = b;
953 $("chatSend").textContent = b ? "Stop" : "Send";
954 $("chatSend").className = b ? "sbtn quiet" : "sbtn";
955 }
956 function chatEmptyState() {
957 chatLog.textContent = "";
958 const e = document.createElement("div");
959 e.id = "chatEmpty";
960 e.textContent = !chatInfo || !chatInfo.available
961 ? (chatInfo && chatInfo.callerNetworkOn ? "The assistant is switched off while the caller network is on." : "No AI is set up yet. Put ANTHROPIC_API_KEY or OPENAI_API_KEY in ~/.dbbasic/env, or set DBB_AI_BASE_URL to a model on this machine or your network, then restart.")
962 : "Ask about the page you are on, or tell me what to do: find something, fill in a form, open a page. You approve each action before it happens.";
963 chatLog.appendChild(e);
964 }
965 function chatRender(e) {
966 if (e.seq <= chatSeen) return;
967 chatSeen = e.seq;
968 const empty = $("chatEmpty"); if (empty) empty.remove();
969 if (e.kind === "user") chatPush("m u", e.text);
970 else if (e.kind === "text") linkify(chatPush("m a", ""), e.text);
971 else if (e.kind === "tool-start") { const d = chatPush("step", "▸ " + e.summary); d.dataset.id = e.id; }
972 else if (e.kind === "tool-end") chatPush("step " + (e.ok ? "ok" : "bad"), (e.ok ? " ✓ " : " ✗ ") + e.name + " — " + e.note);
973 else if (e.kind === "tool-denied") chatPush("step bad", " ✗ not done — " + e.reason);
974 else if (e.kind === "confirm") {
975 if (!chatOpen) setChat(true);
976 const card = document.createElement("div");
977 card.className = "ask" + (e.danger ? " danger" : "");
978 const tag = document.createElement("div"); tag.className = "tag"; tag.textContent = e.danger ? "Needs your OK — risky" : "Needs your OK";
979 const what = document.createElement("div"); what.className = "what"; what.textContent = e.summary;
980 const row = document.createElement("div"); row.className = "row2";
981 const yes = document.createElement("button"); yes.className = "sbtn"; yes.textContent = "Do it";
982 const no = document.createElement("button"); no.className = "sbtn quiet"; no.textContent = "Skip";
983 yes.onclick = () => window.x402.chat.confirm(e.id, true);
984 no.onclick = () => window.x402.chat.confirm(e.id, false);
985 row.append(yes, no); card.append(tag, what, row);
986 chatLog.appendChild(card); chatLog.scrollTop = chatLog.scrollHeight;
987 askCards.set(e.id, card);
988 }
989 else if (e.kind === "confirm-settled") { const c = askCards.get(e.id); if (c) { c.classList.add("done"); const t = c.querySelector(".tag"); if (t) t.textContent = e.ok ? "Approved" : "Skipped"; askCards.delete(e.id); } }
990 else if (e.kind === "done") {
991 chatSetBusy(false);
992 const why = { answered: "", stopped: "Stopped.", "max-steps": "I stopped after too many steps. Ask me to continue if you want.", length: "The answer was cut off (too long).", refused: "The model declined to help with that.", error: "Something went wrong: " + (e.message || "unknown error") }[e.reason];
993 if (why) chatPush("note", why);
994 }
995 else if (e.kind === "cleared") chatEmptyState();
996 else if (e.kind === "command") { chatLog.appendChild(cmdCard(e)); chatLog.scrollTop = chatLog.scrollHeight; }
997 }
998 // A command you ran from the address bar: what you typed, what it means, links to what it made or found, and the answer as data.
999 function cmdCard(e) {
1000 const card = document.createElement("div"); card.className = "cmd";
1001 const typed = document.createElement("div"); typed.className = "typed"; typed.textContent = e.typed;
1002 const s = document.createElement("div"); s.className = "s"; s.textContent = "✓ " + e.sentence;
1003 if (e.page) s.appendChild(openLink(e.page));
1004 card.append(typed, s);
1005 if (e.items && e.items.length) {
1006 const ol = document.createElement("ol");
1007 for (const it of e.items) {
1008 const li = document.createElement("li");
1009 if (it.group) { const g = document.createElement("span"); g.className = "g"; g.textContent = it.group; li.appendChild(g); }
1010 if (it.page) li.appendChild(openLink(it.page, it.title)); else li.appendChild(document.createTextNode(it.title));
1011 ol.appendChild(li);
1012 }
1013 card.appendChild(ol);
1014 }
1015 if (e.details) {
1016 const d = document.createElement("details");
1017 if (e.readOnly && !(e.items && e.items.length)) d.open = true;
1018 const sm = document.createElement("summary"); sm.textContent = "answer from askrobots";
1019 const pre = document.createElement("pre"); pre.textContent = e.details;
1020 d.append(sm, pre); card.appendChild(d);
1021 }
1022 return card;
1023 }
1024 // Only ever an address the main process checked is on the service's own site; it opens in a new tab.
1025 function openLink(url, text) {
1026 const a = document.createElement("a"); a.textContent = text || "Open"; a.title = url;
1027 a.onclick = (ev) => { ev.preventDefault(); newTab(url); };
1028 return a;
1029 }
1030 async function chatRefresh() {
1031 chatInfo = await window.x402.chat.state();
1032 const models = chatInfo.available ? chatInfo.models || [] : [];
1033 const pickModel = $("chatModel");
1034 pickModel.hidden = models.length < 2;
1035 if (!pickModel.hidden) {
1036 pickModel.replaceChildren(...models.map((m) => { const o = document.createElement("option"); o.value = m.id; o.textContent = m.label; return o; }));
1037 pickModel.value = chatInfo.modelId;
1038 }
1039 $("chatSub").textContent = !chatInfo.available ? "off" : pickModel.hidden ? chatInfo.model + (chatInfo.endpoint ? " @ " + chatInfo.endpoint : "") : "";
1040 $("chatMode").value = chatInfo.mode;
1041 $("chatPriv").textContent = chatInfo.available
1042 ? "Your messages, what the assistant reads from your pages, and from services you connect (contacts, notes…) go to " + (chatInfo.endpoint || (chatInfo.provider === "anthropic" ? "Anthropic" : "OpenAI")) + ". Passwords, card and code fields are never filled."
1043 : "";
1044 chatLog.textContent = "";
1045 chatSeen = 0;
1046 askCards.clear();
1047 if (!chatInfo.transcript.length) chatEmptyState();
1048 for (const e of chatInfo.transcript) chatRender(e);
1049 chatSetBusy(chatInfo.running);
1050 }
1051
1052 // Connections to other services (MCP): sign in with OAuth in your own browser; the tools then show up for the assistant.
1053 async function mcpRender() {
1054 const box = $("chatConn");
1055 let list = [];
1056 try { list = await window.x402.mcp.state(); } catch {}
1057 box.textContent = "";
1058 for (const sv of list) {
1059 const row = document.createElement("div");
1060 row.className = "cn" + (sv.signedIn ? " on" : sv.connecting ? " wait" : "");
1061 const dot = document.createElement("span"); dot.className = "dot";
1062 const nm = document.createElement("span"); nm.className = "nm";
1063 nm.textContent = sv.name + (sv.connecting ? " — waiting for you to approve in the tab that opened…" : sv.signedIn ? " — connected" + (sv.persistent ? "" : " (until you close the browser)") : "");
1064 const btn = document.createElement("button"); btn.className = "sbtn" + (sv.signedIn ? " quiet" : "");
1065 btn.textContent = sv.connecting ? "Cancel" : sv.signedIn ? "Disconnect" : "Connect";
1066 btn.onclick = async () => {
1067 btn.disabled = true;
1068 if (sv.connecting) await window.x402.mcp.cancel(sv.id);
1069 else if (sv.signedIn) await window.x402.mcp.disconnect(sv.id);
1070 else { const p = window.x402.mcp.connect(sv.id); setTimeout(mcpRender, 400); await p; }
1071 mcpRender();
1072 };
1073 row.append(dot, nm, btn);
1074 box.appendChild(row);
1075 if (sv.error && !sv.signedIn) { const er = document.createElement("div"); er.className = "er"; er.textContent = sv.error; box.appendChild(er); }
1076 if (sv.signedIn && sv.missingScopes && sv.missingScopes.length) { const er = document.createElement("div"); er.className = "er"; er.textContent = sv.missingScopes.includes("files:upload") ? "Not allowed to save kept pages in your Files yet. Disconnect and connect again to allow it." : "Connect again to give the new permissions: " + sv.missingScopes.join(", "); box.appendChild(er); }
1077 }
1078 }
1079 function setChat(open) {
1080 chatOpen = open;
1081 chatEl.classList.toggle("open", open);
1082 if (open) { chatRefresh().then(() => chatIn.focus()); mcpRender(); }
1083 }
1084 function toggleChat() { setChat(!chatOpen); }
1085 async function chatSend() {
1086 if (chatBusy) { await window.x402.chat.stop(); return; }
1087 const text = chatIn.value.trim();
1088 if (!text) return;
1089 chatIn.value = "";
1090 chatSetBusy(true);
1091 const r = await window.x402.chat.send(text);
1092 if (!r.ok) { chatSetBusy(false); if (r.reason === "empty") return; chatPush("note", r.message || "Could not send."); if (r.reason === "declined") chatIn.value = text; }
1093 }
1094 $("chatBtn").onclick = toggleChat;
1095 $("chatClose").onclick = () => setChat(false);
1096 $("chatClear").onclick = () => window.x402.chat.clear();
1097 $("chatSend").onclick = chatSend;
1098 $("chatMode").onchange = (e) => window.x402.chat.setMode(e.target.value);
1099 $("chatModel").onchange = async (e) => { await window.x402.chat.setModel(e.target.value); chatRefresh(); };
1100 chatIn.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing) { e.preventDefault(); chatSend(); } });
1101 window.x402.chat.onEvent((e) => {
1102 if (e.kind === "confirm" && !chatOpen) { setChat(true); return; } // opening it redraws the whole conversation, this question included
1103 if (chatOpen) chatRender(e);
1104 if (e.kind === "user") chatSetBusy(true);
1105 });
1106
1107
1108
1109 // ---- bookmarks (askrobots links) -------------------------------------------------------------------
1110 // One click on ☆ saves the page; the star fills in, and there is no dialog after it. The list loads when you open it.
1111 let bm = { items: [], connected: false, updatedAt: null, source: "none", limit: 100 };
1112 let bmView = "bookmarks", keptItems = [], keptQuery = "", keptTimer = null;
1113 let bmChecked = new Set(), bmKeys = new Set(), bmOpen = false, bmLoading = false, bmQuery = "", bmRemote = { q: "", items: [], busy: false, error: "" }, bmTimer = null;
1114 const BM_TRACKING = /^(utm_[a-z]+|fbclid|gclid|dclid|msclkid|mc_cid|mc_eid|ref_src|guccounter|guce_referrer|guce_referrer_sig|_ga|igshid|si)$/i;
1115 const normUrl = (u) => { try { const x = new URL(u); x.hash = ""; for (const k of [...x.searchParams.keys()]) if (BM_TRACKING.test(k)) x.searchParams.delete(k); x.hostname = x.hostname.toLowerCase(); let v = x.href; if (x.pathname !== "/" && v.endsWith("/") && !x.search) v = v.slice(0, -1); if (x.pathname === "/" && !x.search) v = x.protocol + "//" + x.host; return v; } catch { return String(u || "").trim(); } };
1116 function bmApply(state) { if (!state) return; bm = state; bmKeys = new Set((state.items || []).concat(state.known || []).map((b) => normUrl(b.url))); paintStar(); if (bmOpen) renderBm(); }
1117 function paintStar() {
1118 const b = $("starBtn"); if (!b) return;
1119 const u = active && !active.reader ? active.url : "";
1120 const web = /^https?:\/\//i.test(u || "");
1121 const saved = web && bmKeys.has(normUrl(u));
1122 // Not this page, but something else on the same site is saved: say so (the star stays a click to save this page).
1123 let host = ""; try { host = web ? new URL(u).host.replace(/^www\./, "") : ""; } catch {}
1124 const onSite = !saved && host ? (bm.items || []).concat(bm.known || []).filter((x) => { try { return new URL(x.url).host.replace(/^www\./, "") === host; } catch { return false; } }) : [];
1125 const lbl = document.createElement("span"); lbl.className = "lbl"; lbl.textContent = saved ? " Saved" : " Save";
1126 b.replaceChildren(iconEl(saved ? "saved" : "save"), lbl);
1127 b.classList.toggle("saved", saved);
1128 b.classList.toggle("site", onSite.length > 0);
1129 b.disabled = !web;
1130 // Not known locally: ask the person's own askrobots account about this site (a setting in the list; once per site).
1131 if (web && !saved && bm.checkPages && bm.connected && !bmChecked.has(normUrl(u))) {
1132 bmChecked.add(normUrl(u));
1133 window.x402.bookmarks.check(u).then((r) => {
1134 if (!r || !r.checked) bmChecked.delete(normUrl(u)); // not checked (not ready yet, or it failed): try again on the next change
1135 if (r && r.saved) window.x402.bookmarks.state().then(bmApply);
1136 }).catch(() => bmChecked.delete(normUrl(u)));
1137 }
1138 b.title = !web ? "Only web pages can be saved" : saved ? "In your askrobots bookmarks" : onSite.length ? "You have " + (onSite.length === 1 ? "a bookmark" : onSite.length + " bookmarks") + " on this site (" + onSite.slice(0, 3).map((x) => x.title).join(", ") + "). Click to save this page too." : "Save this page to your askrobots bookmarks (one click)";
1139 }
1140 $("starBtn").onclick = async () => {
1141 if (!active || !/^https?:\/\//i.test(active.url || "")) return;
1142 if (bmKeys.has(normUrl(active.url))) { setBm(true); return; } // already saved: show the list
1143 const b = $("starBtn"); b.replaceChildren(iconEl("saved")); b.classList.add("saved");
1144 const r = await window.x402.bookmarks.add(active.url, active.title || "");
1145 if (!r.ok) { paintStar(); toast("skipped", r.message || "Could not save the bookmark"); return; }
1146 bmApply(await window.x402.bookmarks.state());
1147 };
1148 function relTime(ms) { if (!ms) return "never"; const s = Math.round((Date.now() - ms) / 1000); return s < 60 ? "just now" : s < 3600 ? Math.round(s / 60) + " min ago" : Math.round(s / 3600) + " h ago"; }
1149 function renderBm() {
1150 const box = $("bmPanel");
1151 const focusSearch = document.activeElement && document.activeElement.id === "bmSearch";
1152 box.textContent = "";
1153 const h = document.createElement("h4"); const t = document.createElement("span"); t.textContent = "Bookmarks"; const sp = document.createElement("span"); sp.className = "sp";
1154 const rf = document.createElement("button"); rf.className = "sbtn quiet"; rf.textContent = bmLoading ? "Loading…" : "Refresh"; rf.disabled = bmLoading; rf.onclick = () => loadBm();
1155 const x = document.createElement("button"); x.className = "sbtn quiet"; x.textContent = "✕"; x.onclick = () => setBm(false);
1156 h.append(t, sp, rf, x); box.appendChild(h);
1157 const sub = document.createElement("div"); sub.className = "sub";
1158 sub.textContent = "Your links on askrobots.com · " + (bm.source === "service" ? "updated " + relTime(bm.updatedAt) : bm.source === "copy" ? "saved copy from " + relTime(bm.updatedAt) : "not loaded yet");
1159 box.appendChild(sub);
1160 const sw = document.createElement("div"); sw.className = "tabs2";
1161 for (const [k, label] of [["bookmarks", "Bookmarks"], ["kept", "Kept copies"]]) {
1162 const b = document.createElement("button"); b.className = "sbtn quiet" + (bmView === k ? " on" : ""); b.textContent = label; b.id = "bmView-" + k;
1163 b.onclick = () => { bmView = k; if (k === "kept") loadKept(); renderBm(); };
1164 sw.appendChild(b);
1165 }
1166 box.appendChild(sw);
1167 if (bmView === "kept") { renderKept(box); return; }
1168 if (bm.error) { const e = document.createElement("div"); e.className = "err"; e.textContent = bm.error; box.appendChild(e); }
1169 if (!bm.connected && !bmLoading) {
1170 const n = document.createElement("div"); n.className = "note"; n.textContent = "Connect askrobots.com to see and save your bookmarks.";
1171 const go = document.createElement("button"); go.className = "sbtn"; go.textContent = "Open the assistant to connect"; go.onclick = () => { setBm(false); setChat(true); };
1172 box.append(n, go);
1173 if (!bm.items.length) return;
1174 }
1175 if (bm.connected) {
1176 const lab = document.createElement("label"); lab.className = "note"; lab.style.display = "flex"; lab.style.gap = "6px"; lab.style.alignItems = "flex-start";
1177 const cb = document.createElement("input"); cb.type = "checkbox"; cb.id = "bmCheck"; cb.checked = !!bm.checkPages; cb.style.width = "auto"; cb.style.margin = "2px 0 0";
1178 cb.onchange = async () => bmApply(await window.x402.bookmarks.setCheck(cb.checked));
1179 const tx = document.createElement("span"); tx.textContent = "Check the sites I visit against my bookmarks on askrobots, so ☆ knows older ones too (sends the site's name to your account).";
1180 lab.append(cb, tx); box.appendChild(lab);
1181 }
1182 const q = document.createElement("input"); q.id = "bmSearch"; q.placeholder = "Search all your bookmarks"; q.value = bmQuery;
1183 q.oninput = () => {
1184 bmQuery = q.value; renderBm();
1185 // The local list has only the newest links: also search all of them on askrobots, once typing pauses.
1186 clearTimeout(bmTimer);
1187 const want = bmQuery.trim();
1188 if (want.length < 2 || !bm.connected) { bmRemote = { q: "", items: [], busy: false, error: "" }; return; }
1189 bmTimer = setTimeout(async () => {
1190 bmRemote = { q: want, items: [], busy: true, error: "" }; if (bmOpen) renderBm();
1191 const r = await window.x402.bookmarks.search(want);
1192 if (bmQuery.trim() !== want) return; // typing moved on
1193 bmRemote = { q: want, items: r.items || [], busy: false, error: r.error || "" };
1194 if (bmOpen) renderBm();
1195 }, 350);
1196 };
1197 box.appendChild(q);
1198 const needle = bmQuery.trim().toLowerCase();
1199 const local = bm.items.filter((b) => !needle || (b.title + " " + b.url + " " + (b.tags || []).join(" ")).toLowerCase().includes(needle));
1200 const seen = new Set(local.map((b) => normUrl(b.url)));
1201 const remote = needle && bmRemote.q.toLowerCase() === needle ? bmRemote.items.filter((b) => !seen.has(normUrl(b.url))) : [];
1202 const list = local.concat(remote);
1203 for (const b of list) {
1204 const row = document.createElement("div"); row.className = "bm"; row.title = b.url;
1205 const tt = document.createElement("div"); tt.className = "t"; tt.textContent = b.title;
1206 const hh = document.createElement("div"); hh.className = "h"; let host = b.url; try { host = new URL(b.url).host; } catch {} hh.textContent = host + (b.tags && b.tags.length ? " · " + b.tags.join(", ") : "");
1207 { const f = iconFor(b.url); if (f) hh.prepend(favImg(f)); }
1208 row.append(tt, hh);
1209 row.onclick = (ev) => { if (ev.metaKey || ev.ctrlKey) newTab(b.url, false); else { setBm(false); go(b.url); } };
1210 row.onauxclick = (ev) => { if (ev.button === 1) newTab(b.url, false); };
1211 box.appendChild(row);
1212 }
1213 if (needle && bmRemote.busy) { const n = document.createElement("div"); n.className = "note"; n.textContent = "Searching all your links on askrobots…"; box.appendChild(n); }
1214 if (needle && bmRemote.error) { const n = document.createElement("div"); n.className = "err"; n.textContent = bmRemote.error; box.appendChild(n); }
1215 if (!list.length && bm.items.length && !bmRemote.busy) { const n = document.createElement("div"); n.className = "note"; n.textContent = "Nothing matches."; box.appendChild(n); }
1216 if (!bm.items.length && bm.connected && !bmLoading) { const n = document.createElement("div"); n.className = "note"; n.textContent = "No bookmarks yet. ☆ next to the address saves the page you are on."; box.appendChild(n); }
1217 if (bm.items.length >= bm.limit && !needle) { const n = document.createElement("div"); n.className = "note"; n.textContent = "Showing your newest " + bm.limit + ". Searching looks through all of them."; box.appendChild(n); }
1218 if (focusSearch) { const el = $("bmSearch"); if (el) { el.focus(); el.setSelectionRange(el.value.length, el.value.length); } }
1219 }
1220 // ---- kept copies --------------------------------------------------------------------------------
1221 async function loadKept() { try { keptItems = await window.x402.keep.list(keptQuery); } catch { keptItems = []; } if (bmOpen && bmView === "kept") renderBm(); }
1222 function renderKept(box) {
1223 const focus = document.activeElement && document.activeElement.id === "keptSearch";
1224 const q = document.createElement("input"); q.id = "keptSearch"; q.placeholder = "Search the text of kept pages"; q.value = keptQuery;
1225 q.oninput = () => { keptQuery = q.value; clearTimeout(keptTimer); keptTimer = setTimeout(loadKept, 200); };
1226 box.appendChild(q);
1227 if (!keptItems.length) { const n = document.createElement("div"); n.className = "note"; n.textContent = keptQuery ? "Nothing kept matches." : "Nothing kept yet. 📥 keeps a copy of the page you are on (what is on screen and its text) and closes the tab."; box.appendChild(n); }
1228 for (const k of keptItems) {
1229 const row = document.createElement("div"); row.className = "bm"; row.title = "Open the kept copy (⌘-click: the live page)";
1230 const tt = document.createElement("div"); tt.className = "t"; tt.textContent = k.title;
1231 const hh = document.createElement("div"); hh.className = "h"; let host = k.url; try { host = new URL(k.url).host; } catch {}
1232 hh.textContent = host + " · kept " + relTime(k.keptAt) + (k.remote && k.remote.files && k.remote.files.length ? " · on askrobots" : "") + (k.reason ? " · " + k.reason : "");
1233 { const f = iconFor(k.url); if (f) hh.prepend(favImg(f)); }
1234 row.append(tt, hh);
1235 if (k.snippet) { const sn = document.createElement("div"); sn.className = "s"; sn.textContent = "…" + k.snippet + "…"; row.appendChild(sn); }
1236 row.onclick = (ev) => { setBm(false); if (ev.metaKey || ev.ctrlKey) newTab(k.url, true); else newTab("dbb-kept://" + k.id + "/", true); };
1237 box.appendChild(row);
1238 }
1239 if (focus) { const el = $("keptSearch"); if (el) { el.focus(); el.setSelectionRange(el.value.length, el.value.length); } }
1240 }
1241 $("keepBtn").onclick = async () => {
1242 if (!active || !/^https?:\/\//i.test(active.url || "")) { toast("skipped", "Only web pages can be kept"); return; }
1243 const b = $("keepBtn"); b.disabled = true;
1244 try {
1245 const r = await window.x402.keep.tab({});
1246 if (!r.ok) toast("skipped", r.message || "Could not keep this page");
1247 else {
1248 const up = r.record.remote && r.record.remote.files ? r.record.remote.files.length : 0;
1249 toast("paid", "Kept “" + r.record.title + "”" + (r.bookmarked || up ? " — on askrobots too (" + [r.bookmarked ? "bookmark" : "", up ? (up === 1 ? "1 file" : up + " files") : ""].filter(Boolean).join(", ") + ")" : "") + (r.record.remote && r.record.remote.error ? ". Picture not saved to askrobots: " + r.record.remote.error : ""), r.record.remote && r.record.remote.error ? 12000 : 4000);
1250 }
1251 } finally { b.disabled = false; }
1252 };
1253 async function loadBm() { bmLoading = true; renderBm(); try { bmApply(await window.x402.bookmarks.refresh()); } finally { bmLoading = false; if (bmOpen) renderBm(); } }
1254 function setBm(open) { bmOpen = open; if (open && bmView === "kept") loadKept(); if (!open) { keptQuery = ""; bmQuery = ""; bmRemote = { q: "", items: [], busy: false, error: "" }; clearTimeout(bmTimer); } $("bmPanel").classList.toggle("open", open); if (open) { renderBm(); loadBm(); } }
1255 $("bmBtn").onclick = () => setBm(!bmOpen);
1256 window.x402.bookmarks.onChanged(bmApply);
1257 window.x402.bookmarks.state().then(bmApply);
1258
1259 // ---- plugins ---------------------------------------------------------------------------------------
1260 // Style rules installed from gitstable. Installing is two steps: look it up (the browser fetches and checks it and
1261 // says what it will change), then Install, which keeps exactly what was shown.
1262 let plugOpen = false, plugSt = { plugins: [], allOff: false, safeMode: false, callerNet: false, origin: "https://gitstable.com" };
1263 let plugAsk = null, plugBusy = false, plugErr = "", plugSource = "";
1264 const shortHost = (o) => String(o || "").replace(/^https?:\/\//, "");
1265 function plugEl(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }
1266 function renderPlug() {
1267 const box = $("plugPanel"); if (!plugOpen) return;
1268 const focusSrc = document.activeElement && document.activeElement.id === "plugSource";
1269 box.textContent = "";
1270 const h = document.createElement("h4"); const x = plugEl("button", "sbtn quiet", "✕"); x.onclick = () => setPlug(false);
1271 h.append(plugEl("span", "", "Plugins"), plugEl("span", "sp"), x); box.appendChild(h);
1272 const sub = plugEl("div", "sub", "Style rules from " + shortHost(plugSt.origin) + ". They change how a site looks, and can't run code, read the page or send anything. ");
1273 const browse = plugEl("a", "", "Browse all plugins"); browse.id = "plugBrowse"; browse.href = "#";
1274 browse.onclick = (e) => { e.preventDefault(); setPlug(false); newTab(plugSt.origin + "/store/#plugins", true); }; // on a plugin's page there, the status bar offers Install
1275 sub.appendChild(browse); box.appendChild(sub);
1276 if (plugSt.safeMode) box.appendChild(plugEl("div", "err", "Safe mode: no plugins are applied this time (the browser was started with DBB_SAFE_MODE=1)."));
1277 if (plugSt.callerNet) box.appendChild(plugEl("div", "err", "No plugins while the caller network is on."));
1278 const sw = plugEl("label", "sw"); const cb = document.createElement("input"); cb.type = "checkbox"; cb.id = "plugAllOff"; cb.checked = !!plugSt.allOff;
1279 cb.onchange = async () => { const r = await window.x402.plugins.allOff(cb.checked); if (!r.ok) plugErr = r.error; };
1280 sw.append(cb, plugEl("span", "", "Turn all plugins off (see sites as they are)")); box.appendChild(sw);
1281 const row = plugEl("div", "row2"); const inp = document.createElement("input"); inp.type = "text"; inp.id = "plugSource"; inp.placeholder = "a plugin's name, or owner/repository on " + shortHost(plugSt.origin); inp.value = plugSource;
1282 inp.oninput = () => { plugSource = inp.value; };
1283 const look = plugEl("button", "sbtn", plugBusy ? "Checking…" : "Look up"); look.id = "plugLook"; look.disabled = plugBusy;
1284 const doLook = () => plugLookUp(plugSource);
1285 look.onclick = doLook; inp.onkeydown = (e) => { if (e.key === "Enter") { e.preventDefault(); doLook(); } };
1286 row.append(inp, look); box.appendChild(row);
1287 if (plugErr) box.appendChild(plugEl("div", "err", plugErr));
1288 if (plugAsk) {
1289 const a = plugEl("div", "pl ask"); a.id = "plugAsk";
1290 const t = plugEl("div", "t"); t.append(plugEl("b", "", plugAsk.name + " " + plugAsk.version)); a.appendChild(t);
1291 if (plugAsk.description) a.appendChild(plugEl("div", "h", plugAsk.description));
1292 a.appendChild(plugEl("div", "note", plugAsk.says));
1293 a.appendChild(plugEl("div", "h", shortHost(plugSt.origin) + "/" + plugAsk.repository + " · release " + plugAsk.tag + " · commit " + plugAsk.commit.slice(0, 7) + (plugAsk.license ? " · " + plugAsk.license : "")));
1294 a.appendChild(plugEl("div", "h", plugAsk.testedHere ? "Tested on this browser version." : "Not tested on this version of the browser" + (plugAsk.testedOn.length ? " (tested on " + plugAsk.testedOn.join(", ") + ")" : "") + "."));
1295 const rel = plugAsk.relation, was = plugAsk.replaces;
1296 a.appendChild(plugEl("div", "h", rel === "newer" ? "An update to the installed " + was + "." : rel === "same" ? (plugAsk.installedProblem ? "This release is installed, but its files changed on this computer. Install it again to repair it." : "This release is installed already.") : rel === "older" ? "Older than the installed " + was + "." : rel === "other" ? "Replaces the installed " + was + "." : ""));
1297 const r2 = plugEl("div", "row2");
1298 const label = rel === "new" ? "Install" : rel === "newer" ? "Update" : rel === "older" ? "Go back to " + plugAsk.version : rel === "same" ? (plugAsk.installedProblem ? "Repair" : "") : "Replace";
1299 const ok = plugEl("button", "sbtn", label); ok.id = "plugInstall"; if (!label) ok.style.display = "none";
1300 ok.onclick = async () => { const r = await window.x402.plugins.install(plugAsk.token); if (r.ok) { toast("paid", "Installed “" + plugAsk.name + "”"); plugAsk = null; plugSource = ""; } else plugErr = r.error; renderPlug(); };
1301 const no = plugEl("button", "sbtn quiet", label ? "Cancel" : "OK"); no.onclick = () => { plugAsk = null; renderPlug(); };
1302 r2.append(ok, no); a.appendChild(r2); box.appendChild(a);
1303 }
1304 if (!plugSt.plugins.length) box.appendChild(plugEl("div", "note", "No plugins yet. Type a plugin's repository, such as askrobots/x-whole-window, and Look up."));
1305 for (const p of plugSt.plugins) {
1306 const d = plugEl("div", "pl"); d.dataset.id = p.id;
1307 const t = plugEl("div", "t"); const on = document.createElement("input"); on.type = "checkbox"; on.checked = !!p.enabled; on.title = "On for its sites";
1308 on.onchange = async () => { const r = await window.x402.plugins.enable(p.id, on.checked); if (!r.ok) { plugErr = r.error; renderPlug(); } };
1309 const rm = plugEl("button", "sbtn quiet", "Remove"); rm.onclick = async () => { if (!rm.dataset.sure) { rm.dataset.sure = "1"; rm.textContent = "Remove it?"; return; } const r = await window.x402.plugins.remove(p.id); if (!r.ok) { plugErr = r.error; renderPlug(); } };
1310 t.append(on, plugEl("b", "", p.name + " " + p.version), rm); d.appendChild(t);
1311 const siteWords = p.sites.length > 1 ? p.sites.slice(0, -1).join(", ") + " and " + p.sites[p.sites.length - 1] : p.sites.join("");
1312 const what = p.kind === "view-rule" && p.button ? "Adds a " + p.button.label + " button on " + siteWords + " (shows its posts as cards)" : "Changes how " + siteWords + " look" + (p.sites.length === 1 ? "s" : "");
1313 d.appendChild(plugEl("div", "h", what + " · " + (p.testedHere ? "tested on this version" : "not tested on this version")));
1314 const src = plugEl("div", "h"); const link = plugEl("a", "", shortHost(plugSt.origin) + "/" + p.source.repository); link.href = "#";
1315 link.onclick = (e) => { e.preventDefault(); setPlug(false); newTab(plugSt.origin + "/repositories/" + p.source.repository + "/", true); };
1316 src.append(link, document.createTextNode(" · release " + p.source.tag + " · commit " + p.source.commit.slice(0, 7))); d.appendChild(src);
1317 if (p.problem) d.appendChild(plugEl("div", "err", p.problem));
1318 box.appendChild(d);
1319 }
1320 if (focusSrc) { const el = $("plugSource"); if (el) { el.focus(); el.setSelectionRange(el.value.length, el.value.length); } }
1321 }
1322 async function plugLookUp(source) {
1323 plugSource = String(source || "");
1324 if (!plugSource.trim() || plugBusy) return;
1325 plugBusy = true; plugErr = ""; plugAsk = null; renderPlug();
1326 const r = await window.x402.plugins.preview(plugSource.trim());
1327 plugBusy = false; if (r.ok) plugAsk = r.value; else plugErr = r.error; renderPlug();
1328 }
1329 async function setPlug(open) { plugOpen = open; $("plugPanel").classList.toggle("open", open); if (!open) { plugAsk = null; plugErr = ""; return; } plugSt = await window.x402.plugins.state(); renderPlug(); const el = $("plugSource"); if (el && !plugSt.plugins.length) el.focus(); }
1330 // The status bar's way into Plugins, always there. It names the plugin changing the page you are on, so an odd
1331 // looking page can be told apart from a plugin at a glance; otherwise it just says Plugins. Click: the Plugins panel.
1332 function plugSiteMatch(host, sites) { const h = String(host || "").toLowerCase(); return sites.some((s) => s.startsWith("*.") ? h.endsWith(s.slice(1)) : h === s || h.endsWith("." + s)); }
1333 const plugPageKey = (u) => { try { const x = new URL(u); return x.origin + x.pathname.replace(/\/+$/, ""); } catch { return ""; } };
1334 // View-rule plugins add a button here on the sites they cover, with an icon the browser draws (the plugin only names
1335 // one of a fixed set, so its button can't pass for one of the browser's own).
1336 let viewKey = "";
1337 function paintViewBtns(host) {
1338 const box = $("viewBtns"); if (!box) return;
1339 const off = plugSt.safeMode || plugSt.callerNet || plugSt.allOff;
1340 const views = host && !off ? (plugSt.plugins || []).filter((p) => p.kind === "view-rule" && p.enabled && !p.problem && p.button && plugSiteMatch(host, p.sites)) : [];
1341 const key = views.map((p) => p.id + ":" + p.button.label + ":" + p.button.icon).join("|");
1342 if (key === viewKey) return;
1343 viewKey = key; box.textContent = "";
1344 for (const p of views) {
1345 const b = document.createElement("button"); b.className = "btn viewBtn"; b.dataset.plugin = p.id;
1346 b.innerHTML = ICONS["plugin-" + p.button.icon] || "";
1347 const t = document.createElement("span"); t.textContent = " " + p.button.label; b.appendChild(t);
1348 b.title = p.button.label + ": " + p.name + " (a plugin). Shows this page's posts as cards in a new tab; it scrolls this page to read more.";
1349 b.onclick = () => openCards(p.id);
1350 box.appendChild(b);
1351 }
1352 }
1353 function paintPlugBtn() {
1354 const b = $("plugBtn"); if (!b) return;
1355 let host = ""; try { const u = new URL(active && !active.reader ? active.url : ""); if (/^https?:$/.test(u.protocol)) host = u.hostname; } catch {}
1356 paintViewBtns(host);
1357 // On a plugin's own page on gitstable (from gitstable's list): offer to install it, or to update to its newest release.
1358 const key = active && !active.reader ? plugPageKey(active.url) : "";
1359 const offer = key ? (plugSt.listed || []).find((it) => (it.url && plugPageKey(it.url) === key) || (it.repositoryUrl && plugPageKey(it.repositoryUrl) === key)) : null;
1360 const have = offer ? plugSt.plugins.find((p) => p.id === offer.id) : null;
1361 b.dataset.offer = "";
1362 if (offer && (!have || (have.version !== offer.tag && have.source.commit !== offer.commit))) {
1363 b.dataset.offer = offer.repository + "@" + offer.tag;
1364 b.classList.remove("applied", "unapplied"); b.classList.add("offer");
1365 b.textContent = (have ? "Update: " : "Install: ") + offer.name;
1366 b.title = (have ? "Update “" + offer.name + "” from " + have.version + " to " + offer.tag : "Install “" + offer.name + "” " + offer.tag) + ". Click to look it up; it is installed only when you press Install.";
1367 return;
1368 }
1369 b.classList.remove("offer");
1370 const here = host ? plugSt.plugins.filter((p) => plugSiteMatch(host, p.sites)) : [];
1371 if (!here.length) {
1372 b.textContent = "Plugins"; b.classList.remove("applied"); b.classList.add("unapplied");
1373 b.title = (plugSt.plugins.length ? "No plugin changes this site. " : "No plugins installed yet. ") + "Click for Plugins: install style rules from gitstable.com.";
1374 return;
1375 }
1376 const why = plugSt.safeMode ? "safe mode" : plugSt.callerNet ? "the caller network is on" : plugSt.allOff ? "all plugins are turned off" : "";
1377 const on = why ? [] : here.filter((p) => p.enabled && !p.problem);
1378 b.classList.toggle("applied", on.length > 0); b.classList.toggle("unapplied", on.length === 0); // not "on": that is a pressed toolbar button
1379 b.textContent = on.length === 1 ? "Plugin: " + on[0].name : on.length > 1 ? on.length + " plugins on" : here.length === 1 ? "Plugin off" : "Plugins off";
1380 b.title = (on.length ? "Changing this page: " + on.map((p) => p.name + " " + p.version).join(", ") + "." : "For this site, but not applied" + (why ? " (" + why + ")" : "") + ": " + here.map((p) => p.name + (p.problem ? " (its files changed)" : !p.enabled ? " (switched off)" : "")).join(", ") + ".") + " Click for Plugins.";
1381 }
1382 $("plugBtn").onclick = async () => {
1383 const offer = $("plugBtn").dataset.offer;
1384 if (!offer) return setPlug(!plugOpen);
1385 await setPlug(true); plugLookUp(offer); // the look-up, done for you; Install is still yours to press
1386 };
1387 window.x402.plugins.onChanged((st) => { plugSt = st; renderPlug(); paintPlugBtn(); });
1388 window.x402.plugins.onOpen(async (m) => { if (!m || !m.source) return; await setPlug(true); plugLookUp(m.source); }); // gitstable's Install button
1389 window.x402.plugins.state().then((st) => { plugSt = st; paintPlugBtn(); }).catch(() => {});
1390 document.addEventListener("keydown", (e) => { if (e.key === "Escape" && plugOpen) setPlug(false); });
1391
1392 // ---- resource status -----------------------------------------------------------------------------
1393 // The operating system's own numbers for each page's process, so something that hogs the machine has a name.
1394 const fmtMB = (mb) => mb == null ? "—" : mb >= 1024 ? (mb / 1024).toFixed(1) + " GB" : Math.round(mb) + " MB";
1395 const resBytes = (b) => b == null ? "—" : fmtMB(b / 1048576);
1396 const HOT_MB = 800, HOT_CPU = 60, WARN_TOTAL_MB = 3000;
1397 let resOpen = false, resBusy = false;
1398 async function resRefresh() {
1399 if (resBusy) return;
1400 resBusy = true;
1401 let r;
1402 try { r = await window.x402.resources.state(); } catch { resBusy = false; return; }
1403 resBusy = false;
1404 const hotTab = r.tabs.some((t) => (t.memoryMB || 0) > HOT_MB || (t.cpu || 0) > HOT_CPU);
1405 $("resBtn").textContent = "Memory " + fmtMB(r.totalMemoryMB);
1406 $("resBtn").classList.toggle("warn", r.totalMemoryMB > WARN_TOTAL_MB || hotTab);
1407 if (!resOpen) return;
1408 const box = $("resPanel");
1409 box.textContent = "";
1410 const add = (cls, text, parent = box) => { const d = document.createElement("div"); d.className = cls; d.textContent = text; parent.appendChild(d); return d; };
1411 const h = document.createElement("h4"); const t = document.createElement("span"); t.textContent = "What the browser is using"; const sp = document.createElement("span"); sp.className = "sp";
1412 const x = document.createElement("button"); x.className = "sbtn quiet"; x.textContent = "✕"; x.onclick = () => setRes(false);
1413 h.append(t, sp, x); box.appendChild(h);
1414 const bt = r.byType;
1415 add("tot", "Memory " + fmtMB(r.totalMemoryMB) + " · CPU " + r.totalCpu + "% — pages " + fmtMB(bt.pages && bt.pages.memoryMB) + ", browser " + fmtMB(bt.browser && bt.browser.memoryMB) + ", graphics " + fmtMB(bt.graphics && bt.graphics.memoryMB) + (bt.other ? ", other " + fmtMB(bt.other.memoryMB) : ""));
1416 add("sec", "Tabs");
1417 const maxMB = Math.max(1, ...r.tabs.map((t) => t.memoryMB || 0));
1418 const sorted = [...r.tabs].sort((a, b) => (b.memoryMB || 0) - (a.memoryMB || 0));
1419 for (const tb of sorted) {
1420 const mine = tabs.find((x) => x.id === tb.id);
1421 const hot = (tb.memoryMB || 0) > HOT_MB || (tb.cpu || 0) > HOT_CPU;
1422 const row = document.createElement("div"); row.className = "trow" + (hot ? " hot" : "");
1423 const t1 = document.createElement("div"); t1.className = "t1";
1424 const nm = document.createElement("span"); nm.className = "nm"; nm.textContent = tb.title || tb.url || "(blank)"; nm.title = tb.url || "";
1425 const mb = document.createElement("span"); mb.className = "mb"; mb.textContent = fmtMB(tb.memoryMB);
1426 const cl = document.createElement("button"); cl.className = "sbtn quiet"; cl.textContent = "Close"; cl.onclick = () => { if (mine) closeTab(mine); setTimeout(resRefresh, 300); };
1427 t1.append(nm, mb, cl); row.appendChild(t1);
1428 const bar = document.createElement("div"); bar.className = "bar"; const bi = document.createElement("i"); bi.style.width = Math.max(2, Math.round(((tb.memoryMB || 0) / maxMB) * 100)) + "%"; bar.appendChild(bi); row.appendChild(bar);
1429 const st = mine && mine.stats;
1430 add("t2", [(tb.cpu == null ? "" : tb.cpu + "% CPU"), st ? resBytes(st.bytes) + " loaded in " + st.requests + " requests" : "", st && st.failures.length ? st.failures.length + " failed" : "", tb.sharedProcess ? "shares a process with another tab" : ""].filter(Boolean).join(" · "), row);
1431 box.appendChild(row);
1432 }
1433 add("sec", "On disk");
1434 add("tot", "Data folder " + resBytes(r.disk.bytes) + (r.disk.truncated ? " (at least)" : "") + " — " + r.disk.top.slice(0, 5).map((d) => d.name + " " + resBytes(d.bytes)).join(", "));
1435 const cr = document.createElement("div"); cr.className = "trow";
1436 const t1 = document.createElement("div"); t1.className = "t1";
1437 const nm = document.createElement("span"); nm.className = "nm"; nm.textContent = "Cache " + resBytes(r.cacheBytes);
1438 const clr = document.createElement("button"); clr.className = "sbtn"; clr.textContent = "Clear cache";
1439 clr.onclick = async () => { clr.disabled = true; const f = await window.x402.resources.clearCache(); toast("skipped", "Cache cleared (" + resBytes(f.freedBytes) + ")"); resRefresh(); };
1440 t1.append(nm, clr); cr.appendChild(t1); box.appendChild(cr);
1441 add("hint", "Each page's memory is what its own process costs the machine (on a Mac, the physical footprint Activity Monitor shows, which includes memory the system has compressed). Clearing the cache keeps your logins. A tab marked in amber is using over " + HOT_MB + " MB or " + HOT_CPU + "% of a CPU.");
1442 }
1443 function setRes(open) { resOpen = open; $("resPanel").classList.toggle("open", open); if (open) resRefresh(); }
1444 $("resBtn").onclick = () => setRes(!resOpen);
1445 (function resLoop() { if (!document.hidden) resRefresh(); setTimeout(resLoop, resOpen ? 3000 : 10000); })();
1446
1447 // Native menu accelerators (⌘T / ⌘W / ⌘L …) arrive here — they work even when
1448 // focus is inside a page, which a document-level keydown would never see.
1449 const MENU_BUTTONS = new Set(["keepBtn", "starBtn", "bmBtn", "keyBtn", "inspectBtn", "resBtn", "fundBtn", "galleryBtn", "tourBtn"]);
1450 window.x402.onTabCommand((cmd) => onTabCmd(cmd));
1451 function onTabCmd(cmd) {
1452 if (cmd === "new") openNewTab();
1453 else if (cmd === "close") closeTab(active);
1454 else if (cmd === "focus-url") { urlInput.focus(); urlInput.select(); }
1455 else if (cmd.startsWith("tab:")) { const n = Number(cmd.slice(4)); const t = n === 9 ? tabs[tabs.length - 1] : tabs[n - 1]; if (t) switchTo(t); }
1456 else if (cmd === "next") cycleTab(1);
1457 else if (cmd === "prev") cycleTab(-1);
1458 else if (cmd === "reload") { try { active.wv.reload(); } catch {} }
1459 else if (cmd.startsWith("motion:")) setMotionMode(cmd.slice(7));
1460 else if (cmd === "reader") openReader();
1461 else if (cmd === "chat") toggleChat();
1462 // The menu bar has every feature: a menu item does what its button does.
1463 else if (cmd.startsWith("click:") && MENU_BUTTONS.has(cmd.slice(6))) $(cmd.slice(6)).click();
1464 else if (cmd === "back") $("back").click();
1465 else if (cmd === "forward") $("fwd").click();
1466 else if (cmd === "kept") { bmView = "kept"; setBm(true); }
1467 else if (cmd === "plugins") setPlug(!plugOpen);
1468 else if (cmd.startsWith("history:")) historyCmd(cmd.slice(8));
1469 else if (cmd === "connections") { setChat(true); }
1470 else if (cmd === "find") openFind();
1471 else if (cmd === "find-next") findStep(1);
1472 else if (cmd === "find-prev") findStep(-1);
1473 else if (PAGE_CMDS.has(cmd)) pageCmd(cmd, "menu");
1474 else if (cmd === "downloads") { if (!samePress(cmd, "menu")) setDl(!dlOpen); }
1475 else if (cmd === "open-external") {
1476 if (active && /^https?:\/\//i.test(active.url)) window.x402.openExternal(active.url);
1477 else toast("skipped", "Only web pages can be opened in the default browser");
1478 }
1479 }
1480 // ---- print, save as PDF, zoom (File and View menus, the page's right-click menu, the zoom badge) ----
1481 const PAGE_CMDS = new Set(["print", "save-pdf", "zoom-in", "zoom-out", "zoom-reset"]);
1482 // A key the page left alone comes from the page (webview-preload.cjs); should the menu also see the same press, the
1483 // second one within 150 ms is the same press, not another step.
1484 let lastPageCmd = { cmd: "", from: "", at: 0 };
1485 function samePress(cmd, from) {
1486 const now = Date.now();
1487 const same = lastPageCmd.cmd === cmd && lastPageCmd.from !== from && now - lastPageCmd.at < 150;
1488 lastPageCmd = { cmd, from, at: now };
1489 return same;
1490 }
1491 async function pageCmd(cmd, from = "menu") {
1492 if (samePress(cmd, from)) return;
1493 if (!active || active.wcId == null || !active.url) return toast("skipped", "Open a page first");
1494 const wcId = active.wcId;
1495 if (cmd === "print") {
1496 const r = await window.x402.page.print(wcId);
1497 if (!r.ok && r.reason !== "cancelled" && r.reason !== "Print job canceled") toast("bad", "Could not print: " + (r.reason || "unknown"));
1498 } else if (cmd === "save-pdf") {
1499 const r = await window.x402.page.pdf(wcId);
1500 if (r.ok) { /* the download event's toast says where it went */ }
1501 else if (r.reason === "caller-network-on") toast("skipped", "Saving is off while the caller network is on");
1502 else if (r.reason !== "cancelled") toast("bad", "Could not save the PDF: " + (r.reason || "unknown"));
1503 } else {
1504 const r = await window.x402.page.zoom(wcId, cmd.slice(5));
1505 if (r.ok) toast("skipped", "Zoom " + Math.round(r.factor * 100) + "%" + (r.site ? " on " + r.site : ""), 1500);
1506 }
1507 }
1508 function paintZoom() {
1509 const b = $("zoomBtn"), f = active && active.zoom || 1;
1510 b.hidden = Math.abs(f - 1) < 0.001;
1511 b.textContent = Math.round(f * 100) + "%";
1512 }
1513 $("zoomBtn").onclick = () => pageCmd("zoom-reset");
1514 window.x402.page.onZoom((z) => {
1515 const t = tabs.find((x) => x.wcId === z.wcId);
1516 if (!t) return;
1517 t.zoom = z.factor;
1518 if (t === active) paintZoom();
1519 });
1520
1521 // ---- the Downloads panel (status bar, File ▸ Downloads, ⌘⇧J): downloads and saved PDFs, newest first ----
1522 // The list lives in the main process (downloads-store.ts) and survives restarts; a row is acted on by its id only.
1523 let dlOpen = false, dlRows = [], dlTimer = 0;
1524 const dlAgo = (t) => {
1525 const s = Math.max(0, (Date.now() - t) / 1000);
1526 if (s < 60) return "just now";
1527 if (s < 3600) return Math.floor(s / 60) + " min ago";
1528 if (s < 86400) return Math.floor(s / 3600) + " h ago";
1529 const d = new Date(t);
1530 return d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: d.getFullYear() === new Date().getFullYear() ? undefined : "numeric" });
1531 };
1532 function paintDlBtn() {
1533 const run = [...downloads.values()].filter((d) => d.state === "progressing" || d.state === "paused");
1534 const b = $("dlBtn");
1535 if (!run.length) { b.textContent = "Downloads"; return; }
1536 const got = run.reduce((n, d) => n + (d.received || 0), 0), all = run.reduce((n, d) => n + (d.total || 0), 0);
1537 b.textContent = "⬇ " + (run.length > 1 ? run.length + " · " : "") + (all ? Math.floor((got / all) * 100) + "%" : fmtBytes(got));
1538 }
1539 function loadDl() {
1540 clearTimeout(dlTimer);
1541 dlTimer = setTimeout(async () => { dlRows = await window.x402.downloads.list(); renderDl(); }, 120);
1542 }
1543 async function dlAct(id, act) {
1544 const r = await window.x402.downloads.act(id, act);
1545 if (!r.ok && r.reason === "missing") toast("skipped", "That file has been moved or deleted");
1546 else if (!r.ok && r.reason === "paid") toast("skipped", "A paid download is fetched again from its page, so it isn't paid for twice");
1547 else if (!r.ok && act !== "cancel") toast("bad", "Could not " + act + (r.reason ? " (" + r.reason + ")" : ""));
1548 loadDl();
1549 }
1550 function renderDl() {
1551 const box = $("dlPanel");
1552 box.textContent = "";
1553 const h = document.createElement("h4");
1554 const ttl = document.createElement("span"); ttl.textContent = "Downloads";
1555 const sp = document.createElement("span"); sp.className = "sp";
1556 const mk = (label, title, fn) => { const b = document.createElement("button"); b.className = "sbtn"; b.textContent = label; b.title = title; b.onclick = fn; return b; };
1557 h.append(ttl, sp, mk("Open folder", "Open your Downloads folder", () => dlAct(0, "folder")), mk("Clear list", "Take the finished downloads off this list (the files stay where they are)", () => dlAct(0, "clear")), mk("✕", "Close (Esc)", () => setDl(false)));
1558 box.appendChild(h);
1559 if (!dlRows.length) {
1560 const e = document.createElement("div"); e.className = "empty";
1561 e.textContent = "Nothing downloaded yet. Files you download and pages you save as PDF (⌘⇧S) show here, and stay listed after a restart.";
1562 box.appendChild(e);
1563 return;
1564 }
1565 for (const d of [...dlRows].reverse()) {
1566 const running = d.state === "progressing" || d.state === "paused";
1567 const done = d.state === "completed";
1568 const row = document.createElement("div"); row.className = "dl" + (done && !d.exists ? " gone" : ""); row.dataset.id = d.id;
1569 const t1 = document.createElement("div"); t1.className = "t1";
1570 const nm = document.createElement(done && d.exists ? "a" : "span"); nm.className = "nm"; nm.textContent = d.name; nm.title = d.path || d.name;
1571 if (done && d.exists) nm.onclick = () => dlAct(d.id, "open");
1572 t1.appendChild(nm);
1573 if (running) t1.appendChild(mk("Cancel", "Stop this download", () => dlAct(d.id, "cancel")));
1574 if ((d.state === "interrupted" || d.state === "cancelled") && d.url && !d.paid) t1.appendChild(mk("Retry", "Download it again from " + d.host, () => dlAct(d.id, "retry")));
1575 if (d.exists) t1.appendChild(mk("Show in Finder", "Show the file in its folder", () => dlAct(d.id, "show")));
1576 if (!running) t1.appendChild(mk("✕", "Take it off the list (the file stays where it is)", () => dlAct(d.id, "remove")));
1577 row.appendChild(t1);
1578 if (running) {
1579 const bar = document.createElement("div"); bar.className = "bar"; const bi = document.createElement("i");
1580 bi.style.width = (d.total ? Math.max(2, Math.floor((d.received / d.total) * 100)) : 30) + "%"; bar.appendChild(bi); row.appendChild(bar);
1581 }
1582 const t2 = document.createElement("div"); t2.className = "t2";
1583 const bits = [];
1584 if (d.kind === "pdf") bits.push("PDF of a page on " + d.host);
1585 else if (d.host) bits.push(d.host);
1586 bits.push(running || (!done && d.total && d.received < d.total) ? fmtBytes(d.received) + (d.total ? " of " + fmtBytes(d.total) : "") + (d.state === "paused" ? " · paused" : "") : fmtBytes(d.total || d.received));
1587 if (d.paid) bits.push("paid " + d.paid);
1588 bits.push(dlAgo(d.endedAt || d.startedAt));
1589 t2.textContent = bits.join(" · ");
1590 const word = d.state === "interrupted" ? "Failed" : d.state === "cancelled" ? "Cancelled" : done && !d.exists ? "Moved or deleted" : "";
1591 if (word) { const w = document.createElement("span"); w.className = "bad"; w.textContent = " · " + word; t2.appendChild(w); }
1592 row.appendChild(t2);
1593 box.appendChild(row);
1594 }
1595 }
1596 function setDl(open) { dlOpen = open; $("dlPanel").classList.toggle("open", open); if (open) { if (resOpen) setRes(false); loadDl(); } }
1597 $("dlBtn").onclick = () => setDl(!dlOpen);
1598 document.addEventListener("keydown", (e) => { if (e.key === "Escape" && dlOpen) setDl(false); });
1599
1600 // target=_blank / window.open from a page → a new tab beside it.
1601 // ⌘-click, middle-click and the right-click menu open it behind the page you are on.
1602 window.x402.onOpenTab((url, o) => newTab(url, !o.background));
1603 window.x402.onMenuAction((a) => {
1604 const text = String(a && a.text || "").trim();
1605 if (!text) return;
1606 if (a.id === "search-selection") newTab(searchFor(text));
1607 else if (a.id === "ask-selection") {
1608 // Put the text in the chat box for the person to finish and send: nothing is sent on its own.
1609 chatIn.value = "About this, from the page:\n“" + text.slice(0, 4000) + "”\n\n";
1610 setChat(true);
1611 chatIn.setSelectionRange(chatIn.value.length, chatIn.value.length);
1612 }
1613 });
1614
1615 // Anything that isn't clearly an address is a search — answered by askrobots.com
1616 // (the template its own opensearch.xml advertises).
1617 const SEARCH_URL = "https://askrobots.com/dashboard/search/?q=%s&source=opensearch";
1618 const isLocalHost = (host) =>
1619 host === "localhost" || host.endsWith(".local") ||
1620 /^127(\.\d+){3}$/.test(host) || /^10(\.\d+){3}$/.test(host) ||
1621 /^192\.168(\.\d+){2}$/.test(host) || /^172\.(1[6-9]|2\d|3[01])(\.\d+){2}$/.test(host);
1622
1623 function toUrl(raw) {
1624 const u = raw.trim();
1625 if (!u) return "";
1626 if (/^[a-z][a-z0-9+.-]*:\/\//i.test(u) || /^(about|file|data|view-source):/i.test(u)) return u;
1627 const host = u.split(/[/?#]/)[0].split(":")[0];
1628 if (!/\s/.test(u) && (isLocalHost(host) || /^[^\s.]+(\.[^\s.]+)+$/.test(host))) {
1629 // Default to https, but loopback and private-LAN dev hosts are almost always http —
1630 // forcing https there just fails the handshake and shows a blank page.
1631 return (isLocalHost(host) ? "http://" : "https://") + u;
1632 }
1633 return SEARCH_URL.replace("%s", encodeURIComponent(u).replace(/%20/g, "+"));
1634 }
1635
1636 function go(raw, tab = active) {
1637 const u = toUrl(raw);
1638 if (!u) return;
1639 tab.url = u.startsWith("data:") || u.startsWith("dbb-reader:") ? "" : u;
1640 tab.stats = { requests: 0, bytes: 0, hosts: new Set(), redirects: [], answered: 0, errorStatus: 0, cancelled: 0, failures: [], statusExamples: [] }; // a new VISIT: facts start over (a page moving itself continues it)
1641 if (tab === active) setUrlBar(tab);
1642 renderTabs();
1643 // loadURL, not the src attribute: setting src to the address the page is already on loads it TWICE (two requests to the site).
1644 if (tab.ready) { try { Promise.resolve(tab.wv.loadURL(u)).catch(() => {}); } catch { tab.wv.src = u; } }
1645 else tab.pending = u; // applied on dom-ready
1646 }
1647 // ---- the address bar's suggestions -------------------------------------------------------------------------
1648 // Open tabs, saved links and kept copies come from this computer; search suggestions from askrobots only for text that is
1649 // not an address (and can be switched off). A site you use is completed inline: "slash" → slashdot.org.
1650 const omni = document.createElement("div"); omni.id = "omni"; document.body.appendChild(omni);
1651 let omniRows = [], omniSel = 0, omniTyped = "", omniSeq = 0, omniRemote = [], omniLocal = [], omniRemoteTimer = null, omniFilled = null;
1652 const omniRemoteOn = () => { try { return localStorage.getItem("omniRemote") !== "off"; } catch { return true; } };
1653 function omniClose() { omni.classList.remove("open"); omniRows = []; omniSeq++; clearTimeout(omniRemoteTimer); }
1654 function omniEnd() { omniEditing = false; omniClose(); }
1655 const searchFor = (text) => SEARCH_URL.replace("%s", encodeURIComponent(text.trim()).replace(/%20/g, "+"));
1656 function omniRender() {
1657 omniRows = omniLocal.length ? [omniLocal[0], ...omniLocal.slice(1).filter((r) => r.kind !== "ask"), ...omniRemote.map((t) => ({ kind: "suggest", text: t })), ...omniLocal.filter((r) => r.kind === "ask")] : [];
1658 if (!omniRows.length || document.activeElement !== urlInput) { omni.classList.remove("open"); return; }
1659 if (omniSel >= omniRows.length) omniSel = 0;
1660 const b = urlInput.getBoundingClientRect();
1661 omni.style.left = b.left + "px"; omni.style.top = (b.bottom + 4) + "px"; omni.style.width = Math.max(b.width, 420) + "px";
1662 omni.textContent = "";
1663 omniRows.forEach((r, i) => {
1664 const el = document.createElement("div"); el.className = "or" + (i === omniSel ? " sel" : ""); el.dataset.kind = r.kind;
1665 const [ic, tt, u, k] =
1666 r.kind === "go" ? ["↗", r.title, "", "Go"] :
1667 r.kind === "search" ? ["🔍", r.text, "", "Search askrobots"] :
1668 r.kind === "suggest" ? ["🔍", r.text, "", ""] :
1669 r.kind === "tab" ? ["⇥", r.title, r.url, "Switch to tab"] :
1670 r.kind === "bookmark" ? ["★", r.title, r.url, ""] :
1671 r.kind === "history" ? ["🕘", r.title, r.url, "History"] :
1672 r.kind === "kept" ? ["📥", r.title, r.original, "Kept copy"] :
1673 r.kind === "cmd" ? ["/", r.line, r.preview || r.description || "", r.readOnly ? "" : r.destructive ? "asks first" : "saves on askrobots"] :
1674 r.kind === "notice" ? ["ⓘ", r.text, "", r.connect ? "Connect" : ""] :
1675 ["✨", r.text, "", "Ask the assistant"];
1676 if (r.kind === "notice" && r.connect) el.classList.add("link");
1677 const fav = r.kind === "tab" || r.kind === "bookmark" || r.kind === "history" ? iconFor(r.url) : r.kind === "kept" ? iconFor(r.original) : null;
1678 for (const [cls, txt] of [["ic", ic], ["tt", tt], ["u", u], ["k", k]]) {
1679 if (!txt && cls !== "u") continue;
1680 const s2 = document.createElement("span"); s2.className = cls;
1681 if (cls === "ic" && fav) s2.appendChild(favImg(fav)); else s2.textContent = txt;
1682 el.appendChild(s2);
1683 }
1684 if (r.kind === "cmd" && r.problem && /\s/.test(omniTyped.trim())) { const pr = document.createElement("span"); pr.className = "p"; pr.textContent = r.problem; el.insertBefore(pr, el.querySelector(".k")); }
1685 el.addEventListener("mousedown", (e) => e.preventDefault()); // keep the focus in the address bar
1686 el.addEventListener("click", () => omniPick(r));
1687 el.addEventListener("mousemove", () => { if (omniSel !== i) { omniSel = i; omniPaintSel(); } });
1688 omni.appendChild(el);
1689 });
1690 const f = document.createElement("div"); f.className = "of";
1691 const on = omniRemoteOn();
1692 if (omniTyped.trim().startsWith("/")) { f.append(document.createTextNode("Tab completes · Enter runs · commands are your askrobots tools, run with your sign-in")); omni.appendChild(f); omni.classList.add("open"); return; }
1693 f.append(document.createTextNode("↑↓ pick · Enter open · Esc close · / for askrobots commands · search suggestions from askrobots.com: " + (on ? "on" : "off") + " "));
1694 const a = document.createElement("a"); a.textContent = on ? "turn off" : "turn on";
1695 a.addEventListener("mousedown", (e) => e.preventDefault());
1696 a.addEventListener("click", () => { try { localStorage.setItem("omniRemote", on ? "off" : "on"); } catch {} omniRemote = []; omniRender(); if (!on) omniFetchRemote(omniTyped, omniSeq); });
1697 f.appendChild(a); omni.appendChild(f);
1698 omni.classList.add("open");
1699 }
1700 function omniPaintSel() { [...omni.querySelectorAll(".or")].forEach((el, i) => el.classList.toggle("sel", i === omniSel)); }
1701 function omniFetchRemote(text, seq) {
1702 clearTimeout(omniRemoteTimer);
1703 if (!omniRemoteOn()) return;
1704 omniRemoteTimer = setTimeout(async () => {
1705 let list = [];
1706 try { list = await window.x402.omnibox.remote(text); } catch {}
1707 if (seq !== omniSeq) return;
1708 omniRemote = list; omniRender();
1709 }, 150);
1710 }
1711 async function omniUpdate(autofill) {
1712 const text = omniTyped, seq = ++omniSeq;
1713 clearTimeout(omniRemoteTimer);
1714 if (!text.trim()) { omniLocal = []; omniRemote = []; omniRender(); return; }
1715 let r = { autofill: null, rows: [] };
1716 try { r = await window.x402.omnibox.suggest({ text, tabs: tabs.map((t) => ({ id: t.id, url: t.url, title: t.title })), activeTab: active && active.id, autofill }); } catch {}
1717 if (seq !== omniSeq || urlInput.value !== text) return; // you typed on meanwhile
1718 if (r.autofill) {
1719 // complete inline: what you typed stays, the rest of the site name is selected, so typing on replaces it
1720 const typedHost = text.trim().replace(/^https?:\/\//i, "").replace(/^www\./i, "");
1721 if (r.autofill.startsWith(typedHost.toLowerCase()) && text === text.trimStart()) {
1722 urlInput.value = text + r.autofill.slice(typedHost.length);
1723 urlInput.setSelectionRange(text.length, urlInput.value.length);
1724 omniFilled = urlInput.value;
1725 }
1726 }
1727 if (!r.autofill) omniFilled = null;
1728 omniLocal = r.rows; omniRemote = []; omniSel = 0;
1729 omniRender();
1730 omniFetchRemote(text, seq);
1731 }
1732 // ---- "/" commands: complete, confirm when asked to, run, show the answer ----
1733 let omniConfirm = null;
1734 function omniComplete(r) {
1735 urlInput.value = r.line + (r.arg ? " " : "");
1736 omniTyped = urlInput.value; omniEditing = true;
1737 urlInput.setSelectionRange(urlInput.value.length, urlInput.value.length);
1738 omniUpdate(false);
1739 }
1740 async function omniRunCmd(text) {
1741 const confirmed = omniConfirm === text;
1742 omniConfirm = null;
1743 let r;
1744 try { r = await window.x402.omnibox.run(text, confirmed); } catch (e) { r = { ok: false, message: String(e && e.message || e) }; }
1745 if (r.confirm) {
1746 omniConfirm = text;
1747 omniLocal = [{ kind: "notice", text: r.message }, ...omniLocal.filter((x) => x.kind !== "notice")];
1748 omniSel = 1; omniRender();
1749 return;
1750 }
1751 if (r.connect) { omniEnd(); setUrlBar(active); setChat(true); toast("skipped", r.message); return; }
1752 if (!r.ok) { omniLocal = [{ kind: "notice", text: r.message }, ...omniLocal.filter((x) => x.kind !== "notice")]; omniSel = 0; omniRender(); return; }
1753 omniEnd(); setUrlBar(active); urlInput.blur();
1754 // Everything goes into the chat, so you can ask about it next. Searches and lists open it; a save just says so.
1755 if (r.readOnly) setChat(true);
1756 else { const n = toast("paid", r.sentence, r.page ? 8000 : 4000); if (r.page) n.appendChild(openLink(r.page)); }
1757 }
1758 function omniPick(r) {
1759 if (r.kind === "cmd") {
1760 const typed = omniTyped.trim();
1761 const complete = typed === r.line || /\s/.test(typed);
1762 if (!complete || (!r.ready && !/\s/.test(typed) && r.arg)) { omniComplete(r); return; }
1763 if (!r.ready) { omniLocal = [{ kind: "notice", text: "/" + r.name + ": " + (r.problem || "cannot run yet") }, ...omniLocal.filter((x) => x.kind !== "notice")]; omniRender(); return; }
1764 omniRunCmd(/\s/.test(typed) ? typed : r.line);
1765 return;
1766 }
1767 if (r.kind === "notice") { if (r.connect) { omniEnd(); setUrlBar(active); setChat(true); } return; }
1768 omniEnd();
1769 if (r.kind === "tab") { const t = tabs.find((x) => x.id === r.id); if (t) { switchTo(t); return; } }
1770 if (r.kind === "ask") { setUrlBar(active); setChat(true); chatIn.value = r.text; chatSend(); return; }
1771 if (r.kind === "search" || r.kind === "suggest") { go(searchFor(r.text)); return; }
1772 go(r.url);
1773 }
1774 urlInput.addEventListener("input", (e) => {
1775 omniEditing = true;
1776 omniTyped = urlInput.value;
1777 omniUpdate(!/^delete/.test(e.inputType || "")); // no completing while you delete
1778 });
1779 urlInput.addEventListener("blur", () => setTimeout(() => { if (document.activeElement !== urlInput) { omniClose(); omniEditing = false; } }, 0));
1780 urlInput.addEventListener("keydown", (e) => {
1781 const open = omni.classList.contains("open") && omniRows.length;
1782 if (e.key === "ArrowDown" || e.key === "ArrowUp") {
1783 if (!open) return;
1784 e.preventDefault();
1785 omniSel = (omniSel + (e.key === "ArrowDown" ? 1 : -1) + omniRows.length) % omniRows.length;
1786 omniPaintSel();
1787 return;
1788 }
1789 if (e.key === "Tab" && open && omniTyped.trim().startsWith("/")) {
1790 const r = omniRows[omniSel];
1791 if (r && r.kind === "cmd") { e.preventDefault(); omniComplete(r); }
1792 return;
1793 }
1794 if (e.key === "Escape") {
1795 omniConfirm = null;
1796 if (open) { omniClose(); if (urlInput.value !== omniTyped && omniEditing) urlInput.value = omniTyped; }
1797 else { omniEditing = false; setUrlBar(active); urlInput.select(); }
1798 return;
1799 }
1800 if (e.key === "Enter" && !e.isComposing) {
1801 e.preventDefault();
1802 if (urlInput.value.trim().startsWith("/")) {
1803 // a command never becomes a search
1804 const r = open ? omniRows[omniSel] : null;
1805 if (r && (r.kind === "cmd" || r.kind === "notice")) omniPick(r);
1806 else if (!open && /\s/.test(urlInput.value.trim())) omniRunCmd(urlInput.value.trim()); // pressed before the list arrived
1807 return;
1808 }
1809 if (open && omniSel > 0) { omniPick(omniRows[omniSel]); return; }
1810 if (omniRows[0] && omniRows[0].kind === "go" && omniFilled && urlInput.value === omniFilled) { omniPick(omniRows[0]); return; } // the completed site, with its own scheme
1811 const v = urlInput.value;
1812 omniEnd();
1813 go(v);
1814 }
1815 });
1816 // ⌘← / ⌘→ (Alt+← / Alt+→ elsewhere) with the browser's own window focused, outside a text field: back and forward.
1817 document.addEventListener("keydown", (e) => {
1818 if (e.shiftKey || (e.key !== "ArrowLeft" && e.key !== "ArrowRight")) return;
1819 const mac = /Mac/.test(navigator.platform);
1820 if (mac ? !e.metaKey || e.altKey || e.ctrlKey : !e.altKey || e.metaKey || e.ctrlKey) return;
1821 const t = document.activeElement;
1822 if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
1823 e.preventDefault();
1824 $(e.key === "ArrowLeft" ? "back" : "fwd").click();
1825 });
1826 // ⌘K belongs to the page (askrobots' own search box uses it): when the address bar or the browser has the focus — as
1827 // right after a new tab — hand it to the page instead of swallowing it.
1828 document.addEventListener("keydown", (e) => {
1829 if (!(e.metaKey || e.ctrlKey) || e.shiftKey || e.altKey || (e.key || "").toLowerCase() !== "k") return;
1830 if (document.activeElement === chatIn || !active || !active.ready) return;
1831 e.preventDefault();
1832 omniEnd(); setUrlBar(active);
1833 try {
1834 active.wv.focus();
1835 const mods = [e.metaKey ? "meta" : "control"];
1836 active.wv.sendInputEvent({ type: "keyDown", keyCode: "K", modifiers: mods });
1837 active.wv.sendInputEvent({ type: "keyUp", keyCode: "K", modifiers: mods });
1838 } catch {}
1839 });
1840 // Reload, which becomes Stop while the page is loading.
1841 const RELOAD_ICON = '<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M13.2 6.2A5.5 5.5 0 1 0 13.5 9.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><path d="M13.6 2.2v4.3H9.3" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>';
1842 const STOP_ICON = ICONS.stop;
1843 function paintReload() {
1844 const b = $("reload");
1845 if (!b) return;
1846 const loading = !!(active && active.loading);
1847 b.innerHTML = loading ? STOP_ICON : RELOAD_ICON; // our own constant markup, never page text
1848 b.setAttribute("aria-label", loading ? "Stop" : "Reload");
1849 b.title = loading ? "Stop loading" : "Reload (⌘R)";
1850 }
1851 paintReload();
1852 $("reload").onclick = () => { if (!active) return; try { active.loading ? active.wv.stop() : active.wv.reload(); } catch {} };
1853 // Back and Forward are greyed out when the tab has nowhere to go that way (a new tab, the newest page).
1854 function paintNav() {
1855 let back = false, fwd = false;
1856 try { back = !!active && active.wv.canGoBack(); fwd = !!active && active.wv.canGoForward(); } catch {} // not attached yet
1857 $("back").disabled = !back;
1858 $("fwd").disabled = !fwd;
1859 }
1860 $("back").onclick = () => { try { active.wv.canGoBack() && active.wv.goBack(); } catch {} };
1861 $("fwd").onclick = () => { try { active.wv.canGoForward() && active.wv.goForward(); } catch {} };
1862
1863 // ---- history (kept on the askrobots account; see history.ts) ----------------------------------
1864 let histState = null;
1865 function paintHistory(st) {
1866 histState = st;
1867 const b = $("histBtn");
1868 if (!st || (!st.on && /not signed in/.test(st.why || ""))) { b.style.display = "none"; return; }
1869 b.style.display = "";
1870 b.classList.toggle("paused", !!(st.on && st.paused));
1871 b.classList.toggle("off", !st.on);
1872 b.textContent = !st.on ? "History off" : st.paused ? "History paused" : "History";
1873 b.title = !st.on
1874 ? "History is off: " + st.why + "."
1875 : st.paused
1876 ? "History is paused: pages are not being recorded. Click to resume."
1877 : "History: the pages you visit are kept on your askrobots account, so you can find one later (sign-in and payment pages never are). Click to pause." + (st.error ? " Last problem: " + st.error : "");
1878 }
1879 window.x402.history.onChanged(paintHistory);
1880 window.x402.history.state().then(paintHistory).catch(() => {});
1881 $("histBtn").onclick = () => historyCmd("pause");
1882 async function historyCmd(what) {
1883 const url = active && /^https?:\/\//i.test(active.url) ? active.url : "";
1884 if (what === "open") return window.x402.history.open();
1885 if (what === "pause") {
1886 if (!histState?.on) { toast("quoted", "History is off: " + (histState?.why || "not signed in to askrobots") + "."); return; }
1887 const st = await window.x402.history.pause(!histState.paused).catch((e) => (toast("bad", "Could not change history: " + e.message), null));
1888 if (st) { paintHistory(st); toast("quoted", st.paused ? "History paused: pages are not recorded until you resume." : "History resumed."); }
1889 return;
1890 }
1891 if (!url) { toast("quoted", "This tab is not a web page."); return; }
1892 if (what === "never") {
1893 const r = await window.x402.history.never(url);
1894 toast(r.ok ? "quoted" : "bad", r.ok ? "Pages from " + new URL(url).hostname + " will not be recorded. What is already there stays until you forget it." : "Could not save that: " + r.message);
1895 return;
1896 }
1897 const scope = { "forget-url": "url", "forget-site": "site", "forget-hour": "last_hour" }[what];
1898 if (!scope) return;
1899 const r = await window.x402.history.forget(scope, url);
1900 if (r.ok) toast("quoted", "Forgotten: " + r.forgotten + (r.forgotten === 1 ? " visit." : " visits."));
1901 else if (!r.cancelled) toast("bad", "Could not forget: " + (r.message || "unknown error"));
1902 }
1903
1904 function toast(cls, text, ms = 4000) {
1905 const n = document.createElement("div");
1906 n.className = "note " + cls;
1907 n.textContent = text;
1908 $("toast").appendChild(n);
1909 setTimeout(() => n.remove(), ms);
1910 return n;
1911 }
1912
1913 // ---- password manager ------------------------------------------------
1914 // Secrets never reach this document: logins go page → main, fills go main → page.
1915 // We only ever see usernames, origins and ids.
1916 const vault = window.x402.vault;
1917 let vstate = { exists: false, unlocked: false, count: null };
1918 let vaultPanelOpen = false;
1919 let vaultMsg = ""; // transient error/info line inside the panel
1920
1921 function h(tag, props, ...kids) {
1922 const el = document.createElement(tag);
1923 for (const [k, v] of Object.entries(props || {})) {
1924 if (k === "class") el.className = v;
1925 else if (k.startsWith("on")) el.addEventListener(k.slice(2), v);
1926 else el.setAttribute(k, v);
1927 }
1928 for (const kid of kids) el.append(kid == null ? "" : kid.nodeType ? kid : document.createTextNode(String(kid)));
1929 return el;
1930 }
1931 const hostOf = (u) => { try { return new URL(u).host; } catch { return u; } };
1932
1933 function applyVaultState(st) {
1934 vstate = st;
1935 $("keyBtn").classList.toggle("unlocked", st.unlocked);
1936 $("keyBtn").title = st.unlocked ? `Passwords — unlocked (${st.count} saved)` : st.exists ? "Passwords — locked" : "Passwords — set up";
1937 if (vaultPanelOpen) renderVaultPanel();
1938 renderOffer();
1939 }
1940 vault.state().then(applyVaultState);
1941 vault.onState(applyVaultState);
1942
1943 function setVaultPanel(open) {
1944 vaultPanelOpen = open;
1945 $("vaultPanel").classList.toggle("open", open);
1946 $("keyBtn").classList.toggle("on", open);
1947 if (open) { vaultMsg = ""; renderVaultPanel(); }
1948 }
1949 $("keyBtn").onclick = () => setVaultPanel(!vaultPanelOpen);
1950 document.addEventListener("keydown", (e) => { if (e.key === "Escape" && vaultPanelOpen) setVaultPanel(false); });
1951
1952 async function renderVaultPanel() {
1953 const P = $("vaultPanel");
1954 P.innerHTML = "";
1955 const err = () => (vaultMsg ? h("div", { class: "err" }, vaultMsg) : "");
1956
1957 if (!vstate.exists) {
1958 const m1 = h("input", { type: "password", placeholder: "Master password (8+ characters)", autocomplete: "off" });
1959 const m2 = h("input", { type: "password", placeholder: "Confirm master password", autocomplete: "off" });
1960 const go = async () => {
1961 if (m1.value !== m2.value) { vaultMsg = "Passwords don't match."; return renderVaultPanel(); }
1962 const r = await vault.create(m1.value);
1963 vaultMsg = r.ok ? "" : r.message;
1964 if (!r.ok) renderVaultPanel();
1965 };
1966 m2.addEventListener("keydown", (e) => { if (e.key === "Enter") go(); });
1967 P.append(h("h4", {}, "🔑 Set up your password vault"),
1968 h("div", { class: "hint" }, "Passwords are encrypted on this computer with your master password. There is no recovery if you forget it, and nothing is sent anywhere."),
1969 m1, m2, err(), h("button", { class: "sbtn", onclick: go }, "Create vault"));
1970 m1.focus();
1971 return;
1972 }
1973
1974 if (!vstate.unlocked) {
1975 const m = h("input", { type: "password", placeholder: "Master password", autocomplete: "off" });
1976 const go = async () => {
1977 const r = await vault.unlock(m.value);
1978 vaultMsg = r.ok ? "" : r.message;
1979 if (!r.ok) renderVaultPanel();
1980 };
1981 m.addEventListener("keydown", (e) => { if (e.key === "Enter") go(); });
1982 P.append(h("h4", {}, "🔑 Vault locked"), m, err(), h("button", { class: "sbtn", onclick: go }, "Unlock"));
1983 m.focus();
1984 return;
1985 }
1986
1987 const siteRes = active && active.wcId != null ? await vault.list(active.wcId) : { ok: true, data: [] };
1988 const allRes = await vault.list();
1989 if (!vaultPanelOpen || !vstate.unlocked) return; // state changed while we awaited
1990 P.innerHTML = "";
1991 const site = siteRes.ok ? siteRes.data : [];
1992 const all = allRes.ok ? allRes.data : [];
1993 const host = active && active.url ? hostOf(active.url) : "";
1994
1995 P.append(h("h4", {}, `🔑 ${all.length} saved`, h("span", { class: "sp" }), h("button", { class: "sbtn quiet", onclick: () => vault.lock() }, "Lock")));
1996 if (vaultMsg) P.append(h("div", { class: "err" }, vaultMsg));
1997
1998 if (host) {
1999 P.append(h("div", { class: "sec" }, "This site · " + host));
2000 if (!site.length) P.append(h("div", { class: "hint" }, "No saved login for this exact site."));
2001 for (const c of site) {
2002 P.append(h("div", { class: "cred" },
2003 h("div", { class: "who" }, c.username || "(no username)"),
2004 h("button", { class: "sbtn", onclick: () => doFill(c.id, false) }, "Fill"),
2005 h("button", { class: "sbtn", onclick: () => doFill(c.id, true) }, "Sign in")));
2006 }
2007 // Manual add for the current page.
2008 const u = h("input", { placeholder: "Username or email", autocomplete: "off" });
2009 const pw = h("input", { type: "password", placeholder: "Password", autocomplete: "off" });
2010 P.append(h("div", { class: "sec" }, "Save a login for this site"), u,
2011 h("div", { class: "row2" }, pw, h("button", { class: "sbtn quiet", onclick: async () => { pw.type = "text"; pw.value = await vault.generate(20); } }, "Generate")),
2012 h("button", { class: "sbtn", onclick: async () => {
2013 if (!pw.value) return;
2014 const r = await vault.add({ wcId: active.wcId, username: u.value, password: pw.value });
2015 vaultMsg = r.ok ? "" : r.message;
2016 if (r.ok) toast("quoted", "Saved " + (u.value || "login") + " for " + host, 2500);
2017 renderVaultPanel();
2018 } }, "Save"));
2019 }
2020
2021 P.append(h("div", { class: "sec" }, "All logins"));
2022 if (!all.length) P.append(h("div", { class: "hint" }, "Nothing saved yet. Sign in to a site and you'll be offered to save it."));
2023 for (const c of all) {
2024 P.append(h("div", { class: "cred" },
2025 h("div", { class: "who" }, c.username || "(no username)", h("small", {}, c.origin)),
2026 h("span", { class: "x", title: "Delete", onclick: async () => {
2027 if (!confirm(`Delete the saved login for ${c.username || "(no username)"} on ${c.origin}?`)) return;
2028 await vault.remove(c.id);
2029 renderVaultPanel();
2030 } }, "✕")));
2031 }
2032 }
2033
2034 async function doFill(id, submit) {
2035 if (!active || active.wcId == null) return;
2036 const r = await vault.fill({ wcId: active.wcId, id, submit });
2037 if (r.ok) { toast("quoted", (submit ? "Signing in as " : "Filled ") + (r.data.username || "login"), 2200); setVaultPanel(false); }
2038 else { vaultMsg = r.message; if (vaultPanelOpen) renderVaultPanel(); else toast("skipped", r.message); }
2039 }
2040
2041 // Offers pushed from main (page has a login form we know / user just submitted one).
2042 vault.onOffer((o) => {
2043 const tab = tabs.find((t) => t.wcId === o.wcId);
2044 if (!tab) return;
2045 if (o.kind === "save") {
2046 tab.saveOffer = o;
2047 // Same lifetime as the main-process copy of the pending login; don't nag forever.
2048 setTimeout(() => { if (tab.saveOffer === o) { tab.saveOffer = null; if (tab === active) renderOffer(); } }, 120000);
2049 } else tab.fillOffer = o;
2050 if (tab === active) renderOffer();
2051 });
2052
2053 function renderOffer() {
2054 const bar = $("offerbar");
2055 bar.innerHTML = "";
2056 const t = active;
2057 if (!t) return void bar.classList.remove("show");
2058 const close = (which) => h("button", { class: "sbtn quiet", onclick: () => {
2059 if (which === "save") { vault.dismiss(t.wcId); t.saveOffer = null; } else t.fillOffer = null;
2060 renderOffer();
2061 } }, which === "save" ? "Not now" : "✕");
2062
2063 if (t.saveOffer) {
2064 const o = t.saveOffer;
2065 const who = o.username || "this login";
2066 const canSave = vstate.unlocked; // mode may be stale (e.g. "locked" before the user unlocked)
2067 const msg = !vstate.exists ? ["Create a password vault to save ", who, " for ", hostOf(o.origin), "?"]
2068 : !canSave ? ["Unlock your vault to save ", who, " for ", hostOf(o.origin), "."]
2069 : [o.mode === "update" ? "Update the saved password for " : "Save password for ", who, " on ", hostOf(o.origin), "?"];
2070 const main = canSave
2071 ? h("button", { class: "sbtn", onclick: async () => {
2072 const r = await vault.accept(t.wcId);
2073 t.saveOffer = null;
2074 toast(r.ok ? "paid" : "skipped", r.ok ? "Saved login for " + hostOf(o.origin) : "Couldn't save: " + r.message);
2075 renderOffer();
2076 } }, o.mode === "update" ? "Update" : "Save")
2077 : h("button", { class: "sbtn", onclick: () => setVaultPanel(true) }, !vstate.exists ? "Create vault…" : "Unlock…");
2078 bar.append(h("span", { class: "msg" }, "🔑 ", h("b", {}, msg[0]), msg[1], h("b", {}, msg[2]), msg[3]), main, close("save"));
2079 return void bar.classList.add("show");
2080 }
2081
2082 if (t.fillOffer && t.fillOffer.matches.length) {
2083 const m = t.fillOffer.matches;
2084 bar.append(h("span", { class: "msg" }, "🔑 Saved login for ", h("b", {}, hostOf(t.fillOffer.origin))));
2085 for (const c of m.slice(0, 3)) {
2086 bar.append(h("button", { class: "sbtn", onclick: () => doFill(c.id, true) }, "Sign in" + (c.username ? " as " + c.username : "")),
2087 h("button", { class: "sbtn quiet", onclick: () => doFill(c.id, false) }, "Fill"));
2088 }
2089 bar.append(close("fill"));
2090 return void bar.classList.add("show");
2091 }
2092 bar.classList.remove("show");
2093 }
2094
2095 // ---- guided tour -----------------------------------------------------
2096 const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2097 function currentBase() {
2098 try {
2099 const u = new URL(active.url);
2100 // Only reuse the current origin if it is local — the tour's routes live on the demo gallery.
2101 if (u.protocol.startsWith("http") && isLocalHost(u.hostname)) return u.origin;
2102 } catch {}
2103 return "http://127.0.0.1:8899"; // default demo gallery
2104 }
2105 const TOUR = [["/", 2600], ["/room", 3400], ["/article", 3400], ["/free", 2800], ["/unknown", 3400], ["/", 1600]];
2106 let touring = false;
2107 $("galleryBtn").onclick = () => newTab("http://127.0.0.1:8899/");
2108 $("tourBtn").onclick = async () => {
2109 if (touring) { touring = false; return; } // second click stops
2110 touring = true;
2111 $("tourBtn").classList.add("on");
2112 setInspector(true);
2113 const base = currentBase();
2114 for (const [route, dwell] of TOUR) {
2115 if (!touring) break;
2116 go(base + route);
2117 await sleep(dwell);
2118 }
2119 touring = false;
2120 $("tourBtn").classList.remove("on");
2121 };
2122
2123 // ---- inspector -------------------------------------------------------
2124 // `rows` (resource URL -> lifecycle) lives on each tab; see the tabs section.
2125 const history = []; // persistent session log across all tabs, newest-first
2126 let view = "page"; // "page" | "session"
2127 let inspectorOpen = false;
2128
2129 function setInspector(open) {
2130 inspectorOpen = open;
2131 $("inspector").classList.toggle("open", open);
2132 $("inspectBtn").classList.toggle("on", open);
2133 }
2134 $("inspectBtn").onclick = () => {
2135 setInspector(!inspectorOpen);
2136 active.userClosed = !inspectorOpen; // once closed on a page, stop auto-opening
2137 };
2138 function setView(v) {
2139 view = v;
2140 $("tabPage").classList.toggle("on", v === "page");
2141 $("tabSession").classList.toggle("on", v === "session");
2142 renderInspector();
2143 }
2144 $("tabPage").onclick = () => setView("page");
2145 $("tabSession").onclick = () => setView("session");
2146
2147 function cheapest(quotes) {
2148 return (quotes || []).reduce((a, b) => (!a || parseFloat(b.price.replace("$","")) < parseFloat(a.price.replace("$","")) ? b : a), null);
2149 }
2150
2151 function statusOf(e) {
2152 if (e.outcome === "paid") return { cls: "paid", label: e.paidStatus === "delivered" ? "paid" : (e.paidStatus || "paid") };
2153 if (e.outcome === "skipped") {
2154 const r = (e.skipReason || "").toLowerCase();
2155 if (r.includes("declined by user")) return { cls: "refused", label: "you declined" };
2156 if (r.includes("unknown asset") || r.includes("cannot price") || r.includes("not allowed") || r.includes("scheme")) return { cls: "refused", label: "refused" };
2157 return { cls: "refused", label: "skipped" };
2158 }
2159 if (e.decision === "prompt") return { cls: "prompt", label: "waiting…" };
2160 if (e.decision === "deny") return { cls: "refused", label: "refused" };
2161 if (e.quote) return { cls: "quoted", label: "quoted" };
2162 return { cls: "quoted", label: "…" };
2163 }
2164
2165 function shortPath(u) {
2166 try { const x = new URL(u); return x.host + x.pathname; } catch { return u; }
2167 }
2168
2169 function isRealTx(tx) {
2170 return typeof tx === "string" && /^0x[0-9a-fA-F]{64}$/.test(tx) && !tx.startsWith("0xDEMO");
2171 }
2172 function txCell(tx) {
2173 if (!tx) return "(pending)";
2174 if (isRealTx(tx)) return '<span class="txlink" data-url="https://sepolia.basescan.org/tx/' + tx + '">' + tx.slice(0, 18) + "… ↗</span>";
2175 return tx.slice(0, 10) + "… (mock)";
2176 }
2177 // Click a real tx → open it on BaseScan in the page.
2178 $("insList").addEventListener("click", (e) => {
2179 const l = e.target.closest(".txlink");
2180 if (l && l.dataset.url) newTab(l.dataset.url); // keep the paid page; open the tx beside it
2181 });
2182
2183 function renderInspector() {
2184 const badge = $("inspectCount");
2185 badge.textContent = rows.size;
2186 badge.style.display = rows.size ? "flex" : "none";
2187 if (view === "session") return renderSession();
2188 return renderPage();
2189 }
2190
2191 function renderSession() {
2192 const list = $("insList");
2193 $("insSub").textContent = history.length ? `${history.length} events` : "session";
2194 if (history.length === 0) {
2195 list.innerHTML = '<div id="insEmpty">Nothing charged yet this session.<br />Every payment and refusal is logged here, timestamped — and it persists as you navigate.</div>';
2196 return;
2197 }
2198 list.innerHTML = `<div id="histTotal">Session total <b style="color:#7ee787">${$("meter").textContent}</b> · ${history.length} events</div>`;
2199 for (const h of history) {
2200 const el = document.createElement("div");
2201 el.className = "histrow";
2202 el.innerHTML =
2203 `<span class="t">${h.at}</span>
2204 <span class="h" title="${h.resource}">${shortPath(h.resource)}</span>
2205 <span class="p">${h.price}</span>
2206 <span class="pill ${h.cls}">${h.label}</span>`;
2207 list.appendChild(el);
2208 }
2209 }
2210
2211 function renderPage() {
2212 const list = $("insList");
2213 const count = rows.size;
2214 $("insSub").textContent = count ? `${count} on this page` : "this page";
2215
2216 if (count === 0) {
2217 list.innerHTML = '<div id="insEmpty">No x402 activity yet.<br />Load a page that returns 402 Payment Required — every challenge, decision, and payment shows up here.</div>';
2218 return;
2219 }
2220 list.innerHTML = "";
2221 for (const e of rows.values()) {
2222 const st = statusOf(e);
2223 const q = e.quote;
2224 const row = document.createElement("div");
2225 row.className = "row";
2226 row.innerHTML =
2227 `<div class="top">
2228 <span class="path" title="${e.resource}">${shortPath(e.resource)}</span>
2229 <span class="price">${q ? q.price : "—"}</span>
2230 <span class="pill ${st.cls}">${st.label}</span>
2231 </div>
2232 <div class="detail">
2233 <div class="step">Request</div>
2234 <dl>
2235 <dt>requested</dt><dd>${e.requested || e.resource}</dd>
2236 ${e.requested && e.requested !== e.resource ? `<dt>402 claims</dt><dd class="warn">${e.resource}</dd>` : ""}
2237 </dl>
2238 <div class="step">Challenge</div>
2239 <dl>
2240 <dt>scheme</dt><dd>${q ? q.scheme : "—"}</dd>
2241 <dt>network</dt><dd>${q ? q.network : "—"}</dd>
2242 <dt>asset</dt><dd>${q ? q.asset + " · " + q.assetAddress : "—"}</dd>
2243 <dt>amount</dt><dd>${q ? q.amountAtomic + " atomic" : "—"}</dd>
2244 <dt>pay to</dt><dd>${q ? q.payTo : "—"}</dd>
2245 <dt>max ttl</dt><dd>${q ? q.maxTimeoutSeconds + "s" : "—"}</dd>
2246 </dl>
2247 ${e.quotes && e.quotes.length > 1 ? `<div class="step">Offered (cheapest wins)</div>
2248 <dl>${e.quotes.map((o) => `<dt>${o.network}</dt><dd>${o.price} ${o.asset}${o === e.quote ? ' <span class="warn">← paid</span>' : ""}</dd>`).join("")}</dl>` : ""}
2249 <div class="step">Decision</div>
2250 <dl><dt>action</dt><dd>${e.decision || "—"}</dd><dt>reason</dt><dd>${e.reason || "—"}</dd></dl>
2251 ${e.outcome === "paid" && e.auth ? `<div class="step">Signed authorization (EIP-3009)</div>
2252 <dl>
2253 <dt>from</dt><dd>${e.auth.from}</dd>
2254 <dt>to</dt><dd>${e.auth.to}</dd>
2255 <dt>value</dt><dd>${e.auth.value} atomic</dd>
2256 <dt>valid</dt><dd>${new Date(e.auth.validAfter*1000).toLocaleTimeString()} – ${new Date(e.auth.validBefore*1000).toLocaleTimeString()}</dd>
2257 <dt>nonce</dt><dd>${e.nonce || "—"}</dd>
2258 <dt>signature</dt><dd>${e.signature ? e.signature.slice(0,42) + "…" : "—"}</dd>
2259 </dl>` : ""}
2260 ${e.outcome === "paid" ? `<div class="step">Settlement</div>
2261 <dl>
2262 <dt>status</dt><dd>${e.paidStatus}</dd>
2263 <dt>tx</dt><dd>${txCell(e.tx)}</dd>
2264 </dl>` : ""}
2265 ${e.rejected && e.rejected.length ? `<div class="step">Rejected options</div><dl><dt>—</dt><dd>${e.rejected.join("<br>")}</dd></dl>` : ""}
2266 </div>`;
2267 row.querySelector(".top").onclick = () => row.classList.toggle("open");
2268 list.appendChild(row);
2269 }
2270 }
2271
2272 function upsert(resource, patch) {
2273 const t = ownerOf(resource);
2274 const e = t.rows.get(resource) || { resource };
2275 Object.assign(e, patch);
2276 t.rows.set(resource, e);
2277 if (patch.outcome === "paid") t.settledUntil = Date.now() + 2500;
2278 if (patch.outcome === "paid" && !t.paid) { t.paid = true; renderTabs(); }
2279 refreshThrobber(t);
2280 if (t !== active) return; // background tab: record it, don't disturb the one in front
2281 if (!inspectorOpen && !t.userClosed) setInspector(true); // surface payment activity
2282 renderInspector();
2283 }
2284
2285 // Log a terminal outcome (paid / refused) to the persistent session history.
2286 function logHistory(resource) {
2287 const e = ownerOf(resource).rows.get(resource);
2288 if (!e) return;
2289 const st = statusOf(e);
2290 history.unshift({
2291 resource,
2292 price: e.quote ? e.quote.price : "—",
2293 label: st.label,
2294 cls: st.cls,
2295 at: new Date().toLocaleTimeString(),
2296 });
2297 if (view === "session") renderInspector();
2298 }
2299
2300 window.x402.onEvent((ev) => {
2301 // "quoted" opens a resource's lifecycle (quoted → decided → paid). Drop any stale
2302 // tab mapping so a second tab loading the same URL isn't credited to the first.
2303 if (ev.kind === "quoted") owners.delete(ev.resource);
2304 if (ev.kind === "quoted") {
2305 const c = cheapest(ev.quotes);
2306 upsert(ev.resource, { quote: c, quotes: ev.quotes, rejected: ev.rejected });
2307 if (c) toast("quoted", `Price: ${c.price} ${c.asset} — ${shortPath(ev.resource)}`, 2500);
2308 } else if (ev.kind === "decided") {
2309 upsert(ev.resource, { decision: ev.action, reason: ev.reason });
2310 } else if (ev.kind === "paid") {
2311 const meter = $("meter");
2312 meter.textContent = ev.totalSpent;
2313 meter.classList.toggle("zero", ev.totalSpent === "$0.00");
2314 upsert(ev.resource, { outcome: "paid", paidStatus: ev.status, nonce: ev.nonce, validBefore: ev.validBefore, tx: ev.tx, requested: ev.requested, auth: ev.auth, signature: ev.signature });
2315 logHistory(ev.resource);
2316 toast("paid", `Paid ${ev.amount} ${ev.asset} → ${new URL(ev.dest).host}${ev.tx ? " ✓" : ""}`);
2317 } else if (ev.kind === "net-provider-changed") {
2318 $("cn").classList.toggle("show", !!ev.enabled);
2319 } else if (ev.kind === "auto-decision") {
2320 // Automation answered a payment prompt - never silent.
2321 toast(ev.approved ? "quoted" : "skipped", "🤖 " + (ev.approved ? "Auto-approved " : "Auto-declined ") + ev.price + " (" + ev.mode + ", cap $" + ev.cap + ") - " + shortPath(ev.resource), 5000);
2322 } else if (ev.kind === "download") {
2323 const prev = downloads.get(ev.id);
2324 downloads.set(ev.id, ev);
2325 if (active) refreshThrobber(active);
2326 paintDlBtn();
2327 if (dlOpen) loadDl();
2328 const finished = !prev || prev.state === "progressing" || prev.state === "paused";
2329 if (finished && ev.state === "completed") {
2330 toast("paid", "⬇ Saved " + ev.name + " (" + fmtBytes(ev.total || ev.received) + ")" + (ev.paid ? " · paid " + ev.paid : "") + " — Downloads in the status bar (⌘⇧J)", 7000);
2331 } else if (finished && ev.state === "interrupted") {
2332 toast("skipped", "⬇ Download failed: " + ev.name, 6000);
2333 }
2334 } else if (ev.kind === "cards-progress") {
2335 if (ev.start) toast("quoted", "▦ Reading the posts on this page for a card view…", 3000);
2336 else if (ev.done && ev.note) toast("skipped", "▦ " + ev.note, 7000);
2337 else if (ev.done && ev.added) toast("quoted", "▦ " + ev.added + " more posts", 3000);
2338 } else if (ev.kind === "reader-busy") {
2339 const t = tabs.find((x) => x.wcId === ev.wcId);
2340 if (t) { t.aiBusy = ev.busy ? (ev.provider + (ev.model ? " · " + ev.model : "")) : null; refreshThrobber(t); }
2341 } else if (ev.kind === "ai-summary") {
2342 // Never silent: what left this computer, to whom, and what it cost.
2343 const cost = ev.costUsd == null ? "" : " · ≈$" + (ev.costUsd < 0.01 ? ev.costUsd.toFixed(4) : ev.costUsd.toFixed(3));
2344 toast("quoted", "📖 Sent " + ev.sentChars.toLocaleString() + " characters from " + ev.host + " to " + ev.provider + " (" + ev.model + ") · " + (ev.ms / 1000).toFixed(1) + "s" + cost, 7000);
2345 } else if (ev.kind === "ai-error") {
2346 toast("skipped", "📖 Summary failed (" + ev.provider + "): " + ev.message, 7000);
2347 } else if (ev.kind === "ai-provider") {
2348 toast("quoted", "📖 AI provider: " + ev.provider + " · " + ev.model, 3500);
2349 } else if (ev.kind === "approval-changed") {
2350 toast("quoted", "🤖 Payment approval set to " + ev.mode + (ev.mode === "auto" ? " up to $" + ev.maxUsd : ""), 5000);
2351 } else if (ev.kind === "skipped") {
2352 upsert(ev.resource, { outcome: "skipped", skipReason: ev.reason });
2353 logHistory(ev.resource);
2354 toast("skipped", `Skipped: ${ev.reason}`);
2355 }
2356 });
2357
2358 window.x402.spent().then((s) => {
2359 const meter = $("meter");
2360 meter.textContent = s;
2361 meter.classList.toggle("zero", s === "$0.00");
2362 });
2363
2364 // ---- wallet balance + funding ----------------------------------------
2365 let walletAddress = "";
2366 window.x402.wallet().then(({ address }) => { walletAddress = address || ""; });
2367 window.x402.onBalance(({ usdc, address, merchantUsdc, merchantAddress }) => {
2368 walletAddress = address || walletAddress;
2369 const b = $("bal");
2370 b.textContent = usdc == null ? "◈ —" : "◈ " + usdc + " USDC";
2371 b.classList.toggle("funded", usdc != null && parseFloat(usdc) > 0);
2372 const mb = $("mbal");
2373 if (merchantAddress && merchantUsdc != null) {
2374 mb.style.display = "";
2375 mb.textContent = "🏪 " + merchantUsdc;
2376 mb.title = "Merchant wallet " + merchantAddress + " — live payments land here";
2377 const earning = parseFloat(merchantUsdc) > 0;
2378 mb.classList.toggle("earning", earning);
2379 $("refundBtn").style.display = earning ? "" : "none";
2380 }
2381 });
2382 $("bal").onclick = async () => {
2383 if (!walletAddress) return;
2384 await window.x402.copy(walletAddress);
2385 toast("quoted", "Address copied: " + walletAddress.slice(0, 12) + "…", 2200);
2386 };
2387 $("fundBtn").onclick = () => {
2388 window.x402.fund();
2389 toast("quoted", "Address copied — faucet opened in your browser. Pick Base Sepolia.", 4500);
2390 };
2391 $("refundBtn").onclick = async () => {
2392 const btn = $("refundBtn");
2393 btn.disabled = true;
2394 btn.textContent = "Refunding…";
2395 try {
2396 const r = await window.x402.refund();
2397 if (r && r.tx) toast("paid", "Refunded → you. tx " + r.tx.slice(0, 14) + "… ✓");
2398 else toast("skipped", "Refund: " + ((r && r.error) || "nothing to refund"));
2399 } finally {
2400 btn.disabled = false;
2401 btn.textContent = "Refund";
2402 }
2403 };
2404
2405 // First tab opens on the homepage; go() defers the navigation until dom-ready.
2406 newTab(window.x402.homepage || null);
2407 if (!window.x402.homepage) urlInput.focus();
2408 </script>
2409 </body>
2410</html>