diffstalkerd 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,7 +5,351 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [Unreleased]
8
+ ## [0.10.0] - 2026-08-03
9
+
10
+ ### Added
11
+
12
+ - **Images are shown, in the Explorer and in a diff.** A PNG, JPEG or GIF
13
+ opens as a picture on a checkerboard stage instead of the "Binary file"
14
+ note, with its format and pixel size in the header — plus a frame count
15
+ for an animated GIF — and a `1:1` toggle between shrink-to-fit and actual
16
+ size. In Changes, a changed image renders as a fixed-height card with both
17
+ versions, in **Side by side**, **Swipe** or **Onion** mode (pure CSS, no
18
+ canvas); swipe and onion need two pictures of the same shape, so they fall
19
+ back to side by side when the two sides differ in size. The meta line
20
+ carries what the picture cannot: each side's byte size, its short object id
21
+ (or "working tree" for an uncommitted file), the byte delta when both sides
22
+ exist and differ, and a "may be metadata only" hint when the pixel
23
+ dimensions match but the bytes do not — because two identical-looking
24
+ images can differ in EXIF or ICC and a reviewer must never conclude
25
+ "nothing changed" from the picture alone. Web UI only; the terminal UI
26
+ cannot draw pixels.
27
+ - **Two new daemon endpoints, `GET /repos/:id/blob` and
28
+ `GET /repos/:id/media`**, on every listener. `/media` resolves the old and
29
+ new side of a changed image server-side (renames included) and reports
30
+ bytes, object id, dimensions or a refusal code; `/blob` serves the bytes
31
+ themselves, and only to an `<img>` — a browser that names any other fetch
32
+ destination, or a cross-site one, is refused. **Only PNG, JPEG and GIF are
33
+ served, and the content type comes from magic bytes** re-derived from the
34
+ exact buffer being written, on every request — never from the extension, a
35
+ query parameter, or a cached verdict, because a repo file called
36
+ `logo.png` holding `<svg><script>` is same-origin script the moment we
37
+ agree with its name. Everything else gets zero bytes and a refusal. The
38
+ daemon never decodes, transcodes or strips metadata: validation is
39
+ fixed-offset reads and bounded walks, no image library enters the tree, and
40
+ the browser stays the sandbox. The byte cap is checked before a byte is
41
+ read, the pixel and frame caps before a byte is written — 8 MiB (2 MiB for
42
+ GIF), 8192 px per side, 16 MPix, 256 frames — with the pixel budget as the
43
+ real control, since a 300-byte PNG can declare 60000×60000. A GIF is
44
+ charged frame by frame as well as in total: a frame's rectangle may legally
45
+ be bigger than the picture it composites into, and a decoder allocates the
46
+ rectangle. See `packages/daemon/README.md`.
47
+ - **One daemon serves the terminal UI and the browser at once.** `--socket`
48
+ and `--port` are no longer mutually exclusive: the unix socket is the
49
+ daemon's identity and is always bound (unless `--no-socket`), and `--port`
50
+ adds the browser's transport on top. `diffstalkerd --port 7337` therefore
51
+ gives one process, one git state, and one event stream that both clients
52
+ observe — where previously a port bind replaced the socket, the CLI found
53
+ nothing to attach to, and you ended up running two independent daemons
54
+ whose states never agreed.
55
+ - **Least privilege is now decided per listener rather than per daemon.**
56
+ Each transport gets its own routing table over the shared state, graded by
57
+ how well it is protected: a unix socket (or an inherited activation fd) is
58
+ owner-only at the filesystem layer and carries the full API, while a TCP
59
+ port carries the web subset. Commit, discard, hunk staging and every
60
+ remote/branch route are simply absent from a port's routing table, so a
61
+ dual-bound daemon is still safe to point a browser at. `createDaemon({
62
+ apiMode })` still forces one surface onto every listener, for embedders.
63
+ - **A systemd user service**, installed by the Arch package at
64
+ `/usr/lib/systemd/user/diffstalkerd.service` —
65
+ `systemctl --user enable --now diffstalkerd` and the web UI is at
66
+ `http://diffstalker.localhost:7337/`. A user unit, not a system one: the
67
+ socket lives under `$XDG_RUNTIME_DIR` and git runs as the invoking user.
68
+ Not socket-activated, because a cold activated start overruns the CLI's
69
+ 250 ms health probe and the TUI would race it by spawning a second daemon.
70
+ - `--no-socket` (requires `--port`) for a browser-only daemon, and `--port 0`
71
+ to let the kernel choose a free port — the daemon reports the one it got.
72
+ - **`diffstalkerd` takes repo paths on the command line.** `diffstalkerd
73
+ --port 7337 .` now opens that repo before the daemon starts listening, so
74
+ the browser has something to show the moment it connects instead of an
75
+ empty daemon waiting for someone to POST `/repos`. A path is expanded
76
+ (`~`), resolved against the current directory, and reported as it opens; a
77
+ path that will not open stops the daemon with a message rather than leaving
78
+ a half-set-up socket behind.
79
+ - **`--version` (and `-v`) on both commands.** `diffstalkerd --version`
80
+ prints its version; `diffstalker --version` prints its own plus the
81
+ `diffstalkerd` it would spawn and the runtime it is running under — the
82
+ answer to "which install am I actually using" when npm, the AUR package and
83
+ a `bun link` checkout are all on the same machine. It answers before any
84
+ daemon contact, so it still works when nothing can start.
85
+
86
+ ### Changed
87
+
88
+ - **The Explorer no longer browses the git directory.** `GET /repos/:id/file`
89
+ and `/repos/:id/tree` now refuse any path whose normalized form contains a
90
+ `.git` segment (`.git/config`, `./.git/config`, `src/../.git/config`,
91
+ `.GIT/config`, `worktrees/x/.git/config`) and any path whose real location
92
+ lands at or under this repository's **own** absolute git dir — which also
93
+ catches a symlink pointing into it, the git dir of a linked worktree, and a
94
+ submodule's `.git` file. Only those two rules are enforced: a repository
95
+ committed into the working tree under some other name is still browsable,
96
+ because it is tracked repo content, not the git dir of the repo being
97
+ served. `/tree` drops the git directory from listings even with
98
+ `hidden=true`. This was reachable before and served `.git/config`, which
99
+ carries tokens embedded in remote URLs. The segment check runs on
100
+ `path.relative(root, path.resolve(root, rel))`, over every segment, case
101
+ insensitively and with trailing dots and spaces stripped; a check on the
102
+ raw string's first segment misses all four spellings after the first.
103
+ - **`GET /repos/:id/tree?dir=.` is now a 400.** Path validation refuses a
104
+ path whose normalized form is empty, and only `dir=` (the empty string) is
105
+ special-cased as the repository root. The web UI sends the empty string, so
106
+ nothing in it changes; a REST caller that spells the root as `.` — or as
107
+ anything else that normalizes to it, like `src/..` — must send the empty
108
+ string instead.
109
+ - **A large binary in the Explorer reads as "Binary file", not "File too
110
+ large to display".** The 1 MB cap is the *text* cap, so it used to be
111
+ reported for a 2 MB tarball as if a bigger budget would have shown you
112
+ something — but a tarball was never displayable text. Whether a file over
113
+ the cap is binary is now decided by the same NUL scan every other file
114
+ gets, and only a binary one is called binary. Large *text* files are
115
+ unchanged: a 2 MB README still reads as too large, which is the truth
116
+ about it.
117
+ - **Tighter response headers on every daemon response.** The CSP gains
118
+ `frame-src`, `child-src`, `media-src`, `worker-src` and `form-action`, all
119
+ `'none'`, and `Cross-Origin-Resource-Policy: same-origin` is now set. The
120
+ UI has no iframe, no media element, no worker and no form, so spelling them
121
+ out costs nothing and makes a regression that adds one fail loudly.
122
+ `img-src` stays `'self' data:` — deliberately no `blob:`, since a `blob:`
123
+ URL inherits the page's origin.
124
+ - **An unknown option is now an error, not a repo path.** `diffstalker
125
+ --port 7337` used to treat `--port` and `7337` as paths and try to open
126
+ `./7337` as a repository; the failure named a directory you never
127
+ mentioned. Any unrecognized argument starting with `-` now exits 2 with
128
+ `unknown option`, and `--port` in particular says what to do instead (give
129
+ it to `diffstalkerd`). A second repo path is an error too, instead of being
130
+ silently dropped. `--socket` and `--instance` with no value still fail,
131
+ now with the same message shape and exit code as every other usage error
132
+ (2, was 1).
133
+ - **A relative repo path is refused instead of being resolved against the
134
+ wrong directory.** The daemon used to resolve a path like `../foo` against
135
+ **its own** working directory, which is not yours whenever you attach to a
136
+ daemon that was already running — so it opened a different repository, or
137
+ reported "Not a git repository" about a path you never typed. It now
138
+ requires an absolute path and says so. A leading `~` is expanded first, and
139
+ the not-a-repo message names the expanded path, so `~/code/x` no longer
140
+ fails as the literal directory `~`.
141
+
142
+ ### Fixed
143
+
144
+ - **A named pipe in the working tree no longer freezes the daemon.** Opening a
145
+ FIFO blocks until something opens the other end to write, and the working-tree
146
+ watcher opened whatever appeared. Under `bun` that block lands on the main
147
+ thread, so one pipe created inside a watched repo stopped the daemon answering
148
+ anything at all — `/health` included — while it still looked alive. The
149
+ watcher now skips anything that is not a regular file or a directory. Node
150
+ handles the same path without trouble, so a `diffstalkerd` installed from npm
151
+ was never affected; `bun run dev` and `bun run serve` were.
152
+ - **A host name that merely begins with `127.` is no longer taken for
153
+ loopback.** The daemon checks the `Host` header on every request so that a
154
+ name an attacker owns cannot be pointed at the daemon's port and become
155
+ same-origin with it — a DNS rebinding attack, which would hand a visited
156
+ page the whole API. The check tested `startsWith('127.')`, and
157
+ `127.0.0.1.evil.com` starts with `127.`. Only real loopback names are
158
+ accepted now: an address in `127.0.0.0/8`, `::1`, `localhost`, and names
159
+ under `.localhost`. This is pre-existing behaviour in the shipped daemon,
160
+ not something the image endpoints introduced — it was found while reviewing
161
+ them, and it applies to every route.
162
+ - **A 500 no longer tells the browser what git was asked and what it
163
+ answered.** An error no route classified had its message copied into the
164
+ response body, and a failed git call carries the whole command line and
165
+ git's stderr with it — absolute paths, branch and remote names, object ids.
166
+ An unexpected 500 now says only that the request failed; the detail is the
167
+ daemon's to report, not the browser's to read. Deliberate errors are
168
+ unchanged: a 400, 404, 413 or 415 still says exactly what was wrong,
169
+ because the caller needs that.
170
+ - **A renamed file now says where it came from.** `FileEntry.originalPath` was
171
+ declared and read — the terminal file lists have always had an `← old/path`
172
+ suffix for it — but `getStatus` never populated it, so the suffix never
173
+ appeared and the pre-rename blob had no route back. It is now filled from
174
+ git's own rename/copy record on the index side (the working-tree column
175
+ never carries `R` or `C`, so only the staged entry can carry it). This lets
176
+ a renamed image resolve its old side: HEAD has never heard of the new name.
177
+ - **An untracked binary file no longer renders as mojibake.** A newly added
178
+ PNG is the most common image in a diff, and `getDiffForUntracked` read
179
+ every untracked file as UTF-8 and emitted each line as an addition — so it
180
+ arrived as a wall of replacement characters and never reached the binary
181
+ path. Untracked files are now read as bytes and classified by a NUL scan
182
+ (the same test the Explorer uses), and a binary one gets git's own marker,
183
+ `Binary files /dev/null and b/logo.png differ`. Text files are byte-for-byte
184
+ unchanged.
185
+ - **The AUR package now warns before pacman's "exists in filesystem" abort.**
186
+ Installing over a previous `npm install -g diffstalker` fails because npm's
187
+ prefix on Arch is `/usr`, leaving `/usr/bin/diffstalker` owned by no
188
+ package. Nothing in a package can clear that at install time — the
189
+ file-conflict check gates the transaction ahead of every scriptlet and
190
+ hook — so the PKGBUILD checks at build time instead and prints the exact
191
+ remedy, in `prepare()` and again at the end of `package()`. Detects the
192
+ dangling symlink a stale `npm link` leaves behind, which `test -e` alone
193
+ reports as absent.
194
+ - **Line numbers after "" are right again.** The
195
+ marker is git's note about the line above it, not a line of either file,
196
+ but it was counted as one — so every line after it in the hunk was
197
+ numbered one too high on both sides, and in side-by-side view the left and
198
+ right gutters stopped agreeing. It now takes no number and shifts nothing.
199
+ The two versions of a changed last line also stay on one row again, with
200
+ their word-level highlighting, instead of being split apart by the marker
201
+ standing between them; and the marker is shown on the side it is actually
202
+ about, rather than on both, so it no longer claims a missing newline for
203
+ the file that has one.
204
+ - **A `chmod +x` reads as a mode change instead of two lines of file
205
+ content.** `old mode 100644` / `new mode 100755` were not recognized as
206
+ diff headers, so they were rendered as context lines of the file itself,
207
+ numbered from 0. Renames, copies and dissimilarity headers are recognized
208
+ in the same place now — there were two header lists that had drifted apart,
209
+ and there is one.
210
+ - **A file with merge conflicts is marked as conflicted.** An unmerged path
211
+ used to read as an ordinary modify, add or delete, so nothing told you it
212
+ was the file holding up the merge. It now carries its own status: `U` in
213
+ the file lists and the Explorer, in its own colour, in both the browser and
214
+ the terminal. In the browser its stage/unstage button is disabled and says
215
+ why — `git add` on an unmerged path claims a resolution that has not
216
+ happened, and unstaging throws away the conflict stages.
217
+ - **A huge untracked file no longer claims to be empty, or stalls the file
218
+ list.** Every untracked file was read whole just to count its lines, so a
219
+ 405 MB log was loaded into memory and reported as `+0 −0`. Files over the
220
+ diff size cap (256 KB — the same cap the untracked diff already used) are
221
+ no longer read, and show no line counts at all rather than zeros.
222
+ - **A refused stage or unstage stays on screen.** The message git gave back
223
+ was wiped by the next state change — often within a fraction of a second,
224
+ since staging is exactly what triggers one — so the button appeared to do
225
+ nothing at all. The refusal now names the action and the file (`Could not
226
+ stage a.ts: …`) and stays until it is genuinely over: the file reaches the
227
+ side you asked for, you try again, or a more urgent problem replaces it.
228
+ - **A journal timestamp older than an hour says which day it is.** The
229
+ relative time ("5 minutes ago") freezes into a clock time at an hour old,
230
+ and that clock time was a bare `14:32` whatever day it belonged to.
231
+ Anything not from today now carries its date, and its year when that
232
+ differs too.
233
+
234
+ ### Internal
235
+
236
+ - **The release gate now boots the packed tarballs under Node.** Every step
237
+ before it runs under bun, so nothing ever executed the published Node
238
+ program on the runtime its users have. The new step installs both tarballs
239
+ with npm into a clean directory, starts the daemon, and checks that `GET /`
240
+ is really the web UI and that every asset it references returns 200 — on
241
+ the engines floor (20.19.0) as well as current Node. It also catches a
242
+ daemon tarball built without `build:prod`, which ships without the web
243
+ assets, installs cleanly, and then fails on first run.
244
+ - **The README states the platform.** Linux is what diffstalker is built and
245
+ tested on. macOS needs an explicit `--socket` because it does not set
246
+ `XDG_RUNTIME_DIR`, and native Windows is not supported; use WSL2.
247
+ - **Three CLI test files were never being run.** The test script globbed
248
+ `src/*.test.ts src/**/*.test.ts`, which the shell expands one directory
249
+ deep, so everything under `src/ui/widgets/` was skipped in CI and in the
250
+ pre-push hook. All packages now run `bun test src/`, which lets bun do the
251
+ discovery.
252
+
253
+ ## [0.9.0] - 2026-07-28
254
+
255
+ ### Fixed
256
+
257
+ - **A worktree is named by its directory everywhere, and its branch is
258
+ never hidden.** The switcher's trigger showed the directory while its
259
+ rows showed the branch, so a `main` worktree with a feature branch
260
+ checked out read as two different names depending on where you looked.
261
+ Worse, the header suppressed the branch name in the breadcrumb whenever
262
+ it matched "what the switcher shows" — computed the row way, not the
263
+ trigger way — so in exactly that case the current branch appeared
264
+ nowhere in plain text. The switcher now names the PLACE (the directory)
265
+ in both, and a row carries the checked-out branch on its own line when
266
+ it differs from the directory name; a detached worktree says "detached"
267
+ in its meta line. The breadcrumb states the branch whenever the switcher
268
+ is not already showing that exact word.
269
+ - **The upstream shortens to its remote when it adds nothing.** A branch
270
+ tracking the same name upstream printed it twice
271
+ (`aer-4569-x → origin/aer-4569-x`); it now reads `aer-4569-x → origin`,
272
+ with the full ref on hover. A genuinely different upstream branch
273
+ (`main → upstream/release-2025.1`) is still spelled out.
274
+ - **Project identity now comes from git, not from path shape.** Worktrees
275
+ were grouped by their deepest common parent directory, which assumed a
276
+ layout: worktrees parked as SIBLINGS of the repo (`…/proj` +
277
+ `…/proj-fix`) share only their parent, so the project was named after
278
+ whatever directory the user happens to keep repos in. Grouping is now
279
+ the repository's MAIN worktree (`git worktree list` reports it first,
280
+ exposed as `isMain` on `WorktreeInfo`), which exists in every layout —
281
+ nested under the repo, sibling, bare-with-worktrees, scattered across
282
+ unrelated directories, or no worktrees at all. A bare main names the
283
+ project from its directory (`…/proj/.bare` → `proj`, `…/proj.git` →
284
+ `proj`). One test per layout.
285
+ - **The repo picker no longer forgets recent repos.** Opening or closing a
286
+ repo — which every repo switch does — cleared the whole worktree cache,
287
+ and recents deliberately do not render until resolved, so the Recent
288
+ list emptied on every switch and re-resolved from scratch. Cache entries
289
+ are now marked stale instead of dropped: the last good answer keeps
290
+ rendering while a re-read runs in the background.
291
+ - **The repo and worktree switchers no longer disagree, and the picker no
292
+ longer depends on when it was opened.** The header could show one
293
+ project's name next to another repo's worktree name, and the panel's
294
+ rows could be populated differently from one opening to the next.
295
+ Three separate caches were answering the same question — the active
296
+ repo's worktrees (a bare list in the daemon store, replaced only when a
297
+ fetch happened to land), the picker's per-repo-id project map, and the
298
+ recents' per-path map — over two endpoints, with three lifetimes and no
299
+ sharing. They are replaced by one `worktrees` store keyed by filesystem
300
+ path, with explicit per-entry state (pending / ready / absent /
301
+ failed), in-flight dedup, and invalidation when the open-repo set
302
+ changes. Every surface derives from the ACTIVE PATH, so a switch of any
303
+ kind — picker, worktree dropdown, follow mode, URL, SSE reconnect —
304
+ cannot leave the previous repo's data on screen, and a failed or
305
+ out-of-order lookup can never be attributed to the wrong repo. Opening
306
+ the worktree dropdown now re-reads its "edited N ago" / commits-ahead
307
+ data without blanking the list while it does.
308
+
309
+ ### Changed
310
+
311
+ - **Compare's diffs follow the tree order.** The file tree groups a
312
+ directory's sub-directories before its loose files; the diff stack below
313
+ kept the daemon's flat path sort, so the two read in different orders as
314
+ soon as a directory held both. The stack now renders in tree order, so
315
+ scrolling the diffs walks the tree. Collapsing a directory is a tree
316
+ affordance only — it never reorders the diffs or drops one.
317
+ - **Diffs are no longer sent twice.** Every diff carried both its raw text
318
+ and the parsed lines that text produces — the raw was a third of every
319
+ diff response, and doubled what the journal retains in memory. `lines`
320
+ is now the only representation; the raw text is derived where it is
321
+ actually needed (hunk staging, hunk counting, per-file splitting) via
322
+ `rawFromLines`. Combined with the size cap below, a large branch compare
323
+ went from 53 MB to 7.2 MB. An empty diff now parses to NO lines rather
324
+ than one phantom blank line, so the round-trip is exact.
325
+ - **Oversized file diffs are announced, not sent.** A single file's diff
326
+ over 256 KB or 5,000 lines is no longer transferred or rendered: the
327
+ file keeps its header, stats, and place in the list, and its body is one
328
+ line — `Large file — diff not shown (5.7 MB, 121,235 lines)`. This is
329
+ the same shape git already uses for binary files, so both cases now
330
+ render through one placeholder everywhere (Changes, Compare, History,
331
+ Journal, Explorer diffs). The cap is applied in core, so every diff the
332
+ daemon serves gets it. On a real branch compare (841 files) this took
333
+ the response from 53 MB to 10.6 MB, withholding six files. The two
334
+ limits are `MAX_FILE_DIFF_BYTES` / `MAX_FILE_DIFF_LINES` in
335
+ `core/git/diffParse`; the byte cap is the one that catches long-line
336
+ files (minified bundles, exported SVGs) that the line cap misses.
337
+ - An untracked file too big to read now gets that same notice instead of
338
+ an empty diff, which used to read as "no changes".
339
+
340
+ ### Added
341
+
342
+ - **Version indicator in the web UI's status bar.** The far right of the
343
+ status bar shows the running version and whether it matches what npm
344
+ publishes: dim `v0.8.1` when it matches, `v0.8.1 → 0.9.0` in the warn
345
+ color when a newer version is out, the accent color for a local build
346
+ ahead of npm. New daemon endpoint `GET /version` backs it — it reads the
347
+ running version from the daemon's own package manifest and compares it
348
+ with npm's `latest` dist-tag, cached six hours (five minutes after a
349
+ failed lookup) and fetched only when a client asks. The new
350
+ `--no-update-check` flag turns the npm lookup off entirely; offline or
351
+ opted out, the running version still shows and the comparison reads
352
+ unknown.
9
353
 
