anvilsign in

collin/browser-terminal-extension · 614e6bf8

Match tab pins by portless name, not devport port

Collin Richards · 2026-08-18 11:52 UTC · 614e6bf8c5a6878a8d94e5370b83b29e2b1ce1fa · parent 70c84263 · browse files

modifiedREADME.md+30 −17
⋯ 283 unchanged lines
284284
285285 A pin can key on two things:
286286
287-- **the site**, e.g. `localhost:26210`. Any tab on that origin matches, and the
288- pin outlives the tab, the window and the browser, because an origin is a name.
289- This is the one to reach for.
287+- **the site**, e.g. `https://mdlab.localhost`. Any tab on that origin matches,
288+ and the pin outlives the tab, the window and the browser, because an origin is
289+ a name. This is the one to reach for.
290290 - **that exact browser tab**, by the id Chrome gave it. Survives nothing, and
291291 exists for what an origin cannot express: two tabs on the same site pointing
292292 at different sessions, or a page whose URL says nothing.
⋯ 48 unchanged lines
341341 end too. There is nothing extra to set up: pin a session to a tab and both
342342 directions light up together.
343343
344-### Guessing from the port
344+### Guessing from the name
345345
346346 Under the explicit pins sits a guess, on by default and switchable in settings:
347-a tab on a `localhost` port that `devport` would hand to a project we have a
348-session in is treated as pinned to that session, without anyone saying so.
347+a tab on a `.localhost` name that [portless][portless] would hand to a project
348+we have a session in is treated as pinned to that session, without anyone saying
349+so.
349350
350-devport gives a project a stable block of ten ports from a checksum of its
351-directory name, so nothing has to be registered anywhere — and that mapping is
352-reproducible offline. `extension/lib/devport.js` reimplements it (POSIX `cksum`
353-and all) and hashes the working directories tmux already reports, which is the
354-same answer `devport -r` gives without a subprocess, a filesystem walk, or
355-devport being installed.
351+portless takes the port out of the URL — a dev server started under it gets a
352+random port and a stable `https://<name>.localhost`, where the name comes from
353+`package.json`'s `name`, else the git root's directory name, else the working
354+directory's, lowercased into a DNS label. In a git worktree the branch goes in
355+front: `https://<branch>.<project>.localhost`.
356356
357-The guess is deliberately timid. Local hosts only, in-range ports only, and an
358-ambiguous match — two sessions in one block, which collisions make possible —
359-resolves to nothing rather than a coin toss. Unpinning a guessed match records a
360-veto against that origin, which is the only way to say "no, not this one" to a
361-rule that would otherwise keep re-deriving itself.
357+`extension/lib/portless.js` reimplements that naming and applies it to the
358+working directories tmux already reports, so `https://mdlab.localhost` finds the
359+session sitting in `~/Code/mdlab` without a subprocess, without reading
360+`~/.portless/routes.json`, and without portless being installed or running. The
361+price of matching names rather than looking them up is that a project whose
362+`package.json` name is not its directory name is invisible to the guess — the
363+panel cannot read `package.json`, and an explicit pin is the answer for those.
364+
365+The guess is deliberately timid. `.localhost` only, which is reserved for this
366+machine, and an ambiguous match — two sessions answering to one name — resolves
367+to nothing rather than a coin toss. A worktree host wants the worktree's own
368+session (a directory called `<branch>`, `<project>-<branch>` or
369+`<branch>-<project>`) and will not settle for the checkout it forked from.
370+Unpinning a guessed match records a veto against that origin, which is the only
371+way to say "no, not this one" to a rule that would otherwise keep re-deriving
372+itself.
373+
374+[portless]: https://www.npmjs.com/package/portless
362375
363376 Everything here is panel state: it lives in extension storage, it is
364377 per-browser-profile, and none of it reaches the daemon, which has never heard of
⋯ 517 unchanged lines
modifiedTODO.md+3 −3
⋯ 4 unchanged lines
55 - [ ] TODO: investigate chrome wterm and vercel wterm
66 - [x] Idea: pinned tab / session mode
77 - right-click a session or window tab to pin it to the browser tab you are
8- on, by site or by that exact tab; localhost ports are matched to sessions
9- by devport's hash when nothing is pinned. See README, "Pinning a session
10- to a browser tab".
8+ on, by site or by that exact tab; portless `.localhost` names are matched
9+ to sessions when nothing is pinned. See README, "Pinning a session to a
10+ browser tab".
1111 - the same pins read backwards too: moving the terminal activates the tab
1212 pinned to where it landed. Own checkbox, "and switch tabs back".
1313 - [ ] send to claude should auto name window using llm
⋯ 8 unchanged lines
modifiedbuild.sh+1 −1
⋯ 6 unchanged lines
77 out="dist/$browser"
88 rm -rf "$out"; mkdir -p "$out"
99 cp extension/sidebar.html extension/sidebar.js extension/sidebar.css extension/picker.js "$out/"
10- mkdir -p "$out/lib" && cp extension/lib/sanitize.js extension/lib/theme.js extension/lib/shot.js extension/lib/split.js extension/lib/devport.js extension/lib/tabpin.js "$out/lib/"
10+ mkdir -p "$out/lib" && cp extension/lib/sanitize.js extension/lib/theme.js extension/lib/shot.js extension/lib/split.js extension/lib/portless.js extension/lib/tabpin.js "$out/lib/"
1111 cp -r extension/vendor extension/icons "$out/"
1212 cp "extension/manifest.$browser.json" "$out/manifest.json"
1313 cp extension/sw.js "$out/" # both browsers now run a background script
⋯ 11 unchanged lines
deletedextension/lib/devport.js+0 −112
1-// The `devport` convention, reimplemented so the panel can apply it offline.
2-//
3-// devport(1) is a shell script that hands a local project a stable block of ten
4-// ports: `BASE + (cksum(name) % BLOCKS) * SLOT`, where the name is the git
5-// repo's directory name. Nothing registers anything — the hash *is* the
6-// registry — which is what makes it reproducible here.
7-//
8-// The panel wants the question the other way round: a browser tab is sitting on
9-// http://localhost:12345, and it wants to know which tmux session that port
10-// belongs to. devport answers that with `-r`, by walking ~/Code and hashing
11-// every directory in it. We do not need the walk: the daemon already tells us
12-// each session's working directory, so hashing those few names forward and
13-// comparing blocks gives the same answer without a subprocess, a filesystem, or
14-// devport being installed at all.
15-//
16-// The one thing that must not drift is the hash. `portof()` in devport is
17-// `printf '%s' "$name" | cksum`, and POSIX cksum is CRC-32/CKSUM: the ordinary
18-// CRC-32 polynomial, unreflected, with the message length appended to the
19-// message. Any faster-looking CRC-32 (zlib's, reflected, no length) computes a
20-// different number and would point at the wrong project.
21-
22-/** First assignable port. Below this is the crowd of framework defaults. */
23-const DEVPORT_BASE = 10240;
24-/** How many blocks exist: 2100 * 10 covers 10240-31239. */
25-const DEVPORT_BLOCKS = 2100;
26-/** Ports per project — app, db, cache, debugger, whatever. */
27-const DEVPORT_SLOT = 10;
28-
29-/** Lazily built, because this runs on every tab activation. @type {number[] | null} */
30-let table = null;
31-
32-/** The CRC-32/CKSUM byte table, poly 0x04C11DB7, unreflected. */
33-function crcTable() {
34- if (table) return table;
35- const t = new Array(256);
36- for (let i = 0; i < 256; i++) {
37- let c = i << 24;
38- for (let k = 0; k < 8; k++) c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : c << 1;
39- t[i] = c >>> 0;
40- }
41- table = t;
42- return t;
43-}
44-
45-/**
46- * POSIX `cksum`, as a number.
47- *
48- * The trailing length loop is not decoration: cksum feeds the byte count in
49- * after the data, low byte first, dropping the high zero bytes. Without it the
50- * checksums differ from the shell's for every input.
51- *
52- * @param {string} s
53- * @returns {number}
54- */
55-function cksum(s) {
56- const t = crcTable();
57- const bytes = new TextEncoder().encode(s);
58- let crc = 0;
59- for (const b of bytes) crc = ((crc << 8) ^ t[((crc >>> 24) ^ b) & 0xff]) >>> 0;
60- for (let n = bytes.length; n !== 0; n = Math.floor(n / 256)) {
61- crc = ((crc << 8) ^ t[((crc >>> 24) ^ (n & 0xff)) & 0xff]) >>> 0;
62- }
63- return (crc ^ 0xffffffff) >>> 0;
64-}
65-
66-/**
67- * The first port of the block a project name owns — what plain `devport` prints
68- * in a directory of that name.
69- *
70- * @param {string} name
71- * @returns {number}
72- */
73-function portOf(name) {
74- return DEVPORT_BASE + (cksum(name) % DEVPORT_BLOCKS) * DEVPORT_SLOT;
75-}
76-
77-/**
78- * The block a port falls in, or null when it is outside the assignable range —
79- * 3000, 5173, 8080 and every other hand-picked port land here, and they carry
80- * no project in them to find.
81- *
82- * @param {number} port
83- * @returns {number | null}
84- */
85-function blockOf(port) {
86- if (!Number.isInteger(port)) return null;
87- if (port < DEVPORT_BASE || port >= DEVPORT_BASE + DEVPORT_BLOCKS * DEVPORT_SLOT) return null;
88- return port - ((port - DEVPORT_BASE) % DEVPORT_SLOT);
89-}
90-
91-/**
92- * Whether `port` is one of the ten this name owns.
93- *
94- * A block is ten ports wide and there are only 2100 blocks, so a match is
95- * evidence and not proof — two projects in ~/Code can share one. That is why
96- * this only ever *suggests* a pin rather than making one.
97- *
98- * @param {number} port
99- * @param {string} name
100- * @returns {boolean}
101- */
102-function owns(port, name) {
103- if (!name) return false;
104- const block = blockOf(port);
105- return block !== null && block === portOf(name);
106-}
107-
108-const Devport = { BASE: DEVPORT_BASE, BLOCKS: DEVPORT_BLOCKS, SLOT: DEVPORT_SLOT, cksum, portOf, blockOf, owns };
109-
110-if (typeof module !== "undefined" && module.exports) {
111- module.exports = Devport;
112-}
deletedextension/lib/devport.test.js+0 −71
1-// Run with: node --test "extension/lib/*.test.js"
2-//
3-// The whole value of this module is agreeing with the devport shell script, so
4-// most of what is checked here are ports taken from running it. If cksum is
5-// ever "optimised" into an ordinary zlib CRC-32 these are the tests that fail.
6-
7-const test = require("node:test");
8-const assert = require("node:assert");
9-
10-const Devport = require("./devport.js");
11-
12-// `devport -n <name>`, run for real.
13-const KNOWN = {
14- "browser-terminal-extension": 26210,
15- myapp: 26270,
16- dotfiles: 26140,
17- termbridge: 12820,
18- Code: 25000,
19- a: 30900,
20-};
21-
22-test("agrees with the devport script", () => {
23- for (const [name, port] of Object.entries(KNOWN)) {
24- assert.equal(Devport.portOf(name), port, name);
25- }
26-});
27-
28-test("cksum matches the POSIX checksum", () => {
29- // `printf '%s' "" | cksum` and `printf '%s' abc | cksum`.
30- assert.equal(Devport.cksum(""), 4294967295);
31- assert.equal(Devport.cksum("abc"), 1219131554);
32-});
33-
34-test("every port lands in the assignable range, on a block boundary", () => {
35- const top = Devport.BASE + Devport.BLOCKS * Devport.SLOT;
36- for (let i = 0; i < 500; i++) {
37- const port = Devport.portOf(`project-${i}`);
38- assert.ok(port >= Devport.BASE && port < top, `${port} out of range`);
39- assert.equal((port - Devport.BASE) % Devport.SLOT, 0);
40- }
41-});
42-
43-test("a block covers the ten ports that follow its base", () => {
44- const base = Devport.portOf("myapp");
45- for (let i = 0; i < Devport.SLOT; i++) {
46- assert.equal(Devport.blockOf(base + i), base, `offset ${i}`);
47- assert.ok(Devport.owns(base + i, "myapp"));
48- }
49- // One past the end belongs to the next block, not this one.
50- assert.notEqual(Devport.blockOf(base + Devport.SLOT), base);
51-});
52-
53-test("ports outside the range belong to nobody", () => {
54- for (const port of [80, 3000, 5173, 8080, 10239, 31240, 65535, -1, 1.5, NaN]) {
55- assert.equal(Devport.blockOf(port), null, String(port));
56- assert.equal(Devport.owns(port, "myapp"), false, String(port));
57- }
58-});
59-
60-test("an empty name owns nothing", () => {
61- // Not because it hashes badly — it hashes fine — but because a session with
62- // no working directory would otherwise match one arbitrary block.
63- assert.equal(Devport.owns(Devport.portOf(""), ""), false);
64-});
65-
66-test("unicode names hash by their bytes", () => {
67- // The shell pipes bytes into cksum, so the name has to be UTF-8 encoded here
68- // rather than iterated as UTF-16 code units.
69- assert.equal(Devport.portOf("café"), Devport.portOf("café"));
70- assert.notEqual(Devport.portOf("café"), Devport.portOf("cafe"));
71-});
addedextension/lib/portless.js+108 −0
1+// The `portless` convention, reimplemented so the panel can apply it offline.
2+//
3+// portless(1) is a local reverse proxy that takes the port out of the URL: a
4+// dev server started under it gets a random port and a stable name, and you
5+// reach it at `https://<name>.localhost`. The name is inferred from the
6+// project — `package.json`'s `name` with any scope stripped, else the git
7+// root's directory name, else the working directory's — lowercased and beaten
8+// into a DNS label. In a git worktree the branch goes in front of it, so a
9+// second checkout of the same project is `https://<branch>.<project>.localhost`
10+// and does not collide with the first.
11+//
12+// The panel wants the question the other way round: a browser tab is sitting on
13+// https://mdlab.localhost, and it wants to know which tmux session that page
14+// belongs to. The daemon already tells us each session's working directory, so
15+// sanitizing those few names the way portless does and comparing labels answers
16+// it without a subprocess, without reading ~/.portless/routes.json, and without
17+// portless being installed or even running.
18+//
19+// What that costs, being a name match rather than a lookup: a project whose
20+// `package.json` name is not its directory name is invisible here, because the
21+// panel cannot read `package.json` — the pin menu is the answer for those. Only
22+// `.localhost` is understood; portless's LAN (`.local`) and tunnel hostnames
23+// are somebody else's machine's idea of a name.
24+
25+/** The suffix portless hangs every route off. */
26+const PORTLESS_TLD = "localhost";
27+
28+/** DNS's limit, and portless's. See `sanitize`. */
29+const MAX_LABEL = 63;
30+
31+/**
32+ * A name as portless would spell it in a hostname.
33+ *
34+ * Longer than a DNS label allows, portless truncates and appends six hex
35+ * characters of a sha256 — which we cannot reproduce without hashing, so names
36+ * that long simply never match here. They are rare enough to be worth the
37+ * silence rather than an async detection path.
38+ *
39+ * @param {string} name
40+ * @returns {string}
41+ */
42+function sanitize(name) {
43+ if (!name) return "";
44+ const label = name
45+ .toLowerCase()
46+ .replace(/[^a-z0-9-]/g, "-")
47+ .replace(/-{2,}/g, "-")
48+ .replace(/^-+|-+$/g, "");
49+ return label.length > MAX_LABEL ? "" : label;
50+}
51+
52+/**
53+ * A portless hostname split into the parts that carry meaning, or null when the
54+ * host is not one.
55+ *
56+ * `mdlab.localhost` -> `{ name: "mdlab", prefix: "" }`
57+ * `feat-x.mdlab.localhost` -> `{ name: "mdlab", prefix: "feat-x" }`
58+ *
59+ * `.localhost` is the whole test for whether this is local: RFC 6761 reserves
60+ * it, so a hostname ending in it resolves to this machine and nowhere else.
61+ *
62+ * @param {string} hostname
63+ * @returns {{ name: string, prefix: string } | null}
64+ */
65+function split(hostname) {
66+ if (!hostname) return null;
67+ const labels = hostname.toLowerCase().split(".");
68+ if (labels.length < 2 || labels[labels.length - 1] !== PORTLESS_TLD) return null;
69+ const name = labels[labels.length - 2];
70+ if (!name) return null;
71+ // Only ever one prefix label, but a deeper host is not a reason to give up on
72+ // the two labels that do mean something.
73+ return { name, prefix: labels[labels.length - 3] ?? "" };
74+}
75+
76+/**
77+ * Whether `name` — a session's name, or its working directory's — is the
78+ * project a portless hostname points at.
79+ *
80+ * The plain case is one comparison. The worktree case cannot be, because the
81+ * prefix is a *branch* and the session is a *directory*: what we can say is
82+ * that a worktree checked out for branch `feat-x` of project `app` is nearly
83+ * always sitting in a directory called `feat-x`, `app-feat-x` or `feat-x-app`.
84+ * A session that only answers to `app` is deliberately not a match for
85+ * `feat-x.app.localhost` — that is the main checkout, a different session, and
86+ * sending the terminal there would be a confident wrong answer.
87+ *
88+ * @param {string} hostname
89+ * @param {string} name
90+ * @returns {boolean}
91+ */
92+function owns(hostname, name) {
93+ const route = split(hostname);
94+ const label = sanitize(name);
95+ if (!route || !label) return false;
96+ if (!route.prefix) return label === route.name;
97+ return (
98+ label === route.prefix ||
99+ label === `${route.name}-${route.prefix}` ||
100+ label === `${route.prefix}-${route.name}`
101+ );
102+}
103+
104+const Portless = { TLD: PORTLESS_TLD, MAX_LABEL, sanitize, split, owns };
105+
106+if (typeof module !== "undefined" && module.exports) {
107+ module.exports = Portless;
108+}
addedextension/lib/portless.test.js+58 −0
1+// Run with: node --test "extension/lib/*.test.js"
2+//
3+// The whole value of this module is agreeing with portless about what a project
4+// is called, so these are mostly the naming rules read back: the sanitizing it
5+// does to make a DNS label, and the worktree prefix it puts in front.
6+
7+const test = require("node:test");
8+const assert = require("node:assert");
9+
10+const Portless = require("./portless.js");
11+
12+test("sanitize spells a name the way a hostname must", () => {
13+ assert.equal(Portless.sanitize("MyApp"), "myapp");
14+ // Scopes are stripped before this by portless; everything else that is not a
15+ // hostname character collapses to a single dash, and dashes never bookend.
16+ assert.equal(Portless.sanitize("My App_v2"), "my-app-v2");
17+ assert.equal(Portless.sanitize("--edge--case--"), "edge-case");
18+ assert.equal(Portless.sanitize("café"), "caf");
19+ assert.equal(Portless.sanitize(""), "");
20+ // Past a DNS label portless appends a hash we cannot reproduce, so nothing
21+ // matches rather than something wrong matching.
22+ assert.equal(Portless.sanitize("a".repeat(63)).length, 63);
23+ assert.equal(Portless.sanitize("a".repeat(64)), "");
24+});
25+
26+test("split reads the project and any worktree label off a host", () => {
27+ assert.deepEqual(Portless.split("mdlab.localhost"), { name: "mdlab", prefix: "" });
28+ assert.deepEqual(Portless.split("feat-x.mdlab.localhost"), { name: "mdlab", prefix: "feat-x" });
29+ assert.deepEqual(Portless.split("MDLAB.LOCALHOST"), { name: "mdlab", prefix: "" });
30+});
31+
32+test("split is what keeps detection local", () => {
33+ // Not portless's suffix, so not portless's business — `.localhost` is
34+ // reserved for this machine and a public name cannot end in it.
35+ for (const host of ["mdlab.local", "example.com", "localhost", "127.0.0.1", ""]) {
36+ assert.equal(Portless.split(host), null, host);
37+ }
38+});
39+
40+test("owns matches the project a plain host names", () => {
41+ assert.ok(Portless.owns("mdlab.localhost", "mdlab"));
42+ // The name is sanitized on the way in, so a directory called `My Lab` is the
43+ // host `my-lab.localhost`.
44+ assert.ok(Portless.owns("my-lab.localhost", "My Lab"));
45+ assert.ok(!Portless.owns("mdlab.localhost", "dotfiles"));
46+ assert.ok(!Portless.owns("mdlab.localhost", ""));
47+});
48+
49+test("a worktree host wants the worktree, not the checkout it forked from", () => {
50+ // The prefix is a branch and a session is a directory, so what matches is a
51+ // directory named after the branch, alone or beside the project.
52+ assert.ok(Portless.owns("feat-x.mdlab.localhost", "feat-x"));
53+ assert.ok(Portless.owns("feat-x.mdlab.localhost", "mdlab-feat-x"));
54+ assert.ok(Portless.owns("feat-x.mdlab.localhost", "feat-x-mdlab"));
55+ // The main checkout answers to `mdlab.localhost` and only that one.
56+ assert.ok(!Portless.owns("feat-x.mdlab.localhost", "mdlab"));
57+ assert.ok(!Portless.owns("mdlab.localhost", "feat-x"));
58+});
modifiedextension/lib/tabpin.js+38 −47
⋯ 20 unchanged lines
2121 //
2222 // Two kinds of pin, and the difference is what they key on:
2323 //
24-// by origin http://localhost:26210 -> a session. Any tab on that origin
24+// by origin https://app.localhost -> a session. Any tab on that origin
2525 // matches, and the pin outlives the tab, the window and the
2626 // browser itself, because an origin is a name and a tab id is a
2727 // handle. This is the one to reach for.
⋯ 5 unchanged lines
3333 // tab, one of five identical Jira boards).
3434 //
3535 // A tab pin wins over an origin pin, being the more specific statement. Below
36-// both sits detection: a tab on a localhost port that devport would hand to a
37-// project we have a session in is treated as pinned to that session even though
38-// nobody said so. That guess is only ever a fallback — an explicit pin at
36+// both sits detection: a tab on a `.localhost` name that portless would hand to
37+// a project we have a session in is treated as pinned to that session even
38+// though nobody said so. That guess is only ever a fallback — an explicit pin at
3939 // either level overrides it, including the explicit *veto* that unpinning an
4040 // auto-matched tab writes, which is the only way to say "no, not this one" to a
4141 // rule that would otherwise keep re-deriving itself.
⋯ 80 unchanged lines
122122 }
123123
124124 /**
125- * The port a local development server would be on, or null.
125+ * The hostname an origin carries, or "".
126126 *
127- * Local only, and deliberately so: devport's mapping says nothing about a port
128- * on someone else's host, and a public site that happens to sit on :26210 is
129- * not your project.
127+ * Detection has nothing else to go on: portless takes the port out of the URL
128+ * on purpose, so `https://app.localhost` and `https://app.localhost:8443` name
129+ * the same project and the port is noise.
130130 *
131131 * @param {string} origin
132- * @returns {number | null}
132+ * @returns {string}
133133 */
134-function localPort(origin) {
135- if (!origin) return null;
134+function hostOf(origin) {
135+ if (!origin) return "";
136136 try {
137- const u = new URL(origin);
138- const host = u.hostname;
139- const local =
140- host === "localhost" ||
141- host === "127.0.0.1" ||
142- host === "[::1]" ||
143- host === "::1" ||
144- host.endsWith(".localhost");
145- if (!local || !u.port) return null;
146- return Number(u.port);
137+ return new URL(origin).hostname;
147138 } catch {
148- return null;
139+ return "";
149140 }
150141 }
151142
152143 /**
153- * The last path segment, which is the name devport hashes: it takes the git
154- * repo's directory name, and a session's working directory is normally that
155- * directory or something under it.
144+ * The last path segment, which is the name portless falls back to: absent a
145+ * `package.json` name it uses the git repo's directory name, and a session's
146+ * working directory is normally that directory or something under it.
156147 *
157148 * @param {string | null | undefined} path
158149 * @returns {string}
⋯ 5 unchanged lines
164155 }
165156
166157 /**
167- * The session a localhost origin most likely belongs to, by devport's hash, or
168- * null when nothing matches.
158+ * The session a `.localhost` origin most likely belongs to, by portless's
159+ * naming, or null when nothing matches.
169160 *
170- * Two candidate names per session, because either can be the one devport was
171- * run under: the working directory's own name, and the session name (the
172- * omnibar names sessions after the project directory, so it usually *is* the
173- * name). The directory is checked first — it is what devport actually reads.
161+ * Two candidate names per session, because either can be the one portless
162+ * inferred: the working directory's own name, and the session name (the omnibar
163+ * names sessions after the project directory, so it usually *is* the name). The
164+ * directory is checked first — it is what portless actually reads.
174165 *
175- * Ambiguity resolves to nothing. Blocks collide by design, and a wrong
176- * auto-switch is worse than no auto-switch: it moves a terminal you were
177- * reading out from under you for a reason you cannot see.
166+ * Ambiguity resolves to nothing. Two checkouts of one project can share a name,
167+ * and a wrong auto-switch is worse than no auto-switch: it moves a terminal you
168+ * were reading out from under you for a reason you cannot see.
178169 *
179170 * @param {string} origin
180171 * @param {TbSessionInfo[]} sessions
181- * @param {typeof Devport} devport
172+ * @param {typeof Portless} portless
182173 * @returns {TbPinTarget | null}
183174 */
184-function detectTarget(origin, sessions, devport) {
185- const port = localPort(origin);
186- if (port === null || devport.blockOf(port) === null) return null;
175+function detectTarget(origin, sessions, portless) {
176+ const host = hostOf(origin);
177+ if (!portless.split(host)) return null;
187178
188179 /** @type {TbSessionInfo[]} */
189180 const hits = [];
190181 for (const s of sessions) {
191- if (devport.owns(port, baseName(s.path)) || devport.owns(port, s.name)) hits.push(s);
182+ if (portless.owns(host, baseName(s.path)) || portless.owns(host, s.name)) hits.push(s);
192183 }
193184 if (hits.length !== 1) return null;
194185 return { session: hits[0].name, window: null };
⋯ 6 unchanged lines
201192 * @param {TbTabPinStore} store
202193 * @param {{ id?: number, url?: string }} tab
203194 * @param {TbSessionInfo[]} sessions
204- * @param {typeof Devport} devport
195+ * @param {typeof Portless} portless
205196 * @returns {{ target: TbPinTarget, source: TbPinSource } | null}
206197 */
207-function resolve(store, tab, sessions, devport) {
198+function resolve(store, tab, sessions, portless) {
208199 if (!store.enabled) return null;
209200 const origin = originOf(tab.url);
210201
⋯ 9 unchanged lines
220211 return t ? { target: t, source: "origin" } : null;
221212 }
222213 if (!store.detect || !origin) return null;
223- const auto = detectTarget(origin, sessions, devport);
214+ const auto = detectTarget(origin, sessions, portless);
224215 return auto ? { target: auto, source: "detect" } : null;
225216 }
226217
⋯ 10 unchanged lines
237228 *
238229 * Deliberately expressed as the forward rule run over every tab rather than as
239230 * a second set of rules read out of the store backwards. A pin, a site pin, a
240- * veto and a devport guess already compose into one answer per tab; asking each
231+ * veto and a portless guess already compose into one answer per tab; asking each
241232 * tab "would you bring the terminal here?" and keeping the ones that say yes
242233 * means the two directions cannot disagree about what a pin means, and that a
243234 * veto keeps vetoing when read from this end.
⋯ 11 unchanged lines
255246 * @param {{ id?: number, url?: string, active?: boolean }[]} tabs the panel's
256247 * own browser window, most recently used first
257248 * @param {TbSessionInfo[]} sessions
258- * @param {typeof Devport} devport
249+ * @param {typeof Portless} portless
259250 * @returns {{ tabId: number, source: TbPinSource } | null}
260251 */
261-function reverse(store, spot, tabs, sessions, devport) {
252+function reverse(store, spot, tabs, sessions, portless) {
262253 if (!store.enabled || !store.reverse) return null;
263254 /** @type {{ tabId: number, source: TbPinSource } | null} */
264255 let best = null;
265256 for (const tab of tabs) {
266257 if (tab.id == null) continue;
267- const hit = resolve(store, tab, sessions, devport);
258+ const hit = resolve(store, tab, sessions, portless);
268259 if (!hit) continue;
269260 // Against the *resolved* pin, not the pin as written, for the reason
270261 // `applyTabPin` compares that way too: a pin to a window that has closed is
⋯ 148 unchanged lines
419410 emptyStore,
420411 loadStore,
421412 originOf,
422- localPort,
413+ hostOf,
423414 baseName,
424415 detectTarget,
425416 resolve,
⋯ 12 unchanged lines
modifiedextension/lib/tabpin.test.js+38 −28
11 // Run with: node --test "extension/lib/*.test.js"
22 //
33 // What matters here is precedence. Four rules can answer "where does this tab
4-// send the terminal" — a tab pin, an origin pin, a veto and a devport guess —
4+// send the terminal" — a tab pin, an origin pin, a veto and a portless guess —
55 // and getting their order wrong means the panel moves somewhere the user did
66 // not ask for, which is the one failure this feature cannot afford.
77
⋯ 1 unchanged line
99 const assert = require("node:assert");
1010
1111 const Tabpin = require("./tabpin.js");
12-const Devport = require("./devport.js");
12+const Portless = require("./portless.js");
1313
1414 /** @param {string} name */
1515 const session = (name, path, windows = []) => ({
⋯ 16 unchanged lines
3232 session("dots", "/home/u/Code/dotfiles", ["@7"]),
3333 ];
3434
35-/** The port devport hands the first session's directory. */
36-const WEB_PORT = Devport.portOf("browser-terminal-extension");
35+/** The origin portless gives the first session's directory. */
36+const WEB_ORIGIN = "https://browser-terminal-extension.localhost";
3737
3838 const store = (over = {}) => ({ ...Tabpin.emptyStore(), ...over });
39-const resolve = (s, tab, sessions = SESSIONS) => Tabpin.resolve(s, tab, sessions, Devport);
39+const resolve = (s, tab, sessions = SESSIONS) => Tabpin.resolve(s, tab, sessions, Portless);
4040
4141 test("an unknown tab moves nothing", () => {
4242 assert.equal(resolve(store(), { id: 1, url: "https://example.com/" }), null);
⋯ 20 unchanged lines
6363 test("a null entry is a veto and stops the search", () => {
6464 const s = store({
6565 byTab: { 5: null },
66- byOrigin: { [`http://localhost:${WEB_PORT}`]: { session: "web", window: null } },
66+ byOrigin: { [WEB_ORIGIN]: { session: "web", window: null } },
6767 });
6868 // The origin pin below it would have matched; the veto is why it does not.
69- assert.equal(resolve(s, { id: 5, url: `http://localhost:${WEB_PORT}/` }), null);
70- // And an origin veto is what turns a devport guess off for good.
71- const vetoed = store({ byOrigin: { [`http://localhost:${WEB_PORT}`]: null } });
72- assert.equal(resolve(vetoed, { id: 5, url: `http://localhost:${WEB_PORT}/` }), null);
69+ assert.equal(resolve(s, { id: 5, url: `${WEB_ORIGIN}/` }), null);
70+ // And an origin veto is what turns a portless guess off for good.
71+ const vetoed = store({ byOrigin: { [WEB_ORIGIN]: null } });
72+ assert.equal(resolve(vetoed, { id: 5, url: `${WEB_ORIGIN}/` }), null);
7373 });
7474
75-test("a localhost devport port finds its session with nothing stored", () => {
76- const hit = resolve(store(), { id: 1, url: `http://localhost:${WEB_PORT}/app` });
75+test("a portless host finds its session with nothing stored", () => {
76+ const hit = resolve(store(), { id: 1, url: `${WEB_ORIGIN}/app` });
7777 assert.deepEqual(hit, { target: { session: "web", window: null }, source: "detect" });
78- // Every port in the block, not just the base one.
79- assert.equal(resolve(store(), { id: 1, url: `http://127.0.0.1:${WEB_PORT + 3}/` }).source, "detect");
78+ // The port portless proxies on is not part of the answer.
79+ assert.equal(resolve(store(), { id: 1, url: `${WEB_ORIGIN}:8443/` }).source, "detect");
8080 });
8181
82-test("detection is local, in-range and unambiguous or it does not fire", () => {
82+test("detection is local, named and unambiguous or it does not fire", () => {
8383 const off = store({ detect: false });
84- assert.equal(resolve(off, { id: 1, url: `http://localhost:${WEB_PORT}/` }), null);
85- // A remote host on the same port says nothing about your projects.
86- assert.equal(resolve(store(), { id: 1, url: `http://example.com:${WEB_PORT}/` }), null);
87- // A hand-picked port is in nobody's block.
84+ assert.equal(resolve(off, { id: 1, url: `${WEB_ORIGIN}/` }), null);
85+ // The same name on a real domain says nothing about your projects.
86+ assert.equal(resolve(store(), { id: 1, url: "https://browser-terminal-extension.com/" }), null);
87+ // A dev server nobody put behind portless carries no name to match.
8888 assert.equal(resolve(store(), { id: 1, url: "http://localhost:3000/" }), null);
89- // Two sessions in the same block is a collision, and a coin toss is worse
89+ // Two sessions answering to one name is a collision, and a coin toss is worse
9090 // than doing nothing.
9191 const twins = [...SESSIONS, session("web2", "/elsewhere/browser-terminal-extension", ["@9"])];
92- assert.equal(resolve(store(), { id: 1, url: `http://localhost:${WEB_PORT}/` }, twins), null);
92+ assert.equal(resolve(store(), { id: 1, url: `${WEB_ORIGIN}/` }, twins), null);
9393 });
9494
9595 test("the session name is a candidate too, not just its directory", () => {
9696 const named = [session("myapp", "/home/u/somewhere/else", ["@1"])];
97- const port = Devport.portOf("myapp");
98- assert.equal(resolve(store(), { id: 1, url: `http://localhost:${port}/` }, named).source, "detect");
97+ assert.equal(resolve(store(), { id: 1, url: "https://myapp.localhost/" }, named).source, "detect");
9998 });
10099
100+test("a worktree host goes to the worktree's own session", () => {
101+ const trees = [
102+ session("web", "/home/u/Code/browser-terminal-extension", ["@1"]),
103+ session("feat", "/home/u/Code/worktrees/feat-x", ["@3"]),
104+ ];
105+ const hit = resolve(store(), { id: 1, url: "https://feat-x.browser-terminal-extension.localhost/" }, trees);
106+ assert.deepEqual(hit, { target: { session: "feat", window: null }, source: "detect" });
107+ // And the main checkout keeps its own host to itself.
108+ assert.equal(resolve(store(), { id: 1, url: `${WEB_ORIGIN}/` }, trees).target.session, "web");
109+});
110+
101111 test("the whole feature can be switched off without losing pins", () => {
102112 const s = store({
103113 enabled: false,
⋯ 141 unchanged lines
245255 assert.ok(!Tabpin.sameSpot(null, { session: "a" }));
246256 });
247257
248-test("baseName reads the directory devport would have hashed", () => {
258+test("baseName reads the directory portless would have named the app after", () => {
249259 assert.equal(Tabpin.baseName("/home/u/Code/thing"), "thing");
250260 assert.equal(Tabpin.baseName("/home/u/Code/thing/"), "thing");
251261 assert.equal(Tabpin.baseName(null), "");
⋯ 8 unchanged lines
260270 // already showing a tab that points here is left alone, which is what keeps the
261271 // two directions from chasing each other.
262272
263-const rev = (s, spot, tabs, sessions = SESSIONS) => Tabpin.reverse(s, spot, tabs, sessions, Devport);
273+const rev = (s, spot, tabs, sessions = SESSIONS) => Tabpin.reverse(s, spot, tabs, sessions, Portless);
264274
265275 test("reverse finds the tab an origin pin names", () => {
266276 const s = store({ byOrigin: { "https://example.com": { session: "web", window: null } } });
⋯ 36 unchanged lines
303313 });
304314
305315 test("reverse honours a veto and the off switches", () => {
306- const tabs = [{ id: 5, url: `http://localhost:${WEB_PORT}/` }];
316+ const tabs = [{ id: 5, url: `${WEB_ORIGIN}/` }];
307317 const spot = { session: "web", window: "@1" };
308- // The devport guess would have matched this tab.
318+ // The portless guess would have matched this tab.
309319 assert.equal(rev(store(), spot, tabs).source, "detect");
310320 // An origin veto turns it off from this end too.
311- assert.equal(rev(store({ byOrigin: { [`http://localhost:${WEB_PORT}`]: null } }), spot, tabs), null);
321+ assert.equal(rev(store({ byOrigin: { [WEB_ORIGIN]: null } }), spot, tabs), null);
312322 // As does either switch.
313323 assert.equal(rev(store({ reverse: false }), spot, tabs), null);
314324 assert.equal(rev(store({ enabled: false }), spot, tabs), null);
⋯ 13 unchanged lines
modifiedextension/sidebar.html+3 −3
⋯ 355 unchanged lines
356356
357357 <!-- Following the browser. Right-click a session or a window to pin it to
358358 the tab you are on; these three only say whether pins are acted on at
359- all, whether an unpinned localhost port may guess at one, and whether
359+ all, whether an unpinned `.localhost` name may guess at one, and whether
360360 the same pins also read backwards. -->
361361 <div class="row">
362362 <label class="row"
⋯ 2 unchanged lines
365365 </div>
366366 <div class="row">
367367 <label class="row"
368- ><input id="detect-devport" type="checkbox" /> guess by devport port</label
368+ ><input id="detect-portless" type="checkbox" /> guess by portless name</label
369369 >
370370 </div>
371371 <div class="row">
⋯ 51 unchanged lines
423423 <script src="lib/sanitize.js"></script>
424424 <script src="lib/shot.js"></script>
425425 <script src="lib/split.js"></script>
426- <script src="lib/devport.js"></script>
426+ <script src="lib/portless.js"></script>
427427 <script src="lib/tabpin.js"></script>
428428 <script src="picker.js"></script>
429429 <script src="vendor/xterm.js"></script>
⋯ 5 unchanged lines
modifiedextension/sidebar.js+4 −4
⋯ 1498 unchanged lines
14991499 * @returns {{ session: string, window: TbWindowInfo | null, source: TbPinSource } | null}
15001500 */
15011501 function currentPinTarget() {
1502- const hit = Tabpin.resolve(tabPins, browserTab, lastSessions, Devport);
1502+ const hit = Tabpin.resolve(tabPins, browserTab, lastSessions, Portless);
15031503 if (!hit) return null;
15041504 const at = Tabpin.locate(hit.target, lastSessions);
15051505 return at ? { ...at, source: hit.source } : null;
⋯ 134 unchanged lines
16401640 // Chrome before 121 has no `lastAccessed`, and then the sort is a no-op
16411641 // and tab order decides — a worse answer, not a broken one.
16421642 const order = [...tabs].sort((a, b) => (b.lastAccessed ?? 0) - (a.lastAccessed ?? 0));
1643- const hit = Tabpin.reverse(tabPins, at, order, lastSessions, Devport);
1643+ const hit = Tabpin.reverse(tabPins, at, order, lastSessions, Portless);
16441644 if (!hit) return;
16451645 reverseGoingTo = hit.tabId;
16461646 api.tabs.update(hit.tabId, { active: true }).catch(() => {
⋯ 123 unchanged lines
17701770 const PIN_SOURCE_NOTE = {
17711771 tab: "pinned to this browser tab",
17721772 origin: "pinned to this site",
1773- detect: "matched to this site by its devport port",
1773+ detect: "matched to this site by its portless name",
17741774 };
17751775
17761776 /**
⋯ 3744 unchanged lines
55215521 // silencing it, not throwing away what you told it — so nothing here touches
55225522 // `byTab` or `byOrigin`.
55235523 const followBox = $input("follow-tabs");
5524-const detectBox = $input("detect-devport");
5524+const detectBox = $input("detect-portless");
55255525 const leadBox = $input("lead-tabs");
55265526
55275527 function applyTabPinSettings() {
⋯ 173 unchanged lines
modifiedextension/types/globals.d.ts+3 −3
⋯ 282 unchanged lines
283283 interface TbTabPinStore {
284284 /** The whole feature, off. Pins are kept while it is off. */
285285 enabled: boolean;
286- /** The devport guess for localhost ports. Explicit pins work regardless. */
286+ /** The portless guess for `.localhost` names. Explicit pins work regardless. */
287287 detect: boolean;
288288 /** The other direction: moving the terminal activates the pinned tab. Reads
289289 the same pins as the forward direction, and is separately switchable
⋯ 2 unchanged lines
292292 /** Keyed by browser tab id, as a string — storage round-trips JSON, and JSON
293293 object keys are strings. A null value is a veto. */
294294 byTab: Record<string, TbPinTarget | null>;
295- /** Keyed by origin, e.g. `http://localhost:26210`. */
295+ /** Keyed by origin, e.g. `https://app.localhost`. */
296296 byOrigin: Record<string, TbPinTarget | null>;
297297 }
298298
⋯ 201 unchanged lines
500500 declare const Sanitize: typeof import("../lib/sanitize.js");
501501 declare const Shot: typeof import("../lib/shot.js");
502502 declare const Split: typeof import("../lib/split.js");
503-declare const Devport: typeof import("../lib/devport.js");
503+declare const Portless: typeof import("../lib/portless.js");
504504 declare const Tabpin: typeof import("../lib/tabpin.js");
505505
506506 /** Set by picker.js inside the *page*, not here — see cancelPick(). */
⋯ 3 unchanged lines