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

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