1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
|
#!/usr/bin/env python3
"""
The phone's photo backup section (photo-sync-settings.js), rendered in Chrome
on its page (android-sync-page.js) at phone widths with names nobody would
choose for a fixture.
Only the Android application has this section, and its engine is Chromium, so
one engine is the whole of it. The bridge is a stand-in that answers the way
the phone does; the group connection (`connection-pool.js`) is replaced in the
copy by one that hands out a node with long, space-free folder names, because
those are what widen a page (CLAUDE.md). Four states: choosing where backups
go, setting up photos, set up with a refusal showing, and setting up with only
selected photos allowed.
photo_sync_probe.py prints one JSON object, keyed <state><width>
"""
import functools
import http.server
import json
import shutil
import socketserver
import subprocess
import sys
import tempfile
import threading
from pathlib import Path
STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static"
LONG_FOLDER = "Media/Photos/Family_holidays_summer_2026_at_the_seaside_with_everyone_and_the_dog"
LONG_GROUP = "A_group_name_with_no_spaces_at_all_whatsoever_long"
LONG_OWNER = "someone_with_a_long_handle"
FAKE_POOL = """
export class ConnectionPool {
async connect() {
return {
transport: {
fetchIndex: async () => ({
roots: [{ name: 'Media', writable: true, available: true }],
dirs: ['Media/Photos',
'Media/Photos/Some_Band_Complete_Discography_1992-2000_FLAC_and_more_pictures',
'__FOLDER__'],
}),
},
ack: { photo_directories: ['Media/Photos'] },
};
}
closeAll() {}
}
""".replace("__FOLDER__", LONG_FOLDER)
PROBE = """<!doctype html><html><head><meta charset=utf-8>
<meta name=viewport content="width=device-width">
<link rel=stylesheet href="style.css"></head><body>
<script>
const note = (m) => {
const el = document.documentElement;
el.dataset.err = (el.dataset.err || '') + ' ' + m;
};
window.addEventListener('error', (e) => note(e.message));
window.addEventListener('unhandledrejection',
(e) => note((e.reason && e.reason.message) || e.reason));
const MODE = location.hash.slice(1);
const dest = MODE === 'dest' ? null
: { account: 'bob', groupId: 'g1', groupName: '__GROUP__', folder: '__FOLDER__' };
const cfg = { albums: ['cam'], includeExisting: true, since: 0 };
window.meshbay = {
hubBase: () => 'https://hub.invalid',
phoneSync: {
destination: async () => dest,
setDestination: async (d) => d,
},
photoSync: {
status: async () => ({
permission: MODE === 'partial' ? 'partial' : 'granted', unmetered: true, sent: 1240,
config: MODE === 'configured' ? cfg : null, lastCompleted: Date.now(),
destination: dest, dir: dest && '__FOLDER__/bob-photos',
failure: MODE === 'configured' ? 'disk_full' : null,
}),
albums: async () => [
{ id: 'cam', name: 'Camera', count: 1240, bytes: 4.1e9, camera: true },
{ id: 'x', name: 'Screenshots_and_saved_images_from_a_messaging_application_long',
count: 12, bytes: 3e6, camera: false },
],
permit: async () => ({}), configure: async () => ({}),
estimate: async () => ({ count: 1, bytes: 1 }), plan: async () => ({ items: [] }),
sent: async () => true, completed: async () => ({}), failed: async () => true,
keepAlive: async () => true,
},
contactSync: {
status: async () => ({
permission: 'granted', on: MODE === 'configured', destination: dest,
dir: dest && '__FOLDER__/bob-contacts', sent: 3, lastCompleted: Date.now(),
lastSent: dest && '__FOLDER__/bob-contacts/contacts-2026-10-10-0900.vcf', failure: null,
}),
permit: async () => ({}), configure: async () => ({}), plan: async () => ({ item: null }),
sent: async () => true, completed: async () => ({}), failed: async () => true,
},
};
</script>
<main class="main"><div id=root></div></main>
<script type=module>
import { html, render } from './vendor/htm-preact.js';
import { initLocale } from './i18n.js';
import { startPhotoSync } from './photo-sync.js';
import { AndroidSyncPage } from './android-sync-page.js';
await initLocale();
startPhotoSync({
hub: '', getUser: () => ({ username: 'bob', userId: 'u-bob', token: 't' }),
hubFetch: async () => ({ admin_id: 'u-bob', members: [{ user_id: 'u-bob', username: 'bob' }] }),
getBundleKey: async () => '' });
const groups = [{ id: 'g1', name: '__GROUP__', owner_username: '__OWNER__' }];
render(html`<${AndroidSyncPage} user=${{ username: 'bob', userId: 'u-bob', token: 't' }}
groups=${groups} />`,
document.getElementById('root'));
setTimeout(() => {
if (MODE === 'configured') return;
[...document.querySelectorAll('button')].find((b) => b.textContent.includes('Set up')).click();
if (MODE !== 'dest') return;
setTimeout(() => {
const sel = document.querySelector('select');
sel.value = 'g1';
sel.dispatchEvent(new Event('change', { bubbles: true }));
}, 300);
}, 500);
</script></body></html>
""".replace("__GROUP__", LONG_GROUP).replace("__OWNER__", LONG_OWNER) \
.replace("__FOLDER__", LONG_FOLDER)
OUTER = """<!doctype html><html><body style="margin:0">
<script>
for (const m of ['dest', 'setup', 'configured', 'partial']) for (const w of [360, 420]) {
const f = document.createElement('iframe');
f.id = m + w;
f.style.cssText = `width:${w}px;height:900px;border:0;display:block`;
f.src = 'probe.html#' + m;
document.body.appendChild(f);
}
setTimeout(() => {
const out = {};
for (const f of document.querySelectorAll('iframe')) {
const d = f.contentDocument;
const vw = f.contentWindow.innerWidth;
const wide = [...d.querySelectorAll('#root *')]
.filter((e) => e.getBoundingClientRect().right > vw + 0.5)
.map((e) => `${e.tagName}.${e.className} ${Math.round(e.getBoundingClientRect().right)}`);
out[f.id] = {
vw, scrollW: d.documentElement.scrollWidth, wide: wide.slice(0, 6),
text: d.querySelector('#root').innerText.slice(0, 3000),
err: d.documentElement.dataset.err || '',
checked: [...d.querySelectorAll('#root input:checked')]
.map((i) => i.closest('label').innerText.split('\\n')[0]),
};
}
const pre = document.createElement('pre');
pre.id = 'out';
pre.textContent = JSON.stringify(out);
document.body.appendChild(pre);
}, 4000);
</script></body></html>
"""
class _Quiet(http.server.SimpleHTTPRequestHandler):
def log_message(self, *args) -> None:
pass
def main() -> int:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "static"
shutil.copytree(STATIC, root)
(root / "connection-pool.js").write_text(FAKE_POOL, encoding="utf-8")
(root / "probe.html").write_text(PROBE, encoding="utf-8")
(root / "outer.html").write_text(OUTER, encoding="utf-8")
handler = functools.partial(_Quiet, directory=str(root))
with socketserver.TCPServer(("127.0.0.1", 0), handler) as httpd:
port = httpd.server_address[1]
threading.Thread(target=httpd.serve_forever, daemon=True).start()
try:
dom = subprocess.run(
["google-chrome", "--headless=new", "--disable-gpu", "--no-first-run",
f"--user-data-dir={tmp}/profile", "--virtual-time-budget=8000",
"--dump-dom", f"http://127.0.0.1:{port}/outer.html"],
capture_output=True, text=True, timeout=120).stdout
finally:
httpd.shutdown()
start = dom.find('<pre id="out">')
if start < 0:
print(json.dumps({"error": "no result in the page"}))
return 1
body = dom[start + len('<pre id="out">'):dom.index("</pre>", start)]
for entity, char in ((""", '"'), ("<", "<"), (">", ">"), ("&", "&")):
body = body.replace(entity, char)
print(json.dumps(json.loads(body)))
return 0
if __name__ == "__main__":
sys.exit(main())
|