10
354
  ## [0.8.1] - 2026-07-28
11
355
 
package/README.md CHANGED
@@ -26,23 +26,53 @@ node packages/daemon/dist/index.js # run the compiled daemon
26
26
  packages/daemon/bin/diffstalkerd # same, via the bin wrapper
27
27
  ```
28
28
 
29
+ Arguments:
30
+
31
+ ```
32
+ REPO_PATH... Repository to open on startup, so a client finds it
33
+ already there. Relative paths resolve against the
34
+ current directory and ~ expands; a path that will not
35
+ open stops the daemon before it listens
36
+ ```
37
+
29
38
  Options:
30
39
 
31
40
  ```
32
41
  --socket PATH Bind a unix socket at PATH
42
+ --instance NAME Bind <NAME>.sock in the runtime dir, so several daemons
43
+ can run side by side (clients select it with the same
44
+ name: diffstalker --instance NAME)
33
45
  (default: $XDG_RUNTIME_DIR/diffstalker/diffstalkerd.sock)
34
- --port N Bind TCP port N (loopback only) instead of a unix socket
46
+ --no-socket Do not bind a unix socket (requires --port)
47
+ --port N Also bind TCP port N (loopback only) for the web UI.
48
+ The port serves the web API subset; the unix socket
49
+ keeps the full API
35
50
  --follow-file PATH Hook file to follow (created when missing)
