tabwright 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tabwright/__init__.py +3 -0
- tabwright/adapters/__init__.py +20 -0
- tabwright/adapters/chromium.py +133 -0
- tabwright/adapters/firefox.py +319 -0
- tabwright/adapters/snss.py +261 -0
- tabwright/cli.py +461 -0
- tabwright/extension/background.js +161 -0
- tabwright/extension/manifest.json +25 -0
- tabwright/gui.py +672 -0
- tabwright/library.py +52 -0
- tabwright/live.py +126 -0
- tabwright/mcp_server.py +107 -0
- tabwright/model.py +183 -0
- tabwright/native_host.py +143 -0
- tabwright/policy.py +36 -0
- tabwright/tools.py +316 -0
- tabwright-0.1.0.dist-info/METADATA +275 -0
- tabwright-0.1.0.dist-info/RECORD +21 -0
- tabwright-0.1.0.dist-info/WHEEL +4 -0
- tabwright-0.1.0.dist-info/entry_points.txt +2 -0
- tabwright-0.1.0.dist-info/licenses/LICENSE +21 -0
tabwright/cli.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
"""tabwright command line.
|
|
2
|
+
|
|
3
|
+
Sources: ``--browser NAME [--profile P]`` (newest live session file) or ``--file SNSS``.
|
|
4
|
+
Sinks for commands that produce a session: ``--json`` (model to stdout), ``--out FILE``
|
|
5
|
+
(SNSS file), ``--apply`` (write into the browser profile; browser must be stopped).
|
|
6
|
+
Default sink is a tree listing.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from tabwright import adapters, library, live, model, policy, tools
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _source(ap: argparse.ArgumentParser) -> None:
|
|
20
|
+
ap.add_argument("--browser", "-b", default="brave")
|
|
21
|
+
ap.add_argument(
|
|
22
|
+
"--profile", "-p", default="Default", help="Chromium profile dir name, or Firefox profile name"
|
|
23
|
+
)
|
|
24
|
+
ap.add_argument("--data-dir", type=Path, help="Chromium user data dir, or a Firefox profile directory")
|
|
25
|
+
ap.add_argument(
|
|
26
|
+
"--file", "-f", type=Path, help="read this SNSS or model-JSON file instead of the profile"
|
|
27
|
+
)
|
|
28
|
+
ap.add_argument("--live", action="store_true", help="read (and with --apply, write) the running browser")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _sink(ap: argparse.ArgumentParser) -> None:
|
|
32
|
+
ap.add_argument("--json", action="store_true", help="print the model as JSON")
|
|
33
|
+
ap.add_argument("--out", "-o", type=Path, help="write a session file in --browser's native format")
|
|
34
|
+
ap.add_argument("--apply", action="store_true", help="write into the browser profile (browser stopped)")
|
|
35
|
+
ap.add_argument("--dry-run", action="store_true", help="describe the change, write nothing")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_session(a) -> model.Session:
|
|
39
|
+
if a.file and a.file.suffix == ".json":
|
|
40
|
+
s = model.loads(a.file.read_text())
|
|
41
|
+
if not isinstance(s, model.Session):
|
|
42
|
+
raise SystemExit(f"{a.file} holds a {model.KINDS[type(s)]}, not a session")
|
|
43
|
+
return s
|
|
44
|
+
ad = adapters.get(a.browser)
|
|
45
|
+
if a.file:
|
|
46
|
+
return ad.read(a.file, browser=a.browser)
|
|
47
|
+
if a.live:
|
|
48
|
+
return live.snapshot(a.browser, a.data_dir)
|
|
49
|
+
return ad.read_profile(a.browser, a.profile, a.data_dir)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def tree(s: model.Session, tabs: bool = False) -> str:
|
|
53
|
+
lines = []
|
|
54
|
+
for wi, w in enumerate(s.windows):
|
|
55
|
+
lines.append(f"w{wi}: {len(w.tabs())} tabs, {len(w.groups())} groups")
|
|
56
|
+
for ii, it in enumerate(w.items):
|
|
57
|
+
if isinstance(it, model.Group):
|
|
58
|
+
lines.append(
|
|
59
|
+
f" g{ii} [{it.title}] {it.color}{' collapsed' if it.collapsed else ''} ({len(it.tabs)})"
|
|
60
|
+
)
|
|
61
|
+
if tabs:
|
|
62
|
+
lines.extend(f" {t.title[:60]} | {t.url[:90]}" for t in it.tabs)
|
|
63
|
+
elif tabs:
|
|
64
|
+
lines.append(f" {'*' if it.active else ' '} {t_short(it)}")
|
|
65
|
+
return "\n".join(lines)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def t_short(t: model.Tab) -> str:
|
|
69
|
+
return f"{t.title[:60]} | {t.url[:90]}"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def emit(s: model.Session, a, note: str = "") -> None:
|
|
73
|
+
if a.dry_run:
|
|
74
|
+
print(note or "dry run; would write:", file=sys.stderr)
|
|
75
|
+
print(tree(s), file=sys.stderr)
|
|
76
|
+
return
|
|
77
|
+
if a.json:
|
|
78
|
+
sys.stdout.write(model.dumps(s))
|
|
79
|
+
elif a.out:
|
|
80
|
+
adapters.get(a.browser).write_file(s, a.out)
|
|
81
|
+
print(f"wrote {a.out}", file=sys.stderr)
|
|
82
|
+
elif a.apply and a.live:
|
|
83
|
+
after = live.apply(s, a.browser, a.data_dir)
|
|
84
|
+
print(f"applied live: {len(after.windows)} windows, {len(after.tabs())} tabs", file=sys.stderr)
|
|
85
|
+
elif a.apply:
|
|
86
|
+
ad = adapters.get(a.browser)
|
|
87
|
+
if ad.pids(a.browser, a.data_dir):
|
|
88
|
+
raise SystemExit(f"{a.browser} is running; run `tabwright stop` first (use --force if hung)")
|
|
89
|
+
out = ad.apply(s, a.browser, a.profile, a.data_dir)
|
|
90
|
+
print(f"wrote {out}; {a.browser} will offer to restore it on next start", file=sys.stderr)
|
|
91
|
+
else:
|
|
92
|
+
print(tree(s))
|
|
93
|
+
if note:
|
|
94
|
+
print(note, file=sys.stderr)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cmd_list(a):
|
|
98
|
+
s = load_session(a)
|
|
99
|
+
sys.stdout.write(model.dumps(s) if a.json else tree(s, a.tabs) + "\n")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def cmd_drop(a):
|
|
103
|
+
s = load_session(a)
|
|
104
|
+
node = model.find(s, a.path)
|
|
105
|
+
rescued = []
|
|
106
|
+
if isinstance(node, model.Window):
|
|
107
|
+
if a.rescue_to:
|
|
108
|
+
target = model.find(s, a.rescue_to)
|
|
109
|
+
elsewhere = {t.url for w in s.windows if w is not node and w is not target for t in w.tabs()}
|
|
110
|
+
elsewhere |= {t.url for t in target.tabs()}
|
|
111
|
+
rescued = [t for t in node.tabs() if t.url not in elsewhere]
|
|
112
|
+
target.items.extend(rescued)
|
|
113
|
+
s.windows.remove(node)
|
|
114
|
+
else:
|
|
115
|
+
for w in s.windows:
|
|
116
|
+
if node in w.items:
|
|
117
|
+
w.items.remove(node)
|
|
118
|
+
for g in w.groups():
|
|
119
|
+
if node in g.tabs:
|
|
120
|
+
g.tabs.remove(node)
|
|
121
|
+
note = "\n".join(f"rescued to {a.rescue_to}: {t.url}" for t in rescued)
|
|
122
|
+
emit(s, a, note)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def cmd_save(a):
|
|
126
|
+
s = load_session(a)
|
|
127
|
+
node = model.find(s, a.path) if a.path else s
|
|
128
|
+
print(f"saved {model.KINDS[type(node)]} as {library.save(a.name, node)}", file=sys.stderr)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def cmd_library(a):
|
|
132
|
+
for name, kind in library.names():
|
|
133
|
+
print(f"{name}\t{kind}")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def cmd_show(a):
|
|
137
|
+
node = library.load(a.name)
|
|
138
|
+
if a.json or not isinstance(node, model.Session):
|
|
139
|
+
sys.stdout.write(model.dumps(node))
|
|
140
|
+
else:
|
|
141
|
+
print(tree(node, True))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def cmd_compose(a):
|
|
145
|
+
"""Assemble a session: sessions contribute windows, windows stay windows,
|
|
146
|
+
groups and tabs collect into one new window (or one each with --separate)."""
|
|
147
|
+
s = model.Session(browser=a.browser)
|
|
148
|
+
bucket = model.Window()
|
|
149
|
+
for name in a.names:
|
|
150
|
+
node = library.load(name)
|
|
151
|
+
if isinstance(node, model.Session):
|
|
152
|
+
s.windows.extend(node.windows)
|
|
153
|
+
elif isinstance(node, model.Window):
|
|
154
|
+
s.windows.append(node)
|
|
155
|
+
elif a.separate:
|
|
156
|
+
s.windows.append(model.Window(items=[node]))
|
|
157
|
+
else:
|
|
158
|
+
bucket.items.append(node)
|
|
159
|
+
if bucket.items:
|
|
160
|
+
s.windows.append(bucket)
|
|
161
|
+
emit(s, a)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def cmd_stop(a):
|
|
165
|
+
ps = adapters.get(a.browser).stop(a.browser, a.data_dir, force=a.force)
|
|
166
|
+
print(f"stopped {len(ps)} process(es): {ps}" if ps else f"{a.browser} not running", file=sys.stderr)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def cmd_start(a):
|
|
170
|
+
pid = adapters.get(a.browser).start(a.browser, a.data_dir, a.args)
|
|
171
|
+
print(f"started {a.browser} pid {pid}", file=sys.stderr)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def cmd_tool(a):
|
|
175
|
+
t = tools.REGISTRY[a.cmd]
|
|
176
|
+
s = load_session(a)
|
|
177
|
+
node = model.find(s, a.path) if a.path else s
|
|
178
|
+
kind = model.KINDS[type(node)]
|
|
179
|
+
if kind not in t.scopes:
|
|
180
|
+
raise SystemExit(f"{t.name} works on {', '.join(t.scopes)}, not on a {kind}")
|
|
181
|
+
opts = {k.lstrip("-").replace("-", "_"): getattr(a, k.lstrip("-").replace("-", "_")) for k in t.options}
|
|
182
|
+
report = t.fn(node, **opts)
|
|
183
|
+
if t.transform:
|
|
184
|
+
print(json.dumps(report, ensure_ascii=False) if a.json else _summary(report), file=sys.stderr)
|
|
185
|
+
emit(s, a)
|
|
186
|
+
elif "text" in report:
|
|
187
|
+
sys.stdout.write(report["text"])
|
|
188
|
+
elif a.json:
|
|
189
|
+
print(json.dumps(report, indent=2, ensure_ascii=False))
|
|
190
|
+
else:
|
|
191
|
+
print(_summary(report))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _summary(report: dict) -> str:
|
|
195
|
+
lines = []
|
|
196
|
+
for k, v in report.items():
|
|
197
|
+
if isinstance(v, (list, dict)) and len(v) > 12:
|
|
198
|
+
lines.append(f"{k}: {len(v)} items (use --json for all)")
|
|
199
|
+
else:
|
|
200
|
+
lines.append(f"{k}: {json.dumps(v, ensure_ascii=False)}")
|
|
201
|
+
return "\n".join(lines)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def cmd_move(a):
|
|
205
|
+
s = load_session(a)
|
|
206
|
+
tools.move(s, a.src, a.dst, index=a.index, before=a.before)
|
|
207
|
+
emit(s, a)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def cmd_color(a):
|
|
211
|
+
s = load_session(a)
|
|
212
|
+
r = tools.color(s, a.path, a.color)
|
|
213
|
+
print(_summary(r), file=sys.stderr)
|
|
214
|
+
emit(s, a)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def cmd_schema(a):
|
|
218
|
+
doc = {
|
|
219
|
+
"model": model.SCHEMA,
|
|
220
|
+
"browsers": sorted(adapters.BROWSERS),
|
|
221
|
+
"sources": {
|
|
222
|
+
"--browser/--profile/--data-dir": "newest session file of a stopped or running browser (read-only)",
|
|
223
|
+
"--file": "an SNSS, mozlz4 or model-JSON file",
|
|
224
|
+
"--live": "snapshot of the running browser through the companion extension",
|
|
225
|
+
},
|
|
226
|
+
"sinks": {
|
|
227
|
+
"--json": "model JSON on stdout",
|
|
228
|
+
"--out FILE": "session file in --browser's native format",
|
|
229
|
+
"--apply": "write into the stopped browser's profile (restore offered on next start)",
|
|
230
|
+
"--live --apply": "reconcile the running browser (tabs absent from the session are closed)",
|
|
231
|
+
"--dry-run": "tree of the result on stderr, nothing written",
|
|
232
|
+
},
|
|
233
|
+
"tools": {
|
|
234
|
+
t.name: {
|
|
235
|
+
"scopes": list(t.scopes),
|
|
236
|
+
"transform": t.transform,
|
|
237
|
+
"options": sorted(t.options),
|
|
238
|
+
"help": t.help,
|
|
239
|
+
}
|
|
240
|
+
for t in tools.REGISTRY.values()
|
|
241
|
+
},
|
|
242
|
+
"exit_codes": {"0": "ok", "1": "refused or failed; reason on stderr", "2": "usage error"},
|
|
243
|
+
"notes": [
|
|
244
|
+
"Lists are ordered; order is the tab strip and is honoured on every write path.",
|
|
245
|
+
"Only groups carry colour; `color` wraps a bare tab in a one-tab group.",
|
|
246
|
+
"Window geometry x/y are ignored by Wayland compositors; width/height/state apply.",
|
|
247
|
+
"Nothing prompts; stdout is data, stderr is commentary.",
|
|
248
|
+
],
|
|
249
|
+
}
|
|
250
|
+
print(json.dumps(doc, indent=2))
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def cmd_gui(a):
|
|
254
|
+
import os
|
|
255
|
+
|
|
256
|
+
# A conda interpreter resolves libxkbcommon to conda's copy, whose compiled-in xkb path is usually
|
|
257
|
+
# missing; point it at the system keyboard config unless the caller already chose one.
|
|
258
|
+
if "XKB_CONFIG_ROOT" not in os.environ and os.path.isdir("/usr/share/X11/xkb"):
|
|
259
|
+
os.environ["XKB_CONFIG_ROOT"] = "/usr/share/X11/xkb"
|
|
260
|
+
try:
|
|
261
|
+
from tabwright import gui
|
|
262
|
+
except ImportError:
|
|
263
|
+
raise SystemExit("PySide6 not installed: pip install 'tabwright[gui]'") from None
|
|
264
|
+
raise SystemExit(gui.main([]))
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def cmd_push(a):
|
|
268
|
+
if not a.file:
|
|
269
|
+
raise SystemExit("push needs --file (SNSS or model JSON)")
|
|
270
|
+
if a.live:
|
|
271
|
+
a.apply = True
|
|
272
|
+
emit(load_session(a), a)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def cmd_live(a):
|
|
276
|
+
if a.live_cmd == "install":
|
|
277
|
+
wrapper, manifest = live.install(a.browser)
|
|
278
|
+
print(f"host wrapper: {wrapper}\nhost manifest: {manifest}\nextension id: {live.extension_id()}")
|
|
279
|
+
print(
|
|
280
|
+
f"Load the extension unpacked from {live.extension_dir()} (brave://extensions, Developer mode, "
|
|
281
|
+
"Load unpacked), or start the browser with --load-extension=<that path>."
|
|
282
|
+
)
|
|
283
|
+
elif a.live_cmd == "status":
|
|
284
|
+
r = live.request("ping", a.browser, a.data_dir, timeout=5)
|
|
285
|
+
print(f"companion {r['version']} ({r['id']}) at {live.socket_path(a.browser, a.data_dir)}")
|
|
286
|
+
elif a.live_cmd == "extensions":
|
|
287
|
+
exts = live.extensions(a.browser, a.data_dir)
|
|
288
|
+
if a.json:
|
|
289
|
+
print(json.dumps(exts, indent=2))
|
|
290
|
+
else:
|
|
291
|
+
for e in sorted(exts, key=lambda e: e["name"].lower()):
|
|
292
|
+
print(
|
|
293
|
+
f"{'on ' if e['enabled'] else 'off'} {e['id']} {e['name']} {e['version']} [{e['type']}]"
|
|
294
|
+
)
|
|
295
|
+
elif a.live_cmd == "extension":
|
|
296
|
+
e = live.set_extension(a.id, a.enable, a.browser, a.data_dir)
|
|
297
|
+
print(f"{e['name']}: {'enabled' if e['enabled'] else 'disabled'}")
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def cmd_policy(a):
|
|
301
|
+
body, path = policy.build(a.browser, a.force, a.block)
|
|
302
|
+
print(json.dumps(body, indent=2))
|
|
303
|
+
print(f"install as root at {path} (e.g. sudo install -D -m 644 FILE {path})", file=sys.stderr)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def cmd_mcp(a):
|
|
307
|
+
try:
|
|
308
|
+
from tabwright import mcp_server
|
|
309
|
+
except ImportError:
|
|
310
|
+
raise SystemExit("mcp not installed: pip install 'tabwright[agent]'") from None
|
|
311
|
+
mcp_server.main()
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def cmd_tools(a):
|
|
315
|
+
for t in tools.REGISTRY.values():
|
|
316
|
+
print(
|
|
317
|
+
f"{t.name:22s} {'transform' if t.transform else 'report '} {','.join(t.scopes):28s} {t.help}"
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def main(argv=None) -> None:
|
|
322
|
+
ap = argparse.ArgumentParser(prog="tabwright", description=__doc__.splitlines()[0])
|
|
323
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
324
|
+
|
|
325
|
+
p = sub.add_parser("list", help="show windows, groups and tabs")
|
|
326
|
+
_source(p)
|
|
327
|
+
p.add_argument("--tabs", action="store_true")
|
|
328
|
+
p.add_argument("--json", action="store_true")
|
|
329
|
+
p.set_defaults(fn=cmd_list)
|
|
330
|
+
|
|
331
|
+
p = sub.add_parser("drop", help="remove a window (w0), group (w0/g1) or tab (w0/t3, w0/g1/t0)")
|
|
332
|
+
_source(p)
|
|
333
|
+
_sink(p)
|
|
334
|
+
p.add_argument("path")
|
|
335
|
+
p.add_argument("--rescue-to", help="window to receive tabs whose URL exists nowhere else")
|
|
336
|
+
p.set_defaults(fn=cmd_drop)
|
|
337
|
+
|
|
338
|
+
p = sub.add_parser("save", help="save the session, or the node at PATH, as a named set")
|
|
339
|
+
_source(p)
|
|
340
|
+
p.add_argument("name")
|
|
341
|
+
p.add_argument("path", nargs="?")
|
|
342
|
+
p.set_defaults(fn=cmd_save)
|
|
343
|
+
|
|
344
|
+
p = sub.add_parser("library", help="list named sets")
|
|
345
|
+
p.set_defaults(fn=cmd_library)
|
|
346
|
+
|
|
347
|
+
p = sub.add_parser("show", help="print a named set")
|
|
348
|
+
p.add_argument("name")
|
|
349
|
+
p.add_argument("--json", action="store_true")
|
|
350
|
+
p.set_defaults(fn=cmd_show)
|
|
351
|
+
|
|
352
|
+
p = sub.add_parser("compose", help="build a session from named sets")
|
|
353
|
+
_source(p)
|
|
354
|
+
_sink(p)
|
|
355
|
+
p.add_argument("names", nargs="+")
|
|
356
|
+
p.add_argument("--separate", action="store_true", help="one window per group/tab set")
|
|
357
|
+
p.set_defaults(fn=cmd_compose)
|
|
358
|
+
|
|
359
|
+
p = sub.add_parser("move", help="move a tab or group (SRC) into a window or group (DST)")
|
|
360
|
+
_source(p)
|
|
361
|
+
_sink(p)
|
|
362
|
+
p.add_argument("src")
|
|
363
|
+
p.add_argument("dst")
|
|
364
|
+
pos = p.add_mutually_exclusive_group()
|
|
365
|
+
pos.add_argument("--index", type=int, help="position inside DST (default: end)")
|
|
366
|
+
pos.add_argument("--before", metavar="PATH", help="insert in front of this node of DST")
|
|
367
|
+
p.set_defaults(fn=cmd_move)
|
|
368
|
+
|
|
369
|
+
p = sub.add_parser("color", help="colour a group, or a tab (wrapped in a one-tab group)")
|
|
370
|
+
_source(p)
|
|
371
|
+
_sink(p)
|
|
372
|
+
p.add_argument("path")
|
|
373
|
+
p.add_argument("color", choices=model.GROUP_COLORS)
|
|
374
|
+
p.set_defaults(fn=cmd_color)
|
|
375
|
+
|
|
376
|
+
p = sub.add_parser("schema", help="print the model JSON Schema and the command contract")
|
|
377
|
+
p.set_defaults(fn=cmd_schema)
|
|
378
|
+
|
|
379
|
+
p = sub.add_parser("rename", help="rename a named set")
|
|
380
|
+
p.add_argument("old")
|
|
381
|
+
p.add_argument("new")
|
|
382
|
+
p.set_defaults(fn=lambda a: library.rename(a.old, a.new))
|
|
383
|
+
|
|
384
|
+
p = sub.add_parser("delete", help="delete a named set")
|
|
385
|
+
p.add_argument("name")
|
|
386
|
+
p.set_defaults(fn=lambda a: library.delete(a.name))
|
|
387
|
+
|
|
388
|
+
p = sub.add_parser("tools", help="list tools with their scopes")
|
|
389
|
+
p.set_defaults(fn=cmd_tools)
|
|
390
|
+
|
|
391
|
+
for t in tools.REGISTRY.values():
|
|
392
|
+
p = sub.add_parser(t.name, help=f"{t.help} [{', '.join(t.scopes)}]")
|
|
393
|
+
_source(p)
|
|
394
|
+
if t.transform:
|
|
395
|
+
_sink(p)
|
|
396
|
+
else:
|
|
397
|
+
p.add_argument("--json", action="store_true")
|
|
398
|
+
p.add_argument("path", nargs="?", help="scope node (default: whole session)")
|
|
399
|
+
for flag, kw in t.options.items():
|
|
400
|
+
p.add_argument(flag, **kw)
|
|
401
|
+
p.set_defaults(fn=cmd_tool)
|
|
402
|
+
|
|
403
|
+
p = sub.add_parser(
|
|
404
|
+
"push", help="write a session file unchanged to a sink (--live: into the running browser)"
|
|
405
|
+
)
|
|
406
|
+
_source(p)
|
|
407
|
+
_sink(p)
|
|
408
|
+
p.set_defaults(fn=cmd_push)
|
|
409
|
+
|
|
410
|
+
p = sub.add_parser("live", help="companion-extension bridge: install, status, extensions")
|
|
411
|
+
lsub = p.add_subparsers(dest="live_cmd", required=True)
|
|
412
|
+
for name, h in [
|
|
413
|
+
("install", "write the native messaging host manifest for --browser"),
|
|
414
|
+
("status", "ping the companion extension"),
|
|
415
|
+
("extensions", "list installed extensions"),
|
|
416
|
+
("extension", "enable or disable an extension by id"),
|
|
417
|
+
]:
|
|
418
|
+
lp = lsub.add_parser(name, help=h)
|
|
419
|
+
_source(lp)
|
|
420
|
+
lp.set_defaults(fn=cmd_live)
|
|
421
|
+
if name == "extensions":
|
|
422
|
+
lp.add_argument("--json", action="store_true")
|
|
423
|
+
if name == "extension":
|
|
424
|
+
lp.add_argument("id")
|
|
425
|
+
g = lp.add_mutually_exclusive_group(required=True)
|
|
426
|
+
g.add_argument("--enable", dest="enable", action="store_true")
|
|
427
|
+
g.add_argument("--disable", dest="enable", action="store_false")
|
|
428
|
+
|
|
429
|
+
p = sub.add_parser("policy", help="print a managed-policy file that force-installs or blocks extensions")
|
|
430
|
+
p.add_argument("--browser", "-b", default="brave")
|
|
431
|
+
p.add_argument("--force", action="append", default=[], metavar="ID", help="force-install this extension")
|
|
432
|
+
p.add_argument("--block", action="append", default=[], metavar="ID", help="block this extension")
|
|
433
|
+
p.set_defaults(fn=cmd_policy)
|
|
434
|
+
|
|
435
|
+
p = sub.add_parser(
|
|
436
|
+
"mcp", help="serve the CLI over the Model Context Protocol on stdio (needs the agent extra)"
|
|
437
|
+
)
|
|
438
|
+
p.set_defaults(fn=cmd_mcp)
|
|
439
|
+
|
|
440
|
+
p = sub.add_parser("gui", help="open the desktop GUI (needs the gui extra)")
|
|
441
|
+
p.set_defaults(fn=cmd_gui)
|
|
442
|
+
|
|
443
|
+
p = sub.add_parser("stop", help="stop the browser")
|
|
444
|
+
_source(p)
|
|
445
|
+
p.add_argument("--force", action="store_true", help="SIGKILL: leave session files exactly as on disk")
|
|
446
|
+
p.set_defaults(fn=cmd_stop)
|
|
447
|
+
|
|
448
|
+
p = sub.add_parser("start", help="start the browser")
|
|
449
|
+
_source(p)
|
|
450
|
+
p.add_argument("args", nargs="*")
|
|
451
|
+
p.set_defaults(fn=cmd_start)
|
|
452
|
+
|
|
453
|
+
a = ap.parse_args(argv)
|
|
454
|
+
try:
|
|
455
|
+
a.fn(a)
|
|
456
|
+
except KeyError as e:
|
|
457
|
+
raise SystemExit(f"no such node: {e.args[0]}") from None
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
if __name__ == "__main__":
|
|
461
|
+
main()
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// tabwright companion: answers requests from the native host (tabwright.native_host).
|
|
2
|
+
// Protocol: host -> {id, op, ...params}; extension -> {id, ok, result | error}.
|
|
3
|
+
const HOST = "com.mostlyharmless.tabwright";
|
|
4
|
+
let port = null;
|
|
5
|
+
|
|
6
|
+
function connect() {
|
|
7
|
+
if (port) return;
|
|
8
|
+
try {
|
|
9
|
+
port = chrome.runtime.connectNative(HOST);
|
|
10
|
+
} catch (e) {
|
|
11
|
+
port = null;
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
port.onMessage.addListener(async (msg) => {
|
|
15
|
+
let reply;
|
|
16
|
+
try {
|
|
17
|
+
reply = { id: msg.id, ok: true, result: await handle(msg) };
|
|
18
|
+
} catch (e) {
|
|
19
|
+
reply = { id: msg.id, ok: false, error: String((e && e.message) || e) };
|
|
20
|
+
}
|
|
21
|
+
if (port) port.postMessage(reply);
|
|
22
|
+
});
|
|
23
|
+
port.onDisconnect.addListener(() => {
|
|
24
|
+
port = null;
|
|
25
|
+
setTimeout(connect, 2000);
|
|
26
|
+
});
|
|
27
|
+
port.postMessage({ hello: chrome.runtime.id, version: chrome.runtime.getManifest().version });
|
|
28
|
+
}
|
|
29
|
+
chrome.runtime.onStartup.addListener(connect);
|
|
30
|
+
chrome.runtime.onInstalled.addListener(connect);
|
|
31
|
+
connect();
|
|
32
|
+
|
|
33
|
+
async function handle(msg) {
|
|
34
|
+
switch (msg.op) {
|
|
35
|
+
case "ping":
|
|
36
|
+
return { id: chrome.runtime.id, version: chrome.runtime.getManifest().version };
|
|
37
|
+
case "snapshot":
|
|
38
|
+
return snapshot();
|
|
39
|
+
case "apply":
|
|
40
|
+
await apply(msg.session);
|
|
41
|
+
return snapshot();
|
|
42
|
+
case "extensions":
|
|
43
|
+
return (await chrome.management.getAll()).map(extInfo);
|
|
44
|
+
case "set_extension":
|
|
45
|
+
await chrome.management.setEnabled(msg.ext, !!msg.enabled);
|
|
46
|
+
return extInfo(await chrome.management.get(msg.ext));
|
|
47
|
+
default:
|
|
48
|
+
throw new Error("unknown op " + msg.op);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function extInfo(e) {
|
|
53
|
+
return {
|
|
54
|
+
id: e.id, name: e.name, version: e.version, enabled: e.enabled, type: e.type,
|
|
55
|
+
installType: e.installType, mayDisable: e.mayDisable, permissions: e.permissions,
|
|
56
|
+
hostPermissions: e.hostPermissions, homepageUrl: e.homepageUrl,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Model shape: Session > Window.items: (Tab | Group.tabs: Tab). Ids live in `extra`.
|
|
61
|
+
async function snapshot() {
|
|
62
|
+
const wins = await chrome.windows.getAll({ populate: true, windowTypes: ["normal"] });
|
|
63
|
+
const groups = new Map((await chrome.tabGroups.query({})).map((g) => [g.id, g]));
|
|
64
|
+
const windows = [];
|
|
65
|
+
for (const w of wins) {
|
|
66
|
+
const items = [];
|
|
67
|
+
for (const t of w.tabs) {
|
|
68
|
+
const tab = {
|
|
69
|
+
kind: "tab", url: t.pendingUrl || t.url || "", title: t.title || "", pinned: !!t.pinned,
|
|
70
|
+
active: !!t.active, extra: { tabId: t.id },
|
|
71
|
+
};
|
|
72
|
+
if (t.groupId !== undefined && t.groupId !== -1) {
|
|
73
|
+
const last = items[items.length - 1];
|
|
74
|
+
if (last && last.kind === "group" && last.extra.groupId === t.groupId) {
|
|
75
|
+
last.tabs.push(tab);
|
|
76
|
+
} else {
|
|
77
|
+
const g = groups.get(t.groupId) || {};
|
|
78
|
+
items.push({
|
|
79
|
+
kind: "group", title: g.title || "", color: g.color || "grey", collapsed: !!g.collapsed,
|
|
80
|
+
tabs: [tab], extra: { groupId: t.groupId },
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
items.push(tab);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const state = ["normal", "maximized", "minimized", "fullscreen"].includes(w.state) ? w.state : "normal";
|
|
88
|
+
windows.push({
|
|
89
|
+
kind: "window", items,
|
|
90
|
+
geometry: { x: w.left, y: w.top, width: w.width, height: w.height, state },
|
|
91
|
+
extra: { windowId: w.id, focused: w.focused },
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
return { kind: "session", windows, browser: "", extra: { live: true } };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Reconcile the browser to `session`. Tabs/groups/windows carrying ids are reused (moved,
|
|
98
|
+
// regrouped); nodes without ids are created; live tabs absent from the session are closed.
|
|
99
|
+
async function apply(session) {
|
|
100
|
+
const liveTabs = new Map((await chrome.tabs.query({})).map((t) => [t.id, t]));
|
|
101
|
+
const liveWins = new Set((await chrome.windows.getAll({ windowTypes: ["normal"] })).map((w) => w.id));
|
|
102
|
+
const keep = new Set();
|
|
103
|
+
const groupedNow = [...liveTabs.values()].filter((t) => t.groupId !== -1).map((t) => t.id);
|
|
104
|
+
if (groupedNow.length) await chrome.tabs.ungroup(groupedNow);
|
|
105
|
+
|
|
106
|
+
for (const w of session.windows) {
|
|
107
|
+
const flat = []; // [{tab, groupNode|null}]
|
|
108
|
+
for (const it of w.items) {
|
|
109
|
+
if (it.kind === "group") for (const t of it.tabs) flat.push({ tab: t, group: it });
|
|
110
|
+
else flat.push({ tab: it, group: null });
|
|
111
|
+
}
|
|
112
|
+
if (!flat.length) continue;
|
|
113
|
+
let winId = w.extra && w.extra.windowId;
|
|
114
|
+
if (!liveWins.has(winId)) {
|
|
115
|
+
const first = flat[0].tab;
|
|
116
|
+
const fid = first.extra && first.extra.tabId;
|
|
117
|
+
const created = liveTabs.has(fid)
|
|
118
|
+
? await chrome.windows.create({ tabId: fid, focused: false })
|
|
119
|
+
: await chrome.windows.create({ url: first.url, focused: false });
|
|
120
|
+
winId = created.id;
|
|
121
|
+
liveWins.add(winId);
|
|
122
|
+
const t0 = (await chrome.tabs.query({ windowId: winId }))[0];
|
|
123
|
+
first.extra = { ...(first.extra || {}), tabId: t0.id };
|
|
124
|
+
liveTabs.set(t0.id, t0);
|
|
125
|
+
}
|
|
126
|
+
for (let i = 0; i < flat.length; i++) {
|
|
127
|
+
const t = flat[i].tab;
|
|
128
|
+
let id = t.extra && t.extra.tabId;
|
|
129
|
+
if (liveTabs.has(id)) {
|
|
130
|
+
const live = liveTabs.get(id);
|
|
131
|
+
if (live.windowId !== winId || live.index !== i) await chrome.tabs.move(id, { windowId: winId, index: i });
|
|
132
|
+
if (!!live.pinned !== !!t.pinned) await chrome.tabs.update(id, { pinned: !!t.pinned });
|
|
133
|
+
} else {
|
|
134
|
+
const nt = await chrome.tabs.create({ windowId: winId, url: t.url, index: i, pinned: !!t.pinned, active: false });
|
|
135
|
+
id = nt.id;
|
|
136
|
+
t.extra = { ...(t.extra || {}), tabId: id };
|
|
137
|
+
liveTabs.set(id, nt);
|
|
138
|
+
}
|
|
139
|
+
keep.add(id);
|
|
140
|
+
}
|
|
141
|
+
for (const g of w.items.filter((it) => it.kind === "group" && it.tabs.length)) {
|
|
142
|
+
// Groups were all dissolved above (an emptied group ceases to exist), so every group is
|
|
143
|
+
// recreated; the snapshot returned after apply carries the fresh ids.
|
|
144
|
+
const tabIds = g.tabs.map((t) => t.extra.tabId);
|
|
145
|
+
const gid = await chrome.tabs.group({ tabIds, createProperties: { windowId: winId } });
|
|
146
|
+
await chrome.tabGroups.update(gid, { title: g.title || "", color: g.color || "grey", collapsed: !!g.collapsed });
|
|
147
|
+
}
|
|
148
|
+
const active = flat.find((f) => f.tab.active);
|
|
149
|
+
if (active) await chrome.tabs.update(active.tab.extra.tabId, { active: true });
|
|
150
|
+
if (w.geometry) {
|
|
151
|
+
const g = w.geometry;
|
|
152
|
+
// bounds only apply to a normal window; Wayland compositors ignore left/top.
|
|
153
|
+
const upd = g.state && g.state !== "normal"
|
|
154
|
+
? { state: g.state }
|
|
155
|
+
: { left: g.x, top: g.y, width: g.width, height: g.height, state: "normal" };
|
|
156
|
+
try { await chrome.windows.update(winId, upd); } catch (e) { /* bounds refused: keep going */ }
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const close = [...liveTabs.keys()].filter((id) => !keep.has(id));
|
|
160
|
+
if (close.length) await chrome.tabs.remove(close);
|
|
161
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"manifest_version": 3,
|
|
3
|
+
"name": "tabwright companion",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "Lets the tabwright CLI and GUI read and edit this browser's windows, tab groups, tabs and extensions over native messaging.",
|
|
6
|
+
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwu6rUtTDQTwnwnrhtm/9xIEMykCdX4IQIjn0X/V+sLj1AXcfL+ZFC9EMoHEABSwgRcwhmHqe3nYOmrWanKvpEXsFEusETpXPOLQEwO8L5q5sxJpX2fwyf7VlAhLyuKxEA7nnHOkSIHp09Sx278Jv1adsECbgkbgzz/NPWjrWQPtxiY78x27siPyEIhTXt08HAhe4QyFa0d1kguZtd7Pp8js90NOLOinSJ446QRc6zAWdz+30zBnjJ6QVbLySIubeYB7EcX5MeLbKD+8vDS1+qSaRsElcUn8mr05dNw+8rBaNbtPfGMQNPMaJ3qhNoTmlOINASHVFYWcaOtoOW2snpQIDAQAB",
|
|
7
|
+
"permissions": [
|
|
8
|
+
"tabs",
|
|
9
|
+
"tabGroups",
|
|
10
|
+
"management",
|
|
11
|
+
"nativeMessaging"
|
|
12
|
+
],
|
|
13
|
+
"background": {
|
|
14
|
+
"service_worker": "background.js",
|
|
15
|
+
"scripts": [
|
|
16
|
+
"background.js"
|
|
17
|
+
]
|
|
18
|
+
},
|
|
19
|
+
"browser_specific_settings": {
|
|
20
|
+
"gecko": {
|
|
21
|
+
"id": "tabwright@mostlyharmless.ai",
|
|
22
|
+
"strict_min_version": "139.0"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|