on master help sign in
25 files changed+1573−284
since splitsnapshots
unifiedsplit
.github/workflows/release.yml+23−8 host/diagonal-host.py+49−30 host/tests/golden/labels.json+102 host/tests/test_host.py+56 host/tests/test_prompts_validate.py+7−7 host/validate.py+92−14 scripts/install-manifest.sh+11−2 src/background/engine.ts+101−5 src/background/host.ts+3 src/background/index.ts+121−36 src/background/naming.ts+77−25 src/background/organize.ts+194−107 src/background/runtime.ts+13−2 src/background/state.ts+18 src/background/tidy.ts+129−17 src/shared/health.ts+4−2 src/shared/label.ts+42−9 test/auto.test.ts+84−2 test/engine.test.ts+126 test/naming.test.ts+72−2 test/organize.test.ts+17 test/sweep.test.ts+181 test/tidy.test.ts+34−3 test/url.test.ts+16−13 tsconfig.json+1
.github/workflows/release.yml+23−8
@@ -9,8 +9,11 @@ on:
99permissions:
1010 contents: write
1111
12+# One release at a time, in push order: an older run finishing last must not become the latest release,
13+# which is what the Homebrew cask downloads.
1214concurrency:
13− group: release-${{ github.sha }}
15+ group: release
16+ cancel-in-progress: false
1417
1518jobs:
1619 release:
@@ -32,8 +35,23 @@ jobs:
3235
3336 - name: Version from commit time
3437 id: version
38+ env:
39+ GH_TOKEN: ${{ github.token }}
3540 run: |
36− version=$(TZ=UTC git log -1 --format=%cd --date=format-local:%Y.%m.%d.%H%M "$GITHUB_SHA")
41+ # The commit's minute, or the next free minute when another commit already released in it. A re-run
42+ # for a commit that already released publishes nothing: a rebuilt zip has new bytes, which would
43+ # break the sha256 the tap already has, and users on that version would never get the new one.
44+ t=$(git log -1 --format=%ct "$GITHUB_SHA")
45+ for _ in $(seq 1 30); do
46+ version=$(date -u -d "@$t" +%Y.%m.%d.%H%M)
47+ target=$(gh release view "$version" --json targetCommitish -q .targetCommitish 2>/dev/null || true)
48+ [ -z "$target" ] && break
49+ if [ "$target" = "$GITHUB_SHA" ]; then
50+ echo "published=true" >> "$GITHUB_OUTPUT"
51+ break
52+ fi
53+ t=$((t + 60))
54+ done
3755 echo "version=$version" >> "$GITHUB_OUTPUT"
3856 echo "Version $version"
3957
@@ -54,22 +72,19 @@ jobs:
5472 npm run zip:store
5573
5674 - name: Publish release
75+ if: steps.version.outputs.published != 'true'
5776 env:
5877 GH_TOKEN: ${{ github.token }}
5978 VERSION: ${{ steps.version.outputs.version }}
6079 run: |
6180 asset="diagonal-extension-${VERSION}.zip"
6281 notes="Built from ${GITHUB_SHA::7}. Install with: brew install iko-soy/tap/diagonal. Or by hand: unzip, load the folder at brave://extensions (Developer mode → Load unpacked), then install the native host once from Terminal: bash <that folder>/install-host.command"
63− if gh release view "$VERSION" >/dev/null 2>&1; then
64− # Two commits in the same minute share a version: refresh the asset on the existing release.
65− gh release upload "$VERSION" "$asset" diagonal-extension.zip diagonal-store.zip --clobber
66− else
67− gh release create "$VERSION" "$asset" diagonal-extension.zip diagonal-store.zip --target "$GITHUB_SHA" --title "Diagonal $VERSION" --notes "$notes" --latest
68− fi
82+ gh release create "$VERSION" "$asset" diagonal-extension.zip diagonal-store.zip --target "$GITHUB_SHA" --title "Diagonal $VERSION" --notes "$notes" --latest
6983
7084 # Uploads the release to the Chrome Web Store and submits it for review, once the listing exists and
7185 # its API credentials are set as repository secrets (docs/store/listing.md). Skipped until then.
7286 - name: Upload to the Chrome Web Store
87+ if: steps.version.outputs.published != 'true'
7388 env:
7489 CWS_EXTENSION_ID: ${{ secrets.CWS_EXTENSION_ID }}
7590 CWS_CLIENT_ID: ${{ secrets.CWS_CLIENT_ID }}
host/diagonal-host.py+49−30
@@ -206,7 +206,7 @@ def count_tokens(prompt):
206206 """fm's exact count (under 0.1 s), or None when it can't give one."""
207207 try:
208208 p = subprocess.run([FM, "count-tokens", "-q", "-i", prompt.instructions], input=prompt.text,
209− capture_output=True, text=True, timeout=10, env=fm_env())
209+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, env=fm_env())
210210 except (OSError, subprocess.TimeoutExpired):
211211 return None
212212 out = p.stdout.strip()
@@ -255,28 +255,41 @@ PERMISSIVE = ["--guardrails", "permissive-content-transformations"]
255255USAGE_EXIT = 64
256256
257257
258−def run_fm(prompt, schema, model, timeout_s):
259− """`prompt` is a prompts.Prompt: its fixed rules go to -i, the tab text on stdin."""
258+# Below this much time left in a request, a second fm call (the permissive retry, naming one more new
259+# group) is not started: it would only be cut off.
260+MIN_CALL_S = 5.0
261+
262+
263+def run_fm(prompt, schema, opts):
264+ """`prompt` is a prompts.Prompt: its fixed rules go to -i, the tab text on stdin. Every call in one
265+ request shares its deadline, so the extension's guard (its timeout plus 10 s) is a real upper bound."""
260266 try:
261− return _run_fm(prompt, schema, model, timeout_s, [])
267+ return _run_fm(prompt, schema, opts, [])
262268 except Fail as f:
263− if f.code != "GUARDRAIL":
269+ if f.code != "GUARDRAIL" or time_left(opts) < MIN_CALL_S:
264270 raise
265− return _run_fm(prompt, schema, model, timeout_s, PERMISSIVE)
271+ return _run_fm(prompt, schema, opts, PERMISSIVE)
272+
273+
274+def time_left(opts):
275+ return opts["deadline"] - time.time()
266276
267277
268−def _run_fm(prompt, schema, model, timeout_s, extra):
278+def _run_fm(prompt, schema, opts, extra):
269279 # The tab text goes on stdin (fm reads it there when no prompt argument is given), so it never shows up
270280 # in the process list. fm has no timeout of its own; subprocess enforces ours.
271281 # --greedy: the same tabs get the same topics and name on every run (measured on macOS 27: five runs,
272− # one answer), so groups don't get renamed or reshuffled each time Diagonal looks at them.
273− args = [FM, "respond", "--model", model, "--no-stream", "--greedy", "--schema", schema, "-i", prompt.instructions, *extra]
282+ # one answer), so groups don't get renamed or reshuffled each time Diagonal looks at them. The strict
283+ # retry after an unusable answer samples instead: greedy would give the same answer again.
284+ greedy = [] if opts.get("strict") else ["--greedy"]
285+ args = [FM, "respond", "--model", opts["model"], "--no-stream", *greedy, "--schema", schema, "-i", prompt.instructions, *extra]
286+ timeout_s = max(1.0, time_left(opts))
274287 try:
275− p = subprocess.run(args, input=prompt.text, capture_output=True, text=True, timeout=timeout_s, env=fm_env())
288+ p = subprocess.run(args, input=prompt.text, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout_s, env=fm_env())
276289 except FileNotFoundError:
277290 raise Fail("MODEL_UNAVAILABLE", f"fm not found at {FM} — requires macOS 27")
278291 except subprocess.TimeoutExpired:
279− raise Fail("TIMEOUT", f"fm exceeded {timeout_s:g}s", retryable=True)
292+ raise Fail("TIMEOUT", f"fm exceeded {opts['timeout_s']:g}s", retryable=True)
280293 if p.returncode != 0:
281294 code = classify(p.stderr, p.returncode)
282295 if code == "LICENSE_REQUIRED":
@@ -295,11 +308,11 @@ def organize_mode():
295308
296309def op_ping(_payload, _opts):
297310 if not os.path.exists(FM):
298− return {"hostVersion": HOST_VERSION, "fmPath": FM, "fmAvailable": False,
311+ return {"hostVersion": HOST_VERSION, "fmPath": FM, "fmAvailable": False, "licenseRequired": False,
299312 "fmMessage": f"fm not found at {FM} — requires macOS 27", "schemasOk": False, "organizeMode": organize_mode()}
300313 license_required = False
301314 try:
302− avail = subprocess.run([FM, "available", "--model", "system"], capture_output=True, text=True, timeout=15, env=fm_env())
315+ avail = subprocess.run([FM, "available", "--model", "system"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15, env=fm_env())
303316 ok, msg = avail.returncode == 0, (avail.stdout + avail.stderr).strip()[:300]
304317 if not ok and license_needed(avail.returncode, avail.stdout + avail.stderr):
305318 license_required, msg = True, LICENSE_MESSAGE
@@ -367,7 +380,7 @@ def op_name(payload, opts):
367380 raise Fail("SCHEMA_MISSING", f"fm could not write {os.path.join(SCHEMAS, 'name.json')}")
368381 prompt = fit(lambda cap: prompts.build_name_prompt(payload, strict=opts.get("strict", False), desc_cap=cap), len(payload["items"]))
369382 try:
370− out = run_fm(prompt, schema, opts["model"], opts["timeout_s"])
383+ out = run_fm(prompt, schema, opts)
371384 except Fail as f:
372385 raise _fit_overflow(f, len(payload["items"]))
373386 try:
@@ -383,7 +396,7 @@ def op_organize(payload, opts):
383396 raise Fail("SCHEMA_MISSING", f"fm could not write {os.path.join(SCHEMAS, 'topics.json')}")
384397 prompt = fit(lambda cap: prompts.build_topics_prompt(payload, strict=opts.get("strict", False), desc_cap=cap), len(payload["items"]))
385398 try:
386− out = run_fm(prompt, schema, opts["model"], opts["timeout_s"])
399+ out = run_fm(prompt, schema, opts)
387400 except Fail as f:
388401 raise _fit_overflow(f, len(payload["items"]))
389402 _, owner = prompts.topic_items(payload)
@@ -393,29 +406,31 @@ def op_organize(payload, opts):
393406 raise Fail("BAD_MODEL_OUTPUT", str(e), retryable=True, raw=json.dumps(out, ensure_ascii=False)[:2000])
394407 chars = prompts.size(prompt)
395408 if payload.get("nameGroups") is not False: # the extension's fit check only needs the topics
396− chars += name_new_groups(result, payload, opts, time.time() + opts["timeout_s"])
409+ chars += name_new_groups(result, payload, opts)
397410 return result, chars, "topics"
398411
399412
400−def name_new_groups(result, payload, opts, deadline):
413+def name_new_groups(result, payload, opts):
401414 """Title each new group with the name op (well under a second each on fm), so groups appear named.
402− A group that fails, or runs past the deadline, keeps "" and the extension's naming loop names it."""
403− taken = [g.get("title") for g in payload.get("existingGroups") or [] if g.get("title")]
415+ A group that fails, runs past the request's deadline, or gets a title another group in the window
416+ already has keeps "" and the extension's naming loop, which checks every sibling, names it."""
417+ taken = [t for t in [g.get("title") for g in payload.get("existingGroups") or []] + list(payload.get("siblingTitles") or []) if t]
404418 chars = 0
405419 for g in result["groups"]:
406420 if "existing" in g or g.get("title"):
407421 continue
408− left = deadline - time.time()
409− if left < 5:
422+ if time_left(opts) < MIN_CALL_S:
410423 break
411424 sub = {"items": [dict(payload["items"][i], i=n) for n, i in enumerate(g["members"])], "siblingTitles": taken[:20]}
412425 try:
413− named, n, _ = op_name(sub, {**opts, "timeout_s": min(opts["timeout_s"], left)})
426+ named, n, _ = op_name(sub, {**opts, "strict": False})
414427 except Fail:
415428 continue
429+ chars += n
430+ if any(validate.same_label(named["title"], t) for t in taken):
431+ continue
416432 g["title"], g["emoji"] = named["title"], named["emoji"]
417433 taken.append(named["title"])
418− chars += n
419434 return chars
420435
421436
@@ -429,8 +444,8 @@ def handle(req):
429444 raw_opts = req.get("opts") or {}
430445 timeout_ms = raw_opts.get("timeoutMs", 45000)
431446 timeout_ms = timeout_ms if isinstance(timeout_ms, (int, float)) and not isinstance(timeout_ms, bool) else 45000
432− opts = {"model": "system", "strict": bool(raw_opts.get("strict")),
433− "timeout_s": max(5.0, min(120.0, timeout_ms / 1000))}
447+ timeout_s = max(5.0, min(120.0, timeout_ms / 1000))
448+ opts = {"model": "system", "strict": bool(raw_opts.get("strict")), "timeout_s": timeout_s, "deadline": t0 + timeout_s}
434449 op = req["op"]
435450 if op == "ping":
436451 return {"v": 1, "id": rid, "ok": True, "result": op_ping(req["payload"], opts)}
@@ -484,7 +499,7 @@ def install_schemas():
484499 if "{%s}" % key not in args:
485500 continue
486501 try:
487− p = subprocess.run([FM, *sub_args], capture_output=True, text=True, timeout=30, env=fm_env())
502+ p = subprocess.run([FM, *sub_args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30, env=fm_env())
488503 except (FileNotFoundError, subprocess.TimeoutExpired) as e:
489504 print(f" {name}: fm failed ({e})", file=sys.stderr)
490505 return "error"
@@ -496,7 +511,7 @@ def install_schemas():
496511 subs["{%s}" % key] = p.stdout.strip()
497512 args = [subs.get(a, a) for a in args]
498513 try:
499− p = subprocess.run([FM, *args], capture_output=True, text=True, timeout=30, env=fm_env())
514+ p = subprocess.run([FM, *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30, env=fm_env())
500515 except (FileNotFoundError, subprocess.TimeoutExpired) as e:
501516 print(f" {name}: fm failed ({e})", file=sys.stderr)
502517 return "error"
@@ -553,14 +568,16 @@ def selftest():
553568
554569 ping = op_ping({}, {})
555570 check("fm found", os.path.exists(FM), FM)
556− if ping["licenseRequired"]:
571+ if not os.path.exists(FM):
572+ return 1 # nothing else can work without it
573+ if ping.get("licenseRequired"):
557574 check("fm terms accepted", False, f"run: {LICENSE_FIX}")
558575 else:
559576 check("model available (fm available --model system)", ping["fmAvailable"], ping["fmMessage"])
560577 for name in SCHEMA_COMMANDS:
561578 path = os.path.join(SCHEMAS, name)
562579 readable = os.path.isfile(path) and os.path.getsize(path) > 0
563− hint = f"written on their own after {LICENSE_FIX}" if ping["licenseRequired"] else "missing: run diagonal-host --install-schemas"
580+ hint = f"written on their own after {LICENSE_FIX}" if ping.get("licenseRequired") else "missing: run diagonal-host --install-schemas"
564581 check(f"schema {name}", readable, path if readable else hint)
565582 check("allowed origin pinned", "<" not in ALLOWED_ORIGIN, ALLOWED_ORIGIN)
566583 if ping["fmAvailable"] and schema_path("name.json"):
@@ -670,7 +687,9 @@ def register(host_path):
670687 f.write("\n".join(written) + "\n")
671688 except OSError:
672689 pass
673− return 1 if failures else 0
690+ # One browser that could not be written (a locked folder, a stale profile) does not undo the others:
691+ # the install goes on and the ones that failed were named above.
692+ return 0 if len(dirs) - failures > 0 else 1
674693
675694
676695def unregister():
host/tests/golden/labels.jsonnew file+102
@@ -0,0 +1,102 @@
1+[
2+ [
3+ "\"Rust async runtimes.\"",
4+ "Rust async runtimes"
5+ ],
6+ [
7+ "rust async runtimes",
8+ "Rust async runtimes"
9+ ],
10+ [
11+ "Rust tabs and docs",
12+ "Rust and docs"
13+ ],
14+ [
15+ "One two three four five six",
16+ "One two three four"
17+ ],
18+ [
19+ "Machine learning research papers reading list",
20+ "Machine learning research"
21+ ],
22+ [
23+ "iPhone camera tips",
24+ "iPhone camera tips"
25+ ],
26+ [
27+ "macOS updates",
28+ "macOS updates"
29+ ],
30+ [
31+ "Children's books",
32+ "Children's books"
33+ ],
34+ [
35+ "'Quoted' title words",
36+ "Quoted title words"
37+ ],
38+ [
39+ "Planning a trip to Japan",
40+ "Planning a trip"
41+ ],
42+ [
43+ "Recipes for",
44+ null
45+ ],
46+ [
47+ "Python教程",
48+ "Python教程"
49+ ],
50+ [
51+ "React 教程",
52+ "React 教程"
53+ ],
54+ [
55+ "日本旅行",
56+ "日本旅行"
57+ ],
58+ [
59+ "京都の旅行計画",
60+ "京都の旅行計画"
61+ ],
62+ [
63+ "日本旅行。",
64+ "日本旅行"
65+ ],
66+ [
67+ "这是一个非常非常非常非常非常长的标题名字",
68+ "这是一个非常非常非常非常非常长的"
69+ ],
70+ [
71+ "Kubernetes 集群部署与运维指南 最佳实践",
72+ "Kubernetes 集群部署与运维指南"
73+ ],
74+ [
75+ "ทริปญี่ปุ่น",
76+ "ทริปญี่ปุ่น"
77+ ],
78+ [
79+ "日",
80+ null
81+ ],
82+ [
83+ "Tabs",
84+ null
85+ ],
86+ [
87+ "Misc stuff",
88+ null
89+ ],
90+ [
91+ "",
92+ null
93+ ],
94+ [
95+ "x",
96+ null
97+ ],
98+ [
99+ "Supercalifragilisticexpialidocious extraordinarily",
100+ null
101+ ]
102+]
host/tests/test_host.py+56
@@ -287,6 +287,19 @@ class ErrorCodes(HostCase):
287287 self.assertIn("Reply with only the object", argv[argv.index("-i") + 1])
288288
289289
290+ def test_strict_retry_samples_instead_of_repeating_the_greedy_answer(self):
291+ self.respond(json.dumps({"title": "Rust async", "emoji": "🦀"}))
292+ self.call("name", {"items": ITEMS3}, strict=True)
293+ self.assertNotIn("--greedy", [a for a in self.argv_log() if a[0] == "respond"][0])
294+
295+ def test_permissive_retry_shares_the_request_deadline(self):
296+ # The first call uses up the request's time: no second call runs past what the extension waits for.
297+ self.control({"respond_queue": [{"stderr": "Error: The model's safety guardrails were triggered.\n", "exit": 1, "sleep": 2.5}]})
298+ r = self.call("name", {"items": ITEMS3}, timeoutMs=5000)
299+ self.assertEqual(r["error"]["code"], "GUARDRAIL")
300+ self.assertEqual(len([a for a in self.argv_log() if a[0] == "respond"]), 1)
301+
302+
290303class Organize(HostCase):
291304 ITEMS = ITEMS3 + [
292305 {"title": "Hotels in Lisbon", "url": "https://booking.com/lisbon"},
@@ -331,6 +344,33 @@ class Organize(HostCase):
331344 self.assertIn("Tokio", name_calls[0])
332345 self.assertIn('"Lisbon trip"', name_calls[0]) # existing titles are off limits
333346
347+ def test_a_new_group_named_like_another_group_is_left_to_the_naming_loop(self):
348+ self.control({"respond_queue": [
349+ {"stdout": json.dumps({"tabs": [{"index": i, "topic": "Programming"} for i in (0, 1, 2)]})},
350+ {"stdout": json.dumps({"title": "Rust async", "emoji": "🦀"})},
351+ ]})
352+ r = self.call("organize", {"items": self.ITEMS, "siblingTitles": ["rust async"]})
353+ self.assertEqual(r["result"]["groups"][0]["title"], "")
354+ self.assertIn('"rust async"', self.stdin_log()[1]) # the name call was told, too
355+
356+ def test_a_topic_two_groups_share_equally_joins_neither_unless_the_words_say_which(self):
357+ existing = [{"g": 0, "title": "Lisbon trip", "samples": ["Flights to Lisbon"]},
358+ {"g": 1, "title": "Porto trip", "samples": ["Porto restaurants"]}]
359+ # Examples 8 (group 0) and 9 (group 1) both got Travel: a tie.
360+ self.topics([(3, "Travel"), (4, "Travel"), (8, "Travel"), (9, "Travel")])
361+ r = self.call("organize", {"items": self.ITEMS, "existingGroups": existing})
362+ self.assertEqual([g.get("existing") for g in r["result"]["groups"]], [0]) # "Lisbon" is in both tabs' titles
363+ items = [{"title": "Beach day", "url": "https://a.example/"}, {"title": "City walk", "url": "https://b.example/"}]
364+ self.topics([(0, "Travel"), (1, "Travel"), (2, "Travel"), (3, "Travel")])
365+ r = self.call("organize", {"items": items, "existingGroups": existing})
366+ self.assertNotIn("existing", r["result"]["groups"][0])
367+
368+ def test_only_vague_topics_leave_every_tab_loose(self):
369+ self.topics([(0, "Other"), (1, "Misc"), (2, "General")])
370+ r = self.call("organize", {"items": ITEMS3})
371+ self.assertTrue(r["ok"], r)
372+ self.assertEqual(r["result"], {"groups": [], "leftovers": [0, 1, 2]})
373+
334374 def test_two_topics_joining_one_group_make_one_join(self):
335375 # The group's two example tabs (8 and 9) got different topics; both topics still join group 0 once.
336376 self.topics([(3, "Travel"), (4, "Hotels"), (8, "Travel"), (9, "Hotels"), (0, "Programming")])
@@ -487,6 +527,15 @@ class Register(HostCase):
487527 self.assertEqual(p.returncode, 1)
488528 self.assertIn("missing or not executable", p.stderr)
489529
530+ def test_one_browser_that_cannot_be_written_does_not_fail_the_rest(self):
531+ chrome = self.make_profile("Google/Chrome")
532+ brave = self.make_profile("BraveSoftware/Brave-Browser")
533+ open(os.path.join(brave, "NativeMessagingHosts"), "w").close() # a file where the folder should be
534+ p = self.run_copy("--register", self.host_copy)
535+ self.assertEqual(p.returncode, 0, p.stderr)
536+ self.assertIn("BraveSoftware/Brave-Browser: could not write", p.stderr)
537+ self.assertTrue(os.path.exists(os.path.join(chrome, "NativeMessagingHosts", "io.diagonal.host.json")))
538+
490539 def test_no_browser_found(self):
491540 os.makedirs(self.env["DIAGONAL_APP_SUPPORT"])
492541 p = self.run_copy("--register", self.host_copy)
@@ -508,6 +557,13 @@ class SelfTest(HostCase):
508557 self.assertEqual(code, 1)
509558 self.assertIn("FAIL model available", p.stdout.decode())
510559
560+ def test_selftest_without_fm_says_so_and_stops(self):
561+ self.env["DIAGONAL_FM"] = os.path.join(self.tmp, "no-such-fm")
562+ code, _, p = self.run_host(args=["--selftest"])
563+ self.assertEqual(code, 1)
564+ self.assertIn("FAIL fm found", p.stdout.decode())
565+ self.assertNotIn("Traceback", p.stderr.decode())
566+
511567 def test_selftest_names_the_license_fix(self):
512568 self.control({"license": True})
513569 code, _, p = self.run_host(args=["--selftest"])
host/tests/test_prompts_validate.py+7−7
@@ -1,3 +1,4 @@
1+import json
12import os
23import unittest
34
@@ -73,13 +74,12 @@ class ValidateName(unittest.TestCase):
7374 with self.assertRaises(validate.ValidationError, msg=bad):
7475 self.v(bad)
7576
76− def test_chinese_and_japanese_titles_need_no_spaces(self):
77− self.assertEqual(self.v("日本旅行")["title"], "日本旅行")
78− self.assertEqual(self.v("京都の旅行計画")["title"], "京都の旅行計画")
79− self.assertEqual(self.v("React 教程")["title"], "React 教程")
80− for bad in ("日", "这是一个非常非常非常非常非常长的标题名字"):
81− with self.assertRaises(validate.ValidationError, msg=bad):
82− self.v(bad)
77+ def test_same_labels_as_the_extension(self):
78+ # test/url.test.ts runs these cases against src/shared/label.ts.
79+ with open(os.path.join(GOLDEN, "labels.json"), encoding="utf-8") as f:
80+ cases = json.load(f)
81+ for raw, fixed in cases:
82+ self.assertEqual(validate.repair_label(raw), fixed, msg=raw)
8383
8484 def test_emoji_default(self):
8585 self.assertEqual(self.v("Rust async", "not-an-emoji")["emoji"], "🧭")
host/validate.py+92−14
@@ -7,7 +7,6 @@ from urllib.parse import urlsplit
77HERE = os.path.dirname(os.path.realpath(__file__))
88COLORS = ["grey", "blue", "red", "yellow", "green", "pink", "purple", "cyan", "orange"]
99BANNED_WORDS = {"tab", "tabs", "group", "groups", "misc", "various", "stuff"}
10−QUOTES = "\"'“”‘’«»`"
1110TRAILING_PUNCT = re.compile(r"[\s.,;:!?…\-–—。、,!?:;]+$")
1211
1312
@@ -89,39 +88,82 @@ def default_emoji(items):
8988 return CATEGORIES[category_for_host(majority)][0]
9089
9190
91+# Quotes go; an apostrophe between two letters ("Children's", "Rock'n'roll") is part of the word and stays.
92+_QUOTE = re.compile(r"(?<![^\W\d_])['’]|['’](?![^\W\d_])|[\"“”‘«»`]")
93+# A label cut short should not end mid-phrase: "Planning a trip to" reads as "Planning a trip".
94+DANGLING = {"a", "an", "the", "to", "of", "for", "in", "on", "at", "by", "and", "or", "with", "from"}
95+
96+
9297def repair_label(raw):
93− """Trim, drop quotes, banned words and trailing punctuation, cap at 4 words / 28 chars, capitalise."""
98+ """Trim, drop quotes, banned words and trailing punctuation, cap at 4 words / 28 chars (16 wide characters
99+ for no-space scripts), drop a dangling "to"/"of", capitalise. Kept in step with src/shared/label.ts."""
94100 if not isinstance(raw, str):
95101 return None
96− s = raw.translate({ord(q): None for q in QUOTES})
102+ s = _QUOTE.sub("", raw)
97103 s = TRAILING_PUNCT.sub("", " ".join(s.split()))
98104 words = [w for w in s.split(" ") if w and re.sub(r"[^\w]", "", w.lower()) not in BANNED_WORDS]
99105 words = words[:4]
100− while len(words) > 2 and len(" ".join(words)) > 28:
106+ if _no_space(" ".join(words)):
107+ while len(words) > 1 and _width(" ".join(words)) > 16:
108+ words.pop()
109+ if _width(" ".join(words)) > 16:
110+ words = [_cut_to_width(" ".join(words), 16)]
111+ else:
112+ while len(words) > 2 and len(" ".join(words)) > 28:
113+ words.pop()
114+ while len(words) > 1 and words[-1].lower() in DANGLING:
101115 words.pop()
102116 label = TRAILING_PUNCT.sub("", " ".join(words))
103117 if not label:
104118 return None
105− label = label[0].upper() + label[1:]
119+ # "rust async" becomes "Rust async"; "iPhone tips" and "macOS updates" keep the brand's own casing.
120+ if not any(c.isupper() for c in words[0][1:]):
121+ label = label[0].upper() + label[1:]
106122 return label if is_valid_label(label) else None
107123
108124
109−# Chinese and Japanese titles have no spaces between words, so they're checked by length instead.
125+# Chinese, Japanese, Korean, Thai, Lao, Khmer and Myanmar titles don't put spaces between words, so a label
126+# with any of their characters ("Python教程") is checked by width instead of word count. Each such character
127+# is about as wide as two Latin letters on the tab strip.
128+NO_SPACE = re.compile(r"[\u0e00-\u0eff\u1000-\u109f\u1780-\u17ff\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff]")
129+# Chinese, Japanese and Korean, for the host's token estimate.
110130CJK = re.compile(r"[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff]")
111131
112132
133+def _no_space(label):
134+ return bool(NO_SPACE.search(label))
135+
136+
137+def _width(label):
138+ wide = len(NO_SPACE.findall(label))
139+ return wide + (len(label) - wide) / 2
140+
141+
142+def _cut_to_width(label, most):
143+ out = ""
144+ for ch in label:
145+ if _width(out + ch) > most:
146+ break
147+ out += ch
148+ return out.strip()
149+
150+
113151def is_valid_label(label):
114152 words = label.split()
115− cjk = len(CJK.findall(label)) * 2 > len(label.replace(" ", ""))
153+ wide = _no_space(label)
116154 return (
117− (2 <= len(label) <= 16 if cjk else 3 <= len(label) <= 28)
118− and (1 <= len(words) <= 4 if cjk else 2 <= len(words) <= 4)
119− and not any(q in label for q in QUOTES)
155+ (2 <= len(label) <= 28 and _width(label) <= 16 if wide else 3 <= len(label) <= 28)
156+ and (1 <= len(words) <= 4 if wide else 2 <= len(words) <= 4)
157+ and not _QUOTE.search(label)
120158 and not TRAILING_PUNCT.search(label)
121159 and not any(w.lower() in BANNED_WORDS for w in words)
122160 )
123161
124162
163+def same_label(a, b):
164+ return bool(a) and bool(b) and " ".join(a.split()).casefold() == " ".join(b.split()).casefold()
165+
166+
125167def validate_name(out, payload):
126168 if not isinstance(out, dict):
127169 raise ValidationError("reply is not an object")
@@ -227,16 +269,52 @@ def organize_from_topics(out, payload, owner):
227269 votes = group_votes.setdefault(topic, {})
228270 votes[owner[i]] = votes.get(owner[i], 0) + 1
229271 if not tab_topic:
230− raise ValidationError("no tab got a topic")
272+ if not any(isinstance(t, dict) and _in_range(t.get("index"), n_items) for t in out["tabs"]):
273+ raise ValidationError("no tab got a topic")
274+ # Every tab got only a vague topic ("Other", "Misc"): the model found nothing in common.
275+ return validate_organize({"groups": [], "leftovers": []}, payload)
231276 clusters = {}
232277 for i in sorted(tab_topic):
233278 clusters.setdefault(tab_topic[i], []).append(i)
234279 groups = []
235280 for topic, members in clusters.items():
236− votes = group_votes.get(topic)
237− if votes:
238− g = max(sorted(votes), key=lambda k: votes[k])
281+ g = _winner(group_votes.get(topic) or {}, members, payload)
282+ if g is not None:
239283 groups.append({"existing": g, "members": members})
240284 else:
241285 groups.append({"title": "", "emoji": "", "color": "", "members": members})
242286 return validate_organize({"groups": groups, "leftovers": []}, payload)
287+
288+
289+def _in_range(i, n):
290+ return isinstance(i, int) and not isinstance(i, bool) and 0 <= i < n
291+
292+
293+_WORD = re.compile(r"\w{3,}")
294+
295+
296+def _words(text):
297+ return {w.casefold() for w in _WORD.findall(text or "")}
298+
299+
300+def _winner(votes, members, payload):
301+ """The existing group a topic's tabs join: the one whose example tabs share it most. When two groups tie,
302+ the one whose title and examples share more words with these tabs; when that ties too, none (the tabs
303+ form a group of their own, or stay loose), rather than whichever group happens to be listed first."""
304+ if not votes:
305+ return None
306+ top = max(votes.values())
307+ tied = sorted(k for k, v in votes.items() if v == top)
308+ if len(tied) == 1:
309+ return tied[0]
310+ tab_words = set().union(*(_words(payload["items"][i].get("title")) for i in members))
311+ groups = {g["g"]: g for g in payload.get("existingGroups") or []}
312+
313+ def overlap(k):
314+ g = groups.get(k) or {}
315+ return len(tab_words & _words(" ".join([g.get("title") or "", *(g.get("samples") or [])])))
316+
317+ scores = {k: overlap(k) for k in tied}
318+ best = max(scores.values())
319+ leaders = [k for k in tied if scores[k] == best]
320+ return leaders[0] if len(leaders) == 1 and best > 0 else None
scripts/install-manifest.sh+11−2
@@ -53,7 +53,16 @@ echo "host: $BIN -> $SHARE/diagonal-host.py"
5353"$BIN" --version >/dev/null # the host must start with the python3 it was pinned to
5454# Writes the manifest into every Chromium browser's NativeMessagingHosts folder (Chrome, Brave and
5555# Brave Origin, Edge, Vivaldi, Arc, Opera, …) and checks each one the way the browser reads it.
56−"$BIN" --register "$BIN"
56+# A browser that was never opened has no folder yet: the rest of the install still runs, and the end
57+# says how to finish.
58+register_rc=0
59+"$BIN" --register "$BIN" || register_rc=$?
60+register_note() {
61+ if [[ $register_rc -ne 0 ]]; then
62+ echo "No browser could be set up for Diagonal yet. Open your browser once, then run: bash '$HERE/$(basename "$0")'"
63+ fi
64+}
65+trap register_note EXIT
5766
5867FM="${DIAGONAL_FM:-/usr/bin/fm}"
5968
@@ -89,7 +98,7 @@ fi
8998# Diagonal also writes these on first use; doing it now lets the self-test below cover the model.
9099schemas_out=$("$BIN" --install-schemas 2>&1) || true
91100if selftest_out=$("$BIN" --selftest 2>&1); then
92− echo "Diagonal's host is ready."
101+ [[ $register_rc -ne 0 ]] || echo "Diagonal's host is ready."
93102else
94103 echo "Diagonal's host is installed, but its self-test found a problem:"
95104 echo "$schemas_out"
src/background/engine.ts+101−5
@@ -1,8 +1,9 @@
11import type { GroupColor } from "../shared/colors";
22import { isColor } from "../shared/colors";
33import { colorFor, isInternalUrl, parse, provisionalTitle, trimText } from "../shared/url";
4+import { titleKey } from "../shared/label";
45import type { Settings } from "./settings";
5−import { markDirty, newGroupRecord, type GroupOrigin, type GroupRecord, type State, type TabRecord } from "./state";
6+import { markDirty, newGroupRecord, type GroupOrigin, type GroupRecord, type RemovedGroup, type State, type TabRecord } from "./state";
67
78/**
89 * Section 5: the structural rules as a pure function `(State, Event) → (State, Action[])`.
@@ -61,6 +62,10 @@ export interface Ctx {
6162export const DISSOLVE_DELAY_MS = 1500;
6263export const OWN_CREATE_WINDOW_MS = 2000;
6364export const OWN_WRITE_WINDOW_MS = 60_000;
65+/** A group moved to another window is removed and recreated with the same id within milliseconds. */
66+export const REVIVE_WINDOW_MS = 10_000;
67+export const REMOVED_KEEP_MS = 24 * 3_600_000;
68+export const REMOVED_CAP = 20;
6469
6570/** The pure form: never touches `prev`. */
6671export function step(prev: State, event: EngineEvent, ctx: Ctx): { state: State; actions: Action[] } {
@@ -85,8 +90,16 @@ type Handlers = { [K in EngineEvent["type"]]: Handler<Extract<EngineEvent, { typ
8590const handlers: Handlers = {
8691 tabCreated(s, { tab, opener }, ctx, out) {
8792 if (tab.incognito) return;
93+ const known = !!s.tabs[tab.id];
8894 const rec = upsertTab(s, tab, ctx.now);
89− if (rec.groupId !== -1) dirty(s, rec.groupId, ctx, out);
95+ if (rec.groupId !== -1) {
96+ // Born inside a group with no page that led to it ("New tab in group"): the user put it there.
97+ // A link opened from a grouped tab has an opener and stays Diagonal's to check.
98+ const g = s.groups[rec.groupId];
99+ const newPage = tab.openerTabId === undefined || isInternalUrl(tab.pendingUrl || tab.url);
100+ if (!known && newPage && g && !revivedLately(g, ctx.now)) rec.handPlaced = true;
101+ dirty(s, rec.groupId, ctx, out);
102+ }
90103 const before = out.length;
91104 openerRule(s, tab, opener ?? snapshotOf(s, tab.openerTabId), ctx, out);
92105 if (out.length === before) loose(rec, ctx, out);
@@ -101,13 +114,23 @@ const handlers: Handlers = {
101114 else loose(rec, ctx, out);
102115 return;
103116 }
104− const titleChanged = before.title !== rec.title;
117+ const titleChanged = titleKey(before.title) !== titleKey(rec.title); // not an unread count ticking over
105118 const pathChanged = pathKey(before.url) !== pathKey(rec.url);
106119 if (pathChanged) rec.keepLoose = undefined; // a new page is fair game again
107120 if (before.groupId !== rec.groupId) {
108121 left(s, before.groupId, ctx, out);
122+ if (inTransit(s, before.groupId, rec.groupId, ctx.now)) {
123+ // Chromium moves a group to another window by removing it, ungrouping its tabs and grouping
124+ // them again under the same id: nobody chose anything, so the tab keeps what it had.
125+ delete s.ownAdds[rec.id];
126+ if (rec.groupId !== -1) dirty(s, rec.groupId, ctx, out);
127+ else loose(rec, ctx, out);
128+ return;
129+ }
109130 rec.fitPending = undefined;
131+ if (s.groups[before.groupId]?.origin === "tidy") rec.parkedAt = undefined; // out of Parked
110132 if (rec.groupId !== -1) {
133+ rec.keepLoose = undefined; // in a group now: there is no loose choice left to protect
111134 // Into a group: ours if the worker put it there, otherwise the user did and it stays.
112135 if (s.ownAdds[rec.id] !== undefined) {
113136 delete s.ownAdds[rec.id];
@@ -135,7 +158,9 @@ const handlers: Handlers = {
135158 if (titleChanged || pathChanged || loaded || before.pinned !== rec.pinned) loose(rec, ctx, out);
136159 return;
137160 }
138− if (pathChanged && fitCheckable(s, rec, ctx.settings)) rec.fitPending = true;
161+ // Only a tab that had finished a page moves on: a new tab's first load redirecting (http to https,
162+ // a link shortener) is still its first page.
163+ if (pathChanged && before.status === "complete" && fitCheckable(s, rec, ctx.settings)) rec.fitPending = true;
139164 if (rec.fitPending && rec.status === "complete") out.push({ type: "checkFit" });
140165 if (titleChanged || pathChanged) dirty(s, rec.groupId, ctx, out);
141166 else if (before.status !== "complete" && rec.status === "complete" && s.groups[rec.groupId]?.dirty) {
@@ -160,6 +185,7 @@ const handlers: Handlers = {
160185 // Using a parked tab means it is not stale: it leaves Parked and auto-organize places it.
161186 if (rec.groupId !== -1 && s.groups[rec.groupId]?.origin === "tidy") {
162187 rec.parkedFrom = undefined;
188+ rec.parkedAt = undefined;
163189 out.push({ type: "unpark", tabId, groupId: rec.groupId });
164190 }
165191 },
@@ -174,6 +200,15 @@ const handlers: Handlers = {
174200 registerGroup(s, group, ctx, out);
175201 return;
176202 }
203+ // A group Chromium restores (a reopened window, the session after a restart) is created untitled
204+ // and gets its title a moment later: that title and colour can say it is one of Diagonal's back.
205+ if (rec.registeredAt !== undefined && ctx.now - rec.registeredAt <= REVIVE_WINDOW_MS) {
206+ const back = buried(s, group.title ?? "", group.color);
207+ if (back) {
208+ revive(s, back, group, ctx);
209+ return;
210+ }
211+ }
177212 rec.windowId = group.windowId;
178213 const own = s.ownWrites[group.id];
179214 const title = group.title ?? "";
@@ -201,9 +236,11 @@ const handlers: Handlers = {
201236 }
202237 },
203238
204− groupRemoved(s, { groupId }) {
239+ groupRemoved(s, { groupId }, ctx) {
240+ const rec = s.groups[groupId];
205241 delete s.groups[groupId];
206242 delete s.ownWrites[groupId];
243+ if (rec) bury(s, rec, ctx.now);
207244 },
208245
209246 meta(s, { tabId, description }, ctx, out) {
@@ -306,16 +343,64 @@ function registerGroup(s: State, group: GroupSnapshot, ctx: Ctx, out: Action[]):
306343 s.groups[group.id] = newGroupRecord(group.id, group.windowId, pending.origin, color, { stripTitle: group.title ?? "" });
307344 return;
308345 }
346+ // Moved to another window (same id, just removed) or reopened (same title and colour): the same group.
347+ const moved = s.removedGroups[group.id];
348+ const back = moved && ctx.now - moved.removedAt <= REVIVE_WINDOW_MS ? moved : buried(s, group.title ?? "", group.color);
349+ if (back) {
350+ revive(s, back, group, ctx);
351+ return;
352+ }
309353 const titled = !!group.title;
310354 const rec = newGroupRecord(group.id, group.windowId, "user", color, {
311355 managed: ctx.settings.nameUserGroups,
312356 userNamed: titled,
313357 stripTitle: group.title ?? "",
358+ registeredAt: ctx.now,
314359 });
315360 s.groups[group.id] = rec;
316361 if (rec.managed && !titled) dirty(s, group.id, ctx, out);
317362}
318363
364+/** Keep a removed group's record for a while, so the group is still Diagonal's if Chromium brings it back. */
365+export function bury(s: State, rec: GroupRecord, now: number): void {
366+ s.removedGroups[rec.id] = { ...rec, removedAt: now };
367+ pruneRemoved(s, now);
368+}
369+
370+/** The most recently removed group with this title and colour, if any. */
371+function buried(s: State, title: string, color: string): RemovedGroup | undefined {
372+ if (!title) return undefined;
373+ let best: RemovedGroup | undefined;
374+ for (const g of Object.values(s.removedGroups)) {
375+ if ((g.stripTitle ?? "") === title && g.color === color && (!best || g.removedAt > best.removedAt)) best = g;
376+ }
377+ return best;
378+}
379+
380+function revive(s: State, back: RemovedGroup, group: GroupSnapshot, ctx: Ctx): void {
381+ const { removedAt: _, registeredAt: __, ...rec } = back;
382+ delete s.removedGroups[back.id];
383+ delete s.groups[group.id];
384+ s.groups[group.id] = {
385+ ...rec,
386+ id: group.id,
387+ windowId: group.windowId,
388+ color: isColor(group.color) ? group.color : rec.color,
389+ // An untitled restore gets its title next: keep the known one so that update is not read as an edit.
390+ stripTitle: group.title || rec.stripTitle,
391+ revivedAt: ctx.now,
392+ };
393+}
394+
395+const revivedLately = (g: GroupRecord | undefined, now: number): boolean => !!g?.revivedAt && now - g.revivedAt <= REVIVE_WINDOW_MS;
396+
397+/** Leaving a group Chromium just removed, or joining one it is bringing back: a move, not a choice. */
398+function inTransit(s: State, from: number, to: number, now: number): boolean {
399+ const gone = (id: number) => !s.groups[id] && !!s.removedGroups[id];
400+ if (to === -1) return from !== -1 && gone(from);
401+ return from === -1 && (gone(to) || revivedLately(s.groups[to], now));
402+}
403+
319404function upsertTab(s: State, tab: TabSnapshot, now: number): TabRecord {
320405 const before = s.tabs[tab.id];
321406 const url = tab.url || tab.pendingUrl || "";
@@ -336,7 +421,10 @@ function upsertTab(s: State, tab: TabSnapshot, now: number): TabRecord {
336421 // A description belongs to a page: keep it only while the tab stays on that page.
337422 if (before?.description && pathKey(before.url) === pathKey(url)) rec.description = before.description;
338423 if (before?.keepLoose) rec.keepLoose = before.keepLoose;
424+ if (before?.parkedFrom) rec.parkedFrom = before.parkedFrom;
425+ if (before?.parkedAt) rec.parkedAt = before.parkedAt;
339426 if (before?.organizedKey) rec.organizedKey = before.organizedKey;
427+ if (before?.organizeRefused) rec.organizeRefused = before.organizeRefused;
340428 if (before?.handPlaced) rec.handPlaced = true;
341429 if (before?.fitPending) rec.fitPending = true;
342430 s.tabs[tab.id] = rec;
@@ -362,4 +450,12 @@ function prune(s: State, now: number): void {
362450 for (const [id, w] of Object.entries(s.ownWrites)) if (now - w.at > OWN_WRITE_WINDOW_MS) delete s.ownWrites[+id];
363451 for (const [id, at] of Object.entries(s.ownUngroups)) if (now - at > OWN_WRITE_WINDOW_MS) delete s.ownUngroups[+id];
364452 for (const [id, at] of Object.entries(s.ownAdds)) if (now - at > OWN_WRITE_WINDOW_MS) delete s.ownAdds[+id];
453+ pruneRemoved(s, now);
454+}
455+
456+function pruneRemoved(s: State, now: number): void {
457+ const removed = Object.values(s.removedGroups).sort((a, b) => b.removedAt - a.removedAt);
458+ removed.forEach((g, i) => {
459+ if (i >= REMOVED_CAP || now - g.removedAt > REMOVED_KEEP_MS) delete s.removedGroups[g.id];
460+ });
365461}
src/background/host.ts+3
@@ -102,6 +102,9 @@ export function normalizeReply<T>(reply: unknown, at: number): HostReply<T> {
102102 };
103103}
104104
105+/** Errors about what one request carried, not about the host: they don't count toward pausing it. */
106+export const REQUEST_ERRORS = new Set<HostErrorCode>(["GUARDRAIL", "BAD_MODEL_OUTPUT", "OVER_BUDGET", "BAD_REQUEST"]);
107+
105108/** Errors that mean "fix the setup", not "try this group again later". */
106109export const SETUP_ERRORS = new Set<HostErrorCode>([
107110 "HOST_NOT_FOUND", "HOST_FORBIDDEN", "FORBIDDEN_ORIGIN", "SCHEMA_MISSING", "MODEL_UNAVAILABLE", "LICENSE_REQUIRED",
src/background/index.ts+121−36
@@ -1,14 +1,14 @@
11import { stripTitle } from "../shared/label";
2−import { applyEvent, type Action, type EngineEvent, type GroupSnapshot, type TabSnapshot } from "./engine";
3−import { callHost, chromeSender, explain, HOST_MANIFEST_PATH, SETUP_ERRORS, type HostOpts, type HostReply, type Op } from "./host";
2+import { applyEvent, bury, type Action, type EngineEvent, type GroupSnapshot, type TabSnapshot } from "./engine";
3+import { callHost, chromeSender, explain, HOST_MANIFEST_PATH, REQUEST_ERRORS, SETUP_ERRORS, type HostOpts, type HostReply, type Op } from "./host";
44import { GLOBAL_PAUSE_AFTER, GLOBAL_PAUSE_MS, Naming, RATE_LIMIT_PAUSES_MS, type Member, type NamePayload, type NameResult } from "./naming";
55import { AutoOrganizer, organizeWindow, undoOrganize, UNDO_WINDOW_MS as ORGANIZE_UNDO_MS } from "./organize";
66import { FitChecker } from "./fit";
77import { addToGroup, createManagedGroup, ungroup, updateGroup, type Runtime } from "./runtime";
88import { withDefaults, type Settings } from "./settings";
9−import { markDirty, migrate, newGroupRecord, type GroupRecord, type HostError, type PingResult, type State, type TabRecord } from "./state";
9+import { markDirty, migrate, newGroupRecord, type GroupRecord, type HostError, type PingResult, type RemovedGroup, type State, type TabRecord } from "./state";
1010import { readDisk, shouldReload, TRIED_KEY, UPDATE_CHECK_MINUTES } from "./selfupdate";
11−import { forgetArchived, parkedTitle, restoreAll, restoreArchived, runSweep, undoSweep, UNDO_WINDOW_MS as SWEEP_UNDO_MS } from "./tidy";
11+import { adoptParked, forgetArchived, looksParked, parkedTitle, restoreAll, restoreArchived, runSweep, undoSweep, UNDO_WINDOW_MS as SWEEP_UNDO_MS } from "./tidy";
1212
1313/** Event wiring only: every rule lives in engine / naming / organize / tidy. */
1414
@@ -20,6 +20,8 @@ const ALARM_HOST = "host-retry";
2020const ALARM_AUTO = "auto-organize";
2121const ALARM_UPDATE = "self-update";
2222const HOST_RETRY_MS = 600_000;
23+/** Records made after this were made by this worker, so after a restart they describe the new session. */
24+const WORKER_STARTED_AT = Date.now();
2325
2426// ----- state cache ------------------------------------------------------------------------------
2527
@@ -91,7 +93,11 @@ async function host<T>(op: Op, payload: object, extra: Partial<HostOpts> = {}):
9193 h.lastOkAt = Date.now();
9294 h.consecutiveFailures = 0;
9395 h.consecutiveTimeouts = 0;
94− h.rateLimitStep = 0;
96+ if (op !== "ping") {
97+ h.rateLimitStep = 0; // a ping doesn't use the model, so it says nothing about its limit
98+ // A model answer (a manual Organize or Name now during a pause) proves the helper works again.
99+ if (h.pausedUntil) recovered();
100+ }
95101 if (reply.meta?.ms !== undefined) void pushRing("latency", reply.meta.ms, 100);
96102 } else {
97103 recordHostError(reply.error);
@@ -105,6 +111,8 @@ async function host<T>(op: Op, payload: object, extra: Partial<HostOpts> = {}):
105111}
106112
107113function recordHostError(e: HostError): void {
114+ // About one request's tabs, not the host's health: the caller retries or sets those tabs aside.
115+ if (REQUEST_ERRORS.has(e.code)) return;
108116 const h = state.host;
109117 const now = Date.now();
110118 h.lastError = { ...e, at: now };
@@ -136,11 +144,7 @@ async function ping(): Promise<HostReply<PingResult>> {
136144 } else if (!reply.result.schemasOk) {
137145 recordHostError({ code: "SCHEMA_MISSING", message: reply.result.schemaMessage || "fm could not write Diagonal's schema files" });
138146 } else {
139− h.pausedUntil = undefined;
140− h.lastError = undefined;
141− chrome.alarms.clear(ALARM_HOST);
142− void naming.sweepDirty();
143− void autoOrganizer.sweep();
147+ recovered();
144148 }
145149 }
146150 commit();
@@ -148,6 +152,16 @@ async function ping(): Promise<HostReply<PingResult>> {
148152 return reply;
149153}
150154
155+/** The helper answers again: lift the pause and pick up what waited for it. */
156+function recovered(): void {
157+ const h = state.host;
158+ h.pausedUntil = undefined;
159+ h.lastError = undefined;
160+ chrome.alarms.clear(ALARM_HOST);
161+ void naming.sweepDirty();
162+ void autoOrganizer.sweep();
163+}
164+
151165// ----- badge -----------------------------------------------------------------------------------
152166
153167function busy(on: boolean): void {
@@ -159,7 +173,6 @@ function hostUnhealthy(): boolean {
159173 const h = state.host;
160174 const now = Date.now();
161175 if (h.pausedUntil && h.pausedUntil > now) return true;
162− if (h.consecutiveFailures >= 3) return true;
163176 return !!h.lastError && SETUP_ERRORS.has(h.lastError.code) && (!h.lastOkAt || h.lastOkAt < (h.lastError.at ?? 0));
164177}
165178
@@ -346,16 +359,24 @@ async function tabById(id: number): Promise<chrome.tabs.Tab | undefined> {
346359 * across restarts, so records are matched by id first and then by URL (tabs) or title and colour
347360 * (groups), which keeps managed groups managed after the browser restarts.
348361 */
349−async function reconcile(): Promise<void> {
362+async function reconcile(reason: "startup" | "installed"): Promise<void> {
350363 const [tabs, groups] = await Promise.all([chrome.tabs.query({}), chrome.tabGroups.query({})]);
351364 const now = Date.now();
352− const oldTabs = Object.values(state.tabs);
353− const byUrl = new Map<string, TabRecord>(oldTabs.map((t) => [t.url, t]));
365+ const liveTabIds = new Set(tabs.map((t) => t.id));
366+ // Records of tabs that are gone, by address: after a restart every tab has a new id.
367+ const byUrl = new Map<string, TabRecord>(Object.values(state.tabs).filter((t) => !liveTabIds.has(t.id)).map((t) => [t.url, t]));
354368 const nextTabs: Record<number, TabRecord> = {};
355369 for (const t of tabs) {
356370 if (t.incognito || t.id === undefined) continue;
357371 const url = t.url || t.pendingUrl || "";
358− const prev = state.tabs[t.id]?.url === url ? state.tabs[t.id] : byUrl.get(url);
372+ const same = state.tabs[t.id]?.url === url ? state.tabs[t.id] : undefined;
373+ // An event handled before this ran may have recorded a restored tab as new: its old record knows more.
374+ const old = byUrl.get(url);
375+ const prev = old && (!same || same.createdAt >= WORKER_STARTED_AT) ? old : same;
376+ // Chromium stamps a restored tab it has not shown yet with the restore time, so after a restart the
377+ // stored time is the truer one for every tab but the one on screen.
378+ const lastSeen =
379+ reason === "startup" && prev && !t.active ? prev.lastActivatedAt : Math.max(prev?.lastActivatedAt ?? 0, t.lastAccessed ?? 0);
359380 nextTabs[t.id] = {
360381 id: t.id,
361382 windowId: t.windowId,
@@ -368,25 +389,51 @@ async function reconcile(): Promise<void> {
368389 openerTabId: t.openerTabId,
369390 description: prev?.description,
370391 parkedFrom: prev?.parkedFrom,
392+ parkedAt: prev?.parkedAt,
371393 keepLoose: prev?.keepLoose,
372394 organizedKey: prev?.organizedKey,
395+ organizeRefused: prev?.organizeRefused,
373396 handPlaced: prev?.handPlaced,
397+ fitPending: prev?.fitPending,
374398 createdAt: prev?.createdAt ?? now,
375− lastActivatedAt: Math.max(prev?.lastActivatedAt ?? 0, t.lastAccessed ?? 0) || now,
399+ lastActivatedAt: lastSeen || now,
376400 };
377401 }
402+ const liveGroupIds = new Set(groups.map((g) => g.id));
378403 const unmatched = new Map(Object.values(state.groups).map((g) => [g.id, g]));
404+ // Made by this worker for a group it did not know: after a restart, that is a restored group whose
405+ // events were handled before this ran, and the record from before the restart is the one to keep.
406+ const fresh = (g: GroupRecord) => g.origin === "user" && (g.registeredAt ?? 0) >= WORKER_STARTED_AT;
407+ const lookalike = (title: string, color: string): GroupRecord | RemovedGroup | undefined => {
408+ if (title === "") return undefined;
409+ const alike = (o: GroupRecord) => (o.stripTitle ?? "") === title && o.color === color;
410+ return (
411+ [...unmatched.values()].find((o) => alike(o) && !liveGroupIds.has(o.id) && !fresh(o)) ??
412+ Object.values(state.removedGroups)
413+ .filter(alike)
414+ .sort((a, b) => b.removedAt - a.removedAt)[0]
415+ );
416+ };
379417 const nextGroups: Record<number, GroupRecord> = {};
380418 for (const g of groups) {
381419 const title = g.title ?? "";
382− let prev = unmatched.get(g.id);
383− if (!prev || (prev.stripTitle ?? "") !== title) {
384− prev = [...unmatched.values()].find((o) => (o.stripTitle ?? "") === title && title !== "" && o.color === g.color);
420+ let prev: GroupRecord | undefined = unmatched.get(g.id);
421+ if (prev && (prev.stripTitle ?? "") !== title) prev = undefined;
422+ const before = !prev || fresh(prev) ? lookalike(title, g.color) : undefined;
423+ if (before) prev = before;
424+ let rec: GroupRecord;
425+ if (prev) {
426+ unmatched.delete(prev.id);
427+ delete state.removedGroups[prev.id];
428+ const { removedAt: _, ...kept } = prev as RemovedGroup;
429+ rec = { ...kept, id: g.id, windowId: g.windowId, color: g.color, stripTitle: title };
430+ if (before) rec.registeredAt = undefined;
431+ } else {
432+ // Untitled so far may still mean restored: its title can arrive next and match (engine.ts groupUpdated).
433+ rec = newGroupRecord(g.id, g.windowId, "user", g.color, { managed: settings.nameUserGroups, userNamed: !!title, stripTitle: title, registeredAt: now });
385434 }
386− if (prev) unmatched.delete(prev.id);
387− const rec: GroupRecord = prev
388− ? { ...prev, id: g.id, windowId: g.windowId, color: g.color, stripTitle: title }
389− : newGroupRecord(g.id, g.windowId, "user", g.color, { managed: settings.nameUserGroups, userNamed: !!title, stripTitle: title });
435+ // Earlier versions turned Parked into a plain group after a restart: give it back its job.
436+ if (rec.origin === "user" && looksParked(g, settings)) adoptParked(rec, settings);
390437 if (rec.managed) {
391438 rec.dirty = true;
392439 rec.dirtyAt = 0;
@@ -394,14 +441,17 @@ async function reconcile(): Promise<void> {
394441 }
395442 nextGroups[g.id] = rec;
396443 }
444+ // Groups not seen now (a closed window, a quit that did not save) may still come back: keep them a day.
445+ for (const old of unmatched.values()) if (!liveGroupIds.has(old.id) && !fresh(old)) bury(state, old, now);
397446 state.tabs = nextTabs;
398447 state.groups = nextGroups;
399448 state.pendingCreates = [];
400449 state.ownWrites = {};
401450 state.ownUngroups = {};
402451 state.ownAdds = {};
403− if (state.lastSweep && now - state.lastSweep.at > SWEEP_UNDO_MS) state.lastSweep = undefined;
404− if (state.lastOrganize && now - state.lastOrganize.at > ORGANIZE_UNDO_MS) state.lastOrganize = undefined;
452+ // Undo lists name tabs by id, and after a restart none of those ids exist.
453+ if (reason === "startup" || (state.lastSweep && now - state.lastSweep.at > SWEEP_UNDO_MS)) state.lastSweep = undefined;
454+ if (reason === "startup" || (state.lastOrganize && now - state.lastOrganize.at > ORGANIZE_UNDO_MS)) state.lastOrganize = undefined;
405455 commit();
406456}
407457
@@ -414,9 +464,13 @@ async function injectBacklog(): Promise<void> {
414464 }
415465}
416466
467+let reconciled: Promise<void> | undefined;
468+
417469async function boot(reason: "startup" | "installed"): Promise<void> {
418− await ready;
419− await serial("reconcile", reconcile);
470+ // Queued before anything else this wake handles (serial waits for `ready` itself): after a restart
471+ // Chromium replays the restored groups right after onStartup, and they must meet the reconciled state.
472+ reconciled = serial("reconcile", () => reconcile(reason));
473+ await reconciled;
420474 if (!(await chrome.alarms.get(ALARM_TIDY))) chrome.alarms.create(ALARM_TIDY, { periodInMinutes: 30, delayInMinutes: 1 });
421475 if (reason === "installed") void injectBacklog();
422476 await ping();
@@ -458,20 +512,29 @@ if (GROUPS_SUPPORTED) {
458512
459513 chrome.tabs.onReplaced.addListener((added, removed) =>
460514 void serial("tabs.onReplaced", async () => {
515+ // Chromium swapped in a new tab (a prerendered page, a discarded tab coming back): it is the same
516+ // tab to the user, so it keeps what Diagonal knew about it, including choices the user made.
461517 const rec = state.tabs[removed];
462518 delete state.tabs[removed];
463519 const t = await tabById(added);
464520 if (t) {
521+ if (rec && !state.tabs[added]) state.tabs[added] = { ...rec, id: added };
465522 await feed({ type: "tabUpdated", tab: snapTab(t) });
466− if (rec?.description && state.tabs[added]) state.tabs[added].description = rec.description;
467523 }
468524 }),
469525 );
470526
471527 chrome.tabs.onActivated.addListener(({ tabId }) => void serial("tabs.onActivated", () => feed({ type: "tabActivated", tabId })));
472528
473− chrome.tabGroups.onCreated.addListener((g) => void serial("tabGroups.onCreated", () => feed({ type: "groupCreated", group: snapGroup(g) })));
474− chrome.tabGroups.onUpdated.addListener((g) => void serial("tabGroups.onUpdated", () => feed({ type: "groupUpdated", group: snapGroup(g) })));
529+ // A group is read when its turn comes, not as Chromium sent it: a restored group reports itself
530+ // untitled and then titled, and replaying the stale "untitled" would read as you clearing the title.
531+ const refetchGroup = (where: string, type: "groupCreated" | "groupUpdated") => (g: chrome.tabGroups.TabGroup) =>
532+ void serial(where, async () => {
533+ const now = await chrome.tabGroups.get(g.id).catch(() => undefined);
534+ if (now) await feed({ type, group: snapGroup(now) });
535+ });
536+ chrome.tabGroups.onCreated.addListener(refetchGroup("tabGroups.onCreated", "groupCreated"));
537+ chrome.tabGroups.onUpdated.addListener(refetchGroup("tabGroups.onUpdated", "groupUpdated"));
475538 chrome.tabGroups.onRemoved.addListener((g) => void serial("tabGroups.onRemoved", () => feed({ type: "groupRemoved", groupId: g.id })));
476539}
477540
@@ -500,7 +563,10 @@ chrome.alarms.onAlarm.addListener((alarm) => {
500563 await ready;
501564 if (alarm.name === ALARM_NAMING) await naming.sweepDirty();
502565 else if (alarm.name === ALARM_AUTO) await autoOrganizer.sweep();
503− else if (alarm.name === ALARM_TIDY) await runSweep(rt).catch((e) => logError("tidy", e));
566+ else if (alarm.name === ALARM_TIDY) {
567+ await reconciled; // an overdue sweep right after a restart waits for the new tab and group ids
568+ await runSweep(rt).catch((e) => logError("tidy", e));
569+ }
504570 else if (alarm.name === ALARM_HOST) {
505571 const r = await ping();
506572 if (!r.ok || hostUnhealthy()) chrome.alarms.create(ALARM_HOST, { when: Date.now() + HOST_RETRY_MS });
@@ -514,27 +580,46 @@ chrome.storage.onChanged.addListener((changes, area) => {
514580 await ready;
515581 const before = settings;
516582 settings = withDefaults(changes.settings.newValue);
517− if (before.emoji !== settings.emoji) await rewriteTitles();
583+ if (before.emoji !== settings.emoji) await rewriteTitles(before);
584+ if (before.nameUserGroups !== settings.nameUserGroups) applyNameUserGroups();
518585 if (before.tidyMode !== settings.tidyMode || before.tidyThreshold !== settings.tidyThreshold) await runSweep(rt).catch(() => undefined);
519586 if (!before.autoOrganize && settings.autoOrganize) await autoOrganizer.sweep();
520587 refreshBadge();
521588 })();
522589});
523590
591+/** "Name groups I make too" applies to the groups you already made, not only to new ones. */
592+function applyNameUserGroups(): void {
593+ for (const g of Object.values(state.groups)) {
594+ if (g.origin !== "user" || g.userNamed) continue;
595+ g.managed = settings.nameUserGroups;
596+ if (g.managed) {
597+ markDirty(g, Date.now());
598+ naming.touch(g.id);
599+ }
600+ }
601+ commit();
602+}
603+
524604/** Emoji switched on or off: rewrite the titles the extension wrote. */
525−async function rewriteTitles(): Promise<void> {
605+async function rewriteTitles(before: Settings): Promise<void> {
526606 for (const g of Object.values(state.groups)) {
527− if (g.origin === "tidy") await updateGroup(rt, g.id, { title: parkedTitle(settings) });
528− else if (g.managed && !g.userNamed && g.title) await updateGroup(rt, g.id, { title: stripTitle(g.title, g.emoji, settings.emoji) });
607+ // Parked is always "user named", so its title is compared instead: one you typed stays.
608+ if (g.origin === "tidy") {
609+ if ((g.stripTitle ?? "") === parkedTitle(before)) await updateGroup(rt, g.id, { title: parkedTitle(settings) });
610+ } else if (g.managed && !g.userNamed && g.title) await updateGroup(rt, g.id, { title: stripTitle(g.title, g.emoji, settings.emoji) });
529611 }
530612}
531613
532614async function nameGroupNow(groupId: number): Promise<void> {
533615 const g = state.groups[groupId];
534616 if (!g) return;
535− // An explicit request overrides "don't name" and a hand-typed title for this group.
617+ // An explicit request overrides "don't name" and a hand-typed title for this group, and the model's
618+ // answer goes on the strip even when it is close to the label it gave before.
536619 g.managed = true;
537620 g.userNamed = false;
621+ g.title = undefined;
622+ g.lastNamedAt = undefined;
538623 commit();
539624 await naming.nameNow(groupId);
540625}
src/background/naming.ts+77−25
@@ -1,6 +1,7 @@
1−import { labelOf, repairLabel, safeEmoji, sameLabel, stripTitle, LABEL_MAX_CHARS } from "../shared/label";
1+import { labelOf, repairLabel, safeEmoji, sameLabel, stripTitle, titleKey, LABEL_MAX_CHARS } from "../shared/label";
22import { sha1 } from "../shared/sha1";
33import { isInternalUrl, promptUrl, trimText } from "../shared/url";
4+import { pathKey } from "./engine";
45import type { HostOpts, HostReply } from "./host";
56import { SETUP_ERRORS } from "./host";
67import type { Settings } from "./settings";
@@ -60,7 +61,7 @@ export const settled = (t: { status?: string }): boolean => t.status !== "loadin
6061
6162/** sha-1 of the sorted `url|title` lines: reorder-proof, changes when a member or its title does. */
6263export const membersHash = (members: Pick<Member, "url" | "title">[]): string =>
63− sha1(members.map((m) => `${m.url}|${m.title}`).sort().join("\n"));
64+ sha1(members.map((m) => `${m.url}|${titleKey(m.title)}`).sort().join("\n"));
6465
6566export const memberUrls = (members: Pick<Member, "url">[]): string[] => members.map((m) => m.url).sort();
6667
@@ -113,8 +114,9 @@ export function shouldApply(g: GroupRecord, label: string, urls: string[]): bool
113114 if (g.userNamed) return false;
114115 if (!g.lastNamedAt || !g.title) return true; // first name replaces the provisional hostname
115116 if (sameLabel(label, g.title)) return false;
116− const before = new Set(g.memberUrls ?? []);
117− const after = new Set(urls);
117+ // By page, not by exact address: a tab that moved to ?page=2 or #comments is the same member.
118+ const before = new Set((g.memberUrls ?? []).map(pathKey));
119+ const after = new Set(urls.map(pathKey));
118120 const changed = [...after].some((u) => !before.has(u)) || [...before].some((u) => !after.has(u));
119121 return changed; // a paraphrase with the same members keeps the old title
120122}
@@ -214,18 +216,32 @@ export class Naming {
214216 }
215217 const now = this.d.now();
216218 if (!force) {
217− if (g.nextAttemptAt && g.nextAttemptAt > now) return;
219+ // A refusal waits for the members to change, which only a look at them can tell.
220+ if (g.nextAttemptAt && g.nextAttemptAt > now && !g.refusedHash) return;
218221 if (s.host.pausedUntil && s.host.pausedUntil > now) return;
219222 if (s.inFlight?.groupId === groupId && this.current !== groupId && now - s.inFlight.startedAt < settings.timeoutMs + 5000) return;
220223 }
221224 const members = (await this.d.liveMembers(groupId))?.filter(nameable);
222225 if (!members) return;
223− if (members.length < 2 || !members.every(settled)) return; // stay dirty; the load finishing touches it again
224− if (!force && membersHash(members) === g.membersHash) {
225− g.dirty = false;
226+ if (!members.every(settled)) return; // stay dirty; the load finishing touches it again
227+ if (members.length < 2) {
228+ // Nothing to name from yet. A tab joining or loading a page marks the group dirty again.
229+ if (g.dirty && !force) {
230+ g.dirty = false;
231+ this.d.commit();
232+ }
233+ return;
234+ }
235+ const hash = membersHash(members);
236+ if (!force && hash === g.membersHash) {
237+ settle(g);
226238 this.d.commit();
227239 return;
228240 }
241+ if (g.refusedHash && !force) {
242+ if (hash === g.refusedHash && g.nextAttemptAt && g.nextAttemptAt > now) return;
243+ clearFailures(g); // different tabs now: Apple's filter may well take them
244+ }
229245 if (this.current === groupId && !force) return; // re-queued when the in-flight reply lands
230246 if (!this.queue.some((q) => q.groupId === groupId)) this.queue.push({ groupId, force });
231247 void this.pump();
@@ -261,7 +277,7 @@ export class Naming {
261277 if (!members || members.length < 2 || !members.every(settled)) return;
262278 const hash = membersHash(members);
263279 if (!force && hash === g.membersHash) {
264− g.dirty = false;
280+ settle(g);
265281 this.d.commit();
266282 return;
267283 }
@@ -296,9 +312,10 @@ export class Naming {
296312 }
297313 if (e.code === "BAD_MODEL_OUTPUT" && !retried.output) {
298314 retried.output = true;
315+ mustDifferFrom = withRejected(mustDifferFrom, e.raw);
299316 continue;
300317 }
301− this.fail(g, e);
318+ this.fail(g, e, hash);
302319 return;
303320 }
304321
@@ -307,9 +324,10 @@ export class Naming {
307324 const e: HostError = { code: "BAD_MODEL_OUTPUT", message: "label failed worker validation", raw: JSON.stringify(reply.result).slice(0, 500), at: this.d.now() };
308325 if (!retried.output) {
309326 retried.output = true;
327+ mustDifferFrom = withRejected(mustDifferFrom, e.raw);
310328 continue;
311329 }
312− this.fail(g, e);
330+ this.fail(g, e, hash);
313331 return;
314332 }
315333 const emoji = safeEmoji(reply.result.emoji);
@@ -324,12 +342,15 @@ export class Naming {
324342 finalLabel = suffixLabel(label, siblings);
325343 }
326344 this.d.hostOk();
327− await this.apply(g, finalLabel, emoji, members, hash);
345+ const written = await this.apply(g, finalLabel, emoji, members, hash);
328346 g = this.d.state().groups[groupId];
329− if (g) {
330− if (g.dirtySeq === seq) g.dirty = false;
331− else this.touch(groupId); // dirtied while in flight: go again with the new membership
332− }
347+ if (!g) return;
348+ if (!written) {
349+ // The strip refused the title (a drag in progress, the window closing): try again shortly.
350+ g.nextAttemptAt = this.d.now() + BACKOFF_MS[0];
351+ this.d.scheduleFallback(g.nextAttemptAt);
352+ } else if (g.dirtySeq === seq) g.dirty = false;
353+ else this.touch(groupId); // dirtied while in flight: go again with the new membership
333354 return;
334355 }
335356 } finally {
@@ -340,16 +361,20 @@ export class Naming {
340361 }
341362 }
342363
343− private async apply(g: GroupRecord, label: string, emoji: string, members: Member[], hash: string): Promise<void> {
364+ /** Put the label on the strip if the policy allows; false when the strip would not take the title. */
365+ private async apply(g: GroupRecord, label: string, emoji: string, members: Member[], hash: string): Promise<boolean> {
344366 const settings = this.d.settings();
345367 const urls = memberUrls(members);
346− if (g.userNamed) return; // renamed by hand while the model was thinking
368+ if (g.userNamed) return true; // renamed by hand while the model was thinking
347369 if (shouldApply(g, label, urls)) {
348370 const title = stripTitle(label, emoji, settings.emoji);
349371 this.d.state().ownWrites[g.id] = { title, at: this.d.now() };
350372 this.d.commit();
351373 const ok = await this.d.writeTitle(g.id, title);
352− if (!ok) return;
374+ if (!ok) {
375+ delete this.d.state().ownWrites[g.id];
376+ return false;
377+ }
353378 g.title = label;
354379 g.emoji = emoji;
355380 g.stripTitle = title;
@@ -357,21 +382,24 @@ export class Naming {
357382 g.lastNamedAt = this.d.now();
358383 g.membersHash = hash;
359384 g.memberUrls = urls;
360− g.nameAttempts = 0;
361− g.firstFailureAt = undefined;
362− g.nextAttemptAt = undefined;
385+ clearFailures(g);
386+ return true;
363387 }
364388
365− private fail(g: GroupRecord, e: HostError): void {
389+ private fail(g: GroupRecord, e: HostError, hash: string): void {
366390 const now = this.d.now();
367391 this.d.hostFailed(e);
368392 if (e.code === "BAD_REQUEST") {
369393 g.dirty = false; // a bug on our side: log and drop
370394 return;
371395 }
396+ // Setup errors pause every model call until the host is fixed, and its recovery picks this group up
397+ // again: they say nothing about this group, so they don't use up its retries.
398+ if (SETUP_ERRORS.has(e.code)) return;
372399 if (e.code === "GUARDRAIL") {
373400 g.nameAttempts = MAX_ATTEMPTS;
374401 g.nextAttemptAt = now + GIVE_UP_AFTER_MS;
402+ g.refusedHash = hash;
375403 this.d.scheduleFallback(g.nextAttemptAt);
376404 return;
377405 }
@@ -381,11 +409,35 @@ export class Naming {
381409 g.dirty = false; // retried for a day: keep the provisional title
382410 return;
383411 }
384− const wait = SETUP_ERRORS.has(e.code) ? Math.max(GLOBAL_PAUSE_MS, backoffFor(g.nameAttempts)) : backoffFor(g.nameAttempts);
385− g.nextAttemptAt = now + wait;
412+ g.nextAttemptAt = now + backoffFor(g.nameAttempts);
386413 this.d.scheduleFallback(g.nextAttemptAt);
387414 }
388415}
389416
417+/** The retry after an unusable title lists that title as not allowed, so the model doesn't give it again. */
418+function withRejected(list: string[] | undefined, raw: string | undefined): string[] | undefined {
419+ let title: unknown;
420+ try {
421+ title = raw ? JSON.parse(raw)?.title : undefined;
422+ } catch {
423+ return list;
424+ }
425+ return typeof title === "string" && title.trim() ? [...(list ?? []), title.trim().slice(0, 60)] : list;
426+}
427+
428+/** The retry bookkeeping of earlier failures, which no longer applies. */
429+function clearFailures(g: GroupRecord): void {
430+ g.nameAttempts = 0;
431+ g.firstFailureAt = undefined;
432+ g.nextAttemptAt = undefined;
433+ g.refusedHash = undefined;
434+}
435+
436+/** The members are the ones last named: nothing to do, and nothing left to retry. */
437+function settle(g: GroupRecord): void {
438+ g.dirty = false;
439+ clearFailures(g);
440+}
441+
390442export const eligible = (g: GroupRecord, settings: Settings): boolean =>
391443 settings.naming && g.managed && !g.userNamed && g.origin !== "tidy";
src/background/organize.ts+194−107
@@ -1,10 +1,11 @@
11import { COLORS, isColor, type GroupColor } from "../shared/colors";
2−import { labelOf, repairLabel, safeEmoji, stripTitle } from "../shared/label";
2+import { labelOf, repairLabel, safeEmoji, stripTitle, titleKey } from "../shared/label";
33import { colorFor, isInternalUrl, promptAddress, provisionalTitle } from "../shared/url";
44import { pathKey } from "./engine";
55import { membersHash, memberUrls, settled, toItems, type Member, type NameItem } from "./naming";
66import { addToGroup, createManagedGroup, groupExists, ungroup, type Runtime } from "./runtime";
7−import { markDirty, type State } from "./state";
7+import type { HostReply } from "./host";
8+import { markDirty, type GroupRecord, type HostError, type HostErrorCode, type State, type TabRecord } from "./state";
89
910/** Section 3/9: "Organize all tabs" — cluster ungrouped tabs in batches sized to the model's window. */
1011
@@ -26,6 +27,8 @@ export interface ExistingGroup {
2627export interface OrganizePayload {
2728 items: NameItem[];
2829 existingGroups: ExistingGroup[];
30+ /** Every group label in the window: a new group the host names must not repeat one. */
31+ siblingTitles?: string[];
2932 allowNew: boolean;
3033 maxGroups: number;
3134 minGroupSize: number;
@@ -151,88 +154,198 @@ export interface OrganizeReport {
151154 error?: string;
152155}
153156
154−/** Existing groups a batch may add tabs to: extension-managed topic groups in this window. */
157+/** Existing groups a batch may add tabs to: Diagonal's topic groups in this window, the ones in use first. */
155158export function existingGroupsFor(state: State, windowId: number, extraIds: number[] = []): { ids: number[]; list: ExistingGroup[] } {
159+ const members = new Map<number, TabRecord[]>();
160+ for (const t of Object.values(state.tabs)) if (t.groupId !== -1) members.set(t.groupId, [...(members.get(t.groupId) ?? []), t]);
161+ const inUse = (g: GroupRecord): number =>
162+ Math.max(g.dirtyAt ?? 0, g.lastNamedAt ?? 0, ...(members.get(g.id) ?? []).map((t) => t.lastActivatedAt ?? 0));
156163 const groups = Object.values(state.groups)
157− .filter((g) => g.windowId === windowId && g.managed && g.origin !== "tidy" && (g.stripTitle || g.title))
158− .sort((a, b) => Number(extraIds.includes(b.id)) - Number(extraIds.includes(a.id)))
159− .slice(0, EXISTING_GROUPS_CAP);
164+ .filter((g) => g.windowId === windowId && g.managed && g.origin !== "tidy" && !g.restored && (g.stripTitle || g.title))
165+ .map((g) => ({ g, first: extraIds.includes(g.id), at: inUse(g) }))
166+ .sort((a, b) => Number(b.first) - Number(a.first) || b.at - a.at)
167+ .slice(0, EXISTING_GROUPS_CAP)
168+ .map(({ g }) => g);
160169 const list = groups.map((g, i) => ({
161170 g: i,
162171 title: labelOf(g.stripTitle || g.title),
163− samples: Object.values(state.tabs)
164− .filter((t) => t.groupId === g.id)
165− .slice(0, 2)
166− .map((t) => t.title.slice(0, 60)),
172+ samples: (members.get(g.id) ?? []).slice(0, 2).map((t) => t.title.slice(0, 60)),
167173 }));
168174 return { ids: groups.map((g) => g.id), list };
169175}
170176
171−export async function organizeWindow(rt: Runtime, windowId: number): Promise<OrganizeReport> {
177+/** Errors about what was sent rather than about the host: a smaller or plainer request may go through. */
178+const CONTENT_ERRORS = new Set<HostErrorCode>(["OVER_BUDGET", "GUARDRAIL", "BAD_MODEL_OUTPUT"]);
179+const MAX_TIMEOUT_SPLITS = 1;
180+
181+/** One organize call, with the retries that can rescue the same tabs: strict output, then no page text. */
182+async function askOrganize(rt: Runtime, part: Member[], windowId: number, existingGroups: ExistingGroup[], withDescriptions: boolean): Promise<HostReply<OrganizeResult>> {
183+ const settings = rt.settings();
184+ const s = rt.state();
185+ const payload: OrganizePayload = {
186+ items: toItems(part, settings, withDescriptions),
187+ existingGroups,
188+ siblingTitles: Object.values(s.groups)
189+ .filter((g) => g.windowId === windowId && g.origin !== "tidy")
190+ .map((g) => labelOf(g.stripTitle || g.title))
191+ .filter(Boolean)
192+ .slice(0, 20),
193+ allowNew: part.length >= 2,
194+ maxGroups: maxGroupsFor(part.length),
195+ minGroupSize: settings.organizeMinGroupSize,
196+ };
197+ let reply = await rt.host<OrganizeResult>("organize", payload);
198+ if (!reply.ok && reply.error.code === "BAD_MODEL_OUTPUT") reply = await rt.host<OrganizeResult>("organize", payload, { strict: true });
199+ if (!reply.ok && reply.error.code === "GUARDRAIL" && payload.items.some((i) => i.description)) {
200+ // What a page says is the likeliest thing to trip Apple's filter; its title and address rarely do.
201+ payload.items = toItems(part, settings, false);
202+ reply = await rt.host<OrganizeResult>("organize", payload);
203+ }
204+ return reply;
205+}
206+
207+/** One organize run over a window: what it made, what it moved, and whether the host stopped it. */
208+export interface SortRun {
209+ windowId: number;
210+ createdIds: number[];
211+ previous: Record<number, number>;
212+ grouped: number;
213+ left: number;
214+ timeoutSplits: number;
215+ /** Auto-organize: remember what was looked at, so the same tabs are not sent again unchanged. */
216+ stamp: boolean;
217+ stopped?: HostError;
218+}
219+
220+export const newRun = (windowId: number, stamp: boolean): SortRun => ({ windowId, createdIds: [], previous: {}, grouped: 0, left: 0, timeoutSplits: 0, stamp });
221+
222+/**
223+ * Sort one part of a window. A reply about the tabs themselves (too long, refused by Apple's filter, not
224+ * valid output) splits the part in halves, so one page the model won't handle leaves the others sorted; a
225+ * tab that fails alone is set aside until its page or title changes. Tabs that changed while the model was
226+ * thinking are left out of its answer.
227+ */
228+export async function sortPart(rt: Runtime, part: Member[], run: SortRun, probe = false): Promise<void> {
229+ if (!part.length || run.stopped) return;
230+ const { ids: existingIds, list: existingGroups } = existingGroupsFor(rt.state(), run.windowId, run.createdIds);
231+ if (part.length < 2 && !existingIds.length && !probe) {
232+ run.left += part.length;
233+ return; // one tab and nothing to join: no call can place it (a probe still learns whether the model takes it)
234+ }
235+ const reply = await askOrganize(rt, part, run.windowId, existingGroups, true);
236+ if (!reply.ok) {
237+ const e = reply.error;
238+ const timedOut = e.code === "TIMEOUT" && part.length > 4 && run.timeoutSplits < MAX_TIMEOUT_SPLITS;
239+ if (part.length > 1 && (CONTENT_ERRORS.has(e.code) || timedOut)) {
240+ if (timedOut) run.timeoutSplits++;
241+ const half = Math.ceil(part.length / 2);
242+ await sortPart(rt, part.slice(0, half), run, true);
243+ await sortPart(rt, part.slice(half), run, true);
244+ return;
245+ }
246+ if (CONTENT_ERRORS.has(e.code)) {
247+ const rec = rt.state().tabs[part[0].id];
248+ if (rec) rec.organizeRefused = organizedKeyOf(part[0]);
249+ rt.log("organize: set aside a tab the model would not sort", e.code);
250+ run.left += 1;
251+ return;
252+ }
253+ run.stopped = e;
254+ return;
255+ }
172256 const settings = rt.settings();
257+ const plan = planFromResult(reply.result, part.map((m) => m.id), existingIds, settings.organizeMinGroupSize, maxGroupsFor(part.length), (ids) =>
258+ colorFor(part.find((m) => m.id === ids[0])?.url ?? ""),
259+ );
260+ const unchanged = await stillAsSent(rt, part, run.windowId);
261+ const trimmed = trimPlan(rt.state(), plan, unchanged, settings.organizeMinGroupSize);
262+ const failed = await applyPlan(rt, trimmed, run.windowId, part, run.previous, run.createdIds);
263+ const placed = [...trimmed.joins, ...trimmed.creates].reduce((n, x) => n + x.tabIds.filter((id) => !failed.has(id)).length, 0);
264+ run.grouped += placed;
265+ run.left += part.length - placed;
266+ if (run.stamp) {
267+ const s = rt.state();
268+ for (const m of part) {
269+ const rec = s.tabs[m.id];
270+ if (rec && unchanged.has(m.id) && !failed.has(m.id)) rec.organizedKey = organizedKeyOf(m);
271+ }
272+ }
273+}
274+
275+/** The tabs of a part that are still loose, in this window, on the page and title the model saw. */
276+async function stillAsSent(rt: Runtime, part: Member[], windowId: number): Promise<Set<number>> {
277+ const live = new Map((await chrome.tabs.query({ windowId }).catch(() => [])).map((t) => [t.id!, t]));
278+ const s = rt.state();
279+ return new Set(
280+ part
281+ .filter((m) => {
282+ const t = live.get(m.id);
283+ return !!t && organizable(t) && !s.tabs[m.id]?.keepLoose && organizedKeyOf(t) === organizedKeyOf(m);
284+ })
285+ .map((m) => m.id),
286+ );
287+}
288+
289+/** A plan with the tabs that moved on taken out: a new group left too small is not made, a join into a group gone is dropped. */
290+export function trimPlan(state: State, plan: Plan, keep: Set<number>, minGroupSize: number): Plan {
291+ const out: Plan = { joins: [], creates: [], leftovers: plan.leftovers.filter((id) => keep.has(id)) };
292+ for (const j of plan.joins) {
293+ const tabIds = j.tabIds.filter((id) => keep.has(id));
294+ const g = state.groups[j.groupId];
295+ if (tabIds.length && g?.managed && !g.restored) out.joins.push({ ...j, tabIds });
296+ else out.leftovers.push(...tabIds);
297+ }
298+ for (const c of plan.creates) {
299+ const tabIds = c.tabIds.filter((id) => keep.has(id));
300+ if (tabIds.length >= Math.max(2, minGroupSize)) out.creates.push({ ...c, tabIds });
301+ else out.leftovers.push(...tabIds);
302+ }
303+ return out;
304+}
305+
306+export async function organizeWindow(rt: Runtime, windowId: number): Promise<OrganizeReport> {
307+ const s0 = rt.state();
173308 const tabs = (await chrome.tabs.query({ windowId })).filter((t) => organizable(t)).sort((a, b) => a.index - b.index);
174309 const report: OrganizeReport = { grouped: 0, groups: 0, left: 0 };
175− if (tabs.length < 2) {
310+ // A tab the model already would not sort, on the same page, is not sent again.
311+ const sendable = tabs.filter((t) => s0.tabs[t.id!]?.organizeRefused !== organizedKeyOf(t));
312+ if (sendable.length < 2) {
176313 report.left = tabs.length;
177314 return report;
178315 }
179− const members: Member[] = tabs.map((t) => ({
180− id: t.id!,
181− index: t.index,
182− url: t.url ?? "",
183− title: t.title ?? "",
184− status: t.status,
185− description: rt.state().tabs[t.id!]?.description,
186− lastActive: t.lastAccessed ?? 0,
187− }));
188− const previous: Record<number, number> = {};
189− const createdIds: number[] = [];
190− const queue = makeBatches(members);
316+ const run = newRun(windowId, true); // auto-organize need not send the same tabs again right after
191317 rt.state().inFlight = { groupId: -1, startedAt: rt.now() };
192318 rt.refreshBadge();
193319 try {
194− while (queue.length) {
195− const batch = queue.shift()!;
196− const { ids: existingIds, list: existingGroups } = existingGroupsFor(rt.state(), windowId, createdIds);
197− const maxGroups = maxGroupsFor(batch.length);
198− const payload: OrganizePayload = {
199− items: toItems(batch, settings),
200− existingGroups,
201− allowNew: true,
202− maxGroups,
203− minGroupSize: settings.organizeMinGroupSize,
204− };
205− let reply = await rt.host<OrganizeResult>("organize", payload);
206− if (!reply.ok && reply.error.code === "OVER_BUDGET" && batch.length > 1) {
207− const half = Math.ceil(batch.length / 2);
208− queue.unshift(batch.slice(0, half), batch.slice(half));
209− continue;
210− }
211− if (!reply.ok && reply.error.code === "BAD_MODEL_OUTPUT") reply = await rt.host<OrganizeResult>("organize", payload, { strict: true });
212− if (!reply.ok) {
213− report.error = `${reply.error.code}: ${reply.error.message}`;
214− report.left += batch.length + queue.flat().length;
215− break;
216− }
217− const batchIds = batch.map((m) => m.id);
218− const plan = planFromResult(reply.result, batchIds, existingIds, settings.organizeMinGroupSize, maxGroups, (ids) =>
219− colorFor(members.find((m) => m.id === ids[0])?.url ?? ""),
220− );
221− await applyPlan(rt, plan, windowId, members, previous, createdIds);
222− report.grouped += plan.joins.reduce((n, j) => n + j.tabIds.length, 0) + plan.creates.reduce((n, c) => n + c.tabIds.length, 0);
223− report.left += plan.leftovers.length;
320+ for (const batch of makeBatches(sendable.map((t) => toMember(rt.state(), t)))) {
321+ await sortPart(rt, batch, run);
322+ if (run.stopped) break;
224323 }
225324 } finally {
226325 const s = rt.state();
227326 if (s.inFlight?.groupId === -1) s.inFlight = undefined;
228− report.groups = createdIds.length;
229− if (Object.keys(previous).length) s.lastOrganize = { at: rt.now(), previous };
327+ report.grouped = run.grouped;
328+ report.groups = run.createdIds.length;
329+ report.left = tabs.length - run.grouped;
330+ if (run.stopped) report.error = `${run.stopped.code}: ${run.stopped.message}`;
331+ if (Object.keys(run.previous).length) s.lastOrganize = { at: rt.now(), previous: run.previous };
230332 rt.commit();
231333 rt.refreshBadge();
232334 }
233335 return report;
234336}
235337
338+const toMember = (s: State, t: chrome.tabs.Tab): Member => ({
339+ id: t.id!,
340+ index: t.index,
341+ url: t.url ?? "",
342+ title: t.title ?? "",
343+ status: t.status,
344+ description: s.tabs[t.id!]?.description,
345+ lastActive: t.lastAccessed ?? 0,
346+});
347+
348+/** Carry out a plan; returns the tabs whose move failed, which stay as they were. */
236349export async function applyPlan(
237350 rt: Runtime,
238351 plan: Plan,
@@ -240,11 +353,15 @@ export async function applyPlan(
240353 members: Member[],
241354 previous: Record<number, number>,
242355 createdIds: number[],
243−): Promise<void> {
356+): Promise<Set<number>> {
244357 const settings = rt.settings();
245358 const byId = new Map(members.map((m) => [m.id, m]));
359+ const failed = new Set<number>();
246360 for (const j of plan.joins) {
247− if (!(await addToGroup(rt, j.tabIds, j.groupId))) continue;
361+ if (!(await addToGroup(rt, j.tabIds, j.groupId))) {
362+ for (const id of j.tabIds) failed.add(id);
363+ continue;
364+ }
248365 for (const id of j.tabIds) previous[id] = -1;
249366 const g = rt.state().groups[j.groupId];
250367 if (g) {
@@ -265,7 +382,10 @@ export async function applyPlan(
265382 lastNamedAt: named ? rt.now() : undefined,
266383 dirty: false,
267384 });
268− if (groupId === undefined) continue;
385+ if (groupId === undefined) {
386+ for (const id of c.tabIds) failed.add(id);
387+ continue;
388+ }
269389 createdIds.push(groupId);
270390 for (const id of c.tabIds) previous[id] = -1;
271391 const g = rt.state().groups[groupId];
@@ -274,6 +394,7 @@ export async function applyPlan(
274394 rt.naming.touch(groupId);
275395 }
276396 }
397+ return failed;
277398}
278399
279400/** Undo within the hour: every tab goes back to the group it was in (organize only takes loose tabs). */
@@ -301,7 +422,7 @@ export async function undoOrganize(rt: Runtime): Promise<number> {
301422}
302423
303424/** What auto-organize remembers about a tab: it looks again only when the page or title changes. */
304−export const organizedKeyOf = (t: { url?: string; title?: string }): string => `${pathKey(t.url)}\n${t.title ?? ""}`;
425+export const organizedKeyOf = (t: { url?: string; title?: string }): string => `${pathKey(t.url)}\n${titleKey(t.title)}`;
305426
306427export const AUTO_RETRY_MS = 300_000;
307428export const AUTO_CONTINUE_MS = 1_500;
@@ -379,59 +500,25 @@ export class AutoOrganizer {
379500 const s = rt.state();
380501 // Still-loading tabs are skipped here; finishing the load touches the window again. Discarded tabs keep
381502 // their title and address, so they're sorted like loaded ones.
382− const loose = tabs.filter((t) => organizable(t) && settled(t) && !s.tabs[t.id!]?.keepLoose);
503+ const loose = tabs.filter((t) => {
504+ const rec = s.tabs[t.id!];
505+ return organizable(t) && settled(t) && !rec?.keepLoose && rec?.organizeRefused !== organizedKeyOf(t);
506+ });
383507 const fresh = loose.filter((t) => s.tabs[t.id!]?.organizedKey !== organizedKeyOf(t));
384508 if (!fresh.length) return;
385− const { ids: existingIds, list: existingGroups } = existingGroupsFor(s, windowId);
386− if (loose.length < 2 && !existingIds.length) return; // one loose tab and nothing to join: wait for company
387− const toMember = (t: chrome.tabs.Tab): Member => ({
388− id: t.id!,
389− index: t.index,
390− url: t.url ?? "",
391− title: t.title ?? "",
392− status: t.status,
393− description: s.tabs[t.id!]?.description,
394− lastActive: t.lastAccessed ?? 0,
395− });
396− const ordered = [...fresh, ...loose.filter((t) => !fresh.includes(t))].map(toMember);
509+ if (loose.length < 2 && !existingGroupsFor(s, windowId).ids.length) return; // one loose tab and nothing to join: wait for company
510+ const ordered = [...fresh, ...loose.filter((t) => !fresh.includes(t))].map((t) => toMember(s, t));
397511 const batch = makeBatches(ordered)[0];
398− const maxGroups = maxGroupsFor(batch.length);
399− const payload: OrganizePayload = {
400− items: toItems(batch, settings),
401− existingGroups,
402− allowNew: batch.length >= 2,
403− maxGroups,
404− minGroupSize: settings.organizeMinGroupSize,
405− };
406− let reply = await rt.host<OrganizeResult>("organize", payload);
407− if (!reply.ok && reply.error.code === "OVER_BUDGET" && batch.length > 1) {
408− // Rare with the budgeted batch; try once with half, the rest follows on the next run.
409− const half = batch.slice(0, Math.ceil(batch.length / 2));
410− payload.items = toItems(half, settings);
411− payload.maxGroups = maxGroupsFor(half.length);
412− payload.allowNew = half.length >= 2;
413− batch.length = half.length;
414− reply = await rt.host<OrganizeResult>("organize", payload);
415− }
416− if (!reply.ok && reply.error.code === "BAD_MODEL_OUTPUT") reply = await rt.host<OrganizeResult>("organize", payload, { strict: true });
417− if (!reply.ok) {
418− rt.log("auto-organize", reply.error.code);
512+ const run = newRun(windowId, true);
513+ await sortPart(rt, batch, run);
514+ rt.commit();
515+ if (run.stopped) {
516+ rt.log("auto-organize", run.stopped.code);
419517 this.deps.scheduleFallback(rt.now() + AUTO_RETRY_MS);
420518 return;
421519 }
422− const batchIds = batch.map((m) => m.id);
423− const plan = planFromResult(reply.result, batchIds, existingIds, settings.organizeMinGroupSize, payload.maxGroups, (ids) =>
424− colorFor(batch.find((m) => m.id === ids[0])?.url ?? ""),
425− );
426− await applyPlan(rt, plan, windowId, batch, {}, []);
427− const live = rt.state();
428− for (const m of batch) {
429− const rec = live.tabs[m.id];
430− if (rec) rec.organizedKey = organizedKeyOf(m);
431− }
432− rt.commit();
433− const remaining = fresh.filter((t) => !batchIds.includes(t.id!));
434− if (remaining.length) this.touch(windowId, AUTO_CONTINUE_MS);
520+ const sent = new Set(batch.map((m) => m.id));
521+ if (fresh.some((t) => !sent.has(t.id!))) this.touch(windowId, AUTO_CONTINUE_MS);
435522 }
436523}
437524
src/background/runtime.ts+13−2
@@ -67,20 +67,25 @@ export async function createManagedGroup(
6767 extra: Partial<GroupRecord> = {},
6868): Promise<number | undefined> {
6969 const s = rt.state();
70− s.pendingCreates.push({ windowId, origin, at: rt.now() });
70+ const pending = { windowId, origin, at: rt.now() };
71+ s.pendingCreates.push(pending);
7172 for (const id of tabIds) s.ownAdds[id] = rt.now();
7273 let groupId: number;
7374 try {
7475 groupId = await withEditRetry(() => chrome.tabs.group({ tabIds: tabIds as [number, ...number[]], createProperties: { windowId } }));
7576 } catch (e) {
7677 rt.log("tabs.group failed", e);
78+ forgetOwnAdds(rt.state(), tabIds);
79+ const live = rt.state();
80+ live.pendingCreates = live.pendingCreates.filter((p) => p !== pending);
7781 return undefined;
7882 }
7983 const live = rt.state();
8084 const rec = live.groups[groupId] ?? newGroupRecord(groupId, windowId, origin, props.color);
8185 Object.assign(rec, { origin, managed: true, windowId, color: props.color }, extra);
8286 live.groups[groupId] = rec;
83− for (const id of tabIds) if (live.tabs[id]) live.tabs[id].groupId = groupId;
87+ // Tab records move when tabs.onUpdated reports the new groupId: that event also tells the group
88+ // each tab left that it lost one, and uses up the ownAdds marker.
8489 await updateGroup(rt, groupId, props);
8590 rt.commit();
8691 return groupId;
@@ -94,10 +99,16 @@ export async function addToGroup(rt: Runtime, tabIds: number[], groupId: number)
9499 return true;
95100 } catch (e) {
96101 rt.log("tabs.group into existing failed", e);
102+ forgetOwnAdds(rt.state(), tabIds);
97103 return false;
98104 }
99105}
100106
107+/** A grouping call failed: nothing moved, so a later move of these tabs is not the worker's. */
108+function forgetOwnAdds(s: State, tabIds: number[]): void {
109+ for (const id of tabIds) delete s.ownAdds[id];
110+}
111+
101112export async function ungroup(rt: Runtime, tabIds: number[]): Promise<void> {
102113 if (!tabIds.length) return;
103114 try {
src/background/state.ts+18
@@ -18,8 +18,10 @@ export interface TabRecord {
1818 createdAt: number;
1919 lastActivatedAt: number; // epoch ms
2020 parkedFrom?: string; // title of the group the tab was in before the tidy sweep parked it
21+ parkedAt?: number; // when the tidy sweep parked it: the archive clock starts here
2122 keepLoose?: string; // the user took this tab out of a group on this page: auto-organize leaves it be
2223 organizedKey?: string; // page + title when auto-organize last considered this tab
24+ organizeRefused?: string; // page + title the model would not sort even alone: not sent again until it changes
2325 handPlaced?: boolean; // the user put this tab into its group: Diagonal won't take it out
2426 fitPending?: boolean; // moved to a new page inside a Diagonal group: check it still fits (fit.ts)
2527}
@@ -45,8 +47,15 @@ export interface GroupRecord {
4547 nameAttempts: number;
4648 firstFailureAt?: number;
4749 nextAttemptAt?: number;
50+ refusedHash?: string; // the members Apple's filter refused to name: not asked again until they change
51+ registeredAt?: number; // first seen as a group Diagonal did not know: it may yet turn out to be one of Diagonal's coming back
52+ revivedAt?: number; // came back after Chromium removed it (window move, reopen, restart)
53+ restored?: boolean; // "Restored": the archive brought back, not a topic other tabs should join
4854}
4955
56+/** A group Chromium removed, kept for a day: it may come back (moved to another window, reopened, restored). */
57+export type RemovedGroup = GroupRecord & { removedAt: number };
58+
5059export interface ArchivedTab {
5160 url: string;
5261 title: string;
@@ -107,6 +116,11 @@ export interface SweepMove {
107116 groupId: number;
108117 index: number;
109118 windowId: number;
119+ /** The group the tab was in, so undo can make it again if parking emptied it. */
120+ group?: Pick<
121+ GroupRecord,
122+ "origin" | "managed" | "userNamed" | "title" | "emoji" | "stripTitle" | "color" | "colorLocked" | "keep" | "membersHash" | "memberUrls" | "lastNamedAt"
123+ >;
110124}
111125
112126export interface State {
@@ -124,6 +138,8 @@ export interface State {
124138 ownUngroups: Record<number, number>;
125139 /** Tabs the worker itself is adding to a group: joining it is not the user's choice. */
126140 ownAdds: Record<number, number>;
141+ /** Groups Chromium removed lately, by their last id. */
142+ removedGroups: Record<number, RemovedGroup>;
127143 lastSweep?: { at: number; moves: SweepMove[] };
128144 lastOrganize?: { at: number; previous: Record<number, number> };
129145 tidyCandidates?: number;
@@ -139,6 +155,7 @@ export const emptyState = (): State => ({
139155 pendingCreates: [],
140156 ownUngroups: {},
141157 ownAdds: {},
158+ removedGroups: {},
142159});
143160
144161/** Accept whatever was stored and bring it to the current shape. */
@@ -160,6 +177,7 @@ export function migrate(raw: unknown): State {
160177 pendingCreates: r.pendingCreates ?? [],
161178 ownUngroups: r.ownUngroups ?? {},
162179 ownAdds: r.ownAdds ?? {},
180+ removedGroups: r.removedGroups ?? {},
163181 };
164182}
165183
src/background/tidy.ts+129−17
@@ -3,7 +3,7 @@ import { labelOf, stripTitle } from "../shared/label";
33import { isInternalUrl } from "../shared/url";
44import { addToGroup, createManagedGroup, groupExists, ungroup, updateGroup, type Runtime } from "./runtime";
55import type { Settings } from "./settings";
6−import type { ArchivedTab, State, SweepMove } from "./state";
6+import { newGroupRecord, type ArchivedTab, type GroupRecord, type State, type SweepMove } from "./state";
77
88/** Section 7: park stale tabs in a collapsed group, then archive and close them. No model calls. */
99
@@ -23,11 +23,22 @@ export interface TidyTab {
2323 audible?: boolean;
2424 incognito?: boolean;
2525 discarded?: boolean;
26+ autoDiscardable?: boolean;
2627 lastAccessed?: number;
2728}
2829
30+/**
31+ * The engine's record wins over Chromium's lastAccessed: after a restart Chromium stamps restored tabs
32+ * nobody has looked at yet with the restore time, which would keep them from ever going stale.
33+ */
2934export const idleMs = (tab: TidyTab, state: State, now: number): number =>
30− now - Math.max(tab.lastAccessed ?? 0, state.tabs[tab.id]?.lastActivatedAt ?? 0);
35+ now - (state.tabs[tab.id]?.lastActivatedAt ?? tab.lastAccessed ?? now);
36+
37+/** How long a tab has sat in Parked. Tabs found there with no parking time start their clock now. */
38+export const parkedMs = (tab: TidyTab, state: State, now: number): number => {
39+ const at = state.tabs[tab.id]?.parkedAt;
40+ return at === undefined ? 0 : now - at;
41+};
3142
3243/** Exclusions are substrings of the URL; a pattern written as /…/ is a regular expression. */
3344export function excluded(url: string, patterns: string[]): boolean {
@@ -55,7 +66,8 @@ export function isParkCandidate(tab: TidyTab, state: State, settings: Settings,
5566 if (tab.groupId !== -1) {
5667 const g = state.groups[tab.groupId];
5768 if (g?.keep) return false;
58− if ((!g || g.origin === "user") && !settings.tidyUserGroups) return false;
69+ // Groups you made or renamed are yours, like Diagonal's other rules treat them.
70+ if ((!g || g.origin === "user" || g.userNamed) && !settings.tidyUserGroups) return false;
5971 }
6072 if (excluded(tab.url, settings.tidyExclusions)) return false;
6173 return idleMs(tab, state, now) >= settings.parkAfterHours * HOUR;
@@ -66,10 +78,18 @@ export function parkCandidates(tabs: TidyTab[], state: State, settings: Settings
6678 return tabs.filter((t) => isParkCandidate(t, state, settings, now, parking));
6779}
6880
81+/** Tabs that have sat in Parked for the archive time, counted from when they were parked. */
6982export function archiveCandidates(tabs: TidyTab[], state: State, settings: Settings, now: number): TidyTab[] {
7083 if (!settings.archiveAfterHours) return [];
7184 const parking = parkingGroupIds(state);
72− return tabs.filter((t) => parking.has(t.groupId) && !t.active && !t.audible && idleMs(t, state, now) >= settings.archiveAfterHours * HOUR);
85+ return tabs.filter(
86+ (t) =>
87+ parking.has(t.groupId) &&
88+ !t.active &&
89+ !t.audible &&
90+ !(t.url && excluded(t.url, settings.tidyExclusions)) &&
91+ parkedMs(t, state, now) >= settings.archiveAfterHours * HOUR,
92+ );
7393}
7494
7595/** Prepend entries newest first and drop the oldest past the cap. */
@@ -79,6 +99,15 @@ export function addToArchive(archive: ArchivedTab[], entries: ArchivedTab[], cap
7999
80100export const parkedTitle = (settings: Settings): string => stripTitle("Parked", PARKED_EMOJI, settings.emoji);
81101
102+/** A grey group titled like Parked: Diagonal's Parked group, even where an older version lost track of it. */
103+export const looksParked = (g: { title?: string; color: string }, settings: Settings): boolean =>
104+ g.color === "grey" && (g.title ?? "") === parkedTitle(settings);
105+
106+/** Make a group Diagonal's Parked group again. */
107+export function adoptParked(g: GroupRecord, settings: Settings): void {
108+ Object.assign(g, { origin: "tidy", managed: true, userNamed: true, stripTitle: parkedTitle(settings) });
109+}
110+
82111// ---------------------------------------------------------------------------------------------
83112
84113const liveTabs = async (): Promise<TidyTab[]> =>
@@ -95,6 +124,7 @@ const liveTabs = async (): Promise<TidyTab[]> =>
95124 audible: t.audible,
96125 incognito: t.incognito,
97126 discarded: t.discarded,
127+ autoDiscardable: t.autoDiscardable,
98128 lastAccessed: t.lastAccessed,
99129 }));
100130
@@ -104,11 +134,20 @@ export interface SweepReport {
104134 archived: number;
105135}
106136
137+let sweeps: Promise<unknown> = Promise.resolve();
138+
107139/**
108140 * The 30-minute sweep (manual = "Tidy now" / "Park N tabs": ignores the threshold and the Ask
109− * consent, still respects eligibility).
141+ * consent, still respects eligibility). One at a time: two at once would park, and archive, the
142+ * same tabs twice.
110143 */
111−export async function runSweep(rt: Runtime, manual = false): Promise<SweepReport> {
144+export function runSweep(rt: Runtime, manual = false): Promise<SweepReport> {
145+ const next = sweeps.then(() => sweep(rt, manual));
146+ sweeps = next.catch(() => undefined);
147+ return next;
148+}
149+
150+async function sweep(rt: Runtime, manual: boolean): Promise<SweepReport> {
112151 const settings = rt.settings();
113152 const report: SweepReport = { candidates: 0, parked: 0, archived: 0 };
114153 if (settings.tidyMode === "off" && !manual) {
@@ -118,6 +157,7 @@ export async function runSweep(rt: Runtime, manual = false): Promise<SweepReport
118157 }
119158 const now = rt.now();
120159 let tabs = await liveTabs();
160+ startParkedClocks(rt.state(), tabs, now);
121161 const candidates = parkCandidates(tabs, rt.state(), settings, now);
122162 report.candidates = candidates.length;
123163 // Auto parks whatever is stale; the threshold only decides when Ask mode puts a count on the badge.
@@ -133,8 +173,52 @@ export async function runSweep(rt: Runtime, manual = false): Promise<SweepReport
133173 return report;
134174}
135175
176+/** Tabs already in Parked with no parking time (from before it was recorded) start their archive clock now. */
177+function startParkedClocks(s: State, tabs: TidyTab[], now: number): void {
178+ const parking = parkingGroupIds(s);
179+ for (const t of tabs) {
180+ const rec = s.tabs[t.id];
181+ if (rec && parking.has(t.groupId) && rec.parkedAt === undefined) rec.parkedAt = now;
182+ }
183+}
184+
185+/** What undo needs to make a group again if parking emptied it, named as it was. */
186+const groupShape = (g: GroupRecord): SweepMove["group"] => ({
187+ origin: g.origin,
188+ managed: g.managed,
189+ userNamed: g.userNamed,
190+ title: g.title,
191+ emoji: g.emoji,
192+ stripTitle: g.stripTitle,
193+ color: g.color,
194+ colorLocked: g.colorLocked,
195+ keep: g.keep,
196+ membersHash: g.membersHash,
197+ memberUrls: g.memberUrls,
198+ lastNamedAt: g.lastNamedAt,
199+});
200+
201+/**
202+ * The window's Parked group: the one on record, or a group already showing the Parked title (one an
203+ * older version lost track of after a restart), which becomes Parked again.
204+ */
205+async function parkingGroupIn(rt: Runtime, windowId: number): Promise<number | undefined> {
206+ const s = rt.state();
207+ const known = Object.values(s.groups).find((g) => g.origin === "tidy" && g.windowId === windowId)?.id;
208+ if (known !== undefined && (await groupExists(known))) return known;
209+ const settings = rt.settings();
210+ const shown = (await chrome.tabGroups.query({ windowId }).catch(() => [])).filter((g) => looksParked(g, settings));
211+ for (const g of shown) {
212+ const rec = s.groups[g.id] ?? newGroupRecord(g.id, windowId, "tidy", "grey");
213+ adoptParked(rec, settings);
214+ s.groups[g.id] = rec;
215+ }
216+ return shown[0]?.id;
217+}
218+
136219async function parkTabs(rt: Runtime, candidates: TidyTab[]): Promise<number> {
137220 const settings = rt.settings();
221+ const now = rt.now();
138222 const moves: SweepMove[] = [];
139223 const byWindow = new Map<number, TidyTab[]>();
140224 for (const t of candidates) byWindow.set(t.windowId, [...(byWindow.get(t.windowId) ?? []), t]);
@@ -142,13 +226,15 @@ async function parkTabs(rt: Runtime, candidates: TidyTab[]): Promise<number> {
142226 const ids = tabs.map((t) => t.id);
143227 const s = rt.state();
144228 for (const t of tabs) {
145− moves.push({ tabId: t.id, groupId: t.groupId, index: t.index, windowId });
146− const rec = s.tabs[t.id];
147229 const from = t.groupId !== -1 ? s.groups[t.groupId] : undefined;
148− if (rec) rec.parkedFrom = from ? labelOf(from.stripTitle || from.title) || undefined : undefined;
230+ moves.push({ tabId: t.id, groupId: t.groupId, index: t.index, windowId, group: from && groupShape(from) });
231+ const rec = s.tabs[t.id];
232+ if (rec) {
233+ rec.parkedFrom = from ? labelOf(from.stripTitle || from.title) || undefined : undefined;
234+ rec.parkedAt = now;
235+ }
149236 }
150− let parking = Object.values(s.groups).find((g) => g.origin === "tidy" && g.windowId === windowId)?.id;
151− if (parking !== undefined && !(await groupExists(parking))) parking = undefined;
237+ let parking = await parkingGroupIn(rt, windowId);
152238 if (parking === undefined) {
153239 parking = await createManagedGroup(rt, ids, windowId, "tidy", { title: parkedTitle(settings), color: "grey", collapsed: true }, { userNamed: true });
154240 } else {
@@ -162,12 +248,16 @@ async function parkTabs(rt: Runtime, candidates: TidyTab[]): Promise<number> {
162248 rt.log("could not move parking group to the end", e);
163249 }
164250 if (settings.discardParked) {
251+ // An extension's discard skips Chromium's own checks, so honour a tab marked "never discard".
165252 for (const t of tabs) {
166− if (!t.discarded) await chrome.tabs.discard(t.id).catch(() => undefined);
253+ if (!t.discarded && t.autoDiscardable !== false) await chrome.tabs.discard(t.id).catch(() => undefined);
167254 }
168255 }
169256 }
170− rt.state().lastSweep = { at: rt.now(), moves };
257+ // Sweeps inside the undo window add up, so Undo puts back everything parked in that hour.
258+ const last = rt.state().lastSweep;
259+ const kept = last && now - last.at < UNDO_WINDOW_MS ? last.moves.filter((m) => !moves.some((n) => n.tabId === m.tabId)) : [];
260+ rt.state().lastSweep = { at: now, moves: [...kept, ...moves] };
171261 rt.commit();
172262 return moves.length;
173263}
@@ -197,18 +287,40 @@ export async function undoSweep(rt: Runtime): Promise<number> {
197287 const last = rt.state().lastSweep;
198288 if (!last || rt.now() - last.at > UNDO_WINDOW_MS) return 0;
199289 const live = new Map((await chrome.tabs.query({})).map((t) => [t.id!, t]));
290+ // Parking every tab of a group removes it: undo makes it again, once, with its title and colour.
291+ const remade = new Map<number, number>();
292+ const target = async (m: SweepMove): Promise<number | undefined> => {
293+ if (m.groupId === -1) return undefined;
294+ const again = remade.get(m.groupId);
295+ if (again !== undefined) return again;
296+ return (await groupExists(m.groupId)) ? m.groupId : undefined;
297+ };
200298 let restored = 0;
201299 for (const m of [...last.moves].sort((a, b) => a.index - b.index)) {
202300 const t = live.get(m.tabId);
203301 if (!t) continue;
204− if (m.groupId !== -1 && (await groupExists(m.groupId))) await addToGroup(rt, [m.tabId], m.groupId);
205− else await ungroup(rt, [m.tabId]);
302+ let groupId = await target(m);
303+ if (groupId !== undefined) await addToGroup(rt, [m.tabId], groupId);
304+ else if (m.groupId !== -1 && m.group) {
305+ const g = m.group;
306+ groupId = await createManagedGroup(rt, [m.tabId], m.windowId, g.origin, { title: g.stripTitle ?? "", color: g.color }, { ...g });
307+ if (groupId !== undefined) remade.set(m.groupId, groupId);
308+ } else {
309+ rt.state().ownUngroups[m.tabId] = rt.now(); // back to loose is the worker's move, not the user pulling it out
310+ await ungroup(rt, [m.tabId]);
311+ }
206312 await chrome.tabs.move(m.tabId, { windowId: m.windowId, index: m.index }).catch(() => undefined);
207313 // Moving a tab next to its old neighbours may pull it into a group they share; re-assert.
208− if (m.groupId !== -1 && (await groupExists(m.groupId))) await addToGroup(rt, [m.tabId], m.groupId);
314+ groupId = await target(m);
315+ if (groupId !== undefined) await addToGroup(rt, [m.tabId], groupId);
316+ else if ((await chrome.tabs.get(m.tabId).catch(() => undefined))?.groupId !== -1) {
317+ rt.state().ownUngroups[m.tabId] = rt.now();
318+ await ungroup(rt, [m.tabId]);
319+ }
209320 const rec = rt.state().tabs[m.tabId];
210321 if (rec) {
211322 rec.parkedFrom = undefined;
323+ rec.parkedAt = undefined;
212324 rec.lastActivatedAt = rt.now(); // un-parking is a touch: do not re-park on the next sweep
213325 }
214326 restored++;
@@ -249,7 +361,7 @@ export async function restoreAll(rt: Runtime, windowId: number): Promise<number>
249361 if (t.id !== undefined) ids.push(t.id);
250362 }
251363 if (ids.length) {
252− await createManagedGroup(rt, ids, windowId, "organize", { title: stripTitle("Restored", RESTORED_EMOJI, rt.settings().emoji), color: "grey" }, { userNamed: true });
364+ await createManagedGroup(rt, ids, windowId, "organize", { title: stripTitle("Restored", RESTORED_EMOJI, rt.settings().emoji), color: "grey" }, { userNamed: true, restored: true });
253365 }
254366 return ids.length;
255367}
src/shared/health.ts+4−2
@@ -46,7 +46,9 @@ export function notices(s: Health): Notice[] {
4646 case "HOST_NOT_FOUND":
4747 out.push({
4848 tone: "bad", title: "Finish setting up Diagonal",
49− body: "Diagonal's helper isn't registered with this browser yet. Run this in Terminal, then reopen Diagonal.",
49+ body: chrome.runtime.getManifest().update_url
50+ ? "Diagonal's helper isn't registered with this browser yet. Run this in Terminal, then reopen Diagonal."
51+ : "Diagonal's helper isn't registered with this browser yet. Installed with Homebrew? Run this in Terminal, then reopen Diagonal. Installed from a zip? Run: bash <the Diagonal folder>/install-host.command",
5052 // A Web Store install has an update_url and may never have had the cask; an unpacked one came from it.
5153 command: chrome.runtime.getManifest().update_url ? "brew install iko-soy/tap/diagonal" : "brew reinstall diagonal",
5254 });
@@ -80,7 +82,7 @@ export function notices(s: Health): Notice[] {
8082 out.push({ tone: "bad", title: "Naming is paused", body: s.message || "The helper didn't answer. Diagonal retries on its own." });
8183 }
8284 }
83− if (s.timeoutHint && s.health !== "degraded") {
85+ if (s.timeoutHint) {
8486 out.push({ tone: "info", title: "The model is slow right now", body: "It timed out three times in a row. You can give it longer under Naming in Settings." });
8587 }
8688 return out;
src/shared/label.ts+42−9
@@ -7,9 +7,12 @@ export const LABEL_MAX_CHARS = 28;
77export const LABEL_MIN_WORDS = 2;
88export const LABEL_MAX_WORDS = 4;
99
10−const QUOTES = /["'“”‘’«»`]/g;
11−const HAS_QUOTE = /["'“”‘’«»`]/;
10+// Quotes go; an apostrophe between two letters ("Children's", "Rock'n'roll") is part of the word and stays.
11+const QUOTES = /(?<!\p{L})['’]|['’](?!\p{L})|["“”‘«»`]/gu;
12+const HAS_QUOTE = /(?<!\p{L})['’]|['’](?!\p{L})|["“”‘«»`]/u;
1213const TRAILING_PUNCT = /[\s.,;:!?…\-–—。、,!?:;]+$/u;
14+// A label cut short should not end mid-phrase: "Planning a trip to" reads as "Planning a trip".
15+const DANGLING = new Set(["a", "an", "the", "to", "of", "for", "in", "on", "at", "by", "and", "or", "with", "from"]);
1316
1417/** Repair what is repairable; return undefined when the label cannot be made valid. */
1518export function repairLabel(raw: unknown): string | undefined {
@@ -17,26 +20,49 @@ export function repairLabel(raw: unknown): string | undefined {
1720 let words = raw.replace(QUOTES, "").replace(/\s+/g, " ").trim().replace(TRAILING_PUNCT, "").split(" ").filter(Boolean);
1821 words = words.filter((w) => !BANNED_WORDS.has(w.toLowerCase().replace(/[^\p{L}\p{N}]/gu, "")));
1922 if (words.length > LABEL_MAX_WORDS) words = words.slice(0, LABEL_MAX_WORDS);
20− while (words.length > LABEL_MIN_WORDS && words.join(" ").length > LABEL_MAX_CHARS) words.pop();
23+ if (noSpace(words.join(" "))) {
24+ while (words.length > 1 && widthOf(words.join(" ")) > CJK_MAX_CHARS) words.pop();
25+ if (widthOf(words.join(" ")) > CJK_MAX_CHARS) words = [cutToWidth(words.join(" "), CJK_MAX_CHARS)];
26+ } else {
27+ while (words.length > LABEL_MIN_WORDS && words.join(" ").length > LABEL_MAX_CHARS) words.pop();
28+ }
29+ while (words.length > 1 && DANGLING.has(words[words.length - 1].toLowerCase())) words.pop();
2130 let label = words.join(" ").replace(TRAILING_PUNCT, "");
2231 if (!label) return undefined;
23− label = label[0].toLocaleUpperCase() + label.slice(1);
32+ // "rust async" becomes "Rust async"; "iPhone tips" and "macOS updates" keep the brand's own casing.
33+ if (!/\p{Lu}/u.test(words[0].slice(1))) label = label[0].toLocaleUpperCase() + label.slice(1);
2434 return isValidLabel(label) ? label : undefined;
2535}
2636
27−/** Chinese, Japanese and Korean titles have no spaces between words, so they're checked by length instead. */
28−const CJK = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff]/g;
37+/**
38+ * Chinese, Japanese, Korean, Thai, Lao, Khmer and Myanmar titles don't put spaces between words, so a label
39+ * with any of their characters ("Python教程") is checked by width instead of word count. Each such character
40+ * is about as wide as two Latin letters on the tab strip.
41+ */
42+const NO_SPACE = /[\u0e00-\u0eff\u1000-\u109f\u1780-\u17ff\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff]/g;
2943export const CJK_MIN_CHARS = 2;
3044export const CJK_MAX_CHARS = 16;
3145
32−const isCjk = (label: string): boolean => (label.match(CJK)?.length ?? 0) * 2 > label.replace(/ /g, "").length;
46+const noSpace = (label: string): boolean => (label.match(NO_SPACE)?.length ?? 0) > 0;
47+const widthOf = (label: string): number => {
48+ const wide = label.match(NO_SPACE)?.length ?? 0;
49+ return wide + (label.length - wide) / 2;
50+};
51+const cutToWidth = (label: string, max: number): string => {
52+ let out = "";
53+ for (const ch of label) {
54+ if (widthOf(out + ch) > max) break;
55+ out += ch;
56+ }
57+ return out.trim();
58+};
3359
3460export function isValidLabel(label: string): boolean {
3561 const words = label.split(" ").filter(Boolean);
36− const cjk = isCjk(label);
62+ const cjk = noSpace(label);
3763 return (
3864 label.length >= (cjk ? CJK_MIN_CHARS : LABEL_MIN_CHARS) &&
39− label.length <= (cjk ? CJK_MAX_CHARS : LABEL_MAX_CHARS) &&
65+ (cjk ? widthOf(label) <= CJK_MAX_CHARS && label.length <= LABEL_MAX_CHARS : label.length <= LABEL_MAX_CHARS) &&
4066 words.length >= (cjk ? 1 : LABEL_MIN_WORDS) &&
4167 words.length <= LABEL_MAX_WORDS &&
4268 !HAS_QUOTE.test(label) &&
@@ -61,3 +87,10 @@ export function labelOf(title: string | undefined): string {
6187
6288export const sameLabel = (a: string | undefined, b: string | undefined): boolean =>
6389 !!a && !!b && labelOf(a).trim().toLocaleLowerCase() === labelOf(b).trim().toLocaleLowerCase();
90+
91+/**
92+ * A page title without the unread counts and bullets sites add to it, "(3) Inbox" or "• Slack", so a count
93+ * ticking over does not read as a new page. Only for noticing change: the model still sees the full title.
94+ */
95+export const titleKey = (title: string | undefined): string =>
96+ (title ?? "").replace(/[(\[]\d[\d,.]*\+?[)\]]/g, "").replace(/^[\s•●▶*]+/u, "").replace(/\s+/g, " ").trim();
test/auto.test.ts+84−2
@@ -15,6 +15,7 @@ let state: State;
1515let calls: OrganizePayload[];
1616let replies: HostReply<unknown>[];
1717let fallbacks: number[];
18+let respond: ((payload: OrganizePayload, opts?: object) => HostReply<unknown> | undefined) | undefined;
1819
1920const liveTab = (id: number, over: Partial<LiveTab> = {}): LiveTab => ({
2021 id, windowId: 1, index: id, groupId: -1, url: `https://site${id}.com/page`, title: `Tab ${id}`, status: "complete", pinned: false, ...over,
@@ -32,9 +33,9 @@ function setup(tabs: LiveTab[]): AutoOrganizer {
3233 settings: () => makeSettings(),
3334 commit: () => undefined,
3435 now: () => 1_000_000,
35− host: async <T,>(_op: string, payload: object) => {
36+ host: async <T,>(_op: string, payload: object, opts?: object) => {
3637 calls.push(JSON.parse(JSON.stringify(payload)));
37− return (replies.shift() ?? { ok: true, result: { groups: [], leftovers: [] } }) as HostReply<T>;
38+ return (respond?.(payload as OrganizePayload, opts) ?? replies.shift() ?? { ok: true, result: { groups: [], leftovers: [] } }) as HostReply<T>;
3839 },
3940 naming: { touch: () => undefined } as unknown as Runtime["naming"],
4041 refreshBadge: () => undefined,
@@ -48,6 +49,7 @@ beforeEach(() => {
4849 calls = [];
4950 replies = [];
5051 fallbacks = [];
52+ respond = undefined;
5153 nextGroup = 100;
5254 (globalThis as any).chrome = {
5355 tabs: {
@@ -92,6 +94,7 @@ describe("auto-organize", () => {
9294 await auto.run(1);
9395 expect(calls[0].items.map((i) => i.title)).toEqual(["Tab 3", "Tab 2"]);
9496 expect(calls[0].existingGroups).toEqual([expect.objectContaining({ g: 0, title: "Rust" })]);
97+ expect(calls[0].siblingTitles).toEqual(["Rust"]);
9598 expect(live.find((t) => t.id === 3)!.groupId).toBe(50);
9699 });
97100
@@ -149,4 +152,83 @@ describe("auto-organize", () => {
149152 vi.useRealTimers();
150153 }
151154 });
155+
156+ it("one tab the model refuses is found and set aside; the others are still sorted", async () => {
157+ const auto = setup([liveTab(1), liveTab(2), liveTab(3, { title: "Refused" }), liveTab(4), liveTab(5)]);
158+ // Apple's filter refuses any request carrying tab 3; anything else becomes one topic.
159+ respond = (p) =>
160+ p.items.some((i) => i.title === "Refused")
161+ ? { ok: false, error: { code: "GUARDRAIL", message: "blocked" } }
162+ : { ok: true, result: { groups: [{ title: "Site pages", emoji: "📚", color: "blue", existing: p.existingGroups.length ? 0 : undefined, members: p.items.map((i) => i.i) }], leftovers: [] } };
163+ await auto.run(1);
164+ expect(live.find((t) => t.id === 3)!.groupId).toBe(-1);
165+ expect(live.filter((t) => t.id !== 3).every((t) => t.groupId === 100)).toBe(true);
166+ expect(state.tabs[3].organizeRefused).toBe(organizedKeyOf(live[2]));
167+ expect(fallbacks).toHaveLength(0); // not a host problem: no retry scheduled
168+
169+ const n = calls.length;
170+ live.push(liveTab(6));
171+ remember(live[5]);
172+ await auto.run(1);
173+ expect(calls.slice(n).flatMap((c) => c.items.map((i) => i.title))).toEqual(["Tab 6"]); // the refused tab is not sent again
174+
175+ const m = calls.length;
176+ live[2].title = "Readable now";
177+ await auto.run(1);
178+ expect(calls.length).toBeGreaterThan(m); // a new title: it gets another chance
179+ });
180+
181+ it("a refused request is tried once more without what the pages say", async () => {
182+ const auto = setup([liveTab(1), liveTab(2)]);
183+ state.tabs[1].description = "Something the filter dislikes";
184+ respond = (p) =>
185+ p.items.some((i) => i.description)
186+ ? { ok: false, error: { code: "GUARDRAIL", message: "blocked" } }
187+ : { ok: true, result: { groups: [{ title: "Pair", emoji: "📚", color: "blue", members: [0, 1] }], leftovers: [] } };
188+ await auto.run(1);
189+ expect(calls).toHaveLength(2);
190+ expect(live.map((t) => t.groupId)).toEqual([100, 100]);
191+ });
192+
193+ it("tabs that changed while the model was thinking are left out of its answer", async () => {
194+ const auto = setup([liveTab(1), liveTab(2), liveTab(3), liveTab(4)]);
195+ respond = () => {
196+ live[1].url = "https://elsewhere.com/"; // tab 2 went to another page
197+ live = live.filter((t) => t.id !== 4); // tab 4 was closed
198+ return { ok: true, result: { groups: [{ title: "Site pages", emoji: "📚", color: "blue", members: [0, 1, 2] }, { title: "Other", emoji: "📚", color: "red", members: [3] }], leftovers: [] } };
199+ };
200+ await auto.run(1);
201+ expect(live.map((t) => [t.id, t.groupId])).toEqual([[1, 100], [2, -1], [3, 100]]);
202+ expect(state.tabs[1].organizedKey).toBeDefined();
203+ expect(state.tabs[2].organizedKey).toBeUndefined(); // looked at again on its new page
204+ });
205+
206+ it("a new group left with one tab after the others moved on is not made", async () => {
207+ const auto = setup([liveTab(1), liveTab(2), liveTab(3)]);
208+ respond = () => {
209+ live[1].groupId = 77; // you dragged tab 2 into a group of yours meanwhile
210+ return { ok: true, result: { groups: [{ title: "Pair", emoji: "📚", color: "blue", members: [0, 1] }], leftovers: [2] } };
211+ };
212+ await auto.run(1);
213+ expect(live.find((t) => t.id === 1)!.groupId).toBe(-1);
214+ expect(nextGroup).toBe(100);
215+ });
216+
217+ it("an unread count ticking over is not a new page", async () => {
218+ const auto = setup([liveTab(1, { title: "(3) Inbox" }), liveTab(2)]);
219+ await auto.run(1);
220+ expect(calls).toHaveLength(1);
221+ live[0].title = "(4) Inbox";
222+ await auto.run(1);
223+ expect(calls).toHaveLength(1);
224+ });
225+
226+ it("a host that stops answering stops the run after one smaller try", async () => {
227+ const auto = setup(Array.from({ length: 10 }, (_, i) => liveTab(i + 1)));
228+ respond = () => ({ ok: false, error: { code: "TIMEOUT", message: "slow" } });
229+ await auto.run(1);
230+ expect(calls.map((c) => c.items.length)).toEqual([10, 5]);
231+ expect(fallbacks).toHaveLength(1);
232+ expect(Object.values(state.tabs).some((t) => t.organizeRefused)).toBe(false);
233+ });
152234});
test/engine.test.ts+126
@@ -240,6 +240,14 @@ describe("auto-organize triggers", () => {
240240 expect(actions).toContainEqual({ type: "loose", windowId: 1 });
241241 });
242242
243+ it("parking keeps the title of the group the tab came from, for the archive", () => {
244+ const s = stateWith([tab(1, { groupId: 10 }), tab(2, { groupId: 20 })], [{ id: 10, origin: "organize", title: "Rust async" }, { id: 20, origin: "tidy" }]);
245+ s.tabs[1].parkedFrom = "Rust async"; // set by the sweep just before it moves the tab
246+ const moved = step(s, { type: "tabUpdated", tab: tab(1, { groupId: 20 }) }, ctx());
247+ const discarded = step(moved.state, { type: "tabUpdated", tab: tab(1, { groupId: 20, status: "unloaded" }) }, ctx());
248+ expect(discarded.state.tabs[1].parkedFrom).toBe("Rust async");
249+ });
250+
243251 it("opening a parked tab takes it out of Parked", () => {
244252 const s = stateWith([tab(1, { groupId: 20 }), tab(2, { groupId: 20 })], [{ id: 20, origin: "tidy" }]);
245253 s.tabs[1].parkedFrom = "Rust async";
@@ -310,3 +318,121 @@ describe("fit check", () => {
310318 expect(out.state.tabs[1].handPlaced).toBeUndefined();
311319 });
312320});
321+
322+describe("groups Chromium removes and brings back", () => {
323+ const opener = () => {
324+ const s = stateWith([tab(1, { groupId: 10 }), tab(2, { groupId: 10 })], [{ id: 10, origin: "opener", title: "🦀 Rust async" }]);
325+ s.groups[10].color = "orange";
326+ return s;
327+ };
328+ const run = (s: ReturnType<typeof opener>, events: Parameters<typeof step>[1][], now = 1_000_000) =>
329+ events.reduce((acc, e) => step(acc, e, ctx(now)).state, s);
330+
331+ it("a group moved to another window stays Diagonal's, and its tabs are not taken for your choices", () => {
332+ const moved = run(opener(), [
333+ { type: "groupRemoved", groupId: 10 },
334+ { type: "tabUpdated", tab: tab(1) },
335+ { type: "tabUpdated", tab: tab(2) },
336+ { type: "groupCreated", group: { id: 10, windowId: 2, title: "🦀 Rust async", color: "orange" } },
337+ { type: "tabUpdated", tab: tab(1, { groupId: 10, windowId: 2 }) },
338+ { type: "tabUpdated", tab: tab(2, { groupId: 10, windowId: 2 }) },
339+ ]);
340+ expect(moved.groups[10]).toMatchObject({ origin: "opener", managed: true, userNamed: false, windowId: 2 });
341+ for (const id of [1, 2]) {
342+ expect(moved.tabs[id].groupId).toBe(10);
343+ expect(moved.tabs[id].keepLoose).toBeUndefined();
344+ expect(moved.tabs[id].handPlaced).toBeUndefined();
345+ }
346+ expect(moved.removedGroups[10]).toBeUndefined();
347+ });
348+
349+ it("the same when a tab's new group is reported before the group itself", () => {
350+ const moved = run(opener(), [
351+ { type: "groupRemoved", groupId: 10 },
352+ { type: "tabUpdated", tab: tab(1) },
353+ { type: "tabUpdated", tab: tab(1, { groupId: 10, windowId: 2 }) },
354+ { type: "groupCreated", group: { id: 10, windowId: 2, title: "🦀 Rust async", color: "orange" } },
355+ ]);
356+ expect(moved.groups[10].origin).toBe("opener");
357+ expect(moved.tabs[1].keepLoose).toBeUndefined();
358+ expect(moved.tabs[1].handPlaced).toBeUndefined();
359+ });
360+
361+ it("a closed group reopened untitled, then titled, is Diagonal's again", () => {
362+ const closed = run(opener(), [
363+ { type: "tabRemoved", tabId: 1 },
364+ { type: "tabRemoved", tabId: 2 },
365+ { type: "groupRemoved", groupId: 10 },
366+ ]);
367+ const later = 1_000_000 + 3_600_000;
368+ const back = run(closed, [
369+ { type: "groupCreated", group: { id: 77, windowId: 1, title: "", color: "orange" } },
370+ { type: "groupUpdated", group: { id: 77, windowId: 1, title: "🦀 Rust async", color: "orange" } },
371+ ], later);
372+ expect(back.groups[77]).toMatchObject({ origin: "opener", managed: true, userNamed: false, stripTitle: "🦀 Rust async" });
373+ });
374+
375+ it("a group you make and title yourself later is still yours", () => {
376+ const closed = run(opener(), [{ type: "groupRemoved", groupId: 10 }]);
377+ const made = run(closed, [{ type: "groupCreated", group: { id: 77, windowId: 1, title: "", color: "orange" } }]);
378+ const titled = step(made, { type: "groupUpdated", group: { id: 77, windowId: 1, title: "🦀 Rust async", color: "orange" } }, ctx(1_000_000 + 60_000)).state;
379+ expect(titled.groups[77]).toMatchObject({ origin: "user", userNamed: true });
380+ });
381+
382+ it("ungrouping by hand still keeps the tabs loose", () => {
383+ const out = run(opener(), [
384+ { type: "tabUpdated", tab: tab(1) },
385+ { type: "tabUpdated", tab: tab(2) },
386+ { type: "groupRemoved", groupId: 10 },
387+ ]);
388+ expect(out.tabs[1].keepLoose).toBe("https://example.com/1");
389+ });
390+
391+ it("keeps a day of removed groups, at most 20", () => {
392+ let s = opener();
393+ for (let id = 100; id < 125; id++) {
394+ s.groups[id] = { ...s.groups[10], id };
395+ s = step(s, { type: "groupRemoved", groupId: id }, ctx(1_000_000 + id)).state;
396+ }
397+ expect(Object.keys(s.removedGroups)).toHaveLength(20);
398+ s = step(s, { type: "tabActivated", tabId: 1 }, ctx(1_000_000 + 25 * 3_600_000)).state;
399+ expect(Object.keys(s.removedGroups)).toHaveLength(0);
400+ });
401+});
402+
403+describe("tabs you place", () => {
404+ it("a new tab made inside a group ('New tab in group') is yours there", () => {
405+ const s = stateWith([tab(1, { groupId: 10 }), tab(2, { groupId: 10 })], [{ id: 10, origin: "organize" }]);
406+ const { state } = step(s, { type: "tabCreated", tab: tab(3, { groupId: 10, url: "brave://newtab/" }) }, ctx());
407+ expect(state.tabs[3].handPlaced).toBe(true);
408+ });
409+
410+ it("a link opened from a grouped tab is not", () => {
411+ const opener = tab(1, { groupId: 10 });
412+ const s = stateWith([opener, tab(2, { groupId: 10 })], [{ id: 10, origin: "organize" }]);
413+ const { state } = step(s, { type: "tabCreated", tab: tab(3, { groupId: 10, openerTabId: 1 }), opener }, ctx());
414+ expect(state.tabs[3].handPlaced).toBeUndefined();
415+ });
416+
417+ it("a tab that joins a group has no loose choice left, even if a late event said it left", () => {
418+ const s = stateWith([tab(1), tab(2)], [{ id: 10, origin: "opener" }]);
419+ s.tabs[1].keepLoose = "https://example.com/1";
420+ s.ownAdds[1] = 1_000_000;
421+ const { state } = step(s, { type: "tabUpdated", tab: tab(1, { groupId: 10 }) }, ctx());
422+ expect(state.tabs[1].keepLoose).toBeUndefined();
423+ });
424+
425+ it("a new tab whose first load redirects is not fit-checked", () => {
426+ const s = stateWith([tab(1, { groupId: 10 }), tab(2, { groupId: 10 }), tab(3, { groupId: 10 })], [{ id: 10, origin: "opener" }]);
427+ const opened = step(s, { type: "tabCreated", tab: tab(4, { groupId: 10, openerTabId: 1, url: "", pendingUrl: "http://blog.example.org/post", status: "loading" }), opener: tab(1, { groupId: 10 }) }, ctx()).state;
428+ const landed = step(opened, { type: "tabUpdated", tab: tab(4, { groupId: 10, openerTabId: 1, url: "https://blog.example.org/post" }) }, ctx());
429+ expect(landed.state.tabs[4].fitPending).toBeUndefined();
430+ });
431+
432+ it("leaving Parked stops the archive clock", () => {
433+ const s = stateWith([tab(1, { groupId: 20 }), tab(2, { groupId: 20 })], [{ id: 20, origin: "tidy" }]);
434+ s.tabs[1].parkedAt = 5;
435+ expect(step(s, { type: "tabUpdated", tab: tab(1) }, ctx()).state.tabs[1].parkedAt).toBeUndefined();
436+ expect(step(s, { type: "tabActivated", tabId: 1 }, ctx()).state.tabs[1].parkedAt).toBeUndefined();
437+ });
438+});
test/naming.test.ts+72−2
@@ -50,6 +50,10 @@ describe("evolving-name policy", () => {
5050 it("same label is never rewritten", () => {
5151 expect(shouldApply(g(), "rust async runtimes", ["a", "b", "c"])).toBe(false);
5252 });
53+ it("a member that only moved within its page is not a membership change", () => {
54+ const g2 = newGroupRecord(1, 1, "opener", "blue", { title: "Rust async runtimes", lastNamedAt: 1, memberUrls: ["https://a.com/x", "https://b.com/y"] });
55+ expect(shouldApply(g2, "Tokio and async-std", ["https://a.com/x?page=2", "https://b.com/y#top"])).toBe(false);
56+ });
5357 it("user-named groups are skipped", () => {
5458 expect(shouldApply({ ...g(), userNamed: true }, "Anything else", ["x"])).toBe(false);
5559 });
@@ -151,15 +155,25 @@ describe("naming queue", () => {
151155 expect(state.groups[7].dirty).toBe(false);
152156 });
153157
154− it("waits while a member is still loading or the group has one tab", async () => {
158+ it("waits while a member is still loading", async () => {
155159 members = [member(1), member(2, { status: "loading" })];
156160 naming.touch(7);
157161 await settle();
162+ expect(calls).toHaveLength(0);
163+ expect(state.groups[7].dirty).toBe(true);
164+ });
165+
166+ it("a group with one tab to name from is not kept waiting; the next tab to join names it", async () => {
158167 members = [member(1)];
159168 naming.touch(7);
160169 await settle();
161170 expect(calls).toHaveLength(0);
162− expect(state.groups[7].dirty).toBe(true);
171+ expect(state.groups[7].dirty).toBe(false);
172+ members = [member(1), member(2)];
173+ markDirty(state.groups[7], 0);
174+ naming.touch(7);
175+ await settle();
176+ expect(calls).toHaveLength(1);
163177 });
164178
165179 it("names a group whose member the browser discarded to save memory", async () => {
@@ -206,6 +220,54 @@ describe("naming queue", () => {
206220 expect(state.groups[7].nextAttemptAt).toBe(now + 24 * 3_600_000);
207221 });
208222
223+ it("a group Apple's filter refused is asked again as soon as its tabs change, not only after a day", async () => {
224+ replies.push({ ok: false, error: { code: "GUARDRAIL", message: "no" } }, { ok: false, error: { code: "GUARDRAIL", message: "no" } });
225+ naming.touch(7);
226+ await settle();
227+ expect(calls).toHaveLength(2);
228+ naming.touch(7);
229+ await settle();
230+ expect(calls).toHaveLength(2); // the same tabs: still refused
231+ members = [member(1), member(3)];
232+ naming.touch(7);
233+ await settle();
234+ expect(calls).toHaveLength(3);
235+ expect(state.groups[7]).toMatchObject({ title: "Rust crate docs", dirty: false, nameAttempts: 0 });
236+ expect(state.groups[7].refusedHash).toBeUndefined();
237+ });
238+
239+ it("setup errors don't use up a group's retries; the host's recovery picks it up", async () => {
240+ replies.push({ ok: false, error: { code: "LICENSE_REQUIRED", message: "terms" } });
241+ naming.touch(7);
242+ await settle();
243+ expect(state.groups[7]).toMatchObject({ dirty: true, nameAttempts: 0 });
244+ expect(state.groups[7].firstFailureAt).toBeUndefined();
245+ expect(state.groups[7].nextAttemptAt).toBeUndefined();
246+ });
247+
248+ it("a title the strip would not take is tried again shortly", async () => {
249+ let refuse = true;
250+ naming = new Naming({ ...(naming as any).d, writeTitle: async () => !refuse });
251+ naming.touch(7);
252+ await settle();
253+ expect(state.groups[7]).toMatchObject({ dirty: true, nextAttemptAt: now + 30_000 });
254+ expect(state.groups[7].title).toBeUndefined();
255+ expect(state.ownWrites[7]).toBeUndefined();
256+ refuse = false;
257+ now += 30_000;
258+ await naming.consider(7);
259+ await settle();
260+ expect(state.groups[7]).toMatchObject({ dirty: false, title: "Rust crate docs" });
261+ });
262+
263+ it("members back as they were last named clear old failures", async () => {
264+ Object.assign(state.groups[7], { membersHash: membersHash(members), nameAttempts: 3, firstFailureAt: 1, nextAttemptAt: 1 });
265+ naming.touch(7);
266+ await settle();
267+ expect(state.groups[7]).toMatchObject({ dirty: false, nameAttempts: 0 });
268+ expect(state.groups[7].firstFailureAt).toBeUndefined();
269+ });
270+
209271 it("failures back off 30 s, 2 min, 10 min, then hourly; the title is left alone", async () => {
210272 const fail: HostReply<NameResult> = { ok: false, error: { code: "FM_ERROR", message: "boom" } };
211273 replies.push(fail);
@@ -237,6 +299,14 @@ describe("naming queue", () => {
237299 expect(writes).toEqual([[7, "🦀 Rust crates"]]);
238300 });
239301
302+ it("the retry after a title the host rejected lists that title as not allowed", async () => {
303+ replies.push({ ok: false, error: { code: "BAD_MODEL_OUTPUT", message: "rules", raw: JSON.stringify({ title: "Python", emoji: "🐍" }) } });
304+ naming.touch(7);
305+ await settle();
306+ expect(calls).toHaveLength(2);
307+ expect(calls[1].mustDifferFrom).toEqual(["Python"]);
308+ });
309+
240310 it("a group renamed by hand while the model runs keeps the user's title", async () => {
241311 const n = new Naming({
242312 ...(naming as any).d,
test/organize.test.ts+17
@@ -107,6 +107,23 @@ describe("existing groups", () => {
107107 expect(list[0]).toEqual({ g: 0, title: "Trip 0", samples: ["Hotel"] });
108108 });
109109
110+ it("offers the groups in use when there are more than 12, not the oldest", () => {
111+ const s = emptyState();
112+ for (let i = 0; i < 15; i++) s.groups[i] = newGroupRecord(i, 1, "organize", "red", { stripTitle: `G ${i}`, lastNamedAt: 1000 - i });
113+ s.tabs[1] = { id: 1, windowId: 1, groupId: 14, index: 0, url: "u", title: "Now", pinned: false, createdAt: 0, lastActivatedAt: 5000 };
114+ const { ids } = existingGroupsFor(s, 1);
115+ expect(ids[0]).toBe(14);
116+ expect(ids).toContain(0);
117+ expect(ids).not.toContain(13);
118+ });
119+
120+ it("leaves out the Restored group, which is not a topic", () => {
121+ const s = emptyState();
122+ s.groups[1] = newGroupRecord(1, 1, "organize", "grey", { userNamed: true, stripTitle: "♻️ Restored", restored: true });
123+ s.groups[2] = newGroupRecord(2, 1, "organize", "red", { stripTitle: "🦀 Rust" });
124+ expect(existingGroupsFor(s, 1).ids).toEqual([2]);
125+ });
126+
110127 it("groups created by batch n come first for batch n+1", () => {
111128 const s = emptyState();
112129 for (let i = 0; i < 15; i++) s.groups[i] = newGroupRecord(i, 1, "organize", "red", { stripTitle: `G ${i}` });
test/sweep.test.tsnew file+181
@@ -0,0 +1,181 @@
1+import { afterEach, beforeEach, describe, expect, it } from "vitest";
2+import type { Runtime } from "../src/background/runtime";
3+import { emptyState, newGroupRecord, type State } from "../src/background/state";
4+import { HOUR, runSweep, undoSweep } from "../src/background/tidy";
5+import { settings as makeSettings } from "./helpers";
6+
7+/** The tidy sweep against a small in-memory strip with Chromium's group rules: an emptied group is removed. */
8+
9+type LiveTab = {
10+ id: number; windowId: number; index: number; groupId: number; url: string; title: string;
11+ pinned: boolean; active: boolean; discarded: boolean; autoDiscardable: boolean; lastAccessed: number;
12+};
13+type LiveGroup = { id: number; windowId: number; title: string; color: string; collapsed: boolean };
14+
15+const T0 = 10_000 * HOUR;
16+let now: number;
17+let live: LiveTab[];
18+let groups: Map<number, LiveGroup>;
19+let nextGroup: number;
20+let state: State;
21+let discarded: number[];
22+
23+const liveTab = (id: number, over: Partial<LiveTab> = {}): LiveTab => ({
24+ id, windowId: 1, index: id, groupId: -1, url: `https://site${id}.com/p`, title: `Tab ${id}`,
25+ pinned: false, active: false, discarded: false, autoDiscardable: true, lastAccessed: T0 - 60 * HOUR, ...over,
26+});
27+
28+function remember(t: LiveTab): void {
29+ state.tabs[t.id] = { id: t.id, windowId: t.windowId, groupId: t.groupId, index: t.index, url: t.url, title: t.title, pinned: t.pinned, createdAt: 0, lastActivatedAt: t.lastAccessed };
30+}
31+
32+const dropEmpty = () => {
33+ for (const id of [...groups.keys()]) if (!live.some((t) => t.groupId === id)) groups.delete(id);
34+};
35+
36+const rt: Runtime = {
37+ state: () => state,
38+ settings: () => makeSettings(),
39+ commit: () => undefined,
40+ now: () => now,
41+ host: async () => ({ ok: false, error: { code: "FM_ERROR", message: "not used" } }) as never,
42+ naming: { touch: () => undefined } as unknown as Runtime["naming"],
43+ refreshBadge: () => undefined,
44+ log: () => undefined,
45+};
46+
47+beforeEach(() => {
48+ now = T0;
49+ state = emptyState();
50+ groups = new Map();
51+ nextGroup = 500;
52+ discarded = [];
53+ (globalThis as any).chrome = {
54+ tabs: {
55+ query: async (q: { windowId?: number; groupId?: number }) =>
56+ live.filter((t) => (q.windowId === undefined || t.windowId === q.windowId) && (q.groupId === undefined || t.groupId === q.groupId)).map((t) => ({ ...t })),
57+ get: async (id: number) => ({ ...live.find((t) => t.id === id)! }),
58+ group: async ({ tabIds, groupId, createProperties }: { tabIds: number[]; groupId?: number; createProperties?: { windowId: number } }) => {
59+ let id = groupId;
60+ if (id === undefined) {
61+ id = nextGroup++;
62+ groups.set(id, { id, windowId: createProperties?.windowId ?? 1, title: "", color: "grey", collapsed: false });
63+ }
64+ for (const t of live) if (tabIds.includes(t.id)) t.groupId = id;
65+ dropEmpty();
66+ return id;
67+ },
68+ ungroup: async (ids: number[]) => {
69+ for (const t of live) if (ids.includes(t.id)) t.groupId = -1;
70+ dropEmpty();
71+ },
72+ move: async () => undefined,
73+ discard: async (id: number) => {
74+ discarded.push(id);
75+ live.find((t) => t.id === id)!.discarded = true;
76+ },
77+ remove: async (ids: number[]) => {
78+ live = live.filter((t) => !ids.includes(t.id));
79+ dropEmpty();
80+ },
81+ },
82+ tabGroups: {
83+ get: async (id: number) => {
84+ const g = groups.get(id);
85+ if (!g) throw new Error(`No group with id: ${id}.`);
86+ return { ...g };
87+ },
88+ query: async (q: { windowId?: number }) => [...groups.values()].filter((g) => q.windowId === undefined || g.windowId === q.windowId).map((g) => ({ ...g })),
89+ update: async (id: number, props: Partial<LiveGroup>) => Object.assign(groups.get(id)!, props),
90+ move: async () => undefined,
91+ },
92+ };
93+});
94+
95+afterEach(() => {
96+ delete (globalThis as any).chrome;
97+});
98+
99+function strip(tabs: LiveTab[], made: LiveGroup[] = []): void {
100+ live = tabs;
101+ for (const g of made) groups.set(g.id, g);
102+ for (const t of tabs) remember(t);
103+}
104+
105+const parkedGroupId = () => Object.values(state.groups).find((g) => g.origin === "tidy")?.id;
106+
107+describe("tidy sweep", () => {
108+ it("parks a stale tab and closes it only after it has sat in Parked for the archive time", async () => {
109+ strip([liveTab(1), liveTab(2, { active: true })]);
110+ expect(await runSweep(rt)).toMatchObject({ parked: 1, archived: 0 });
111+ expect(live.find((t) => t.id === 1)!.groupId).toBe(parkedGroupId());
112+ expect(state.tabs[1].parkedAt).toBe(T0);
113+
114+ now = T0 + 47 * HOUR;
115+ expect(await runSweep(rt)).toMatchObject({ archived: 0 });
116+ now = T0 + 48 * HOUR;
117+ expect(await runSweep(rt)).toMatchObject({ archived: 1 });
118+ expect(state.archive.map((a) => a.url)).toEqual(["https://site1.com/p"]);
119+ });
120+
121+ it("two sweeps at once archive a tab once", async () => {
122+ strip([liveTab(1, { groupId: 9 }), liveTab(2, { active: true })], [{ id: 9, windowId: 1, title: "💤 Parked", color: "grey", collapsed: true }]);
123+ state.groups[9] = newGroupRecord(9, 1, "tidy", "grey", { userNamed: true, stripTitle: "💤 Parked" });
124+ state.tabs[1].parkedAt = T0 - 49 * HOUR;
125+ await Promise.all([runSweep(rt), runSweep(rt, true)]);
126+ expect(state.archive).toHaveLength(1);
127+ });
128+
129+ it("a Parked group whose record an older version lost is Parked again", async () => {
130+ strip([liveTab(1, { groupId: 50 }), liveTab(2)], [{ id: 50, windowId: 1, title: "💤 Parked", color: "grey", collapsed: true }]);
131+ state.groups[50] = newGroupRecord(50, 1, "user", "grey", { userNamed: true, stripTitle: "💤 Parked" });
132+ await runSweep(rt);
133+ expect(live.find((t) => t.id === 2)!.groupId).toBe(50);
134+ expect(groups.size).toBe(1);
135+ expect(state.groups[50]).toMatchObject({ origin: "tidy", managed: true });
136+ });
137+
138+ it("does not discard a tab marked never to be discarded", async () => {
139+ strip([liveTab(1), liveTab(2, { autoDiscardable: false }), liveTab(3, { active: true })]);
140+ await runSweep(rt);
141+ expect(discarded).toEqual([1]);
142+ });
143+});
144+
145+describe("undo tidy", () => {
146+ it("brings back a group that parking emptied, with its title", async () => {
147+ strip(
148+ [liveTab(1, { active: true }), liveTab(2, { groupId: 7 }), liveTab(3, { groupId: 7 })],
149+ [{ id: 7, windowId: 1, title: "🦀 Rust async", color: "orange", collapsed: false }],
150+ );
151+ state.groups[7] = newGroupRecord(7, 1, "organize", "orange", { title: "Rust async", emoji: "🦀", stripTitle: "🦀 Rust async" });
152+ await runSweep(rt);
153+ expect(groups.has(7)).toBe(false);
154+
155+ expect(await undoSweep(rt)).toBe(2);
156+ const back = live.find((t) => t.id === 2)!.groupId;
157+ expect(back).not.toBe(-1);
158+ expect(live.find((t) => t.id === 3)!.groupId).toBe(back);
159+ expect(groups.get(back)).toMatchObject({ title: "🦀 Rust async", color: "orange" });
160+ expect(state.groups[back]).toMatchObject({ origin: "organize", title: "Rust async", userNamed: false });
161+ expect(state.tabs[2].parkedAt).toBeUndefined();
162+ });
163+
164+ it("puts loose tabs back as the worker's own move, so they are not taken for tabs you pulled out", async () => {
165+ strip([liveTab(1, { active: true }), liveTab(4)]);
166+ await runSweep(rt);
167+ await undoSweep(rt);
168+ expect(live.find((t) => t.id === 4)!.groupId).toBe(-1);
169+ expect(state.ownUngroups[4]).toBeDefined();
170+ });
171+
172+ it("covers every sweep in the last hour, not only the latest", async () => {
173+ strip([liveTab(1, { active: true }), liveTab(2), liveTab(3, { lastAccessed: T0 - 23.5 * HOUR })]);
174+ state.tabs[3].lastActivatedAt = T0 - 23.5 * HOUR;
175+ await runSweep(rt, true);
176+ now = T0 + HOUR / 2;
177+ await runSweep(rt);
178+ expect(live.filter((t) => t.groupId !== -1).map((t) => t.id)).toEqual([2, 3]);
179+ expect(await undoSweep(rt)).toBe(2);
180+ });
181+});
test/tidy.test.ts+34−3
@@ -34,6 +34,19 @@ describe("park eligibility", () => {
3434 expect(isParkCandidate(tab, s, cfg, NOW)).toBe(expected);
3535 });
3636
37+ it("a Diagonal group you renamed counts as yours", () => {
38+ const s2 = emptyState();
39+ s2.groups[14] = newGroupRecord(14, 1, "organize", "red", { userNamed: true, stripTitle: "Tax 2026" });
40+ expect(isParkCandidate(tt({ groupId: 14 }), s2, cfg, NOW)).toBe(false);
41+ expect(isParkCandidate(tt({ groupId: 14 }), s2, settings({ tidyUserGroups: true }), NOW)).toBe(true);
42+ });
43+
44+ it("after a restart, the stored last use wins over Chromium's restore time", () => {
45+ const s2 = emptyState();
46+ s2.tabs[1] = { id: 1, windowId: 1, groupId: -1, index: 0, url: "", title: "", pinned: false, createdAt: 0, lastActivatedAt: NOW - 30 * HOUR };
47+ expect(isParkCandidate(tt({ lastAccessed: NOW - 60_000 }), s2, cfg, NOW)).toBe(true);
48+ });
49+
3750 it("user groups are eligible when 'Tidy inside my own groups' is on", () => {
3851 expect(isParkCandidate(tt({ groupId: 10 }), s, settings({ tidyUserGroups: true }), NOW)).toBe(true);
3952 });
@@ -51,14 +64,32 @@ describe("park eligibility", () => {
5164});
5265
5366describe("archive", () => {
54− it("parked tabs idle past archiveAfter are archived; 0 means never", () => {
67+ const record = (id: number, over: object = {}) => ({ id, windowId: 1, groupId: 12, index: 0, url: "", title: "", pinned: false, createdAt: 0, lastActivatedAt: NOW - 60 * HOUR, ...over });
68+
69+ it("parked tabs that sat in Parked past archiveAfter are archived; 0 means never", () => {
5570 const s = emptyState();
5671 s.groups[12] = newGroupRecord(12, 1, "tidy", "grey");
57− const parked = tt({ groupId: 12, lastAccessed: NOW - 49 * HOUR });
58− expect(archiveCandidates([parked, tt()], s, settings(), NOW)).toEqual([parked]);
72+ s.tabs[1] = record(1, { parkedAt: NOW - 49 * HOUR });
73+ const parked = tt({ groupId: 12, lastAccessed: NOW - 60 * HOUR });
74+ expect(archiveCandidates([parked, tt({ id: 2 })], s, settings(), NOW)).toEqual([parked]);
5975 expect(archiveCandidates([parked], s, settings({ archiveAfterHours: 0 }), NOW)).toEqual([]);
6076 });
6177
78+ it("counts from when the tab was parked, not from when it was last used", () => {
79+ const s = emptyState();
80+ s.groups[12] = newGroupRecord(12, 1, "tidy", "grey");
81+ s.tabs[1] = record(1, { parkedAt: NOW - HOUR }); // unused for 60 h, but parked only an hour ago
82+ s.tabs[2] = record(2); // in Parked with no parking time: its clock has not started
83+ expect(archiveCandidates([tt({ groupId: 12, lastAccessed: NOW - 60 * HOUR }), tt({ id: 2, groupId: 12 })], s, settings(), NOW)).toEqual([]);
84+ });
85+
86+ it("an address added to Never tidy is not closed from Parked", () => {
87+ const s = emptyState();
88+ s.groups[12] = newGroupRecord(12, 1, "tidy", "grey");
89+ s.tabs[1] = record(1, { parkedAt: NOW - 49 * HOUR });
90+ expect(archiveCandidates([tt({ groupId: 12, url: "https://jira.corp/x" })], s, settings({ tidyExclusions: ["jira."] }), NOW)).toEqual([]);
91+ });
92+
6293 it("is newest first and capped, oldest dropped", () => {
6394 const entry = (n: number): ArchivedTab => ({ url: `u${n}`, title: `t${n}`, archivedAt: n, lastActivatedAt: 0 });
6495 const existing = [3, 2, 1].map(entry);
test/url.test.ts+16−13
@@ -1,7 +1,8 @@
11import { describe, expect, it } from "vitest";
2−import { isValidLabel, labelOf, repairLabel, safeEmoji } from "../src/shared/label";
2+import { isValidLabel, labelOf, repairLabel, safeEmoji, titleKey } from "../src/shared/label";
33import { colorFor, hostname, isInternalUrl, promptAddress, promptUrl, provisionalTitle, registrableDomain, trimText } from "../src/shared/url";
44import { withDefaults } from "../src/background/settings";
5+import labelCases from "../host/tests/golden/labels.json";
56
67describe("url helpers", () => {
78 it("strips www.", () => {
@@ -45,19 +46,12 @@ describe("url helpers", () => {
4546 });
4647});
4748
48−describe("labels", () => {
49− it.each([
50− ['"Rust async runtimes."', "Rust async runtimes"],
51− ["rust async runtimes", "Rust async runtimes"],
52− ["Rust tabs and docs", "Rust and docs"],
53− ["One two three four five six", "One two three four"],
54− ["Machine learning research papers reading list", "Machine learning research"],
55− ])("repairs %s", (raw, fixed) => {
56− expect(repairLabel(raw)).toBe(fixed);
57− });
49+// The same cases run against the host's validate.repair_label, so the two sides agree on every label.
50+const LABEL_CASES = labelCases as [string, string | null][];
5851
59− it.each(["Tabs", "Misc stuff", "", "x", "Supercalifragilisticexpialidocious extraordinarily"])("rejects %s", (raw) => {
60− expect(repairLabel(raw)).toBeUndefined();
52+describe("labels", () => {
53+ it.each(LABEL_CASES)("repairs %s", (raw, fixed) => {
54+ expect(repairLabel(raw) ?? null).toBe(fixed);
6155 });
6256
6357 it("validates", () => {
@@ -74,6 +68,15 @@ describe("labels", () => {
7468 expect(safeEmoji("🦄")).toBe("🧭");
7569 });
7670
71+ it("titleKey ignores the unread counts and bullets sites put in titles", () => {
72+ expect(titleKey("(3) Inbox - Mail")).toBe(titleKey("(12) Inbox - Mail"));
73+ expect(titleKey("Inbox (1,204) - me@example.com - Gmail")).toBe("Inbox - me@example.com - Gmail");
74+ expect(titleKey("• Slack | general")).toBe("Slack | general");
75+ expect(titleKey("[99+] Chat")).toBe("Chat");
76+ expect(titleKey("Rust async")).toBe("Rust async");
77+ expect(titleKey("Rust async")).not.toBe(titleKey("Rust sync"));
78+ });
79+
7780 it("labelOf strips our emoji prefix", () => {
7881 expect(labelOf("🦀 Rust async")).toBe("Rust async");
7982 expect(labelOf("Plain title")).toBe("Plain title");
tsconfig.json+1
@@ -9,6 +9,7 @@
99 "noEmit": true,
1010 "skipLibCheck": true,
1111 "isolatedModules": true,
12+ "resolveJsonModule": true,
1213 "noFallthroughCasesInSwitch": true,
1314 "forceConsistentCasingInFileNames": true
1415 },