36
51
  (default: ~/.cache/diffstalker/target)
37
52
  --no-follow Disable follow mode (no hook-file watcher)
38
53
  --web-root PATH Directory of built web-UI assets to serve at GET /
39
54
  (default: ./web next to the daemon bundle; the published
40
55
  package ships it there. Missing dir → API-only, non-fatal)
56
+ --no-update-check Never ask npm which version is latest; GET /version
57
+ then reports the running version only
58
+ --version, -v Print the running version and exit
41
59
  --help, -h Show this help
42
60
  ```
43
61
 
44
- `--socket` and `--port` are mutually exclusive; so are `--follow-file` and
45
- `--no-follow`.
62
+ `--socket` and `--port` are **not** mutually exclusive — binding both is the
63
+ normal deployment. The unix socket is the daemon's identity (one per user) and
64
+ is always bound unless `--no-socket`; `--port` adds the browser's transport on
65
+ top, over the same git state. `--follow-file` and `--no-follow` are exclusive,
66
+ as are `--socket` and `--no-socket`.
67
+
68
+ ```bash
69
+ diffstalkerd --port 7337 # socket for the TUI + :7337 for the browser
70
+ ```
71
+
72
+ That single daemon is what both clients talk to: `diffstalker` finds the socket
73
+ and attaches instead of spawning its own, so the TUI and the browser observe one
74
+ state over one event stream. Binding only a port (`--no-socket --port N`) leaves
75
+ the CLI nothing to attach to, and it will start a second, separate daemon.
46
76
 
47
77
  A browser can only reach the daemon over TCP (`--port`), not a unix socket, and
48
78
  the daemon sends no CORS headers — so the web UI is served same-origin from the
@@ -50,11 +80,17 @@ daemon itself. `GET /` and any unmatched non-API GET path return the SPA's
50
80
  `index.html` (client-side routing); hashed `/assets/*` are served with a long
51
81
  immutable cache. The REST/SSE API always takes precedence over static files.
52
82
 
53
- Without `--socket`/`--port`, the daemon binds a unix socket at
83
+ Without `--socket`, the daemon binds a unix socket at
54
84
  `$XDG_RUNTIME_DIR/diffstalker/diffstalkerd.sock`. The directory is created
55
85
  with mode `0700` and the socket is chmod'd to `0600` (owner only). If
56
86
  `XDG_RUNTIME_DIR` is unset, the daemon refuses to start — there is
57
87
  deliberately no `/tmp` fallback. Pass `--socket PATH` explicitly instead.
88
+ (With a `--port` to fall back on, an unset `XDG_RUNTIME_DIR` is a warning
89
+ rather than a failure: the web UI still works, only the CLI transport is
90
+ missing.)
91
+
92
+ `--port 0` asks the kernel to pick a free port; the daemon prints the one it
93
+ actually got.
58
94
 
59
95
  If a live daemon already answers on the socket path, startup fails; a stale
60
96
  socket file (nothing listening) is removed and reused.
@@ -73,12 +109,23 @@ headers (`X-Content-Type-Options`, `X-Frame-Options: DENY`,
73
109
  SPA). To reach the daemon from another machine, forward the port over SSH
74
110
  (`ssh -L`). See `SECURITY.md` at the repo root.
75
111
 
76
- A `--port` daemon also exposes a **reduced API** (least privilege): only the
77
- endpoints the web UI uses — reads, `POST`/`DELETE /repos`, and
78
- `POST /repos/:id/stage`/`unstage`. The CLI-only mutations (commit, discard,
79
- hunk staging, `PUT /compare/base`, and every remote/branch operation) are
80
- not routed on a port; they exist only over the unix socket. Requesting one
81
- on a port returns `404 Unknown route`.
112
+ The API surface is chosen **per listener**, by how well that transport is
113
+ protected — not per daemon. A unix socket (or an inherited activation fd) is
114
+ owner-only at the filesystem layer and carries the **full** API. A TCP port is
115
+ reachable by any process on the host and carries a **reduced** API (least
116
+ privilege): only the endpoints the web UI uses — reads, `POST`/`DELETE /repos`,
117
+ and `POST /repos/:id/stage`/`unstage`. The CLI-only mutations (commit, discard,
118
+ hunk staging, `PUT /compare/base`, and every remote/branch operation) are not
119
+ routed on a port at all; requesting one there returns `404 Unknown route`.
120
+
121
+ So a daemon bound to both transports simultaneously is still safe to expose to a
122
+ browser: the write-capable surface stays behind `0600` file permissions, and no
123
+ origin-guard bypass can reach it, because those routes are not in the port's
124
+ routing table to begin with. Each listener gets its own routing table over one
125
+ shared registry, SSE hub and follow controller.
126
+
127
+ Embedders can override this with `createDaemon({ apiMode })`, which forces one
128
+ surface onto every listener regardless of transport.
82
129
 
83
130
  ## Environment
84
131
 
@@ -89,7 +136,37 @@ on a port returns `404 Unknown route`.
89
136
  - `LISTEN_FDS` / `LISTEN_PID` — systemd socket activation. When systemd hands
90
137
  the process a pre-bound socket (`LISTEN_PID` matches and `LISTEN_FDS >= 1`),
91
138
  the daemon listens on the inherited fd (fd 3) and does not create, chmod, or
92
- unlink any socket file. Explicit `--socket`/`--port` takes precedence.
139
+ unlink any socket file. An explicit `--socket` (or `--no-socket`) takes
140
+ precedence; `--port` does not suppress it, since the port is additive.
141
+ Only fd 3 is used — a `.socket` unit with several `ListenStream=` entries
142
+ would have all but the first ignored.
143
+
144
+ ## systemd (user service)
145
+
146
+ The Arch package installs a **user** unit at
147
+ `/usr/lib/systemd/user/diffstalkerd.service`:
148
+
149
+ ```bash
150
+ systemctl --user enable --now diffstalkerd
151
+ # web UI at http://diffstalker.localhost:7337/
152
+ ```
153
+
154
+ It runs `diffstalkerd --port 7337`, which binds the default unix socket *and*
155
+ the port — so the terminal UI attaches to the same daemon the browser is
156
+ talking to, and `systemctl --user status diffstalkerd` is the whole story.
157
+
158
+ A **user** unit, never a system one: the socket lives under `$XDG_RUNTIME_DIR`
159
+ (per-user, `0700`), and every git call runs as the invoking user with their
160
+ config, ssh keys and worktrees. A system service would be the wrong uid for
161
+ all three.
162
+
163
+ Deliberately **not** socket-activated, even though the daemon implements the
164
+ `sd_listen_fds` protocol. The CLI health-probes the socket with a 250 ms budget
165
+ before falling back to spawning its own daemon; a cold activated start overruns
166
+ that, so the TUI would try to spawn a second daemon and hit `already running`.
167
+ An always-warm service answers the probe immediately. The daemon also has no
168
+ idle timeout — it holds watchers on open repos and is meant to stay warm for
169
+ the session — so lazy activation buys little here.
93
170
 
94
171
  ## API
95
172
 
@@ -116,14 +193,16 @@ values are rejected with a 400 so they can never be parsed as git flags.
116
193
  | Method | Path | What |
117
194
  | ------ | -------------------------- | ------------------------------------------------ |
118
195
  | GET | `/health` | `{ok, ready}` |
196
+ | GET | `/version` | `{current, latest, status}` — the running version against npm's `latest` dist-tag (`current` \| `outdated` \| `ahead` \| `unknown`). The npm lookup is cached (6h, 5min after a failure) and only ever runs when this endpoint is called; `--no-update-check` skips it, leaving `latest: null` |
119
197
  | GET | `/repos` | List open repos (`id`, `path`, `branch`) |
120
198
  | POST | `/repos` | Open a repo: `{"path": "/abs/path"}` → `{id, path}` (201 created, 200 already open) |
121
199
  | DELETE | `/repos/:id` | Close a repo (refcounted per open) |
122
200
  | GET | `/repos/:id/worktrees` | Registered worktrees (`path`, `branch`, `head`, `isBare`, `lastActivity`, `aheadOfBase`): main worktree, linked worktrees, and the bare entry in a bare-worktree layout |
123
201
  | GET | `/worktrees?path=` | Same as above, but for a raw filesystem path instead of an already-opened repo id (e.g. a recently-visited repo a client hasn't opened on this daemon) |
124
202
  | GET | `/repos/:id/status` | Shared state: status, hunk counts, stash list, in-progress operation, error, working-file mtimes (path → mtimeMs; what browser clients build mtime-based auto mode on) |
125
- | GET | `/repos/:id/diff?path=&staged=` | Diff; whole tree without `path`, staged side with `staged=true` |
203
+ | GET | `/repos/:id/diff?path=&staged=` | Diff; whole tree without `path`, staged side with `staged=true`. Per-file cap: a file's diff over 256 KB or 5,000 lines is withheld — its headers are kept and its body becomes one `Large file — diff not shown (…)` line, the same shape git uses for `Binary files … differ`. Applies to every diff-bearing response (compare, commit diffs, journal) |
126
204
  | GET | `/repos/:id/history?count=` | Commit history (`CommitInfo[]`, default 100, ISO dates) |
205
+ | GET | `/repos/:id/commits/:hash` | One commit by hash or short hash (404 on unknown) — what a link to a commit outside a client's loaded log resolves through |
127
206
  | GET | `/repos/:id/commits/:hash/diff` | Diff introduced by one commit (404 on unknown hash; merge and `--allow-empty` commits are 200 with an empty diff, matching the CLI) |
128
207
  | GET | `/repos/:id/head-message` | HEAD commit message for amend prefill: `{message}` (`""` when the repo has no commits) |
129
208
  | GET | `/repos/:id/branches` | Local branches (`name`, `current`, `tracking`) |
@@ -131,8 +210,10 @@ values are rejected with a 400 so they can never be parsed as git flags.
131
210
  | GET | `/repos/:id/compare/base` | Effective compare base: `{base}` (persisted choice or discovered default, null when none) |
132
211
  | PUT | `/repos/:id/compare/base` | Persist the compare base: `{"branch": "origin/main"}` → `{base}`; the ref is validated first (400 on an unknown ref, nothing persisted) |
133
212
  | GET | `/repos/:id/compare?base=&uncommitted=` | Base-vs-HEAD `CompareDiff` (three-dot); base defaults to the effective base — a stale persisted base falls back to the discovered default, 422 when nothing usable resolves; an explicit unknown `base` is a 400; a base with no common history is a 422; `uncommitted=true` merges working-tree changes |
134
- | GET | `/repos/:id/tree?dir=&hidden=&ignored=` | One directory level (`name`, `path`, `type`), gitignored/hidden filtered by default (`hidden=true` / `ignored=true` include them, mirroring the TUI toggles), files annotated with `gitStatus` + `staged`, changed dirs with `hasChanges` (400 outside the repo root or on a file, 404 unknown dir) |
135
- | GET | `/repos/:id/file?path=` | File content for display with flags: `{content, binary, truncated, tooLarge, size, totalLines}` — binary/oversized come back with empty content and the flag set, never prose; 400 for anything that is not a regular file (directory, FIFO, device) or resolves outside the repo root |
213
+ | GET | `/repos/:id/tree?dir=&hidden=&ignored=` | One directory level (`name`, `path`, `type`), gitignored/hidden filtered by default (`hidden=true` / `ignored=true` include them, mirroring the TUI toggles), files annotated with `gitStatus` + `staged`, changed dirs with `hasChanges` (400 outside the repo root, on a file, or on the git directory, 404 unknown dir). The git directory is never listed, even with `hidden=true` |
214
+ | GET | `/repos/:id/file?path=` | File content for display with flags: `{content, binary, truncated, tooLarge, size, totalLines, media?}` — binary/oversized come back with empty content and the flag set, never prose; `media` carries the image verdict (`{image, refusal, version}`) when the bytes say something about it; 400 for anything that is not a regular file (directory, FIFO, device), resolves outside the repo root, or addresses the git directory |
215
+ | GET | `/repos/:id/media?path=&staged=` | Image metadata for one changed file, both sides resolved server-side (renames included): `{old, new}`, each side `{path, side, bytes, oid, image, refusal, version}` or `null` when the file does not exist there. `staged` must be spelled `0` or `1`. 404 when the path is not in status. See [Image bytes](#image-bytes) |
216
+ | GET | `/repos/:id/blob?path=&side=&v=` | Raw image bytes for `<img src>`; `side` is `worktree` \| `index` \| `head`, `v` is an ignored cache key. Only PNG/JPEG/GIF, typed from magic bytes. Status-independent (no `git status`), so a clean committed image is reachable. See [Image bytes](#image-bytes) |
136
217
  | GET | `/repos/:id/files` | All tracked + untracked (not ignored) paths: the fuzzy-finder source |
137
218
  | GET | `/repos/:id/journal?since=` | Append-only edit journal: `{epoch, prunedBefore, entries}`; `since=<seq>` returns only entries with a higher seq (all when omitted) |
138
219
  | GET | `/repos/:id/events` | SSE: `snapshot` on connect, then `state-change` events from the file watcher and `journal-append {entries}` per journal observation |
@@ -207,6 +288,109 @@ repo's last client (a browser F5) disposes the manager but keeps the
207
288
  store, so a reopen resumes the same chronology under the same epoch.
208
289
  Stores are LRU-capped daemon-wide; an open repo's store is never evicted.
209
290
 
291
+ ## Image bytes
292
+
293
+ `GET /repos/:id/blob` is the only endpoint that hands raw repository bytes to a
294
+ browser, and `GET /repos/:id/media` is the metadata that tells the web UI which
295
+ bytes to ask for. Both are routed on **every** listener (the socket and the
296
+ port), because the web UI is what needs them.
297
+
298
+ The rule the whole design rests on: **what we say a file is comes from its
299
+ magic bytes**, re-derived from the exact buffer the route is about to write, on
300
+ every request. Never from the extension, never from a query parameter, never
301
+ from a verdict an earlier `/file` or `/media` response cached. A repo file
302
+ called `logo.png` holding `<svg><script>` is same-origin script the moment we
303
+ agree with its name, so it gets zero bytes and a 415.
304
+
305
+ ### Allow-list
306
+
307
+ Three formats, and nothing else is ever served:
308
+
309
+ | Format | Content-Type | Structural gate |
310
+ | ------ | ------------ | --------------- |
311
+ | PNG (still) | `image/png` | PNG signature, `IHDR` dimensions, a legal bit-depth/colour-type pair, a bounded walk to the first `IDAT`. An `acTL` chunk (APNG) is refused — it is a second animation decoder |
312
+ | JPEG (baseline / progressive) | `image/jpeg` | SOI plus a legal marker, a bounded segment walk to the first SOF; **SOF0/SOF1/SOF2 only** (lossless, arithmetic and hierarchical SOFs are refused) |
313
+ | GIF (still or animated) | `image/gif` | `GIF87a`/`GIF89a`, a walk over the whole block stream counting image descriptors. Validated only with the entire file in hand, which is what `MAX_GIF_BYTES` bounds |
314
+
315
+ Everything else is refused by default: SVG, HTML/XML, PDF, WebP, AVIF/HEIC,
316
+ TIFF, BMP, ICO, JPEG XL, fonts, wasm/ELF/PE, archives, video and audio, and
317
+ anything unrecognized or recognized-but-invalid. The daemon **never decodes,
318
+ transcodes, re-encodes or strips metadata** — validation is fixed-offset
319
+ integer reads and bounded walks. No image library (sharp, jimp, canvas,
320
+ libvips) is a dependency of any package, and the browser stays the sandbox.
321
+
322
+ ### Caps
323
+
324
+ Enforced before any byte is written, and again on the buffer being written:
325
+
326
+ ```
327
+ MAX_IMAGE_BYTES = 8 MiB any allowed format
328
+ MAX_GIF_BYTES = 2 MiB GIF only, bounds the frame walk
329
+ MAX_IMAGE_DIMENSION = 8192 px per side
330
+ MAX_IMAGE_PIXELS = 16 MPix width * height, and any one GIF frame rect
331
+ MAX_GIF_FRAMES = 256
332
+ MAX_ANIMATED_PIXELS = 32 MPix frames * screen, and the sum of the frame rects
333
+ MAX_ICC_BYTES = 64 KiB PNG iCCP / JPEG APP2 run
334
+ ```
335
+
336
+ The **pixel budget, not the byte cap, is the real control**: compression ratio
337
+ is unbounded, so a 300-byte PNG can declare 60000×60000 and cost the renderer
338
+ gigabytes of RGBA. `MAX_FILE_SIZE` (1 MiB) is untouched — that is the *text*
339
+ cap for `/file`.
340
+
341
+ A GIF declares its dimensions twice — the logical screen in the header, and a
342
+ rectangle on every frame's image descriptor — and a rect may legally be bigger
343
+ than the screen it composites into. So both are charged: every rect against the
344
+ per-side and per-image caps a still image gets, and the sum of the rects against
345
+ the animated cap on top. Checking the header alone would let a 1×1 GIF carry an
346
+ 8000×4000 frame.
347
+
348
+ Concurrency is bounded too: 4 requests in flight per daemon with a queue of 64
349
+ waiters, then 503. One budget for the whole daemon, shared by every listener
350
+ **and by both endpoints** — `/media` inspects up to two sides, so it costs the
351
+ same spawns and the same buffers as `/blob` and takes the same slot. One
352
+ changed binary file costs up to three of those requests: a `/media` for the
353
+ verdict plus a `/blob` per side.
354
+
355
+ A slot is held until the response is finished on the socket, not just until the
356
+ read is done: the bytes stay resident while the client drains them, so an
357
+ earlier release would bound reads and leave memory unbounded. The release is
358
+ wired to the request **and** the response, because the two runtimes report the
359
+ end differently — node destroys the response when a client aborts, while bun
360
+ signals the abort only on the request. Every path either ends the response or
361
+ destroys the request, so the slot always comes back.
362
+
363
+ The two endpoints read different amounts, but they always reach the **same
364
+ verdict** about what a file is. `/media` only reports that verdict, so it reads
365
+ the window that decides the file and no more — a 64 KiB header for PNG and
366
+ JPEG, the whole file for a GIF, whose frame walk spans it. When that window is
367
+ inconclusive (a JPEG whose frame header sits behind a maximal EXIF segment, say)
368
+ the read is extended to the whole blob, which `MAX_IMAGE_BYTES` already bounds,
369
+ so `/media` never refuses a file `/blob` would serve. Only `/blob` reads the
370
+ bytes it is going to write.
371
+
372
+ ### Refusals
373
+
374
+ | Status | Cause |
375
+ | ------ | ----- |
376
+ | 400 | empty/NUL path, a leading `-` (git option) or `:` (pathspec magic), traversal, a symlink escaping the root, any `.git` path, a non-regular file (directory, symlink, gitlink, FIFO), a bad `side`, a `staged` that is not `0`/`1` |
377
+ | 403 | `Sec-Fetch-Site` present and cross-site, or `Sec-Fetch-Dest` present and not `image` (`/blob` only — `/media` is JSON and the SPA's own `fetch` sends `Sec-Fetch-Dest: empty`). Both absent passes, so `curl` and the Node client are unaffected |
378
+ | 404 | unknown repo, or the path does not exist on that side. `/media` also 404s a path with no status entry |
379
+ | 413 | over the byte, dimension, pixel or frame cap |
380
+ | 415 | not allow-listed, or the signature matched and the structure failed. An APNG lands here too: it is not over any budget, it is a format we refuse |
381
+ | 421 | non-loopback `Host` (the global origin guard) |
382
+ | 503 | the blob queue overflowed |
383
+
384
+ Every refusal writes **zero bytes** and a plain `{"error": "..."}` body.
385
+
386
+ A 200 carries the magic-derived `content-type`, `content-disposition: inline`
387
+ with **no** `filename` parameter (a repo-supplied string is never interpolated
388
+ into a header), a re-asserted `x-content-type-options: nosniff`,
389
+ `cross-origin-resource-policy: same-origin`, `vary: sec-fetch-site,
390
+ sec-fetch-dest`, and either `cache-control: no-store` (`side=worktree`, whose
391
+ bytes can change under us) or `cache-control: private, no-cache` plus an
392
+ `etag` of the object id (`side=index|head`, which are immutable).
393
+
210
394
  ## Follow mode
211
395
 
212
396
  The daemon owns the truth, clients decide policy. It watches ONE hook file